1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690
|
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifdef UNSAFE_BUFFERS_BUILD
// TODO(crbug.com/390223051): Remove C-library calls to fix the errors.
#pragma allow_unsafe_libc_calls
#endif
// This file contains download browser tests that are known to be runnable
// in a pure content context. Over time tests should be migrated here.
#include <stddef.h>
#include <stdint.h>
#include <memory>
#include <optional>
#include <tuple>
#include <utility>
#include <vector>
#include "base/compiler_specific.h"
#include "base/containers/contains.h"
#include "base/feature_list.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/format_macros.h"
#include "base/functional/bind.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/ref_counted.h"
#include "base/metrics/field_trial.h"
#include "base/metrics/field_trial_params.h"
#include "base/path_service.h"
#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/bind.h"
#include "base/test/mock_entropy_provider.h"
#include "base/test/scoped_feature_list.h"
#include "base/threading/thread_restrictions.h"
#include "base/time/time.h"
#include "build/build_config.h"
#include "components/download/public/common/download_danger_type.h"
#include "components/download/public/common/download_features.h"
#include "components/download/public/common/download_file_factory.h"
#include "components/download/public/common/download_file_impl.h"
#include "components/download/public/common/download_item.h"
#include "components/download/public/common/download_item_impl.h"
#include "components/download/public/common/download_stats.h"
#include "components/download/public/common/download_task_runner.h"
#include "components/download/public/common/parallel_download_configs.h"
#include "content/browser/download/download_manager_impl.h"
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/download_request_utils.h"
#include "content/public/common/content_client.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_paths.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/url_constants.h"
#include "content/public/common/webplugininfo.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/content_browser_test.h"
#include "content/public/test/content_browser_test_content_browser_client.h"
#include "content/public/test/content_browser_test_utils.h"
#include "content/public/test/download_test_observer.h"
#include "content/public/test/fenced_frame_test_util.h"
#include "content/public/test/prerender_test_util.h"
#include "content/public/test/slow_download_http_response.h"
#include "content/public/test/test_download_http_response.h"
#include "content/public/test/test_file_error_injector.h"
#include "content/public/test/test_navigation_observer.h"
#include "content/public/test/test_utils.h"
#include "content/public/test/url_loader_monitor.h"
#include "content/shell/browser/shell.h"
#include "content/shell/browser/shell_browser_context.h"
#include "content/shell/browser/shell_download_manager_delegate.h"
#include "content/test/content_browser_test_utils_internal.h"
#include "content/test/fake_network_url_loader_factory.h"
#include "net/base/features.h"
#include "net/base/filename_util.h"
#include "net/dns/mock_host_resolver.h"
#include "net/http/http_connection_info.h"
#include "net/test/embedded_test_server/controllable_http_response.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "net/test/embedded_test_server/http_request.h"
#include "net/test/embedded_test_server/http_response.h"
#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
#include "ppapi/buildflags/buildflags.h"
#include "services/network/public/cpp/content_decoding_interceptor.h"
#include "services/network/public/cpp/features.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/common/features.h"
#include "third_party/blink/public/common/input/web_mouse_event.h"
#include "third_party/blink/public/common/switches.h"
#include "url/gurl.h"
#include "url/origin.h"
#if BUILDFLAG(ENABLE_PLUGINS)
#include "content/browser/plugin_service_impl.h"
#endif
#if BUILDFLAG(IS_ANDROID)
#include "base/android/build_info.h"
#endif
using ::testing::_;
using ::testing::AllOf;
using ::testing::Field;
using ::testing::InSequence;
using ::testing::Property;
using ::testing::Return;
using ::testing::StrictMock;
using ::testing::Values;
namespace net {
class NetLogWithSource;
}
namespace content {
namespace {
// Default request count for parallel download tests.
constexpr int kTestRequestCount = 3;
// Offset for download to pause.
const int kPauseOffset = 100 * 1024;
const char kOriginOne[] = "one.example";
const char kOriginTwo[] = "two.example";
const char kOrigin[] = "example.com";
const char kOriginSubdomain[] = "subdomain.example.com";
const char kOtherOrigin[] = "example.site";
const char kBlogspotSite1[] = "a.blogspot.com";
const char kBlogspotSite2[] = "b.blogspot.com";
const char k404Response[] = "HTTP/1.1 404 Not found\r\n\r\n";
void ExpectRequestIsolationInfo(
const GURL& request_url,
const net::IsolationInfo& expected_isolation_info,
base::OnceCallback<void()> function) {
URLLoaderMonitor monitor({request_url});
std::move(function).Run();
monitor.WaitForUrls();
std::optional<network::ResourceRequest> request =
monitor.GetRequestInfo(request_url);
ASSERT_TRUE(request->trusted_params.has_value());
EXPECT_TRUE(expected_isolation_info.IsEqualForTesting(
request->trusted_params->isolation_info));
// SiteForCookies should be consistent with the NIK.
EXPECT_TRUE(expected_isolation_info.site_for_cookies().IsEquivalent(
request->site_for_cookies));
}
// Implementation of TestContentBrowserClient that overrides
// AllowRenderingMhtmlOverHttp() and allows consumers to set a value.
class DownloadTestContentBrowserClient
: public ContentBrowserTestContentBrowserClient {
public:
DownloadTestContentBrowserClient() {
#if BUILDFLAG(IS_ANDROID)
content_url_loader_factory_ = std::make_unique<FakeNetworkURLLoaderFactory>(
"HTTP/1.1 200 OK\nContent-Type: multipart/related\n\n",
"This is a test for download mhtml through non http/https urls",
/* network_accessed */ true, net::OK);
#endif // BUILDFLAG(IS_ANDROID)
file_url_loader_factory_ = std::make_unique<FakeNetworkURLLoaderFactory>(
"HTTP/1.1 200 OK\nContent-Type: multipart/related\n\n",
"This is a test for download mhtml through non http/https urls",
/* network_accessed */ true, net::OK);
}
DownloadTestContentBrowserClient(const DownloadTestContentBrowserClient&) =
delete;
DownloadTestContentBrowserClient& operator=(
const DownloadTestContentBrowserClient&) = delete;
bool AllowRenderingMhtmlOverHttp(NavigationUIData* navigation_data) override {
return allowed_rendering_mhtml_over_http_;
}
void set_allowed_rendering_mhtml_over_http(bool allowed) {
allowed_rendering_mhtml_over_http_ = allowed;
}
void enable_register_non_network_url_loader(bool enabled) {
enable_register_non_network_url_loader_ = enabled;
}
base::FilePath GetDefaultDownloadDirectory() override {
return base::FilePath();
}
mojo::PendingRemote<network::mojom::URLLoaderFactory>
CreateNonNetworkNavigationURLLoaderFactory(
const std::string& scheme,
FrameTreeNodeId frame_tree_node_id) override {
if (!enable_register_non_network_url_loader_) {
return {};
}
#if BUILDFLAG(IS_ANDROID)
if (scheme == url::kContentScheme) {
mojo::PendingRemote<network::mojom::URLLoaderFactory>
content_factory_remote;
content_url_loader_factory_->Clone(
content_factory_remote.InitWithNewPipeAndPassReceiver());
return content_factory_remote;
}
#endif // BUILDFLAG(IS_ANDROID)
if (scheme == url::kFileScheme) {
mojo::PendingRemote<network::mojom::URLLoaderFactory> file_factory_remote;
file_url_loader_factory_->Clone(
file_factory_remote.InitWithNewPipeAndPassReceiver());
return file_factory_remote;
}
return {};
}
private:
bool allowed_rendering_mhtml_over_http_ = false;
bool enable_register_non_network_url_loader_ = false;
std::unique_ptr<FakeNetworkURLLoaderFactory> content_url_loader_factory_;
std::unique_ptr<FakeNetworkURLLoaderFactory> file_url_loader_factory_;
};
class MockDownloadItemObserver : public download::DownloadItem::Observer {
public:
MockDownloadItemObserver() {}
~MockDownloadItemObserver() override {}
MOCK_METHOD1(OnDownloadUpdated, void(download::DownloadItem*));
MOCK_METHOD1(OnDownloadOpened, void(download::DownloadItem*));
MOCK_METHOD1(OnDownloadRemoved, void(download::DownloadItem*));
MOCK_METHOD1(OnDownloadDestroyed, void(download::DownloadItem*));
};
class MockDownloadManagerObserver : public DownloadManager::Observer {
public:
explicit MockDownloadManagerObserver(DownloadManager* manager) {
manager_ = manager;
manager->AddObserver(this);
}
~MockDownloadManagerObserver() override {
if (manager_)
manager_->RemoveObserver(this);
}
MOCK_METHOD2(OnDownloadCreated,
void(DownloadManager*, download::DownloadItem*));
MOCK_METHOD1(OnDownloadDropped, void(DownloadManager*));
MOCK_METHOD1(ModelChanged, void(DownloadManager*));
void ManagerGoingDown(DownloadManager* manager) override {
DCHECK_EQ(manager_, manager);
MockManagerGoingDown(manager);
manager_->RemoveObserver(this);
manager_ = nullptr;
}
MOCK_METHOD1(MockManagerGoingDown, void(DownloadManager*));
private:
raw_ptr<DownloadManager> manager_;
};
class DownloadFileWithDelayFactory;
static DownloadManagerImpl* DownloadManagerForShell(Shell* shell) {
// We're in a content_browsertest; we know that the DownloadManager
// is a DownloadManagerImpl.
return static_cast<DownloadManagerImpl*>(
shell->web_contents()->GetBrowserContext()->GetDownloadManager());
}
class DownloadFileWithDelay : public download::DownloadFileImpl {
public:
DownloadFileWithDelay(
std::unique_ptr<download::DownloadSaveInfo> save_info,
const base::FilePath& default_download_directory,
std::unique_ptr<download::InputStream> stream,
uint32_t download_id,
base::WeakPtr<download::DownloadDestinationObserver> observer,
base::WeakPtr<DownloadFileWithDelayFactory> owner);
DownloadFileWithDelay(const DownloadFileWithDelay&) = delete;
DownloadFileWithDelay& operator=(const DownloadFileWithDelay&) = delete;
~DownloadFileWithDelay() override;
// Wraps DownloadFileImpl::Rename* and intercepts the return callback,
// storing it in the factory that produced this object for later
// retrieval.
void RenameAndUniquify(const base::FilePath& full_path,
RenameCompletionCallback callback) override;
void RenameAndAnnotate(
const base::FilePath& full_path,
const std::string& client_guid,
const GURL& source_url,
const GURL& referrer_url,
const std::optional<url::Origin>& request_initiator,
mojo::PendingRemote<quarantine::mojom::Quarantine> remote_quarantine,
RenameCompletionCallback callback) override;
private:
static void RenameCallbackWrapper(
const base::WeakPtr<DownloadFileWithDelayFactory>& factory,
RenameCompletionCallback original_callback,
download::DownloadInterruptReason reason,
const base::FilePath& path);
// This variable may only be read on the download sequence, and may only be
// indirected through (e.g. methods on DownloadFileWithDelayFactory called)
// on the UI thread. This is because after construction,
// DownloadFileWithDelay lives on the file thread, but
// DownloadFileWithDelayFactory is purely a UI thread object.
base::WeakPtr<DownloadFileWithDelayFactory> owner_;
};
// All routines on this class must be called on the UI thread.
class DownloadFileWithDelayFactory : public download::DownloadFileFactory {
public:
DownloadFileWithDelayFactory();
DownloadFileWithDelayFactory(const DownloadFileWithDelayFactory&) = delete;
DownloadFileWithDelayFactory& operator=(const DownloadFileWithDelayFactory&) =
delete;
~DownloadFileWithDelayFactory() override;
// DownloadFileFactory interface.
download::DownloadFile* CreateFile(
std::unique_ptr<download::DownloadSaveInfo> save_info,
const base::FilePath& default_download_directory,
std::unique_ptr<download::InputStream> stream,
uint32_t download_id,
const base::FilePath& duplicate_download_file_path,
base::WeakPtr<download::DownloadDestinationObserver> observer) override;
void AddRenameCallback(base::OnceClosure callback);
void GetAllRenameCallbacks(std::vector<base::OnceClosure>* results);
// Do not return until GetAllRenameCallbacks() will return a non-empty list.
void WaitForSomeCallback();
private:
std::vector<base::OnceClosure> rename_callbacks_;
base::OnceClosure stop_waiting_;
base::WeakPtrFactory<DownloadFileWithDelayFactory> weak_ptr_factory_{this};
};
DownloadFileWithDelay::DownloadFileWithDelay(
std::unique_ptr<download::DownloadSaveInfo> save_info,
const base::FilePath& default_download_directory,
std::unique_ptr<download::InputStream> stream,
uint32_t download_id,
base::WeakPtr<download::DownloadDestinationObserver> observer,
base::WeakPtr<DownloadFileWithDelayFactory> owner)
: download::DownloadFileImpl(std::move(save_info),
default_download_directory,
std::move(stream),
download_id,
observer),
owner_(owner) {}
DownloadFileWithDelay::~DownloadFileWithDelay() {}
void DownloadFileWithDelay::RenameAndUniquify(
const base::FilePath& full_path,
RenameCompletionCallback callback) {
DCHECK(download::GetDownloadTaskRunner()->RunsTasksInCurrentSequence());
download::DownloadFileImpl::RenameAndUniquify(
full_path, base::BindOnce(DownloadFileWithDelay::RenameCallbackWrapper,
owner_, std::move(callback)));
}
void DownloadFileWithDelay::RenameAndAnnotate(
const base::FilePath& full_path,
const std::string& client_guid,
const GURL& source_url,
const GURL& referrer_url,
const std::optional<url::Origin>& request_initiator,
mojo::PendingRemote<quarantine::mojom::Quarantine> remote_quarantine,
RenameCompletionCallback callback) {
DCHECK(download::GetDownloadTaskRunner()->RunsTasksInCurrentSequence());
download::DownloadFileImpl::RenameAndAnnotate(
full_path, client_guid, source_url, referrer_url, request_initiator,
mojo::NullRemote(),
base::BindOnce(DownloadFileWithDelay::RenameCallbackWrapper, owner_,
std::move(callback)));
}
// static
void DownloadFileWithDelay::RenameCallbackWrapper(
const base::WeakPtr<DownloadFileWithDelayFactory>& factory,
RenameCompletionCallback original_callback,
download::DownloadInterruptReason reason,
const base::FilePath& path) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!factory)
return;
factory->AddRenameCallback(
base::BindOnce(std::move(original_callback), reason, path));
}
DownloadFileWithDelayFactory::DownloadFileWithDelayFactory() {}
DownloadFileWithDelayFactory::~DownloadFileWithDelayFactory() {}
download::DownloadFile* DownloadFileWithDelayFactory::CreateFile(
std::unique_ptr<download::DownloadSaveInfo> save_info,
const base::FilePath& default_download_directory,
std::unique_ptr<download::InputStream> stream,
uint32_t download_id,
const base::FilePath& duplicate_download_file_path,
base::WeakPtr<download::DownloadDestinationObserver> observer) {
return new DownloadFileWithDelay(
std::move(save_info), default_download_directory, std::move(stream),
download_id, observer, weak_ptr_factory_.GetWeakPtr());
}
void DownloadFileWithDelayFactory::AddRenameCallback(
base::OnceClosure callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
rename_callbacks_.push_back(std::move(callback));
if (stop_waiting_)
std::move(stop_waiting_).Run();
}
void DownloadFileWithDelayFactory::GetAllRenameCallbacks(
std::vector<base::OnceClosure>* results) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
results->swap(rename_callbacks_);
}
void DownloadFileWithDelayFactory::WaitForSomeCallback() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (rename_callbacks_.empty()) {
base::RunLoop run_loop;
stop_waiting_ = run_loop.QuitClosure();
run_loop.Run();
}
}
class CountingDownloadFile : public download::DownloadFileImpl {
public:
CountingDownloadFile(
std::unique_ptr<download::DownloadSaveInfo> save_info,
const base::FilePath& default_downloads_directory,
std::unique_ptr<download::InputStream> stream,
uint32_t download_id,
base::WeakPtr<download::DownloadDestinationObserver> observer)
: download::DownloadFileImpl(std::move(save_info),
default_downloads_directory,
std::move(stream),
download_id,
observer) {}
~CountingDownloadFile() override {
DCHECK(download::GetDownloadTaskRunner()->RunsTasksInCurrentSequence());
active_files_--;
}
void Initialize(
InitializeCallback callback,
CancelRequestCallback cancel_request_callback,
const download::DownloadItem::ReceivedSlices& received_slices) override {
DCHECK(download::GetDownloadTaskRunner()->RunsTasksInCurrentSequence());
active_files_++;
download::DownloadFileImpl::Initialize(std::move(callback),
std::move(cancel_request_callback),
received_slices);
}
static void GetNumberActiveFiles(int* result) {
DCHECK(download::GetDownloadTaskRunner()->RunsTasksInCurrentSequence());
*result = active_files_;
}
// Can be called on any thread, and will block (running message loop)
// until data is returned.
static int GetNumberActiveFilesFromFileThread() {
int result = -1;
base::RunLoop run_loop;
download::GetDownloadTaskRunner()->PostTaskAndReply(
FROM_HERE,
base::BindOnce(&CountingDownloadFile::GetNumberActiveFiles, &result),
run_loop.QuitClosure());
run_loop.Run();
DCHECK_NE(-1, result);
return result;
}
private:
static int active_files_;
};
int CountingDownloadFile::active_files_ = 0;
class CountingDownloadFileFactory : public download::DownloadFileFactory {
public:
CountingDownloadFileFactory() {}
~CountingDownloadFileFactory() override {}
// DownloadFileFactory interface.
download::DownloadFile* CreateFile(
std::unique_ptr<download::DownloadSaveInfo> save_info,
const base::FilePath& default_downloads_directory,
std::unique_ptr<download::InputStream> stream,
uint32_t download_id,
const base::FilePath& duplicate_download_file_path,
base::WeakPtr<download::DownloadDestinationObserver> observer) override {
return new CountingDownloadFile(std::move(save_info),
default_downloads_directory,
std::move(stream), download_id, observer);
}
};
class ErrorInjectionDownloadFile : public download::DownloadFileImpl {
public:
ErrorInjectionDownloadFile(
std::unique_ptr<download::DownloadSaveInfo> save_info,
const base::FilePath& default_downloads_directory,
std::unique_ptr<download::InputStream> stream,
uint32_t download_id,
base::WeakPtr<download::DownloadDestinationObserver> observer,
int64_t error_stream_offset,
int64_t error_stream_length)
: download::DownloadFileImpl(std::move(save_info),
default_downloads_directory,
std::move(stream),
download_id,
observer),
error_stream_offset_(error_stream_offset),
error_stream_length_(error_stream_length) {}
~ErrorInjectionDownloadFile() override = default;
void InjectStreamError(int64_t error_stream_offset,
int64_t error_stream_length) {
error_stream_offset_ = error_stream_offset;
error_stream_length_ = error_stream_length;
}
download::DownloadInterruptReason HandleStreamCompletionStatus(
SourceStream* source_stream) override {
if (source_stream->offset() == error_stream_offset_ &&
source_stream->bytes_written() >= error_stream_length_) {
return download::DOWNLOAD_INTERRUPT_REASON_SERVER_FAILED;
}
return download::DownloadFileImpl::HandleStreamCompletionStatus(
source_stream);
}
private:
int64_t error_stream_offset_;
int64_t error_stream_length_;
};
// Factory for creating download files that allow error injection. All routines
// on this class must be called on the UI thread.
class ErrorInjectionDownloadFileFactory : public download::DownloadFileFactory {
public:
ErrorInjectionDownloadFileFactory() : download_file_(nullptr) {}
ErrorInjectionDownloadFileFactory(const ErrorInjectionDownloadFileFactory&) =
delete;
ErrorInjectionDownloadFileFactory& operator=(
const ErrorInjectionDownloadFileFactory&) = delete;
~ErrorInjectionDownloadFileFactory() override = default;
// DownloadFileFactory interface.
download::DownloadFile* CreateFile(
std::unique_ptr<download::DownloadSaveInfo> save_info,
const base::FilePath& default_download_directory,
std::unique_ptr<download::InputStream> stream,
uint32_t download_id,
const base::FilePath& duplicate_download_file_path,
base::WeakPtr<download::DownloadDestinationObserver> observer) override {
ErrorInjectionDownloadFile* download_file = new ErrorInjectionDownloadFile(
std::move(save_info), default_download_directory, std::move(stream),
download_id, observer, injected_error_offset_, injected_error_length_);
// If the InjectError() is not called yet, memorize |download_file| and wait
// for error to be injected.
if (injected_error_offset_ < 0)
download_file_ = download_file;
injected_error_offset_ = -1;
injected_error_length_ = 0;
return download_file;
}
void InjectError(int64_t offset, int64_t length) {
injected_error_offset_ = offset;
injected_error_length_ = length;
if (!download_file_)
return;
InjectErrorIntoDownloadFile();
}
base::WeakPtr<ErrorInjectionDownloadFileFactory> GetWeakPtr() {
return weak_ptr_factory_.GetWeakPtr();
}
private:
void InjectErrorIntoDownloadFile() {
download::GetDownloadTaskRunner()->PostTask(
FROM_HERE,
base::BindOnce(&ErrorInjectionDownloadFile::InjectStreamError,
base::Unretained(download_file_), injected_error_offset_,
injected_error_length_));
injected_error_offset_ = -1;
injected_error_length_ = 0;
download_file_ = nullptr;
}
raw_ptr<ErrorInjectionDownloadFile, AcrossTasksDanglingUntriaged>
download_file_;
int64_t injected_error_offset_ = -1;
int64_t injected_error_length_ = 0;
base::WeakPtrFactory<ErrorInjectionDownloadFileFactory> weak_ptr_factory_{
this};
};
class TestShellDownloadManagerDelegate : public ShellDownloadManagerDelegate {
public:
TestShellDownloadManagerDelegate()
: delay_download_open_(false) {}
~TestShellDownloadManagerDelegate() override {}
bool ShouldOpenDownload(download::DownloadItem* item,
DownloadOpenDelayedCallback callback) override {
if (delay_download_open_) {
delayed_callbacks_.push_back(std::move(callback));
return false;
}
return true;
}
void SetDelayedOpen(bool delay) {
delay_download_open_ = delay;
}
void GetDelayedCallbacks(
std::vector<DownloadOpenDelayedCallback>* callbacks) {
callbacks->swap(delayed_callbacks_);
}
private:
bool delay_download_open_;
std::vector<DownloadOpenDelayedCallback> delayed_callbacks_;
};
// Get the next created download.
class DownloadCreateObserver : DownloadManager::Observer {
public:
explicit DownloadCreateObserver(DownloadManager* manager)
: manager_(manager), item_(nullptr) {
manager_->AddObserver(this);
}
~DownloadCreateObserver() override {
if (manager_)
manager_->RemoveObserver(this);
manager_ = nullptr;
}
void ManagerGoingDown(DownloadManager* manager) override {
DCHECK_EQ(manager_, manager);
manager_->RemoveObserver(this);
manager_ = nullptr;
}
void OnDownloadCreated(DownloadManager* manager,
download::DownloadItem* download) override {
if (!item_)
item_ = download;
if (completion_closure_)
std::move(completion_closure_).Run();
}
download::DownloadItem* WaitForFinished() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!item_) {
base::RunLoop run_loop;
completion_closure_ = run_loop.QuitClosure();
run_loop.Run();
}
return item_;
}
private:
raw_ptr<DownloadManager> manager_;
raw_ptr<download::DownloadItem> item_;
base::OnceClosure completion_closure_;
};
class DownloadInProgressObserver : public DownloadTestObserverInProgress {
public:
explicit DownloadInProgressObserver(DownloadManager* manager)
: DownloadTestObserverInProgress(manager, 1 /* wait_count */),
manager_(manager) {}
download::DownloadItem* WaitAndGetInProgressDownload() {
DownloadTestObserverInProgress::WaitForFinished();
DownloadManager::DownloadVector items;
manager_->GetAllDownloads(&items);
download::DownloadItem* download_item = nullptr;
for (auto iter = items.begin(); iter != items.end(); ++iter) {
if ((*iter)->GetState() == download::DownloadItem::IN_PROGRESS) {
// There should be only one IN_PROGRESS item.
EXPECT_FALSE(download_item);
download_item = *iter;
}
}
EXPECT_TRUE(download_item);
EXPECT_EQ(download::DownloadItem::IN_PROGRESS, download_item->GetState());
return download_item;
}
private:
raw_ptr<DownloadManager> manager_;
};
class DownloadCountingObserver : public download::DownloadItem::Observer {
public:
DownloadCountingObserver() : item_(nullptr), count_(0) {}
~DownloadCountingObserver() override {
if (item_)
item_->RemoveObserver(this);
}
void OnDownloadUpdated(download::DownloadItem* download) override {
if (IsCountReached(download, count_) && completion_closure_)
std::move(completion_closure_).Run();
}
void OnDownloadDestroyed(download::DownloadItem* download) override {
item_ = nullptr;
}
void WaitForFinished(download::DownloadItem* item, int count) {
if (IsCountReached(item, count))
return;
item_ = item;
count_ = count;
if (item_) {
item_->AddObserver(this);
base::RunLoop run_loop;
completion_closure_ = run_loop.QuitClosure();
run_loop.Run();
}
}
protected:
virtual bool IsCountReached(download::DownloadItem* download, int count) = 0;
private:
raw_ptr<download::DownloadItem> item_;
int count_;
base::OnceClosure completion_closure_;
};
class ReceivedSlicesCountingObserver : public DownloadCountingObserver {
private:
bool IsCountReached(download::DownloadItem* download, int count) override {
return download->GetReceivedSlices().size() >= static_cast<size_t>(count);
}
};
class ErrorStreamCountingObserver : public DownloadCountingObserver {
private:
bool IsCountReached(download::DownloadItem* download, int count) override {
return download::GetParallelRequestCreationFailureCountForTesting() ==
count;
}
private:
base::HistogramTester histogram_tester_;
};
class ReceivedBytesCountingObserver : public DownloadCountingObserver {
private:
bool IsCountReached(download::DownloadItem* download, int count) override {
return download->GetReceivedBytes() == count;
}
};
// Class to wait for a WebContents to kick off a specified number of
// navigations.
class NavigationStartObserver : public WebContentsObserver {
public:
explicit NavigationStartObserver(WebContents* web_contents)
: WebContentsObserver(web_contents) {}
NavigationStartObserver(const NavigationStartObserver&) = delete;
NavigationStartObserver& operator=(const NavigationStartObserver&) = delete;
~NavigationStartObserver() override {}
void WaitForFinished(int navigation_count) {
if (start_count_ >= navigation_count)
return;
navigation_count_ = navigation_count;
base::RunLoop run_loop;
completion_closure_ = run_loop.QuitClosure();
run_loop.Run();
}
private:
// WebContentsObserver implementations.
void DidStartNavigation(NavigationHandle* navigation_handle) override {
start_count_++;
if (start_count_ >= navigation_count_ && completion_closure_) {
std::move(completion_closure_).Run();
}
}
int navigation_count_ = 0;
int start_count_ = 0;
base::OnceClosure completion_closure_;
};
bool IsDownloadInState(download::DownloadItem::DownloadState state,
download::DownloadItem* item) {
return item->GetState() == state;
}
// Request handler to be used with CreateRedirectHandler().
std::unique_ptr<net::test_server::HttpResponse>
HandleRequestAndSendRedirectResponse(
const std::string& relative_url,
const GURL& target_url,
const net::test_server::HttpRequest& request) {
std::unique_ptr<net::test_server::BasicHttpResponse> response;
if (request.relative_url == relative_url) {
response = std::make_unique<net::test_server::BasicHttpResponse>();
response->set_code(net::HTTP_FOUND);
response->AddCustomHeader("Location", target_url.spec());
}
return std::move(response);
}
// Creates a request handler for EmbeddedTestServer that responds with a HTTP
// 302 redirect if the request URL matches |relative_url|.
net::EmbeddedTestServer::HandleRequestCallback CreateRedirectHandler(
const std::string& relative_url,
const GURL& target_url) {
return base::BindRepeating(&HandleRequestAndSendRedirectResponse,
relative_url, target_url);
}
// Request handler to be used with CreateBasicResponseHandler().
std::unique_ptr<net::test_server::HttpResponse>
HandleRequestAndSendBasicResponse(
const std::string& relative_url,
net::HttpStatusCode code,
const base::StringPairs& headers,
const std::string& content_type,
const std::string& body,
const net::test_server::HttpRequest& request) {
std::unique_ptr<net::test_server::BasicHttpResponse> response;
if (request.relative_url == relative_url) {
response = std::make_unique<net::test_server::BasicHttpResponse>();
for (const auto& pair : headers)
response->AddCustomHeader(pair.first, pair.second);
response->set_content_type(content_type);
response->set_content(body);
response->set_code(code);
}
return std::move(response);
}
// Creates a request handler for an EmbeddedTestServer that response with an
// HTTP 200 status code, a Content-Type header and a body.
net::EmbeddedTestServer::HandleRequestCallback CreateBasicResponseHandler(
const std::string& relative_url,
net::HttpStatusCode code,
const base::StringPairs& headers,
const std::string& content_type,
const std::string& body) {
return base::BindRepeating(&HandleRequestAndSendBasicResponse, relative_url,
code, headers, content_type, body);
}
std::unique_ptr<net::test_server::HttpResponse> HandleRequestAndEchoCookies(
const std::string& relative_url,
const net::test_server::HttpRequest& request) {
std::unique_ptr<net::test_server::BasicHttpResponse> response;
if (request.relative_url == relative_url) {
response = std::make_unique<net::test_server::BasicHttpResponse>();
response->AddCustomHeader("Content-Disposition", "attachment");
response->AddCustomHeader("Vary", "");
response->AddCustomHeader("Cache-Control", "no-cache");
response->set_content_type("text/plain");
response->set_content(request.headers.at("cookie"));
}
return std::move(response);
}
// Creates a request handler for an EmbeddedTestServer that echos the value
// of the cookie header back as a body, and sends a Content-Disposition header.
net::EmbeddedTestServer::HandleRequestCallback CreateEchoCookieHandler(
const std::string& relative_url) {
return base::BindRepeating(&HandleRequestAndEchoCookies, relative_url);
}
// A request handler that takes the content of the request and sends it back on
// the response.
std::unique_ptr<net::test_server::HttpResponse> HandleUploadRequest(
const net::test_server::HttpRequest& request) {
std::unique_ptr<net::test_server::BasicHttpResponse> response(
(new net::test_server::BasicHttpResponse()));
response->set_content(request.content);
return std::move(response);
}
// Helper class to "flatten" handling of
// TestDownloadHttpResponse::OnPauseHandler.
class TestRequestPauseHandler {
public:
// Construct an OnPauseHandler that can be set as the on_pause_handler for
// TestDownloadHttpResponse::Parameters.
TestDownloadHttpResponse::OnPauseHandler GetOnPauseHandler() {
EXPECT_FALSE(used_) << "GetOnPauseHandler() should only be called once for "
"an instance of TestRequestPauseHandler.";
used_ = true;
return base::BindRepeating(&TestRequestPauseHandler::OnPauseHandler,
base::Unretained(this));
}
// Wait until the OnPauseHandler returned in a prior call to
// GetOnPauseHandler() is invoked.
void WaitForCallback() {
if (resume_callback_.is_null())
run_loop_.Run();
}
// Resume the server response.
void Resume() {
ASSERT_FALSE(resume_callback_.is_null());
std::move(resume_callback_).Run();
}
private:
void OnPauseHandler(base::OnceClosure resume_callback) {
resume_callback_ = std::move(resume_callback);
if (run_loop_.running())
run_loop_.Quit();
}
bool used_ = false;
base::RunLoop run_loop_;
base::OnceClosure resume_callback_;
};
class DownloadContentTest : public ContentBrowserTest {
public:
DownloadContentTest() {
feature_list_.InitWithFeatures(
{},
{
download::features::kAllowDownloadResumptionWithoutStrongValidators,
// Link Preview hides alt+click. Disables it not to do so.
blink::features::kLinkPreview,
});
}
protected:
void SetUpOnMainThread() override {
ASSERT_TRUE(downloads_directory_.CreateUniqueTempDir());
test_delegate_ = std::make_unique<TestShellDownloadManagerDelegate>();
test_delegate_->SetDownloadBehaviorForTesting(
downloads_directory_.GetPath());
DownloadManager* manager = DownloadManagerForShell(shell());
manager->GetDelegate()->Shutdown();
manager->SetDelegate(test_delegate_.get());
test_delegate_->SetDownloadManager(manager);
base::FilePath test_data_dir;
ASSERT_TRUE(base::PathService::Get(content::DIR_TEST_DATA, &test_data_dir));
embedded_test_server()->ServeFilesFromDirectory(test_data_dir);
embedded_test_server()->RegisterRequestHandler(base::BindRepeating(
&SlowDownloadHttpResponse::HandleSlowDownloadRequest));
test_response_handler_.RegisterToTestServer(embedded_test_server());
ASSERT_TRUE(embedded_test_server()->Start());
const std::string real_host =
embedded_test_server()->host_port_pair().host();
host_resolver()->AddRule(kOriginOne, real_host);
host_resolver()->AddRule(kOriginTwo, real_host);
host_resolver()->AddRule(kOrigin, real_host);
host_resolver()->AddRule(kOriginSubdomain, real_host);
host_resolver()->AddRule(kOtherOrigin, real_host);
host_resolver()->AddRule(kBlogspotSite1, real_host);
host_resolver()->AddRule(kBlogspotSite2, real_host);
host_resolver()->AddRule(SlowDownloadHttpResponse::kSlowResponseHostName,
real_host);
host_resolver()->AddRule(TestDownloadHttpResponse::kTestDownloadHostName,
real_host);
host_resolver()->AddRule("a.test", "127.0.0.1");
host_resolver()->AddRule("b.test", "127.0.0.1");
}
void SetUpCommandLine(base::CommandLine* command_line) override {
IsolateAllSitesForTesting(command_line);
// Some tests are flaky due to slower loading interacting with deferred
// commits so allow early input.
command_line->AppendSwitch(blink::switches::kAllowPreCommitInput);
}
TestShellDownloadManagerDelegate* GetDownloadManagerDelegate() {
return test_delegate_.get();
}
const base::FilePath& GetDownloadDirectory() const {
return downloads_directory_.GetPath();
}
// Create a DownloadTestObserverTerminal that will wait for the
// specified number of downloads to finish.
DownloadTestObserver* CreateWaiter(
Shell* shell, int num_downloads) {
DownloadManager* download_manager = DownloadManagerForShell(shell);
return new DownloadTestObserverTerminal(download_manager, num_downloads,
DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL);
}
// Create a DownloadTestObserverInProgress that will wait for the
// specified number of downloads to start.
DownloadTestObserver* CreateInProgressWaiter(Shell* shell,
int num_downloads) {
DownloadManager* download_manager = DownloadManagerForShell(shell);
return new DownloadTestObserverInProgress(download_manager, num_downloads);
}
void WaitForInterrupt(download::DownloadItem* download) {
DownloadUpdatedObserver(
download, base::BindRepeating(&IsDownloadInState,
download::DownloadItem::INTERRUPTED))
.WaitForEvent();
}
void WaitForInProgress(download::DownloadItem* download) {
DownloadUpdatedObserver(
download, base::BindRepeating(&IsDownloadInState,
download::DownloadItem::IN_PROGRESS))
.WaitForEvent();
}
void WaitForCompletion(download::DownloadItem* download) {
DownloadUpdatedObserver(
download, base::BindRepeating(&IsDownloadInState,
download::DownloadItem::COMPLETE))
.WaitForEvent();
}
void WaitForCancel(download::DownloadItem* download) {
DownloadUpdatedObserver(
download, base::BindRepeating(&IsDownloadInState,
download::DownloadItem::CANCELLED))
.WaitForEvent();
}
// Note: Cannot be used with other alternative DownloadFileFactorys
void SetupEnsureNoPendingDownloads() {
DownloadManagerForShell(shell())->SetDownloadFileFactoryForTesting(
std::unique_ptr<download::DownloadFileFactory>(
new CountingDownloadFileFactory()));
}
bool EnsureNoPendingDownloads() {
return CountingDownloadFile::GetNumberActiveFilesFromFileThread() == 0;
}
void SetupErrorInjectionDownloads() {
auto factory = std::make_unique<ErrorInjectionDownloadFileFactory>();
inject_error_callback_ = base::BindRepeating(
&ErrorInjectionDownloadFileFactory::InjectError, factory->GetWeakPtr());
DownloadManagerForShell(shell())->SetDownloadFileFactoryForTesting(
std::move(factory));
}
// Navigate to a URL and wait for a download, expecting that the URL will not
// result in a new committed navigation. This is typically the case for most
// downloads.
void NavigateToURLAndWaitForDownload(
Shell* shell,
const GURL& url,
download::DownloadItem::DownloadState expected_terminal_state) {
std::unique_ptr<DownloadTestObserver> observer(CreateWaiter(shell, 1));
EXPECT_TRUE(NavigateToURLAndExpectNoCommit(shell, url));
observer->WaitForFinished();
EXPECT_EQ(1u, observer->NumDownloadsSeenInState(expected_terminal_state));
}
// Navigate to a URL, expecting it to commit and donn't canceled by download.
// This is useful when the URL actually commits and donn't start any download.
void NavigateToCommittedURLAndExpectNoDownload(Shell* shell,
const GURL& url) {
EXPECT_TRUE(NavigateToURL(shell, url));
}
// Navigate to a URL, expecting it to commit, and wait for a download. This
// is useful when the URL actually commits and then starts a download via
// script.
void NavigateToCommittedURLAndWaitForDownload(
Shell* shell,
const GURL& url,
download::DownloadItem::DownloadState expected_terminal_state) {
std::unique_ptr<DownloadTestObserver> observer(CreateWaiter(shell, 1));
EXPECT_TRUE(NavigateToURL(shell, url));
observer->WaitForFinished();
EXPECT_EQ(1u, observer->NumDownloadsSeenInState(expected_terminal_state));
}
// Checks that |path| is has |file_size| bytes, and matches the |value|
// string.
bool VerifyFile(const base::FilePath& path,
const std::string& value,
const int64_t file_size) {
std::string file_contents;
{
base::ScopedAllowBlockingForTesting allow_blocking;
bool read = base::ReadFileToString(path, &file_contents);
EXPECT_TRUE(read) << "Failed reading file: " << path.value() << std::endl;
if (!read)
return false; // Couldn't read the file.
}
// Note: we don't handle really large files (more than size_t can hold)
// so we will fail in that case.
size_t expected_size = static_cast<size_t>(file_size);
// Check the size.
EXPECT_EQ(expected_size, file_contents.size());
if (expected_size != file_contents.size())
return false;
// Check the contents.
EXPECT_EQ(value, file_contents);
if (memcmp(file_contents.c_str(), value.c_str(), expected_size) != 0)
return false;
return true;
}
// Start a download and return the item.
download::DownloadItem* StartDownloadAndReturnItem(Shell* shell, GURL url) {
std::unique_ptr<DownloadCreateObserver> observer(
new DownloadCreateObserver(DownloadManagerForShell(shell)));
shell->LoadURL(url);
return observer->WaitForFinished();
}
TestDownloadResponseHandler* test_response_handler() {
return &test_response_handler_;
}
static bool PathExists(const base::FilePath& path) {
base::ScopedAllowBlockingForTesting allow_blocking;
return base::PathExists(path);
}
static void ReadAndVerifyFileContents(int seed,
int64_t expected_size,
const base::FilePath& path) {
base::ScopedAllowBlockingForTesting allow_blocking;
base::File file(path, base::File::FLAG_OPEN | base::File::FLAG_READ);
ASSERT_TRUE(file.IsValid());
int64_t file_length = file.GetLength();
ASSERT_EQ(expected_size, file_length);
const int64_t kBufferSize = 64 * 1024;
std::string pattern;
std::vector<char> data;
pattern.resize(kBufferSize);
data.resize(kBufferSize);
for (int64_t offset = 0; offset < file_length;) {
int bytes_read =
UNSAFE_TODO(file.Read(offset, &data.front(), kBufferSize));
ASSERT_LT(0, bytes_read);
ASSERT_GE(kBufferSize, bytes_read);
pattern =
TestDownloadHttpResponse::GetPatternBytes(seed, offset, bytes_read);
ASSERT_EQ(0, memcmp(pattern.data(), &data.front(), bytes_read))
<< "Comparing block at offset " << offset << " and length "
<< bytes_read;
offset += bytes_read;
}
}
TestDownloadHttpResponse::InjectErrorCallback inject_error_callback() {
return inject_error_callback_;
}
void RegisterServiceWorker(Shell* shell, const std::string& worker_url) {
EXPECT_TRUE(NavigateToURL(shell, embedded_test_server()->GetURL(
"/register_service_worker.html")));
EXPECT_EQ("DONE", EvalJs(shell, "register('" + worker_url + "')"));
}
void ClearAutoResumptionCount(download::DownloadItem* download) {
static_cast<download::DownloadItemImpl*>(download)
->SetAutoResumeCountForTesting(0);
}
private:
// Location of the downloads directory for these tests
base::ScopedTempDir downloads_directory_;
std::unique_ptr<TestShellDownloadManagerDelegate> test_delegate_;
TestDownloadResponseHandler test_response_handler_;
TestDownloadHttpResponse::InjectErrorCallback inject_error_callback_;
base::test::ScopedFeatureList feature_list_;
};
constexpr int kValidationLength = 1024;
class DownloadContentTestWithoutStrongValidators : public DownloadContentTest {
public:
DownloadContentTestWithoutStrongValidators() {
std::map<std::string, std::string> params = {
{download::kDownloadContentValidationLengthFinchKey,
base::NumberToString(kValidationLength)}};
scoped_feature_list_.InitAndEnableFeatureWithParameters(
download::features::kAllowDownloadResumptionWithoutStrongValidators,
params);
}
// Starts a download without strong validators, interrupts it, and resumes it.
// If |fail_content_validation| is true, download content will change during
// resumption.
void InterruptAndResumeDownloadWithoutStrongValidators(
bool fail_content_validation) {
SetupErrorInjectionDownloads();
GURL url = TestDownloadHttpResponse::GetNextURLForDownload();
GURL server_url = embedded_test_server()->GetURL(url.host(), url.path());
TestDownloadHttpResponse::Parameters parameters =
TestDownloadHttpResponse::Parameters::WithSingleInterruption(
inject_error_callback());
parameters.etag.clear();
parameters.last_modified.clear();
TestDownloadHttpResponse::StartServing(parameters, server_url);
int64_t interruption_offset = parameters.injected_errors.front();
download::DownloadItem* download =
StartDownloadAndReturnItem(shell(), server_url);
WaitForInterrupt(download);
ASSERT_EQ(interruption_offset, download->GetReceivedBytes());
ASSERT_EQ(parameters.size, download->GetTotalBytes());
parameters.ClearInjectedErrors();
if (fail_content_validation)
++parameters.pattern_generator_seed;
TestDownloadHttpResponse::StartServing(parameters, server_url);
// Download should complete regardless whether content changes or not.
download->Resume(false);
WaitForCompletion(download);
ASSERT_EQ(parameters.size, download->GetReceivedBytes());
ASSERT_EQ(parameters.size, download->GetTotalBytes());
ASSERT_NO_FATAL_FAILURE(ReadAndVerifyFileContents(
parameters.pattern_generator_seed, parameters.size,
download->GetTargetFilePath()));
const TestDownloadResponseHandler::CompletedRequests& requests =
test_response_handler()->completed_requests();
ASSERT_EQ(fail_content_validation ? 3u : 2u, requests.size());
// The first request only transferrs bytes up until the interruption point.
EXPECT_EQ(interruption_offset, requests[0]->transferred_byte_count);
// The second request is a range request.
std::string value;
ASSERT_FALSE(base::Contains(requests[1]->http_request.headers,
net::HttpRequestHeaders::kIfRange));
ASSERT_TRUE(base::Contains(requests[1]->http_request.headers,
net::HttpRequestHeaders::kRange));
EXPECT_EQ(
base::StringPrintf("bytes=%" PRId64 "-",
interruption_offset - kValidationLength),
requests[1]->http_request.headers.at(net::HttpRequestHeaders::kRange));
if (fail_content_validation) {
// The third request is a restart request.
ASSERT_FALSE(base::Contains(requests[2]->http_request.headers,
net::HttpRequestHeaders::kRange));
EXPECT_EQ(parameters.size, requests[2]->transferred_byte_count);
}
}
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
// Test fixture for parallel downloading.
class ParallelDownloadTest : public DownloadContentTest {
public:
ParallelDownloadTest(const ParallelDownloadTest&) = delete;
ParallelDownloadTest& operator=(const ParallelDownloadTest&) = delete;
protected:
ParallelDownloadTest() {
std::map<std::string, std::string> params = {
{download::kMinSliceSizeFinchKey, "1"},
{download::kParallelRequestCountFinchKey,
base::NumberToString(kTestRequestCount)},
{download::kParallelRequestDelayFinchKey, "0"},
{download::kParallelRequestRemainingTimeFinchKey, "0"}};
scoped_feature_list_.InitAndEnableFeatureWithParameters(
download::features::kParallelDownloading, params);
}
~ParallelDownloadTest() override {}
// Creates the intermediate file that has already contained randomly generated
// download data pieces.
download::DownloadItem* CreateDownloadAndIntermediateFile(
const base::FilePath& path,
const std::vector<GURL>& url_chain,
const download::DownloadItem::ReceivedSlices& slices,
const TestDownloadHttpResponse::Parameters& parameters) {
std::string output;
int64_t total_bytes = 0u;
const int64_t kBufferSize = 64 * 1024;
{
base::ScopedAllowBlockingForTesting allow_io_for_test_setup;
base::File file(path, base::File::FLAG_CREATE | base::File::FLAG_WRITE);
for (const auto& slice : slices) {
EXPECT_TRUE(file.IsValid());
int64_t length = slice.offset + slice.received_bytes;
for (int64_t offset = slice.offset; offset < length;) {
int64_t bytes_to_write =
length - offset > kBufferSize ? kBufferSize : length - offset;
output = TestDownloadHttpResponse::GetPatternBytes(
parameters.pattern_generator_seed, offset, bytes_to_write);
EXPECT_EQ(
bytes_to_write,
UNSAFE_TODO(file.Write(offset, output.data(), bytes_to_write)));
total_bytes += bytes_to_write;
offset += bytes_to_write;
}
}
file.Close();
}
// Parallel download should create more than 1 slices in most cases. If
// there is only one slice, consider this is a regular download and remove
// all slices.
download::DownloadItem::ReceivedSlices parallel_slices;
if (slices.size() != 1 || slices[0].offset != 0)
parallel_slices = slices;
download::DownloadItem* download =
DownloadManagerForShell(shell())->CreateDownloadItem(
"F7FB1F59-7DE1-4845-AFDB-8A688F70F583", 1, path, base::FilePath(),
url_chain, GURL(),
StoragePartitionConfig::CreateDefault(
shell()->web_contents()->GetBrowserContext()),
GURL(), GURL(), url::Origin(), "application/octet-stream",
"application/octet-stream", base::Time::Now(), base::Time(),
parameters.etag, parameters.last_modified, total_bytes,
parameters.size, std::string(), download::DownloadItem::INTERRUPTED,
download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
download::DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED, false,
base::Time(), false, parallel_slices);
ClearAutoResumptionCount(download);
return download;
}
// Verifies parallel download resumption in different scenarios, where the
// intermediate file is generated based on |slices| and has a full length of
// |total_length|.
void RunResumptionTest(
const download::DownloadItem::ReceivedSlices& received_slices,
int64_t total_length,
size_t expected_request_count,
bool support_partial_response) {
TestDownloadHttpResponse::Parameters parameters;
parameters.etag = "ABC";
parameters.size = total_length;
parameters.last_modified = std::string();
parameters.support_partial_response = support_partial_response;
// Needed to specify HTTP connection type to create parallel download.
parameters.connection_type = net::HttpConnectionInfo::kHTTP1_1;
RunResumptionTestWithParameters(received_slices, expected_request_count,
parameters);
}
// Similar to the above method, but with given http response parameters.
void RunResumptionTestWithParameters(
const download::DownloadItem::ReceivedSlices& received_slices,
size_t expected_request_count,
const TestDownloadHttpResponse::Parameters& parameters) {
EXPECT_TRUE(
base::FeatureList::IsEnabled(download::features::kParallelDownloading));
GURL url = TestDownloadHttpResponse::GetNextURLForDownload();
GURL server_url = embedded_test_server()->GetURL(url.host(), url.path());
TestDownloadHttpResponse::StartServing(parameters, server_url);
base::FilePath intermediate_file_path =
GetDownloadDirectory().AppendASCII("intermediate");
std::vector<GURL> url_chain;
url_chain.push_back(server_url);
// Create the intermediate file reflecting the received slices.
download::DownloadItem* download = CreateDownloadAndIntermediateFile(
intermediate_file_path, url_chain, received_slices, parameters);
// Resume the parallel download with sparse file and received slices data.
download->Resume(false);
WaitForCompletion(download);
// TODO(qinmin): count the failed partial responses in DownloadJob when
// support_partial_response is false. EmbeddedTestServer doesn't know
// whether completing or canceling the response will come first.
if (parameters.support_partial_response) {
test_response_handler()->WaitUntilCompletion(expected_request_count);
// Verify number of requests sent to the server.
const TestDownloadResponseHandler::CompletedRequests& completed_requests =
test_response_handler()->completed_requests();
EXPECT_EQ(expected_request_count, completed_requests.size());
}
// Verify download content on disk.
ReadAndVerifyFileContents(parameters.pattern_generator_seed,
parameters.size, download->GetTargetFilePath());
}
// Kicks off the verifies parallel download completion
void RunCompletionTest(TestDownloadHttpResponse::Parameters& parameters) {
ErrorStreamCountingObserver observer;
EXPECT_TRUE(
base::FeatureList::IsEnabled(download::features::kParallelDownloading));
GURL url = TestDownloadHttpResponse::GetNextURLForDownload();
GURL server_url = embedded_test_server()->GetURL(url.host(), url.path());
// Only parallel download needs to specify the connection type to http 1.1,
// other tests will automatically fall back to non-parallel download even if
// the ParallelDownloading feature is enabled based on
// fieldtrial_testing_config.json.
parameters.connection_type = net::HttpConnectionInfo::kHTTP1_1;
TestRequestPauseHandler request_pause_handler;
parameters.on_pause_handler = request_pause_handler.GetOnPauseHandler();
// Send some data for the first request and pause it so download won't
// complete before other parallel requests are created.
parameters.pause_offset = kPauseOffset;
TestDownloadHttpResponse::StartServing(parameters, server_url);
download::DownloadItem* download =
StartDownloadAndReturnItem(shell(), server_url);
if (parameters.support_partial_response)
test_response_handler()->WaitUntilCompletion(2u);
else
observer.WaitForFinished(download, 2);
// Now resume the first request.
request_pause_handler.Resume();
WaitForCompletion(download);
if (parameters.support_partial_response) {
test_response_handler()->WaitUntilCompletion(3u);
const TestDownloadResponseHandler::CompletedRequests& completed_requests =
test_response_handler()->completed_requests();
EXPECT_EQ(3u, completed_requests.size());
}
ReadAndVerifyFileContents(parameters.pattern_generator_seed,
parameters.size, download->GetTargetFilePath());
}
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
class DownloadPrerenderTest : public DownloadContentTest {
public:
DownloadPrerenderTest()
: prerender_helper_(
base::BindRepeating(&DownloadPrerenderTest::GetWebContents,
base::Unretained(this))) {}
~DownloadPrerenderTest() override = default;
void SetUp() override {
prerender_helper_.RegisterServerRequestMonitor(embedded_test_server());
DownloadContentTest::SetUp();
}
void SetUpOnMainThread() override {
DownloadContentTest::SetUpOnMainThread();
ASSERT_TRUE(embedded_test_server()->Started());
}
test::PrerenderTestHelper* prerender_helper() { return &prerender_helper_; }
private:
WebContents* GetWebContents() { return shell()->web_contents(); }
test::PrerenderTestHelper prerender_helper_;
};
class DownloadFencedFrameTest : public DownloadContentTest {
public:
DownloadFencedFrameTest() {
fenced_frame_helper_ = std::make_unique<test::FencedFrameTestHelper>();
// Fenced frame requires a secure context to disable untrusted network.
embedded_https_test_server().SetSSLConfig(
net::EmbeddedTestServer::CERT_TEST_NAMES);
}
~DownloadFencedFrameTest() override = default;
void SetUpOnMainThread() override {
DownloadContentTest::SetUpOnMainThread();
ASSERT_TRUE(embedded_test_server()->Started());
}
protected:
RenderFrameHost* CreateFencedFrame(RenderFrameHost* fenced_frame_parent,
const GURL& url) {
if (fenced_frame_helper_)
return fenced_frame_helper_->CreateFencedFrame(fenced_frame_parent, url);
// FencedFrameTestHelper only supports the MPArch version of fenced frames.
// So need to maually create a fenced frame for the ShadowDOM version.
constexpr char kAddFencedFrameScript[] = R"({
const fenced_frame = document.createElement('fencedframe');
document.body.appendChild(fenced_frame);
})";
EXPECT_TRUE(ExecJs(fenced_frame_parent, kAddFencedFrameScript));
// Navigate the fenced frame from inside itself, just like the
// `FencedFrameTestHelper` does for MPArch.
RenderFrameHostImpl* rfh =
static_cast<RenderFrameHostImpl*>(ChildFrameAt(fenced_frame_parent, 0));
FrameTreeNode* target_node = rfh->frame_tree_node();
constexpr char kNavigateInFencedFrameScript[] = R"({
location.href = $1;
})";
TestNavigationManager navigation(shell()->web_contents(), url);
EXPECT_EQ(url.spec(),
EvalJs(rfh, JsReplace(kNavigateInFencedFrameScript, url)));
EXPECT_TRUE(navigation.WaitForNavigationFinished());
EXPECT_FALSE(target_node->current_frame_host()->IsErrorDocument());
return target_node->current_frame_host();
}
test::FencedFrameTestHelper* fenced_frame_helper() {
return fenced_frame_helper_.get();
}
private:
std::unique_ptr<test::FencedFrameTestHelper> fenced_frame_helper_;
base::test::ScopedFeatureList feature_list_;
};
} // namespace
// Flaky. See https://crbug.com/754679.
IN_PROC_BROWSER_TEST_F(DownloadContentTest, DownloadCancelled) {
SetupEnsureNoPendingDownloads();
// Create a download, wait until it's started, and confirm
// we're in the expected state.
download::DownloadItem* download = StartDownloadAndReturnItem(
shell(), embedded_test_server()->GetURL(
SlowDownloadHttpResponse::kSlowResponseHostName,
SlowDownloadHttpResponse::kUnknownSizeUrl));
ASSERT_EQ(download::DownloadItem::IN_PROGRESS, download->GetState());
// Cancel the download and wait for download system quiesce.
download->Cancel(true);
DownloadTestFlushObserver flush_observer(DownloadManagerForShell(shell()));
flush_observer.WaitForFlush();
// Get the important info from other threads and check it.
EXPECT_TRUE(EnsureNoPendingDownloads());
}
// Check that downloading multiple (in this case, 2) files does not result in
// corrupted files.
IN_PROC_BROWSER_TEST_F(DownloadContentTest, MultiDownload) {
SetupEnsureNoPendingDownloads();
// Create a download, wait until it's started, and confirm
// we're in the expected state.
download::DownloadItem* download1 = StartDownloadAndReturnItem(
shell(), embedded_test_server()->GetURL(
SlowDownloadHttpResponse::kSlowResponseHostName,
SlowDownloadHttpResponse::kUnknownSizeUrl));
ASSERT_EQ(download::DownloadItem::IN_PROGRESS, download1->GetState());
// Start the second download and wait until it's done.
download::DownloadItem* download2 = StartDownloadAndReturnItem(
shell(), embedded_test_server()->GetURL("/download/download-test.lib"));
WaitForCompletion(download2);
ASSERT_EQ(download::DownloadItem::IN_PROGRESS, download1->GetState());
ASSERT_EQ(download::DownloadItem::COMPLETE, download2->GetState());
// Allow the first request to finish.
std::unique_ptr<DownloadTestObserver> observer2(CreateWaiter(shell(), 1));
EXPECT_TRUE(NavigateToURL(
shell(), embedded_test_server()->GetURL(
SlowDownloadHttpResponse::kSlowResponseHostName,
SlowDownloadHttpResponse::kFinishSlowResponseUrl)));
observer2->WaitForFinished(); // Wait for the third request.
EXPECT_EQ(
1u, observer2->NumDownloadsSeenInState(download::DownloadItem::COMPLETE));
// Get the important info from other threads and check it.
EXPECT_TRUE(EnsureNoPendingDownloads());
// The |DownloadItem|s should now be done and have the final file names.
// Verify that the files have the expected data and size.
// |file1| should be full of '*'s, and |file2| should be the same as the
// source file.
base::FilePath file1(download1->GetTargetFilePath());
size_t file_size1 = SlowDownloadHttpResponse::kFirstResponsePartSize +
SlowDownloadHttpResponse::kSecondResponsePartSize;
std::string expected_contents(file_size1, '*');
ASSERT_TRUE(VerifyFile(file1, expected_contents, file_size1));
base::FilePath file2(download2->GetTargetFilePath());
ASSERT_TRUE(base::ContentsEqual(
file2, GetTestFilePath("download", "download-test.lib")));
}
// Tests that metrics are recorded when a page opens a named window, navigates
// it to a URL, then navigates it again to a download. The navigated URL is same
// origin as the opener (example.com). The actual download URL doesn't matter.
IN_PROC_BROWSER_TEST_F(DownloadContentTest,
InitiatedByWindowOpener_SameOrigin) {
EXPECT_TRUE(
NavigateToURL(shell()->web_contents(),
embedded_test_server()->GetURL(kOrigin, "/empty.html")));
// From the initial tab, open a window named 'foo' and navigate it to a same
// origin page.
const GURL url = embedded_test_server()->GetURL(kOrigin, "/title1.html");
const std::string script = "window.open('" + url.spec() + "', 'foo')";
ShellAddedObserver new_shell_observer;
EXPECT_TRUE(ExecJs(shell()->web_contents(), script));
Shell* new_shell = new_shell_observer.GetShell();
ASSERT_TRUE(new_shell);
EXPECT_TRUE(WaitForLoadStop(new_shell->web_contents()));
// From the initial tab, navigate the 'foo' window to a download and wait for
// completion.
base::HistogramTester histogram_tester;
std::unique_ptr<DownloadTestObserver> observer(CreateWaiter(new_shell, 1));
const GURL download_url = embedded_test_server()->GetURL(
kOtherOrigin, "/download/download-test.lib");
const std::string download_script =
"window.open('" + download_url.spec() + "', 'foo')";
EXPECT_TRUE(ExecJs(shell()->web_contents(), download_script));
observer->WaitForFinished();
histogram_tester.ExpectTotalCount("Download.InitiatedByWindowOpener", 1);
histogram_tester.ExpectUniqueSample(
"Download.InitiatedByWindowOpener",
static_cast<int>(InitiatedByWindowOpenerType::kSameOrigin), 1);
}
// Same as InitiatedByWindowOpener_SameOrigin, but the navigated URL is same
// site as the opener (example.com vs one.example.com).
IN_PROC_BROWSER_TEST_F(DownloadContentTest, InitiatedByWindowOpener_SameSite) {
EXPECT_TRUE(
NavigateToURL(shell()->web_contents(),
embedded_test_server()->GetURL(kOrigin, "/empty.html")));
// From the initial tab, open a window named 'foo' and navigate it to a
// subdomain. This is cross-origin but same site.
const GURL url =
embedded_test_server()->GetURL(kOriginSubdomain, "/title1.html");
const std::string script = "window.open('" + url.spec() + "', 'foo')";
ShellAddedObserver new_shell_observer;
EXPECT_TRUE(ExecJs(shell()->web_contents(), script));
Shell* new_shell = new_shell_observer.GetShell();
ASSERT_TRUE(new_shell);
EXPECT_TRUE(WaitForLoadStop(new_shell->web_contents()));
// From the initial tab, navigate the 'foo' window to a download and wait for
// completion.
base::HistogramTester histogram_tester;
std::unique_ptr<DownloadTestObserver> observer(CreateWaiter(new_shell, 1));
const GURL download_url = embedded_test_server()->GetURL(
kOtherOrigin, "/download/download-test.lib");
const std::string download_script =
"window.open('" + download_url.spec() + "', 'foo')";
EXPECT_TRUE(ExecJs(shell()->web_contents(), download_script));
observer->WaitForFinished();
histogram_tester.ExpectTotalCount("Download.InitiatedByWindowOpener", 1);
histogram_tester.ExpectUniqueSample(
"Download.InitiatedByWindowOpener",
static_cast<int>(InitiatedByWindowOpenerType::kSameSite), 1);
}
// The opener and the openee are under the same domain name blogspot.com, but
// blogspot.com is a private registry according to the Public Suffix List, so
// its subdomains are not considered same host.
IN_PROC_BROWSER_TEST_F(DownloadContentTest,
InitiatedByWindowOpener_PrivateRegistry) {
EXPECT_TRUE(NavigateToURL(
shell()->web_contents(),
embedded_test_server()->GetURL(kBlogspotSite1, "/empty.html")));
// From the initial tab, open a window named 'foo' and navigate it to another
// subdomain of blogspot.com.
const GURL url =
embedded_test_server()->GetURL(kBlogspotSite2, "/title1.html");
const std::string script = "window.open('" + url.spec() + "', 'foo')";
ShellAddedObserver new_shell_observer;
EXPECT_TRUE(ExecJs(shell()->web_contents(), script));
Shell* new_shell = new_shell_observer.GetShell();
ASSERT_TRUE(new_shell);
EXPECT_TRUE(WaitForLoadStop(new_shell->web_contents()));
// From the initial tab, navigate the 'foo' window to a download and wait for
// completion.
base::HistogramTester histogram_tester;
std::unique_ptr<DownloadTestObserver> observer(CreateWaiter(new_shell, 1));
const GURL download_url = embedded_test_server()->GetURL(
kOtherOrigin, "/download/download-test.lib");
const std::string download_script =
"window.open('" + download_url.spec() + "', 'foo')";
EXPECT_TRUE(ExecJs(shell()->web_contents(), download_script));
observer->WaitForFinished();
histogram_tester.ExpectTotalCount("Download.InitiatedByWindowOpener", 1);
histogram_tester.ExpectUniqueSample(
"Download.InitiatedByWindowOpener",
static_cast<int>(InitiatedByWindowOpenerType::kCrossOrigin), 1);
}
// Same as InitiatedByWindowOpener_SameOrigin, but the navigated URL is cross
// origin to the opener (example.com vs example.site).
IN_PROC_BROWSER_TEST_F(DownloadContentTest,
InitiatedByWindowOpener_CrossOrigin) {
EXPECT_TRUE(NavigateToURL(shell()->web_contents(),
embedded_test_server()->GetURL("/empty.html")));
// From the initial tab, open a window named 'foo' and navigate it to a cross
// origin page.
const GURL url = embedded_test_server()->GetURL(kOtherOrigin, "/title1.html");
ShellAddedObserver new_shell_observer;
EXPECT_TRUE(ExecJs(shell()->web_contents(),
"window.open('" + url.spec() + "', 'foo')"));
Shell* new_shell = new_shell_observer.GetShell();
ASSERT_TRUE(new_shell);
EXPECT_TRUE(WaitForLoadStop(new_shell->web_contents()));
// From the initial tab, navigate the 'foo' window to a download and wait for
// completion.
base::HistogramTester histogram_tester;
std::unique_ptr<DownloadTestObserver> observer(CreateWaiter(new_shell, 1));
const GURL download_url = embedded_test_server()->GetURL(
kOtherOrigin, "/download/download-test.lib");
const std::string download_script =
"window.open('" + download_url.spec() + "', 'foo')";
EXPECT_TRUE(ExecJs(shell()->web_contents(), download_script));
observer->WaitForFinished();
histogram_tester.ExpectTotalCount("Download.InitiatedByWindowOpener", 1);
histogram_tester.ExpectUniqueSample(
"Download.InitiatedByWindowOpener",
static_cast<int>(InitiatedByWindowOpenerType::kCrossOrigin), 1);
}
// Same as InitiatedByWindowOpener_CrossOrigin, but the newly opened tab is
// about:blank.
IN_PROC_BROWSER_TEST_F(DownloadContentTest,
InitiatedByWindowOpener_CrossOrigin_NonHttpOrHttps) {
EXPECT_TRUE(NavigateToURL(shell()->web_contents(),
embedded_test_server()->GetURL("/empty.html")));
// From the initial tab, open a window named 'foo' and navigate it to
// about:blank.
ShellAddedObserver new_shell_observer;
EXPECT_TRUE(
ExecJs(shell()->web_contents(), "window.open('about:blank', 'foo')"));
Shell* new_shell = new_shell_observer.GetShell();
ASSERT_TRUE(new_shell);
EXPECT_TRUE(WaitForLoadStop(new_shell->web_contents()));
// From the initial tab, navigate the 'foo' window to a download and wait for
// completion.
base::HistogramTester histogram_tester;
std::unique_ptr<DownloadTestObserver> observer(CreateWaiter(new_shell, 1));
const GURL download_url = embedded_test_server()->GetURL(
kOtherOrigin, "/download/download-test.lib");
const std::string download_script =
"window.open('" + download_url.spec() + "', 'foo')";
EXPECT_TRUE(ExecJs(shell()->web_contents(), download_script));
observer->WaitForFinished();
histogram_tester.ExpectTotalCount("Download.InitiatedByWindowOpener", 1);
histogram_tester.ExpectUniqueSample(
"Download.InitiatedByWindowOpener",
static_cast<int>(InitiatedByWindowOpenerType::kNonHTTPOrHTTPS), 1);
}
#if BUILDFLAG(ENABLE_PLUGINS)
// Content served with a MIME type of application/octet-stream should be
// downloaded even when a plugin can be found that handles the file type.
// See https://crbug.com/104331 for the details.
IN_PROC_BROWSER_TEST_F(DownloadContentTest, DownloadOctetStream) {
const char16_t kTestPluginName[] = u"TestPlugin";
const char kTestMimeType[] = "application/x-test-mime-type";
const char kTestFileType[] = "abc";
WebPluginInfo plugin_info;
plugin_info.name = kTestPluginName;
plugin_info.mime_types.push_back(
WebPluginMimeType(kTestMimeType, kTestFileType, ""));
plugin_info.type = WebPluginInfo::PLUGIN_TYPE_PEPPER_IN_PROCESS;
PluginServiceImpl::GetInstance()->RegisterInternalPlugin(plugin_info, false);
// The following is served with a Content-Type of application/octet-stream.
NavigateToURLAndWaitForDownload(
shell(), embedded_test_server()->GetURL("/download/octet-stream.abc"),
download::DownloadItem::COMPLETE);
}
// Content served with a MIME type of application/octet-stream should be
// downloaded even when a plugin can be found that handles the file type.
// See https://crbug.com/104331 for the details.
// In this test, the url is in scope of a service worker but the response is
// served from network.
// This is regression test for https://crbug.com/896696.
IN_PROC_BROWSER_TEST_F(DownloadContentTest,
DownloadOctetStream_PassThroughServiceWorker) {
const char16_t kTestPluginName[] = u"TestPlugin";
const char kTestMimeType[] = "application/x-test-mime-type";
const char kTestFileType[] = "abc";
RegisterServiceWorker(shell(), "/fetch_event_passthrough.js");
WebPluginInfo plugin_info;
plugin_info.name = kTestPluginName;
plugin_info.mime_types.push_back(
WebPluginMimeType(kTestMimeType, kTestFileType, ""));
plugin_info.type = WebPluginInfo::PLUGIN_TYPE_PEPPER_IN_PROCESS;
PluginServiceImpl::GetInstance()->RegisterInternalPlugin(plugin_info, false);
// The following is served with a Content-Type of application/octet-stream.
NavigateToURLAndWaitForDownload(
shell(), embedded_test_server()->GetURL("/download/octet-stream.abc"),
download::DownloadItem::COMPLETE);
}
// Content served with a MIME type of application/octet-stream should be
// downloaded even when a plugin can be found that handles the file type.
// See https://crbug.com/104331 for the details.
// In this test, the response will be served from a service worker.
// This is regression test for https://crbug.com/896696.
IN_PROC_BROWSER_TEST_F(DownloadContentTest,
DownloadOctetStream_OctetStreamServiceWorker) {
const char16_t kTestPluginName[] = u"TestPlugin";
const char kTestMimeType[] = "application/x-test-mime-type";
const char kTestFileType[] = "abc";
RegisterServiceWorker(shell(), "/fetch_event_octet_stream.js");
WebPluginInfo plugin_info;
plugin_info.name = kTestPluginName;
plugin_info.mime_types.push_back(
WebPluginMimeType(kTestMimeType, kTestFileType, ""));
plugin_info.type = WebPluginInfo::PLUGIN_TYPE_PEPPER_IN_PROCESS;
PluginServiceImpl::GetInstance()->RegisterInternalPlugin(plugin_info, false);
// The following is served with a Content-Type of application/octet-stream.
NavigateToURLAndWaitForDownload(
shell(), embedded_test_server()->GetURL("/download/octet-stream.abc"),
download::DownloadItem::COMPLETE);
}
// Content served with a MIME type of application/octet-stream should be
// downloaded even when a plugin can be found that handles the file type.
// See https://crbug.com/104331 for the details.
// In this test, the url is in scope of a service worker and the response is
// served from the network via service worker.
// This is regression test for https://crbug.com/896696.
IN_PROC_BROWSER_TEST_F(DownloadContentTest,
DownloadOctetStream_RespondWithFetchServiceWorker) {
const char16_t kTestPluginName[] = u"TestPlugin";
const char kTestMimeType[] = "application/x-test-mime-type";
const char kTestFileType[] = "abc";
RegisterServiceWorker(shell(), "/fetch_event_respond_with_fetch.js");
WebPluginInfo plugin_info;
plugin_info.name = kTestPluginName;
plugin_info.mime_types.push_back(
WebPluginMimeType(kTestMimeType, kTestFileType, ""));
plugin_info.type = WebPluginInfo::PLUGIN_TYPE_PEPPER_IN_PROCESS;
PluginServiceImpl::GetInstance()->RegisterInternalPlugin(plugin_info, false);
// The following is served with a Content-Type of application/octet-stream.
NavigateToURLAndWaitForDownload(
shell(), embedded_test_server()->GetURL("/download/octet-stream.abc"),
download::DownloadItem::COMPLETE);
}
#endif
// Try to cancel just before we release the download file, by delaying final
// rename callback.
IN_PROC_BROWSER_TEST_F(DownloadContentTest, CancelAtFinalRename) {
// Setup new factory.
DownloadFileWithDelayFactory* file_factory =
new DownloadFileWithDelayFactory();
DownloadManagerImpl* download_manager(DownloadManagerForShell(shell()));
download_manager->SetDownloadFileFactoryForTesting(
std::unique_ptr<download::DownloadFileFactory>(file_factory));
// Create a download
EXPECT_TRUE(NavigateToURLAndExpectNoCommit(
shell(), embedded_test_server()->GetURL("/download/download-test.lib")));
// Wait until the first (intermediate file) rename and execute the callback.
file_factory->WaitForSomeCallback();
std::vector<base::OnceClosure> callbacks;
file_factory->GetAllRenameCallbacks(&callbacks);
ASSERT_EQ(1u, callbacks.size());
std::move(callbacks[0]).Run();
callbacks.clear();
// Wait until the second (final) rename callback is posted.
file_factory->WaitForSomeCallback();
file_factory->GetAllRenameCallbacks(&callbacks);
ASSERT_EQ(1u, callbacks.size());
// Cancel it.
std::vector<raw_ptr<download::DownloadItem, VectorExperimental>> items;
download_manager->GetAllDownloads(&items);
ASSERT_EQ(1u, items.size());
items[0]->Cancel(true);
RunAllTasksUntilIdle();
// Check state.
EXPECT_EQ(download::DownloadItem::CANCELLED, items[0]->GetState());
// Run final rename callback.
std::move(callbacks[0]).Run();
callbacks.clear();
// Check state.
EXPECT_EQ(download::DownloadItem::CANCELLED, items[0]->GetState());
}
// Try to cancel just after we release the download file, by delaying
// in ShouldOpenDownload.
IN_PROC_BROWSER_TEST_F(DownloadContentTest, CancelAtRelease) {
DownloadManagerImpl* download_manager(DownloadManagerForShell(shell()));
// Mark delegate for delayed open.
GetDownloadManagerDelegate()->SetDelayedOpen(true);
// Setup new factory.
DownloadFileWithDelayFactory* file_factory =
new DownloadFileWithDelayFactory();
download_manager->SetDownloadFileFactoryForTesting(
std::unique_ptr<download::DownloadFileFactory>(file_factory));
// Create a download
EXPECT_TRUE(NavigateToURLAndExpectNoCommit(
shell(), embedded_test_server()->GetURL("/download/download-test.lib")));
// Wait until the first (intermediate file) rename and execute the callback.
file_factory->WaitForSomeCallback();
std::vector<base::OnceClosure> callbacks;
file_factory->GetAllRenameCallbacks(&callbacks);
ASSERT_EQ(1u, callbacks.size());
std::move(callbacks[0]).Run();
callbacks.clear();
// Wait until the second (final) rename callback is posted.
file_factory->WaitForSomeCallback();
file_factory->GetAllRenameCallbacks(&callbacks);
ASSERT_EQ(1u, callbacks.size());
// Call it.
std::move(callbacks[0]).Run();
callbacks.clear();
// Confirm download still IN_PROGRESS (internal state COMPLETING).
std::vector<raw_ptr<download::DownloadItem, VectorExperimental>> items;
download_manager->GetAllDownloads(&items);
EXPECT_EQ(download::DownloadItem::IN_PROGRESS, items[0]->GetState());
// Cancel the download; confirm cancel fails.
ASSERT_EQ(1u, items.size());
items[0]->Cancel(true);
EXPECT_EQ(download::DownloadItem::IN_PROGRESS, items[0]->GetState());
// Need to complete open test.
std::vector<DownloadOpenDelayedCallback> delayed_callbacks;
GetDownloadManagerDelegate()->GetDelayedCallbacks(
&delayed_callbacks);
ASSERT_EQ(1u, delayed_callbacks.size());
std::move(delayed_callbacks[0]).Run(true);
// *Now* the download should be complete.
EXPECT_EQ(download::DownloadItem::COMPLETE, items[0]->GetState());
}
// Try to shutdown with a download in progress to make sure shutdown path
// works properly.
IN_PROC_BROWSER_TEST_F(DownloadContentTest, ShutdownInProgress) {
// Create a download that won't complete.
download::DownloadItem* download = StartDownloadAndReturnItem(
shell(), embedded_test_server()->GetURL(
SlowDownloadHttpResponse::kSlowResponseHostName,
SlowDownloadHttpResponse::kUnknownSizeUrl));
EXPECT_EQ(download::DownloadItem::IN_PROGRESS, download->GetState());
// Shutdown the download manager and make sure we get the right
// notifications in the right order.
StrictMock<MockDownloadItemObserver> item_observer;
download->AddObserver(&item_observer);
MockDownloadManagerObserver manager_observer(
DownloadManagerForShell(shell()));
// Don't care about ModelChanged() events.
EXPECT_CALL(manager_observer, ModelChanged(_))
.WillRepeatedly(Return());
{
InSequence notifications;
EXPECT_CALL(manager_observer, MockManagerGoingDown(
DownloadManagerForShell(shell())))
.WillOnce(Return());
EXPECT_CALL(item_observer,
OnDownloadUpdated(AllOf(
download, Property(&download::DownloadItem::GetState,
download::DownloadItem::CANCELLED))))
.WillOnce(Return());
EXPECT_CALL(item_observer, OnDownloadDestroyed(download))
.WillOnce(Return());
}
DownloadManagerForShell(shell())->Shutdown();
}
// Try to shutdown just after we release the download file, by delaying
// release.
IN_PROC_BROWSER_TEST_F(DownloadContentTest, ShutdownAtRelease) {
DownloadManagerImpl* download_manager(DownloadManagerForShell(shell()));
// Mark delegate for delayed open.
GetDownloadManagerDelegate()->SetDelayedOpen(true);
// Setup new factory.
DownloadFileWithDelayFactory* file_factory =
new DownloadFileWithDelayFactory();
download_manager->SetDownloadFileFactoryForTesting(
std::unique_ptr<download::DownloadFileFactory>(file_factory));
// Create a download
EXPECT_TRUE(NavigateToURLAndExpectNoCommit(
shell(), embedded_test_server()->GetURL("/download/download-test.lib")));
// Wait until the first (intermediate file) rename and execute the callback.
file_factory->WaitForSomeCallback();
std::vector<base::OnceClosure> callbacks;
file_factory->GetAllRenameCallbacks(&callbacks);
ASSERT_EQ(1u, callbacks.size());
std::move(callbacks[0]).Run();
callbacks.clear();
// Wait until the second (final) rename callback is posted.
file_factory->WaitForSomeCallback();
file_factory->GetAllRenameCallbacks(&callbacks);
ASSERT_EQ(1u, callbacks.size());
// Call it.
std::move(callbacks[0]).Run();
callbacks.clear();
// Confirm download isn't complete yet.
std::vector<raw_ptr<download::DownloadItem, VectorExperimental>> items;
DownloadManagerForShell(shell())->GetAllDownloads(&items);
EXPECT_EQ(download::DownloadItem::IN_PROGRESS, items[0]->GetState());
// Cancel the download; confirm cancel fails anyway.
ASSERT_EQ(1u, items.size());
items[0]->Cancel(true);
EXPECT_EQ(download::DownloadItem::IN_PROGRESS, items[0]->GetState());
RunAllTasksUntilIdle();
EXPECT_EQ(download::DownloadItem::IN_PROGRESS, items[0]->GetState());
MockDownloadItemObserver observer;
items[0]->AddObserver(&observer);
EXPECT_CALL(observer, OnDownloadDestroyed(items[0].get()));
// Shutdown the download manager. Mostly this is confirming a lack of
// crashes.
DownloadManagerForShell(shell())->Shutdown();
}
// Test resumption with a response that contains strong validators.
IN_PROC_BROWSER_TEST_F(DownloadContentTest, ResumeWithStrongValidators) {
SetupErrorInjectionDownloads();
GURL url = TestDownloadHttpResponse::GetNextURLForDownload();
GURL server_url = embedded_test_server()->GetURL(url.host(), url.path());
TestDownloadHttpResponse::Parameters parameters =
TestDownloadHttpResponse::Parameters::WithSingleInterruption(
inject_error_callback());
TestDownloadHttpResponse::StartServing(parameters, server_url);
int64_t interruption_offset = parameters.injected_errors.front();
download::DownloadItem* download =
StartDownloadAndReturnItem(shell(), server_url);
WaitForInterrupt(download);
ASSERT_EQ(interruption_offset, download->GetReceivedBytes());
ASSERT_EQ(parameters.size, download->GetTotalBytes());
parameters.ClearInjectedErrors();
TestDownloadHttpResponse::StartServing(parameters, server_url);
download->Resume(false);
WaitForCompletion(download);
ASSERT_EQ(parameters.size, download->GetReceivedBytes());
ASSERT_EQ(parameters.size, download->GetTotalBytes());
ASSERT_NO_FATAL_FAILURE(ReadAndVerifyFileContents(
parameters.pattern_generator_seed, parameters.size,
download->GetTargetFilePath()));
// Characterization risk: The next portion of the test examines the requests
// that were sent out while downloading our resource. These requests
// correspond to the requests that were generated by the browser and the
// downloads system and may change as implementation details change.
const TestDownloadResponseHandler::CompletedRequests& requests =
test_response_handler()->completed_requests();
ASSERT_EQ(2u, requests.size());
// The first request only transferrs bytes up until the interruption point.
EXPECT_EQ(interruption_offset, requests[0]->transferred_byte_count);
// The next request should only have transferred the remainder of the
// resource.
EXPECT_EQ(parameters.size - interruption_offset,
requests[1]->transferred_byte_count);
std::string value;
ASSERT_TRUE(base::Contains(requests[1]->http_request.headers,
net::HttpRequestHeaders::kIfRange));
EXPECT_EQ(parameters.etag, requests[1]->http_request.headers.at(
net::HttpRequestHeaders::kIfRange));
ASSERT_TRUE(base::Contains(requests[1]->http_request.headers,
net::HttpRequestHeaders::kRange));
EXPECT_EQ(
base::StringPrintf("bytes=%" PRId64 "-", interruption_offset),
requests[1]->http_request.headers.at(net::HttpRequestHeaders::kRange));
}
// Test resumption when strong validators are not present in the response.
IN_PROC_BROWSER_TEST_F(DownloadContentTestWithoutStrongValidators,
ResumeWithoutStrongValidators) {
InterruptAndResumeDownloadWithoutStrongValidators(false);
}
// Test resumption when strong validators are not present in the response and
// the content of the download changes.
IN_PROC_BROWSER_TEST_F(DownloadContentTestWithoutStrongValidators,
ResumeWithoutStrongValidatorsAndFailValidation) {
InterruptAndResumeDownloadWithoutStrongValidators(true);
}
// Resumption should only attempt to contact the final URL if the download has a
// URL chain.
IN_PROC_BROWSER_TEST_F(DownloadContentTest, RedirectBeforeResume) {
SetupErrorInjectionDownloads();
GURL first_url = embedded_test_server()->GetURL("example.com", "/first-url");
GURL second_url =
embedded_test_server()->GetURL("example.com", "/second-url");
GURL third_url = embedded_test_server()->GetURL("example.com", "/third-url");
GURL download_url =
embedded_test_server()->GetURL("example.com", "/download");
TestDownloadHttpResponse::StartServingStaticResponse(
base::StringPrintf("HTTP/1.1 302 Redirect\r\n"
"Location: %s\r\n\r\n",
second_url.spec().c_str()),
first_url);
TestDownloadHttpResponse::StartServingStaticResponse(
base::StringPrintf("HTTP/1.1 302 Redirect\r\n"
"Location: %s\r\n\r\n",
third_url.spec().c_str()),
second_url);
TestDownloadHttpResponse::StartServingStaticResponse(
base::StringPrintf("HTTP/1.1 302 Redirect\r\n"
"Location: %s\r\n\r\n",
download_url.spec().c_str()),
third_url);
TestDownloadHttpResponse::Parameters parameters =
TestDownloadHttpResponse::Parameters::WithSingleInterruption(
inject_error_callback());
TestDownloadHttpResponse::StartServing(parameters, download_url);
download::DownloadItem* download =
StartDownloadAndReturnItem(shell(), first_url);
WaitForInterrupt(download);
EXPECT_EQ(4u, download->GetUrlChain().size());
EXPECT_EQ(first_url, download->GetOriginalUrl());
EXPECT_EQ(download_url, download->GetURL());
// Now that the download is interrupted, make all intermediate servers return
// a 404. The only way a resumption request would succeed if the resumption
// request is sent to the final server in the chain.
TestDownloadHttpResponse::StartServingStaticResponse(k404Response, first_url);
TestDownloadHttpResponse::StartServingStaticResponse(k404Response,
second_url);
TestDownloadHttpResponse::StartServingStaticResponse(k404Response, third_url);
parameters.ClearInjectedErrors();
TestDownloadHttpResponse::StartServing(parameters, download_url);
download->Resume(false);
WaitForCompletion(download);
ASSERT_NO_FATAL_FAILURE(ReadAndVerifyFileContents(
parameters.pattern_generator_seed, parameters.size,
download->GetTargetFilePath()));
}
// If a resumption request results in a redirect, the response should be ignored
// and the download should be marked as interrupted again.
IN_PROC_BROWSER_TEST_F(DownloadContentTest, RedirectWhileResume) {
SetupErrorInjectionDownloads();
GURL first_url = embedded_test_server()->GetURL("example.com", "/first-url");
TestDownloadHttpResponse::Parameters parameters =
TestDownloadHttpResponse::Parameters::WithSingleInterruption(
inject_error_callback());
++parameters.pattern_generator_seed;
TestDownloadHttpResponse::StartServing(parameters, first_url);
// We should never send a request to the decoy. If we do, the request will
// always succeed, which results in behavior that diverges from what we want,
// which is for the download to return to being interrupted.
GURL second_url = embedded_test_server()->GetURL("example.com", "/decoy");
TestDownloadHttpResponse::StartServing(TestDownloadHttpResponse::Parameters(),
second_url);
download::DownloadItem* download =
StartDownloadAndReturnItem(shell(), first_url);
WaitForInterrupt(download);
// Upon resumption, the server starts responding with a redirect. This
// response should not be accepted.
TestDownloadHttpResponse::StartServingStaticResponse(
base::StringPrintf("HTTP/1.1 302 Redirect\r\n"
"Location: %s\r\n\r\n",
second_url.spec().c_str()),
first_url);
download->Resume(false);
WaitForInterrupt(download);
EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_SERVER_UNREACHABLE,
download->GetLastReason());
// Back to the original request handler. Resumption should now succeed, and
// use the partial data it had prior to the first interruption.
parameters.ClearInjectedErrors();
TestDownloadHttpResponse::StartServing(parameters, first_url);
download->Resume(false);
WaitForCompletion(download);
ASSERT_EQ(parameters.size, download->GetReceivedBytes());
ASSERT_EQ(parameters.size, download->GetTotalBytes());
ASSERT_NO_FATAL_FAILURE(ReadAndVerifyFileContents(
parameters.pattern_generator_seed, parameters.size,
download->GetTargetFilePath()));
// Characterization risk: The next portion of the test examines the requests
// that were sent out while downloading our resource. These requests
// correspond to the requests that were generated by the browser and the
// downloads system and may change as implementation details change.
const TestDownloadResponseHandler::CompletedRequests& requests =
test_response_handler()->completed_requests();
ASSERT_EQ(3u, requests.size());
// None of the request should have transferred the entire resource. The
// redirect response shows up as a response with 0 bytes transferred.
EXPECT_GT(parameters.size, requests[0]->transferred_byte_count);
EXPECT_EQ(0, requests[1]->transferred_byte_count);
EXPECT_GT(parameters.size, requests[2]->transferred_byte_count);
}
// Verify that DownloadUrl can support URL redirect.
IN_PROC_BROWSER_TEST_F(DownloadContentTest, RedirectDownload) {
// Setup a redirect chain with two URL.
GURL first_url = embedded_test_server()->GetURL("example.com", "/first-url");
GURL download_url =
embedded_test_server()->GetURL("example.com", "/download");
TestDownloadHttpResponse::StartServingStaticResponse(
base::StringPrintf("HTTP/1.1 302 Redirect\r\n"
"Location: %s\r\n\r\n",
download_url.spec().c_str()),
first_url);
TestDownloadHttpResponse::StartServing(TestDownloadHttpResponse::Parameters(),
download_url);
// Start a download and explicitly specify to support redirect.
std::unique_ptr<DownloadTestObserver> observer(CreateWaiter(shell(), 1));
auto download_parameters = std::make_unique<download::DownloadUrlParameters>(
first_url, TRAFFIC_ANNOTATION_FOR_TESTS);
download_parameters->set_cross_origin_redirects(
network::mojom::RedirectMode::kFollow);
DownloadManagerForShell(shell())->DownloadUrl(std::move(download_parameters));
observer->WaitForFinished();
// Verify download failed.
std::vector<raw_ptr<download::DownloadItem, VectorExperimental>> downloads;
DownloadManagerForShell(shell())->GetAllDownloads(&downloads);
EXPECT_EQ(1u, downloads.size());
EXPECT_EQ(download::DownloadItem::COMPLETE, downloads[0]->GetState());
}
// Verify that DownloadUrl can detect and fail a cross-origin URL redirect.
IN_PROC_BROWSER_TEST_F(DownloadContentTest, FailCrossOriginDownload) {
// Setup a cross-origin redirect chain with two URLs.
net::EmbeddedTestServer origin_one;
net::EmbeddedTestServer origin_two;
ASSERT_TRUE(origin_one.InitializeAndListen());
ASSERT_TRUE(origin_two.InitializeAndListen());
GURL first_url = origin_one.GetURL("/first-url");
GURL second_url = origin_two.GetURL("/download");
origin_one.ServeFilesFromDirectory(GetTestFilePath("download", ""));
origin_one.RegisterRequestHandler(
CreateRedirectHandler("/first-url", second_url));
origin_one.StartAcceptingConnections();
origin_two.StartAcceptingConnections();
// Start a download and explicitly specify to fail cross-origin redirect.
std::unique_ptr<DownloadTestObserver> observer(CreateWaiter(shell(), 1));
auto download_parameters = std::make_unique<download::DownloadUrlParameters>(
first_url, TRAFFIC_ANNOTATION_FOR_TESTS);
download_parameters->set_cross_origin_redirects(
network::mojom::RedirectMode::kError);
DownloadManagerForShell(shell())->DownloadUrl(std::move(download_parameters));
observer->WaitForFinished();
// Verify download is done.
std::vector<raw_ptr<download::DownloadItem, VectorExperimental>> downloads;
DownloadManagerForShell(shell())->GetAllDownloads(&downloads);
EXPECT_EQ(1u, downloads.size());
EXPECT_EQ(download::DownloadItem::INTERRUPTED, downloads[0]->GetState());
ASSERT_TRUE(origin_two.ShutdownAndWaitUntilComplete());
ASSERT_TRUE(origin_one.ShutdownAndWaitUntilComplete());
}
// Verify that DownloadUrl() to URL with unsafe scheme should fail.
IN_PROC_BROWSER_TEST_F(DownloadContentTest, RedirectUnsafeDownload) {
// Setup a redirect chain with two URL.
GURL first_url = embedded_test_server()->GetURL("example.com", "/first-url");
GURL unsafe_url = GURL("unsafe:///etc/passwd");
TestDownloadHttpResponse::StartServingStaticResponse(
base::StringPrintf("HTTP/1.1 302 Redirect\r\n"
"Location: %s\r\n\r\n",
unsafe_url.spec().c_str()),
first_url);
TestDownloadHttpResponse::StartServing(TestDownloadHttpResponse::Parameters(),
unsafe_url);
// Start a download and explicitly specify to support redirect.
DownloadManager* download_manager = DownloadManagerForShell(shell());
std::unique_ptr<DownloadTestObserverInterrupted> observer =
std::make_unique<DownloadTestObserverInterrupted>(
download_manager, 1,
DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL);
auto download_parameters = std::make_unique<download::DownloadUrlParameters>(
first_url, TRAFFIC_ANNOTATION_FOR_TESTS);
download_parameters->set_cross_origin_redirects(
network::mojom::RedirectMode::kFollow);
download_manager->DownloadUrl(std::move(download_parameters));
observer->WaitForFinished();
// Verify download failed.
std::vector<raw_ptr<download::DownloadItem, VectorExperimental>> downloads;
DownloadManagerForShell(shell())->GetAllDownloads(&downloads);
EXPECT_EQ(1u, downloads.size());
EXPECT_EQ(download::DownloadItem::INTERRUPTED, downloads[0]->GetState());
// The interrupt reason must match, notice the embedded test server used in
// tests may also fail even if the download passed the security check.
EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_NETWORK_INVALID_REQUEST,
downloads[0]->GetLastReason());
}
// Verify that DownloadUrl() with no DownloadManagerDelegate drops the download.
IN_PROC_BROWSER_TEST_F(DownloadContentTest, NoDownloadManagerDelegateDownload) {
const GURL download_url =
embedded_test_server()->GetURL("/download/download-test.lib");
// Unset the DownloadManagerDelegate.
auto* download_manager = DownloadManagerForShell(shell());
download_manager->GetDelegate()->Shutdown();
download_manager->SetDelegate(nullptr);
MockDownloadManagerObserver dm_observer(download_manager);
EXPECT_CALL(dm_observer, OnDownloadCreated(_, _)).Times(0);
EXPECT_CALL(dm_observer, OnDownloadDropped(_)).Times(1);
// Create download parameters with renderer process information. This is
// required to go through the DownloadManagerDelegate code path.
auto download_parameters =
DownloadRequestUtils::CreateDownloadForWebContentsMainFrame(
shell()->web_contents(), download_url, TRAFFIC_ANNOTATION_FOR_TESTS);
download_parameters->set_content_initiated(true);
download_manager->DownloadUrl(std::move(download_parameters));
// Verify there were no downloads.
EXPECT_TRUE(EnsureNoPendingDownloads());
std::vector<raw_ptr<download::DownloadItem, VectorExperimental>> downloads;
download_manager->GetAllDownloads(&downloads);
EXPECT_TRUE(downloads.empty());
}
// If the server response for the resumption request specifies a bad range (i.e.
// not the range that was requested), then the download should be marked as
// interrupted and restart from the beginning.
IN_PROC_BROWSER_TEST_F(DownloadContentTest, BadRangeHeader) {
SetupErrorInjectionDownloads();
GURL url = TestDownloadHttpResponse::GetNextURLForDownload();
GURL server_url = embedded_test_server()->GetURL(url.host(), url.path());
TestDownloadHttpResponse::Parameters parameters =
TestDownloadHttpResponse::Parameters::WithSingleInterruption(
inject_error_callback());
TestDownloadHttpResponse::StartServing(parameters, server_url);
download::DownloadItem* download =
StartDownloadAndReturnItem(shell(), server_url);
WaitForInterrupt(download);
// Upon resumption, the server starts responding with a bad range header.
parameters.ClearInjectedErrors();
parameters.SetResponseForRangeRequest(
10000, -1,
"HTTP/1.1 206 Partial Content\r\n"
"Content-Range: bytes 1000000-2000000/3000000\r\n"
"\r\n");
TestDownloadHttpResponse::StartServing(parameters, server_url);
download->Resume(false);
WaitForCompletion(download);
EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_SERVER_NO_RANGE,
download->GetLastReason());
}
// If the server response for the resumption request specifies an invalid range,
// then the download should be marked as interrupted and as interrupted again
// without discarding the partial state.
IN_PROC_BROWSER_TEST_F(DownloadContentTest, InvalidRangeHeader) {
SetupErrorInjectionDownloads();
GURL url = TestDownloadHttpResponse::GetNextURLForDownload();
GURL server_url = embedded_test_server()->GetURL(url.host(), url.path());
TestDownloadHttpResponse::Parameters parameters =
TestDownloadHttpResponse::Parameters::WithSingleInterruption(
inject_error_callback());
TestDownloadHttpResponse::StartServing(parameters, server_url);
download::DownloadItem* download =
StartDownloadAndReturnItem(shell(), server_url);
WaitForInterrupt(download);
// Or this time, the server sends a response with an invalid Content-Range
// header.
TestDownloadHttpResponse::StartServingStaticResponse(
"HTTP/1.1 206 Partial Content\r\n"
"Content-Range: ooga-booga-booga-booga\r\n"
"\r\n",
server_url);
download->Resume(false);
WaitForInterrupt(download);
EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_SERVER_BAD_CONTENT,
download->GetLastReason());
// Or no Content-Range header at all.
TestDownloadHttpResponse::StartServingStaticResponse(
"HTTP/1.1 206 Partial Content\r\n"
"Some-Headers: ooga-booga-booga-booga\r\n"
"\r\n",
server_url);
download->Resume(false);
WaitForInterrupt(download);
EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_SERVER_BAD_CONTENT,
download->GetLastReason());
// Back to the original request handler. Resumption should now succeed, and
// use the partial data it had prior to the first interruption.
parameters.ClearInjectedErrors();
TestDownloadHttpResponse::StartServing(parameters, server_url);
download->Resume(false);
WaitForCompletion(download);
ASSERT_EQ(parameters.size, download->GetReceivedBytes());
ASSERT_EQ(parameters.size, download->GetTotalBytes());
ASSERT_NO_FATAL_FAILURE(ReadAndVerifyFileContents(
parameters.pattern_generator_seed, parameters.size,
download->GetTargetFilePath()));
// Characterization risk: The next portion of the test examines the requests
// that were sent out while downloading our resource. These requests
// correspond to the requests that were generated by the browser and the
// downloads system and may change as implementation details change.
const TestDownloadResponseHandler::CompletedRequests& requests =
test_response_handler()->completed_requests();
ASSERT_EQ(4u, requests.size());
// The last request will transfer the entire resource as the interrupt
// reason doesn't allow download to continue.
EXPECT_GT(parameters.size, requests[0]->transferred_byte_count);
EXPECT_EQ(0, requests[1]->transferred_byte_count);
EXPECT_EQ(0, requests[2]->transferred_byte_count);
EXPECT_EQ(parameters.size, requests[3]->transferred_byte_count);
}
// If the server response for the resumption request cannot be decoded,
// the download will need to restart. This is to simulate some servers
// that doesn't handle range request properly.
IN_PROC_BROWSER_TEST_F(DownloadContentTest, BadEncoding) {
SetupErrorInjectionDownloads();
GURL url = TestDownloadHttpResponse::GetNextURLForDownload();
GURL server_url = embedded_test_server()->GetURL(url.host(), url.path());
TestDownloadHttpResponse::Parameters parameters =
TestDownloadHttpResponse::Parameters::WithSingleInterruption(
inject_error_callback());
TestDownloadHttpResponse::StartServing(parameters, server_url);
download::DownloadItem* download =
StartDownloadAndReturnItem(shell(), server_url);
WaitForInterrupt(download);
parameters.ClearInjectedErrors();
// Server's response to range request cannot be decoded.
parameters.SetResponseForRangeRequest(
10000, -1,
"HTTP/1.1 206 Partial Content\r\n"
"Content-Range: bytes 1000000-2000000/3000000\r\n"
"Content-Encoding: gzip\r\n"
"\r\n"
"x\r\n");
TestDownloadHttpResponse::StartServing(parameters, server_url);
// The download will restart and complete successfully.
download->Resume(false);
WaitForCompletion(download);
EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_SERVER_NO_RANGE,
download->GetLastReason());
}
// A partial resumption results in an HTTP 200 response. I.e. the server ignored
// the range request and sent the entire resource instead. For If-Range requests
// (as opposed to If-Match), the behavior for a precondition failure is also to
// respond with a 200. So this test case covers both validation failure and
// ignoring the range request.
IN_PROC_BROWSER_TEST_F(DownloadContentTest, RestartIfNotPartialResponse) {
SetupErrorInjectionDownloads();
const int kOriginalPatternGeneratorSeed = 1;
const int kNewPatternGeneratorSeed = 2;
GURL url = TestDownloadHttpResponse::GetNextURLForDownload();
GURL server_url = embedded_test_server()->GetURL(url.host(), url.path());
TestDownloadHttpResponse::Parameters parameters =
TestDownloadHttpResponse::Parameters::WithSingleInterruption(
inject_error_callback());
parameters.pattern_generator_seed = kOriginalPatternGeneratorSeed;
int64_t interruption_offset = parameters.injected_errors.front();
TestDownloadHttpResponse::StartServing(parameters, server_url);
download::DownloadItem* download =
StartDownloadAndReturnItem(shell(), server_url);
WaitForInterrupt(download);
ASSERT_EQ(interruption_offset, download->GetReceivedBytes());
ASSERT_EQ(parameters.size, download->GetTotalBytes());
parameters = TestDownloadHttpResponse::Parameters();
parameters.support_byte_ranges = false;
parameters.pattern_generator_seed = kNewPatternGeneratorSeed;
TestDownloadHttpResponse::StartServing(parameters, server_url);
download->Resume(false);
WaitForCompletion(download);
ASSERT_EQ(interruption_offset, download->GetBytesWasted());
ASSERT_EQ(parameters.size, download->GetReceivedBytes());
ASSERT_EQ(parameters.size, download->GetTotalBytes());
ASSERT_NO_FATAL_FAILURE(
ReadAndVerifyFileContents(kNewPatternGeneratorSeed, parameters.size,
download->GetTargetFilePath()));
// When the downloads system sees the full response, it should accept the
// response without restarting. On the network, we should deterministically
// see two requests:
// * The original request which transfers upto our interruption point.
// * The resumption attempt, which receives the entire entity.
const TestDownloadResponseHandler::CompletedRequests& requests =
test_response_handler()->completed_requests();
ASSERT_EQ(2u, requests.size());
// The first request only transfers data up to the interruption point.
EXPECT_EQ(interruption_offset, requests[0]->transferred_byte_count);
// The second request transfers the entire response.
EXPECT_EQ(parameters.size, requests[1]->transferred_byte_count);
ASSERT_TRUE(base::Contains(requests[1]->http_request.headers,
net::HttpRequestHeaders::kIfRange));
EXPECT_EQ(parameters.etag, requests[1]->http_request.headers.at(
net::HttpRequestHeaders::kIfRange));
ASSERT_TRUE(base::Contains(requests[1]->http_request.headers,
net::HttpRequestHeaders::kRange));
EXPECT_EQ(
base::StringPrintf("bytes=%" PRId64 "-", interruption_offset),
requests[1]->http_request.headers.at(net::HttpRequestHeaders::kRange));
}
// Confirm we restart if we don't have a verifier.
IN_PROC_BROWSER_TEST_F(DownloadContentTest, RestartIfNoETag) {
SetupErrorInjectionDownloads();
const int kOriginalPatternGeneratorSeed = 1;
const int kNewPatternGeneratorSeed = 2;
GURL url = TestDownloadHttpResponse::GetNextURLForDownload();
GURL server_url = embedded_test_server()->GetURL(url.host(), url.path());
TestDownloadHttpResponse::Parameters parameters =
TestDownloadHttpResponse::Parameters::WithSingleInterruption(
inject_error_callback());
ASSERT_EQ(1u, parameters.injected_errors.size());
parameters.etag.clear();
parameters.pattern_generator_seed = kOriginalPatternGeneratorSeed;
TestDownloadHttpResponse::StartServing(parameters, server_url);
download::DownloadItem* download =
StartDownloadAndReturnItem(shell(), server_url);
WaitForInterrupt(download);
parameters.pattern_generator_seed = kNewPatternGeneratorSeed;
parameters.ClearInjectedErrors();
TestDownloadHttpResponse::StartServing(parameters, server_url);
download->Resume(false);
WaitForCompletion(download);
ASSERT_EQ(parameters.size, download->GetReceivedBytes());
ASSERT_EQ(parameters.size, download->GetTotalBytes());
ASSERT_NO_FATAL_FAILURE(
ReadAndVerifyFileContents(kNewPatternGeneratorSeed, parameters.size,
download->GetTargetFilePath()));
const TestDownloadResponseHandler::CompletedRequests& requests =
test_response_handler()->completed_requests();
// Neither If-Range nor Range headers should be present in the second request.
ASSERT_EQ(2u, requests.size());
EXPECT_FALSE(base::Contains(requests[1]->http_request.headers,
net::HttpRequestHeaders::kIfRange));
EXPECT_FALSE(base::Contains(requests[1]->http_request.headers,
net::HttpRequestHeaders::kRange));
}
// Partial file goes missing before the download is resumed. The download should
// restart.
IN_PROC_BROWSER_TEST_F(DownloadContentTest, RestartIfNoPartialFile) {
SetupErrorInjectionDownloads();
GURL url = TestDownloadHttpResponse::GetNextURLForDownload();
GURL server_url = embedded_test_server()->GetURL(url.host(), url.path());
TestDownloadHttpResponse::Parameters parameters =
TestDownloadHttpResponse::Parameters::WithSingleInterruption(
inject_error_callback());
int64_t interruption_offset = parameters.injected_errors.front();
TestDownloadHttpResponse::StartServing(parameters, server_url);
download::DownloadItem* download =
StartDownloadAndReturnItem(shell(), server_url);
WaitForInterrupt(download);
// Delete the intermediate file.
{
base::ScopedAllowBlockingForTesting allow_blocking;
ASSERT_TRUE(PathExists(download->GetFullPath()));
ASSERT_TRUE(base::DeleteFile(download->GetFullPath()));
}
parameters.ClearInjectedErrors();
TestDownloadHttpResponse::StartServing(parameters, server_url);
download->Resume(false);
WaitForCompletion(download);
ASSERT_EQ(interruption_offset, download->GetBytesWasted());
ASSERT_EQ(parameters.size, download->GetReceivedBytes());
ASSERT_EQ(parameters.size, download->GetTotalBytes());
ASSERT_NO_FATAL_FAILURE(ReadAndVerifyFileContents(
parameters.pattern_generator_seed, parameters.size,
download->GetTargetFilePath()));
}
IN_PROC_BROWSER_TEST_F(DownloadContentTest, RecoverFromInitFileError) {
GURL url = TestDownloadHttpResponse::GetNextURLForDownload();
GURL server_url = embedded_test_server()->GetURL(url.host(), url.path());
TestDownloadHttpResponse::StartServing(TestDownloadHttpResponse::Parameters(),
server_url);
// Setup the error injector.
scoped_refptr<TestFileErrorInjector> injector(
TestFileErrorInjector::Create(DownloadManagerForShell(shell())));
const TestFileErrorInjector::FileErrorInfo err = {
TestFileErrorInjector::FILE_OPERATION_INITIALIZE, 0,
download::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE};
injector->InjectError(err);
// Start and watch for interrupt.
download::DownloadItem* download(
StartDownloadAndReturnItem(shell(), server_url));
WaitForInterrupt(download);
ASSERT_EQ(download::DownloadItem::INTERRUPTED, download->GetState());
EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
download->GetLastReason());
EXPECT_EQ(0, download->GetReceivedBytes());
EXPECT_TRUE(download->GetFullPath().empty());
EXPECT_FALSE(download->GetTargetFilePath().empty());
// We need to make sure that any cross-thread downloads communication has
// quiesced before clearing and injecting the new errors, as the
// InjectErrors() routine alters the currently in use download file
// factory.
RunAllTasksUntilIdle();
// Clear the old errors list.
injector->ClearError();
// Resume and watch completion.
download->Resume(false);
WaitForCompletion(download);
EXPECT_EQ(download->GetState(), download::DownloadItem::COMPLETE);
}
IN_PROC_BROWSER_TEST_F(DownloadContentTest,
RecoverFromIntermediateFileRenameError) {
GURL url = TestDownloadHttpResponse::GetNextURLForDownload();
GURL server_url = embedded_test_server()->GetURL(url.host(), url.path());
TestDownloadHttpResponse::StartServing(TestDownloadHttpResponse::Parameters(),
server_url);
// Setup the error injector.
scoped_refptr<TestFileErrorInjector> injector(
TestFileErrorInjector::Create(DownloadManagerForShell(shell())));
const TestFileErrorInjector::FileErrorInfo err = {
TestFileErrorInjector::FILE_OPERATION_RENAME_UNIQUIFY, 0,
download::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE};
injector->InjectError(err);
// Start and watch for interrupt.
download::DownloadItem* download(
StartDownloadAndReturnItem(shell(), server_url));
WaitForInterrupt(download);
ASSERT_EQ(download::DownloadItem::INTERRUPTED, download->GetState());
EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
download->GetLastReason());
EXPECT_TRUE(download->GetFullPath().empty());
// Target path will have been set after file name determination. GetFullPath()
// being empty is sufficient to signal that filename determination needs to be
// redone.
EXPECT_FALSE(download->GetTargetFilePath().empty());
// We need to make sure that any cross-thread downloads communication has
// quiesced before clearing and injecting the new errors, as the
// InjectErrors() routine alters the currently in use download file
// factory.
RunAllTasksUntilIdle();
// Clear the old errors list.
injector->ClearError();
download->Resume(false);
WaitForCompletion(download);
EXPECT_EQ(download->GetState(), download::DownloadItem::COMPLETE);
}
IN_PROC_BROWSER_TEST_F(DownloadContentTest, RecoverFromFinalRenameError) {
GURL url = TestDownloadHttpResponse::GetNextURLForDownload();
GURL server_url = embedded_test_server()->GetURL(url.host(), url.path());
TestDownloadHttpResponse::StartServing(TestDownloadHttpResponse::Parameters(),
server_url);
// Setup the error injector.
scoped_refptr<TestFileErrorInjector> injector(
TestFileErrorInjector::Create(DownloadManagerForShell(shell())));
TestFileErrorInjector::FileErrorInfo err = {
TestFileErrorInjector::FILE_OPERATION_RENAME_ANNOTATE, 0,
download::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED};
injector->InjectError(err);
// Start and watch for interrupt.
download::DownloadItem* download(
StartDownloadAndReturnItem(shell(), server_url));
WaitForInterrupt(download);
ASSERT_EQ(download::DownloadItem::INTERRUPTED, download->GetState());
EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
download->GetLastReason());
EXPECT_TRUE(download->GetFullPath().empty());
// Target path should still be intact.
EXPECT_FALSE(download->GetTargetFilePath().empty());
// We need to make sure that any cross-thread downloads communication has
// quiesced before clearing and injecting the new errors, as the
// InjectErrors() routine alters the currently in use download file
// factory, which is a download sequence object.
RunAllTasksUntilIdle();
// Clear the old errors list.
injector->ClearError();
download->Resume(false);
WaitForCompletion(download);
EXPECT_EQ(download->GetState(), download::DownloadItem::COMPLETE);
}
IN_PROC_BROWSER_TEST_F(DownloadContentTest, Resume_Hash) {
const char kExpectedHash[] =
"\xa7\x44\x49\x86\x24\xc6\x84\x6c\x89\xdf\xd8\xec\xa0\xe0\x61\x12\xdc\x80"
"\x13\xf2\x83\x49\xa9\x14\x52\x32\xf0\x95\x20\xca\x5b\x30";
std::string expected_hash(kExpectedHash);
TestDownloadHttpResponse::Parameters parameters;
// As a control, let's try GetHash() on an uninterrupted download.
GURL url1 = TestDownloadHttpResponse::GetNextURLForDownload();
GURL server_url1 = embedded_test_server()->GetURL(url1.host(), url1.path());
TestDownloadHttpResponse::StartServing(parameters, server_url1);
download::DownloadItem* uninterrupted_download(
StartDownloadAndReturnItem(shell(), server_url1));
WaitForCompletion(uninterrupted_download);
EXPECT_EQ(expected_hash, uninterrupted_download->GetHash());
SetupErrorInjectionDownloads();
// Now with interruptions.
GURL url2 = TestDownloadHttpResponse::GetNextURLForDownload();
GURL server_url2 = embedded_test_server()->GetURL(url2.host(), url2.path());
parameters.inject_error_cb = inject_error_callback();
parameters.injected_errors.push(100);
parameters.injected_errors.push(211);
parameters.injected_errors.push(337);
parameters.injected_errors.push(400);
parameters.injected_errors.push(512);
TestDownloadHttpResponse::StartServing(parameters, server_url2);
// Start and watch for interrupt.
download::DownloadItem* download(
StartDownloadAndReturnItem(shell(), server_url2));
WaitForInterrupt(download);
parameters.injected_errors.pop();
TestDownloadHttpResponse::StartServing(parameters, server_url2);
download->Resume(true);
WaitForInterrupt(download);
parameters.injected_errors.pop();
TestDownloadHttpResponse::StartServing(parameters, server_url2);
download->Resume(true);
WaitForInterrupt(download);
parameters.injected_errors.pop();
TestDownloadHttpResponse::StartServing(parameters, server_url2);
download->Resume(true);
WaitForInterrupt(download);
parameters.injected_errors.pop();
TestDownloadHttpResponse::StartServing(parameters, server_url2);
download->Resume(true);
WaitForInterrupt(download);
parameters.injected_errors.pop();
TestDownloadHttpResponse::StartServing(parameters, server_url2);
download->Resume(true);
WaitForCompletion(download);
EXPECT_EQ(expected_hash, download->GetHash());
}
// An interrupted download should remove the intermediate file when it is
// cancelled.
IN_PROC_BROWSER_TEST_F(DownloadContentTest, CancelInterruptedDownload) {
SetupErrorInjectionDownloads();
GURL url = TestDownloadHttpResponse::GetNextURLForDownload();
GURL server_url = embedded_test_server()->GetURL(url.host(), url.path());
TestDownloadHttpResponse::StartServing(
TestDownloadHttpResponse::Parameters::WithSingleInterruption(
inject_error_callback()),
server_url);
download::DownloadItem* download =
StartDownloadAndReturnItem(shell(), server_url);
WaitForInterrupt(download);
base::FilePath intermediate_path = download->GetFullPath();
ASSERT_FALSE(intermediate_path.empty());
ASSERT_TRUE(PathExists(intermediate_path));
download->Cancel(true /* user_cancel */);
RunAllTasksUntilIdle();
// The intermediate file should now be gone.
EXPECT_FALSE(PathExists(intermediate_path));
EXPECT_TRUE(download->GetFullPath().empty());
}
IN_PROC_BROWSER_TEST_F(DownloadContentTest, RemoveInterruptedDownload) {
SetupErrorInjectionDownloads();
GURL url = TestDownloadHttpResponse::GetNextURLForDownload();
GURL server_url = embedded_test_server()->GetURL(url.host(), url.path());
TestDownloadHttpResponse::StartServing(
TestDownloadHttpResponse::Parameters::WithSingleInterruption(
inject_error_callback()),
server_url);
download::DownloadItem* download =
StartDownloadAndReturnItem(shell(), server_url);
WaitForInterrupt(download);
base::FilePath intermediate_path = download->GetFullPath();
ASSERT_FALSE(intermediate_path.empty());
ASSERT_TRUE(PathExists(intermediate_path));
download->Remove();
RunAllTasksUntilIdle();
// The intermediate file should now be gone.
EXPECT_FALSE(PathExists(intermediate_path));
}
IN_PROC_BROWSER_TEST_F(DownloadContentTest, RemoveCompletedDownload) {
// A completed download shouldn't delete the downloaded file when it is
// removed.
GURL url = TestDownloadHttpResponse::GetNextURLForDownload();
GURL server_url = embedded_test_server()->GetURL(url.host(), url.path());
TestDownloadHttpResponse::StartServing(TestDownloadHttpResponse::Parameters(),
server_url);
std::unique_ptr<DownloadTestObserver> completion_observer(
CreateWaiter(shell(), 1));
download::DownloadItem* download(
StartDownloadAndReturnItem(shell(), server_url));
completion_observer->WaitForFinished();
// The target path should exist.
base::FilePath target_path(download->GetTargetFilePath());
EXPECT_TRUE(PathExists(target_path));
download->Remove();
RunAllTasksUntilIdle();
// The file should still exist.
EXPECT_TRUE(PathExists(target_path));
}
IN_PROC_BROWSER_TEST_F(DownloadContentTest, RemoveResumingDownload) {
SetupErrorInjectionDownloads();
GURL url = TestDownloadHttpResponse::GetNextURLForDownload();
GURL server_url = embedded_test_server()->GetURL(url.host(), url.path());
TestDownloadHttpResponse::Parameters parameters =
TestDownloadHttpResponse::Parameters::WithSingleInterruption(
inject_error_callback());
TestDownloadHttpResponse::StartServing(parameters, server_url);
download::DownloadItem* download =
StartDownloadAndReturnItem(shell(), server_url);
WaitForInterrupt(download);
base::FilePath intermediate_path(download->GetFullPath());
ASSERT_FALSE(intermediate_path.empty());
EXPECT_TRUE(PathExists(intermediate_path));
// Resume and remove download. We expect only a single OnDownloadCreated()
// call, and that's for the second download created below.
MockDownloadManagerObserver dm_observer(DownloadManagerForShell(shell()));
EXPECT_CALL(dm_observer, OnDownloadCreated(_, _)).Times(1);
TestRequestPauseHandler request_pause_handler;
parameters.on_pause_handler = request_pause_handler.GetOnPauseHandler();
parameters.pause_offset = -1;
TestDownloadHttpResponse::StartServing(parameters, server_url);
download->Resume(false);
request_pause_handler.WaitForCallback();
// At this point, the download resumption request has been sent out, but the
// response hasn't been received yet.
download->Remove();
request_pause_handler.Resume();
// The intermediate file should now be gone.
RunAllTasksUntilIdle();
EXPECT_FALSE(PathExists(intermediate_path));
parameters.ClearInjectedErrors();
parameters.on_pause_handler.Reset();
TestDownloadHttpResponse::StartServing(parameters, server_url);
// Start the second download and wait until it's done. This exercises the
// entire downloads stack and effectively flushes all of our worker threads.
// We are testing whether the URL request created in the previous
// download::DownloadItem::Resume() call reulted in a new download or not.
NavigateToURLAndWaitForDownload(shell(), server_url,
download::DownloadItem::COMPLETE);
EXPECT_TRUE(EnsureNoPendingDownloads());
}
IN_PROC_BROWSER_TEST_F(DownloadContentTest, CancelResumingDownload) {
SetupErrorInjectionDownloads();
GURL url = TestDownloadHttpResponse::GetNextURLForDownload();
GURL server_url = embedded_test_server()->GetURL(url.host(), url.path());
TestDownloadHttpResponse::Parameters parameters =
TestDownloadHttpResponse::Parameters::WithSingleInterruption(
inject_error_callback());
TestDownloadHttpResponse::StartServing(parameters, server_url);
download::DownloadItem* download =
StartDownloadAndReturnItem(shell(), server_url);
WaitForInterrupt(download);
base::FilePath intermediate_path(download->GetFullPath());
ASSERT_FALSE(intermediate_path.empty());
EXPECT_TRUE(PathExists(intermediate_path));
// Resume and cancel download. We expect only a single OnDownloadCreated()
// call, and that's for the second download created below.
MockDownloadManagerObserver dm_observer(DownloadManagerForShell(shell()));
EXPECT_CALL(dm_observer, OnDownloadCreated(_, _)).Times(1);
TestRequestPauseHandler request_pause_handler;
parameters.on_pause_handler = request_pause_handler.GetOnPauseHandler();
parameters.pause_offset = -1;
parameters.ClearInjectedErrors();
TestDownloadHttpResponse::StartServing(parameters, server_url);
download->Resume(false);
request_pause_handler.WaitForCallback();
// At this point, the download item has initiated a network request for the
// resumption attempt, but hasn't received a response yet.
download->Cancel(true /* user_cancel */);
request_pause_handler.Resume();
// The intermediate file should now be gone.
RunAllPendingInMessageLoop(BrowserThread::IO);
RunAllTasksUntilIdle();
EXPECT_FALSE(PathExists(intermediate_path));
parameters.ClearInjectedErrors();
parameters.on_pause_handler.Reset();
TestDownloadHttpResponse::StartServing(parameters, server_url);
// Start the second download and wait until it's done. This exercises the
// entire downloads stack and effectively flushes all of our worker threads.
// We are testing whether the URL request created in the previous
// download::DownloadItem::Resume() call reulted in a new download or not.
NavigateToURLAndWaitForDownload(shell(), server_url,
download::DownloadItem::COMPLETE);
EXPECT_TRUE(EnsureNoPendingDownloads());
}
IN_PROC_BROWSER_TEST_F(DownloadContentTest, RemoveResumedDownload) {
SetupErrorInjectionDownloads();
TestDownloadHttpResponse::Parameters parameters =
TestDownloadHttpResponse::Parameters::WithSingleInterruption(
inject_error_callback());
GURL url = TestDownloadHttpResponse::GetNextURLForDownload();
GURL server_url = embedded_test_server()->GetURL(url.host(), url.path());
TestDownloadHttpResponse::StartServing(parameters, server_url);
download::DownloadItem* download =
StartDownloadAndReturnItem(shell(), server_url);
WaitForInterrupt(download);
base::FilePath intermediate_path(download->GetFullPath());
base::FilePath target_path(download->GetTargetFilePath());
ASSERT_FALSE(intermediate_path.empty());
EXPECT_TRUE(PathExists(intermediate_path));
EXPECT_FALSE(PathExists(target_path));
// Resume and remove download. We don't expect OnDownloadCreated() calls.
MockDownloadManagerObserver dm_observer(DownloadManagerForShell(shell()));
EXPECT_CALL(dm_observer, OnDownloadCreated(_, _)).Times(0);
parameters.ClearInjectedErrors();
TestDownloadHttpResponse::StartServing(parameters, server_url);
download->Resume(false);
WaitForInProgress(download);
download->Remove();
// The intermediate file should now be gone.
RunAllTasksUntilIdle();
EXPECT_FALSE(PathExists(intermediate_path));
EXPECT_FALSE(PathExists(target_path));
EXPECT_TRUE(EnsureNoPendingDownloads());
test_response_handler()->WaitUntilCompletion(2u);
}
// TODO(qinmin): Flaky crashes on ASAN Linux. https://crbug.com/836689
#if BUILDFLAG(IS_ANDROID) || \
(BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)) && \
defined(ADDRESS_SANITIZER)
#define MAYBE_CancelResumedDownload DISABLED_CancelResumedDownload
#else
#define MAYBE_CancelResumedDownload CancelResumedDownload
#endif
IN_PROC_BROWSER_TEST_F(DownloadContentTest, MAYBE_CancelResumedDownload) {
SetupErrorInjectionDownloads();
TestDownloadHttpResponse::Parameters parameters =
TestDownloadHttpResponse::Parameters::WithSingleInterruption(
inject_error_callback());
GURL url = TestDownloadHttpResponse::GetNextURLForDownload();
GURL server_url = embedded_test_server()->GetURL(url.host(), url.path());
TestDownloadHttpResponse::StartServing(parameters, server_url);
download::DownloadItem* download =
StartDownloadAndReturnItem(shell(), server_url);
WaitForInterrupt(download);
base::FilePath intermediate_path(download->GetFullPath());
base::FilePath target_path(download->GetTargetFilePath());
ASSERT_FALSE(intermediate_path.empty());
EXPECT_TRUE(PathExists(intermediate_path));
EXPECT_FALSE(PathExists(target_path));
// Resume and remove download. We don't expect OnDownloadCreated() calls.
MockDownloadManagerObserver dm_observer(DownloadManagerForShell(shell()));
EXPECT_CALL(dm_observer, OnDownloadCreated(_, _)).Times(0);
parameters.ClearInjectedErrors();
TestDownloadHttpResponse::StartServing(parameters, server_url);
download->Resume(false);
WaitForInProgress(download);
download->Cancel(true);
// The intermediate file should now be gone.
RunAllTasksUntilIdle();
EXPECT_FALSE(PathExists(intermediate_path));
EXPECT_FALSE(PathExists(target_path));
EXPECT_TRUE(EnsureNoPendingDownloads());
test_response_handler()->WaitUntilCompletion(2u);
}
IN_PROC_BROWSER_TEST_F(DownloadContentTest, ResumeRestoredDownload_NoFile) {
TestDownloadHttpResponse::Parameters parameters;
GURL url = TestDownloadHttpResponse::GetNextURLForDownload();
GURL server_url = embedded_test_server()->GetURL(url.host(), url.path());
TestDownloadHttpResponse::StartServing(parameters, server_url);
base::FilePath intermediate_file_path =
GetDownloadDirectory().AppendASCII("intermediate");
std::vector<GURL> url_chain;
const int kIntermediateSize = 1331;
url_chain.push_back(server_url);
download::DownloadItem* download =
DownloadManagerForShell(shell())->CreateDownloadItem(
"F7FB1F59-7DE1-4845-AFDB-8A688F70F583", 1, intermediate_file_path,
base::FilePath(), url_chain, GURL(),
StoragePartitionConfig::CreateDefault(
shell()->web_contents()->GetBrowserContext()),
GURL(), GURL(), url::Origin(), "application/octet-stream",
"application/octet-stream", base::Time::Now(), base::Time(),
parameters.etag, std::string(), kIntermediateSize, parameters.size,
std::string(), download::DownloadItem::INTERRUPTED,
download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
download::DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED, false,
base::Time(), false,
std::vector<download::DownloadItem::ReceivedSlice>());
ClearAutoResumptionCount(download);
download->Resume(false);
WaitForCompletion(download);
EXPECT_FALSE(PathExists(intermediate_file_path));
ReadAndVerifyFileContents(parameters.pattern_generator_seed,
parameters.size,
download->GetTargetFilePath());
const TestDownloadResponseHandler::CompletedRequests& requests =
test_response_handler()->completed_requests();
// There will be two requests. The first one is issued optimistically assuming
// that the intermediate file exists and matches the size expectations set
// forth in the download metadata (i.e. assuming that a 1331 byte file exists
// at |intermediate_file_path|.
//
// However, once the response is received, DownloadFile will report that the
// intermediate file doesn't exist and hence the download is marked
// interrupted again.
//
// The second request reads the entire entity.
//
// N.b. we can't make any assumptions about how many bytes are transferred by
// the first request since response data will be bufferred until DownloadFile
// is done initializing.
//
// TODO(asanka): Ideally we'll check that the intermediate file matches
// expectations prior to issuing the first resumption request.
ASSERT_EQ(2u, requests.size());
EXPECT_EQ(parameters.size, requests[1]->transferred_byte_count);
}
IN_PROC_BROWSER_TEST_F(DownloadContentTest, ResumeRestoredDownload_NoHash) {
TestDownloadHttpResponse::Parameters parameters;
GURL url = TestDownloadHttpResponse::GetNextURLForDownload();
GURL server_url = embedded_test_server()->GetURL(url.host(), url.path());
TestDownloadHttpResponse::StartServing(parameters, server_url);
base::FilePath intermediate_file_path =
GetDownloadDirectory().AppendASCII("intermediate");
std::vector<GURL> url_chain;
const int kIntermediateSize = 1331;
std::string output = TestDownloadHttpResponse::GetPatternBytes(
parameters.pattern_generator_seed, 0, kIntermediateSize);
{
base::ScopedAllowBlockingForTesting allow_blocking;
ASSERT_TRUE(base::WriteFile(intermediate_file_path, output));
}
url_chain.push_back(server_url);
download::DownloadItem* download =
DownloadManagerForShell(shell())->CreateDownloadItem(
"F7FB1F59-7DE1-4845-AFDB-8A688F70F583", 1, intermediate_file_path,
base::FilePath(), url_chain, GURL(),
StoragePartitionConfig::CreateDefault(
shell()->web_contents()->GetBrowserContext()),
GURL(), GURL(), url::Origin(), "application/octet-stream",
"application/octet-stream", base::Time::Now(), base::Time(),
parameters.etag, std::string(), kIntermediateSize, parameters.size,
std::string(), download::DownloadItem::INTERRUPTED,
download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
download::DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED, false,
base::Time(), false,
std::vector<download::DownloadItem::ReceivedSlice>());
ClearAutoResumptionCount(download);
download->Resume(false);
WaitForCompletion(download);
EXPECT_FALSE(PathExists(intermediate_file_path));
ReadAndVerifyFileContents(parameters.pattern_generator_seed,
parameters.size,
download->GetTargetFilePath());
const TestDownloadResponseHandler::CompletedRequests& completed_requests =
test_response_handler()->completed_requests();
// There's only one network request issued, and that is for the remainder of
// the file.
ASSERT_EQ(1u, completed_requests.size());
EXPECT_EQ(parameters.size - kIntermediateSize,
completed_requests[0]->transferred_byte_count);
}
IN_PROC_BROWSER_TEST_F(DownloadContentTest,
ResumeRestoredDownload_EtagMismatch) {
TestDownloadHttpResponse::Parameters parameters;
GURL url = TestDownloadHttpResponse::GetNextURLForDownload();
GURL server_url = embedded_test_server()->GetURL(url.host(), url.path());
TestDownloadHttpResponse::StartServing(parameters, server_url);
base::FilePath intermediate_file_path =
GetDownloadDirectory().AppendASCII("intermediate");
std::vector<GURL> url_chain;
const int kIntermediateSize = 1331;
std::string output = TestDownloadHttpResponse::GetPatternBytes(
parameters.pattern_generator_seed + 1, 0, kIntermediateSize);
{
base::ScopedAllowBlockingForTesting allow_blocking;
ASSERT_TRUE(base::WriteFile(intermediate_file_path, output));
}
url_chain.push_back(server_url);
download::DownloadItem* download =
DownloadManagerForShell(shell())->CreateDownloadItem(
"F7FB1F59-7DE1-4845-AFDB-8A688F70F583", 1, intermediate_file_path,
base::FilePath(), url_chain, GURL(),
StoragePartitionConfig::CreateDefault(
shell()->web_contents()->GetBrowserContext()),
GURL(), GURL(), url::Origin(), "application/octet-stream",
"application/octet-stream", base::Time::Now(), base::Time(),
"fake-etag", std::string(), kIntermediateSize, parameters.size,
std::string(), download::DownloadItem::INTERRUPTED,
download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
download::DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED, false,
base::Time(), false,
std::vector<download::DownloadItem::ReceivedSlice>());
ClearAutoResumptionCount(download);
download->Resume(false);
WaitForCompletion(download);
EXPECT_EQ(kIntermediateSize, download->GetBytesWasted());
EXPECT_FALSE(PathExists(intermediate_file_path));
ReadAndVerifyFileContents(parameters.pattern_generator_seed,
parameters.size,
download->GetTargetFilePath());
const TestDownloadResponseHandler::CompletedRequests& completed_requests =
test_response_handler()->completed_requests();
// There's only one network request issued. The If-Range header allows the
// server to respond with the entire entity in one go. The existing contents
// of the file should be discarded, and overwritten by the new contents.
ASSERT_EQ(1u, completed_requests.size());
EXPECT_EQ(parameters.size, completed_requests[0]->transferred_byte_count);
}
IN_PROC_BROWSER_TEST_F(DownloadContentTest,
ResumeRestoredDownload_CorrectHash) {
TestDownloadHttpResponse::Parameters parameters;
GURL url = TestDownloadHttpResponse::GetNextURLForDownload();
GURL server_url = embedded_test_server()->GetURL(url.host(), url.path());
TestDownloadHttpResponse::StartServing(parameters, server_url);
base::FilePath intermediate_file_path =
GetDownloadDirectory().AppendASCII("intermediate");
std::vector<GURL> url_chain;
const int kIntermediateSize = 1331;
std::string output = TestDownloadHttpResponse::GetPatternBytes(
parameters.pattern_generator_seed, 0, kIntermediateSize);
{
base::ScopedAllowBlockingForTesting allow_blocking;
ASSERT_TRUE(base::WriteFile(intermediate_file_path, output));
}
// SHA-256 hash of the pattern bytes in buffer.
static const uint8_t kPartialHash[] = {
0x77, 0x14, 0xfd, 0x83, 0x06, 0x15, 0x10, 0x7a, 0x47, 0x15, 0xd3,
0xcf, 0xdd, 0x46, 0xa2, 0x61, 0x96, 0xff, 0xc3, 0xbb, 0x49, 0x30,
0xaf, 0x31, 0x3a, 0x64, 0x0b, 0xd5, 0xfa, 0xb1, 0xe3, 0x81};
url_chain.push_back(server_url);
download::DownloadItem* download =
DownloadManagerForShell(shell())->CreateDownloadItem(
"F7FB1F59-7DE1-4845-AFDB-8A688F70F583", 1, intermediate_file_path,
base::FilePath(), url_chain, GURL(),
StoragePartitionConfig::CreateDefault(
shell()->web_contents()->GetBrowserContext()),
GURL(), GURL(), url::Origin(), "application/octet-stream",
"application/octet-stream", base::Time::Now(), base::Time(),
parameters.etag, std::string(), kIntermediateSize, parameters.size,
std::string(std::begin(kPartialHash), std::end(kPartialHash)),
download::DownloadItem::INTERRUPTED,
download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
download::DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED, false,
base::Time(), false,
std::vector<download::DownloadItem::ReceivedSlice>());
ClearAutoResumptionCount(download);
download->Resume(false);
WaitForCompletion(download);
EXPECT_FALSE(PathExists(intermediate_file_path));
ReadAndVerifyFileContents(parameters.pattern_generator_seed,
parameters.size,
download->GetTargetFilePath());
const TestDownloadResponseHandler::CompletedRequests& completed_requests =
test_response_handler()->completed_requests();
// There's only one network request issued, and that is for the remainder of
// the file.
ASSERT_EQ(1u, completed_requests.size());
EXPECT_EQ(parameters.size - kIntermediateSize,
completed_requests[0]->transferred_byte_count);
// SHA-256 hash of the entire 102400 bytes in the target file.
static const uint8_t kFullHash[] = {
0xa7, 0x44, 0x49, 0x86, 0x24, 0xc6, 0x84, 0x6c, 0x89, 0xdf, 0xd8,
0xec, 0xa0, 0xe0, 0x61, 0x12, 0xdc, 0x80, 0x13, 0xf2, 0x83, 0x49,
0xa9, 0x14, 0x52, 0x32, 0xf0, 0x95, 0x20, 0xca, 0x5b, 0x30};
EXPECT_EQ(std::string(std::begin(kFullHash), std::end(kFullHash)),
download->GetHash());
}
IN_PROC_BROWSER_TEST_F(DownloadContentTest, ResumeRestoredDownload_WrongHash) {
TestDownloadHttpResponse::Parameters parameters;
GURL url = TestDownloadHttpResponse::GetNextURLForDownload();
GURL server_url = embedded_test_server()->GetURL(url.host(), url.path());
TestDownloadHttpResponse::StartServing(parameters, server_url);
base::FilePath intermediate_file_path =
GetDownloadDirectory().AppendASCII("intermediate");
std::vector<GURL> url_chain;
const int kIntermediateSize = 1331;
std::vector<char> buffer(kIntermediateSize);
{
base::ScopedAllowBlockingForTesting allow_blocking;
ASSERT_TRUE(base::WriteFile(intermediate_file_path,
{buffer.data(), buffer.size()}));
}
// SHA-256 hash of the expected pattern bytes in buffer. This doesn't match
// the current contents of the intermediate file which should all be 0.
static const uint8_t kPartialHash[] = {
0x77, 0x14, 0xfd, 0x83, 0x06, 0x15, 0x10, 0x7a, 0x47, 0x15, 0xd3,
0xcf, 0xdd, 0x46, 0xa2, 0x61, 0x96, 0xff, 0xc3, 0xbb, 0x49, 0x30,
0xaf, 0x31, 0x3a, 0x64, 0x0b, 0xd5, 0xfa, 0xb1, 0xe3, 0x81};
url_chain.push_back(server_url);
download::DownloadItem* download =
DownloadManagerForShell(shell())->CreateDownloadItem(
"F7FB1F59-7DE1-4845-AFDB-8A688F70F583", 1, intermediate_file_path,
base::FilePath(), url_chain, GURL(),
StoragePartitionConfig::CreateDefault(
shell()->web_contents()->GetBrowserContext()),
GURL(), GURL(), url::Origin(), "application/octet-stream",
"application/octet-stream", base::Time::Now(), base::Time(),
parameters.etag, std::string(), kIntermediateSize, parameters.size,
std::string(std::begin(kPartialHash), std::end(kPartialHash)),
download::DownloadItem::INTERRUPTED,
download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
download::DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED, false,
base::Time(), false,
std::vector<download::DownloadItem::ReceivedSlice>());
ClearAutoResumptionCount(download);
download->Resume(false);
WaitForCompletion(download);
EXPECT_FALSE(PathExists(intermediate_file_path));
ReadAndVerifyFileContents(parameters.pattern_generator_seed,
parameters.size,
download->GetTargetFilePath());
const TestDownloadResponseHandler::CompletedRequests& completed_requests =
test_response_handler()->completed_requests();
// There will be two requests. The first one is issued optimistically assuming
// that the intermediate file exists and matches the size expectations set
// forth in the download metadata (i.e. assuming that a 1331 byte file exists
// at |intermediate_file_path|.
//
// However, once the response is received, DownloadFile will report that the
// intermediate file doesn't match the expected hash.
//
// The second request reads the entire entity.
//
// N.b. we can't make any assumptions about how many bytes are transferred by
// the first request since response data will be bufferred until DownloadFile
// is done initializing.
//
// TODO(asanka): Ideally we'll check that the intermediate file matches
// expectations prior to issuing the first resumption request.
ASSERT_EQ(2u, completed_requests.size());
EXPECT_EQ(parameters.size, completed_requests[1]->transferred_byte_count);
// SHA-256 hash of the entire 102400 bytes in the target file.
static const uint8_t kFullHash[] = {
0xa7, 0x44, 0x49, 0x86, 0x24, 0xc6, 0x84, 0x6c, 0x89, 0xdf, 0xd8,
0xec, 0xa0, 0xe0, 0x61, 0x12, 0xdc, 0x80, 0x13, 0xf2, 0x83, 0x49,
0xa9, 0x14, 0x52, 0x32, 0xf0, 0x95, 0x20, 0xca, 0x5b, 0x30};
EXPECT_EQ(std::string(std::begin(kFullHash), std::end(kFullHash)),
download->GetHash());
}
IN_PROC_BROWSER_TEST_F(DownloadContentTest, ResumeRestoredDownload_ShortFile) {
TestDownloadHttpResponse::Parameters parameters;
GURL url = TestDownloadHttpResponse::GetNextURLForDownload();
GURL server_url = embedded_test_server()->GetURL(url.host(), url.path());
TestDownloadHttpResponse::StartServing(parameters, server_url);
base::FilePath intermediate_file_path =
GetDownloadDirectory().AppendASCII("intermediate");
std::vector<GURL> url_chain;
const int kIntermediateSize = 1331;
// Size of file is slightly shorter than the size known to
// download::DownloadItem.
std::string output = TestDownloadHttpResponse::GetPatternBytes(
parameters.pattern_generator_seed, 0, kIntermediateSize - 100);
{
base::ScopedAllowBlockingForTesting allow_blocking;
ASSERT_TRUE(base::WriteFile(intermediate_file_path, output));
}
url_chain.push_back(server_url);
download::DownloadItem* download =
DownloadManagerForShell(shell())->CreateDownloadItem(
"F7FB1F59-7DE1-4845-AFDB-8A688F70F583", 1, intermediate_file_path,
base::FilePath(), url_chain, GURL(),
StoragePartitionConfig::CreateDefault(
shell()->web_contents()->GetBrowserContext()),
GURL(), GURL(), url::Origin(), "application/octet-stream",
"application/octet-stream", base::Time::Now(), base::Time(),
parameters.etag, std::string(), kIntermediateSize, parameters.size,
std::string(), download::DownloadItem::INTERRUPTED,
download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
download::DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED, false,
base::Time(), false,
std::vector<download::DownloadItem::ReceivedSlice>());
ClearAutoResumptionCount(download);
download->Resume(false);
WaitForCompletion(download);
EXPECT_FALSE(PathExists(intermediate_file_path));
ReadAndVerifyFileContents(parameters.pattern_generator_seed,
parameters.size,
download->GetTargetFilePath());
const TestDownloadResponseHandler::CompletedRequests& completed_requests =
test_response_handler()->completed_requests();
// There will be two requests. The first one is issued optimistically assuming
// that the intermediate file exists and matches the size expectations set
// forth in the download metadata (i.e. assuming that a 1331 byte file exists
// at |intermediate_file_path|.
//
// However, once the response is received, DownloadFile will report that the
// intermediate file is too short and hence the download is marked interrupted
// again.
//
// The second request reads the entire entity.
//
// N.b. we can't make any assumptions about how many bytes are transferred by
// the first request since response data will be bufferred until DownloadFile
// is done initializing.
//
// TODO(asanka): Ideally we'll check that the intermediate file matches
// expectations prior to issuing the first resumption request.
ASSERT_EQ(2u, completed_requests.size());
EXPECT_EQ(parameters.size, completed_requests[1]->transferred_byte_count);
}
IN_PROC_BROWSER_TEST_F(DownloadContentTest, ResumeRestoredDownload_LongFile) {
// These numbers are sufficiently large that the intermediate file won't be
// read in a single Read().
const int kFileSize = 1024 * 1024;
const int kIntermediateSize = kFileSize / 2 + 111;
TestDownloadHttpResponse::Parameters parameters;
parameters.size = kFileSize;
GURL url = TestDownloadHttpResponse::GetNextURLForDownload();
GURL server_url = embedded_test_server()->GetURL(url.host(), url.path());
TestDownloadHttpResponse::StartServing(parameters, server_url);
base::FilePath intermediate_file_path =
GetDownloadDirectory().AppendASCII("intermediate");
std::vector<GURL> url_chain;
// Size of file is slightly longer than the size known to
// download::DownloadItem.
std::string output = TestDownloadHttpResponse::GetPatternBytes(
parameters.pattern_generator_seed, 0, kIntermediateSize + 100);
{
base::ScopedAllowBlockingForTesting allow_blocking;
ASSERT_TRUE(base::WriteFile(intermediate_file_path, output));
}
url_chain.push_back(server_url);
download::DownloadItem* download =
DownloadManagerForShell(shell())->CreateDownloadItem(
"F7FB1F59-7DE1-4845-AFDB-8A688F70F583", 1, intermediate_file_path,
base::FilePath(), url_chain, GURL(),
StoragePartitionConfig::CreateDefault(
shell()->web_contents()->GetBrowserContext()),
GURL(), GURL(), url::Origin(), "application/octet-stream",
"application/octet-stream", base::Time::Now(), base::Time(),
parameters.etag, std::string(), kIntermediateSize, parameters.size,
std::string(), download::DownloadItem::INTERRUPTED,
download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
download::DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED, false,
base::Time(), false,
std::vector<download::DownloadItem::ReceivedSlice>());
ClearAutoResumptionCount(download);
download->Resume(false);
WaitForCompletion(download);
// The amount "extra" that was added to the file.
EXPECT_EQ(100, download->GetBytesWasted());
EXPECT_FALSE(PathExists(intermediate_file_path));
ReadAndVerifyFileContents(parameters.pattern_generator_seed,
parameters.size,
download->GetTargetFilePath());
const TestDownloadResponseHandler::CompletedRequests& completed_requests =
test_response_handler()->completed_requests();
// There should be only one request. The intermediate file should be truncated
// to the expected size, and the request should be issued for the remainder.
//
// TODO(asanka): Ideally we'll check that the intermediate file matches
// expectations prior to issuing the first resumption request.
ASSERT_EQ(1u, completed_requests.size());
EXPECT_EQ(parameters.size - kIntermediateSize,
completed_requests[0]->transferred_byte_count);
}
// Test that the referrer header is set correctly for a download that's resumed
// partially.
IN_PROC_BROWSER_TEST_F(DownloadContentTest, ReferrerForPartialResumption) {
SetupErrorInjectionDownloads();
GURL url = TestDownloadHttpResponse::GetNextURLForDownload();
GURL server_url = embedded_test_server()->GetURL(url.host(), url.path());
TestDownloadHttpResponse::Parameters parameters =
TestDownloadHttpResponse::Parameters::WithSingleInterruption(
inject_error_callback());
TestDownloadHttpResponse::StartServing(parameters, server_url);
GURL document_url = embedded_test_server()->GetURL(
std::string("/download/download-link.html?dl=")
.append(server_url.spec()));
download::DownloadItem* download =
StartDownloadAndReturnItem(shell(), document_url);
WaitForInterrupt(download);
parameters.ClearInjectedErrors();
TestDownloadHttpResponse::StartServing(parameters, server_url);
download->Resume(false);
WaitForCompletion(download);
ASSERT_EQ(parameters.size, download->GetReceivedBytes());
ASSERT_EQ(parameters.size, download->GetTotalBytes());
ASSERT_NO_FATAL_FAILURE(ReadAndVerifyFileContents(
parameters.pattern_generator_seed, parameters.size,
download->GetTargetFilePath()));
const TestDownloadResponseHandler::CompletedRequests& requests =
test_response_handler()->completed_requests();
ASSERT_GE(2u, requests.size());
net::test_server::HttpRequest last_request = requests.back()->http_request;
ASSERT_TRUE(
base::Contains(last_request.headers, net::HttpRequestHeaders::kReferer));
EXPECT_EQ(last_request.headers.at(net::HttpRequestHeaders::kReferer),
document_url.DeprecatedGetOriginAsURL().spec());
}
// Test that the referrer header is dropped for HTTP downloads from HTTPS.
IN_PROC_BROWSER_TEST_F(DownloadContentTest, ReferrerForHTTPS) {
net::EmbeddedTestServer https_origin(
net::EmbeddedTestServer::Type::TYPE_HTTPS);
net::EmbeddedTestServer http_origin(net::EmbeddedTestServer::Type::TYPE_HTTP);
https_origin.ServeFilesFromDirectory(GetTestFilePath("download", ""));
http_origin.RegisterRequestHandler(
CreateBasicResponseHandler("/download", net::HTTP_OK, base::StringPairs(),
"application/octet-stream", "Hello"));
ASSERT_TRUE(https_origin.InitializeAndListen());
ASSERT_TRUE(http_origin.InitializeAndListen());
GURL download_url = http_origin.GetURL("/download");
GURL referrer_url = https_origin.GetURL(
std::string("/download-link.html?dl=") + download_url.spec());
https_origin.StartAcceptingConnections();
http_origin.StartAcceptingConnections();
download::DownloadItem* download =
StartDownloadAndReturnItem(shell(), referrer_url);
WaitForCompletion(download);
ASSERT_EQ(5, download->GetReceivedBytes());
EXPECT_EQ("", download->GetReferrerUrl().spec());
ASSERT_TRUE(https_origin.ShutdownAndWaitUntilComplete());
ASSERT_TRUE(http_origin.ShutdownAndWaitUntilComplete());
}
// Check that the site-for-cookies is correctly updated when downloading a file
// that redirects cross site, by verifying that a SameSite cookie can be set
// following a cross-site redirect.
// (It is not enough to redirect across origins with the same host but different
// port numbers, because cookies do not respect ports.)
IN_PROC_BROWSER_TEST_F(DownloadContentTest, UpdateSiteForCookies) {
net::EmbeddedTestServer site_a;
net::EmbeddedTestServer site_b;
base::StringPairs cookie_headers;
cookie_headers.push_back(std::make_pair(std::string("Set-Cookie"),
std::string("A=lax; SameSite=Lax")));
cookie_headers.push_back(std::make_pair(
std::string("Set-Cookie"), std::string("B=strict; SameSite=Strict")));
// This will request a URL on b.test, which redirects to a url that sets the
// cookies on a.test.
site_a.RegisterRequestHandler(CreateBasicResponseHandler(
"/sets-samesite-cookies", net::HTTP_OK, cookie_headers,
"application/octet-stream", "abcd"));
ASSERT_TRUE(site_a.Start());
site_b.RegisterRequestHandler(
CreateRedirectHandler("/redirected-download",
site_a.GetURL("a.test", "/sets-samesite-cookies")));
ASSERT_TRUE(site_b.Start());
// Download the file.
SetupEnsureNoPendingDownloads();
std::unique_ptr<download::DownloadUrlParameters> download_parameters(
DownloadRequestUtils::CreateDownloadForWebContentsMainFrame(
shell()->web_contents(),
site_b.GetURL("b.test", "/redirected-download"),
TRAFFIC_ANNOTATION_FOR_TESTS));
std::unique_ptr<DownloadTestObserver> observer(CreateWaiter(shell(), 1));
DownloadManagerForShell(shell())->DownloadUrl(std::move(download_parameters));
observer->WaitForFinished();
// Get the important info from other threads and check it.
EXPECT_TRUE(EnsureNoPendingDownloads());
std::vector<raw_ptr<download::DownloadItem, VectorExperimental>> downloads;
DownloadManagerForShell(shell())->GetAllDownloads(&downloads);
ASSERT_EQ(1u, downloads.size());
ASSERT_EQ(download::DownloadItem::COMPLETE, downloads[0]->GetState());
// Check that the cookies were correctly set on a.test.
EXPECT_EQ("A=lax; B=strict",
content::GetCookies(shell()->web_contents()->GetBrowserContext(),
site_a.GetURL("a.test", "/")));
}
// Tests that if `update_first_party_url_on_redirect` is set to false, download
// will not behave like a top-level frame navigation and SameSite=Strict cookies
// will not be set on a redirection.
IN_PROC_BROWSER_TEST_F(
DownloadContentTest,
SiteForCookies_DownloadUrl_NotUpdateFirstPartyUrlOnRedirect) {
net::EmbeddedTestServer site_a;
net::EmbeddedTestServer site_b;
base::StringPairs cookie_headers;
cookie_headers.push_back(std::make_pair(
std::string("Set-Cookie"), std::string("A=strict; SameSite=Strict")));
cookie_headers.push_back(std::make_pair(std::string("Set-Cookie"),
std::string("B=lax; SameSite=Lax")));
// This will request a URL on b.test, which redirects to a url that sets the
// cookies on a.test.
site_a.RegisterRequestHandler(CreateBasicResponseHandler(
"/sets-samesite-cookies", net::HTTP_OK, cookie_headers,
"application/octet-stream", "abcd"));
ASSERT_TRUE(site_a.Start());
site_b.RegisterRequestHandler(
CreateRedirectHandler("/redirected-download",
site_a.GetURL("a.test", "/sets-samesite-cookies")));
ASSERT_TRUE(site_b.Start());
// Download the file.
SetupEnsureNoPendingDownloads();
std::unique_ptr<download::DownloadUrlParameters> download_parameters(
DownloadRequestUtils::CreateDownloadForWebContentsMainFrame(
shell()->web_contents(),
site_b.GetURL("b.test", "/redirected-download"),
TRAFFIC_ANNOTATION_FOR_TESTS));
download_parameters->set_update_first_party_url_on_redirect(false);
std::unique_ptr<DownloadTestObserver> observer(CreateWaiter(shell(), 1));
DownloadManagerForShell(shell())->DownloadUrl(std::move(download_parameters));
observer->WaitForFinished();
// Get the important info from other threads and check it.
EXPECT_TRUE(EnsureNoPendingDownloads());
std::vector<raw_ptr<download::DownloadItem, VectorExperimental>> downloads;
DownloadManagerForShell(shell())->GetAllDownloads(&downloads);
ASSERT_EQ(1u, downloads.size());
ASSERT_EQ(download::DownloadItem::COMPLETE, downloads[0]->GetState());
// Check that the cookies were not set on a.test.
EXPECT_EQ("",
content::GetCookies(shell()->web_contents()->GetBrowserContext(),
site_a.GetURL("a.test", "/")));
}
// Verifies that isolation info set in DownloadUrlParameters can be populated.
IN_PROC_BROWSER_TEST_F(DownloadContentTest,
SiteForCookies_DownloadUrl_IsolationInfoPopulated) {
// Setup a server that sets cookie.
net::EmbeddedTestServer site_a;
base::StringPairs cookie_headers;
cookie_headers.push_back(std::make_pair(std::string("Set-Cookie"),
std::string("A=lax; SameSite=Lax")));
cookie_headers.push_back(std::make_pair(
std::string("Set-Cookie"), std::string("B=strict; SameSite=Strict")));
site_a.RegisterRequestHandler(CreateBasicResponseHandler(
"/sets-samesite-cookies", net::HTTP_OK, cookie_headers,
"application/octet-stream", "abcd"));
ASSERT_TRUE(site_a.Start());
// Download the file.
SetupEnsureNoPendingDownloads();
GURL download_url = site_a.GetURL("a.test", "/sets-samesite-cookies");
std::unique_ptr<download::DownloadUrlParameters> download_parameters(
DownloadRequestUtils::CreateDownloadForWebContentsMainFrame(
shell()->web_contents(), download_url, TRAFFIC_ANNOTATION_FOR_TESTS));
// Mark this request a third party request, cookie should be blocked.
net::IsolationInfo isolation_info =
net::IsolationInfo::CreateForInternalRequest(
url::Origin::Create(GURL("http://www.example.com")));
download_parameters->set_isolation_info(isolation_info);
// Verify the isolation info.
std::unique_ptr<DownloadTestObserver> observer(CreateWaiter(shell(), 1));
ExpectRequestIsolationInfo(download_url, isolation_info,
base::BindLambdaForTesting([&]() {
DownloadManagerForShell(shell())->DownloadUrl(
std::move(download_parameters));
observer->WaitForFinished();
}));
// Get the important info from other threads and check it.
EXPECT_TRUE(EnsureNoPendingDownloads());
// Check no cookies are written for URL a.test since it's a third party
// cookie.
EXPECT_TRUE(content::GetCookies(shell()->web_contents()->GetBrowserContext(),
download_url)
.empty());
}
// A filename suggestion specified via a @download attribute should not be
// effective if the final download URL is in another origin from the original
// download URL.
IN_PROC_BROWSER_TEST_F(DownloadContentTest,
DownloadAttributeCrossOriginRedirect) {
net::EmbeddedTestServer origin_one;
net::EmbeddedTestServer origin_two;
ASSERT_TRUE(origin_one.InitializeAndListen());
ASSERT_TRUE(origin_two.InitializeAndListen());
// The download-attribute.html page contains an anchor element whose href is
// set to the value of the query parameter (specified as |target| in the URL
// below). The suggested filename for the anchor is 'suggested-filename'. When
// the page is loaded, a script simulates a click on the anchor, triggering a
// download of the target URL.
//
// We construct two test servers; origin_one and origin_two. Once started, the
// server URLs will differ by the port number. Therefore they will be in
// different origins.
GURL download_url = origin_one.GetURL("/ping");
GURL referrer_url = origin_one.GetURL(
std::string("/download-attribute.html?target=") + download_url.spec());
GURL final_url = origin_two.GetURL(kOriginTwo, "/download");
url::Origin final_url_origin = url::Origin::Create(final_url);
// The IsolationInfo after the cross-site redirect should be the same as
// if there were a top-level navigation to the final URL.
net::IsolationInfo expected_isolation_info = net::IsolationInfo::Create(
net::IsolationInfo::RequestType::kMainFrame, final_url_origin,
final_url_origin, net::SiteForCookies::FromOrigin(final_url_origin));
// <origin_one>/download-attribute.html initiates a download of
// <origin_one>/ping, which redirects to <origin_two>/download.
origin_one.ServeFilesFromDirectory(GetTestFilePath("download", ""));
origin_one.RegisterRequestHandler(CreateRedirectHandler("/ping", final_url));
origin_one.StartAcceptingConnections();
origin_two.RegisterRequestHandler(
CreateBasicResponseHandler("/download", net::HTTP_OK, base::StringPairs(),
"application/octet-stream", "Hello"));
origin_two.StartAcceptingConnections();
ExpectRequestIsolationInfo(
final_url, expected_isolation_info, base::BindLambdaForTesting([&]() {
NavigateToCommittedURLAndWaitForDownload(
shell(), referrer_url, download::DownloadItem::COMPLETE);
}));
std::vector<raw_ptr<download::DownloadItem, VectorExperimental>> downloads;
DownloadManagerForShell(shell())->GetAllDownloads(&downloads);
ASSERT_EQ(1u, downloads.size());
EXPECT_EQ(FILE_PATH_LITERAL("download"),
downloads[0]->GetTargetFilePath().BaseName().value());
ASSERT_TRUE(origin_one.ShutdownAndWaitUntilComplete());
ASSERT_TRUE(origin_two.ShutdownAndWaitUntilComplete());
}
// A filename suggestion specified via a @download attribute should not be
// effective if there are cross origin redirects in the middle of the redirect
// chain.
IN_PROC_BROWSER_TEST_F(DownloadContentTest,
DownloadAttributeSameOriginRedirect) {
net::EmbeddedTestServer origin_one;
net::EmbeddedTestServer origin_two;
ASSERT_TRUE(origin_one.InitializeAndListen());
ASSERT_TRUE(origin_two.InitializeAndListen());
// The download-attribute.html page contains an anchor element whose href is
// set to the value of the query parameter (specified as |target| in the URL
// below). The suggested filename for the anchor is 'suggested-filename'. When
// the page is loaded, a script simulates a click on the anchor, triggering a
// download of the target URL.
//
// We construct two test servers; origin_one and origin_two. Once started, the
// server URLs will differ by the port number. Therefore they will be in
// different origins.
GURL download_url = origin_one.GetURL("/ping");
GURL referrer_url = origin_one.GetURL(
std::string("/download-attribute.html?target=") + download_url.spec());
origin_one.ServeFilesFromDirectory(GetTestFilePath("download", ""));
// <origin_one>/download-attribute.html initiates a download of
// <origin_one>/ping, which redirects to <origin_two>/pong, and then finally
// to <origin_one>/download.
origin_one.RegisterRequestHandler(
CreateRedirectHandler("/ping", origin_two.GetURL("/pong")));
origin_two.RegisterRequestHandler(
CreateRedirectHandler("/pong", origin_one.GetURL("/download")));
origin_one.RegisterRequestHandler(
CreateBasicResponseHandler("/download", net::HTTP_OK, base::StringPairs(),
"application/octet-stream", "Hello"));
origin_one.StartAcceptingConnections();
origin_two.StartAcceptingConnections();
NavigateToCommittedURLAndWaitForDownload(shell(), referrer_url,
download::DownloadItem::COMPLETE);
std::vector<raw_ptr<download::DownloadItem, VectorExperimental>> downloads;
DownloadManagerForShell(shell())->GetAllDownloads(&downloads);
ASSERT_EQ(1u, downloads.size());
EXPECT_EQ(FILE_PATH_LITERAL("download"),
downloads[0]->GetTargetFilePath().BaseName().value());
ASSERT_TRUE(origin_one.ShutdownAndWaitUntilComplete());
ASSERT_TRUE(origin_two.ShutdownAndWaitUntilComplete());
}
// A file type that Blink can handle should not be downloaded if there are cross
// origin redirects in the middle of the redirect chain.
// TODO(crbug.com/40650833): Fix flakes on various bots and re-enable
// this test.
IN_PROC_BROWSER_TEST_F(DownloadContentTest,
DISABLED_DownloadAttributeSameOriginRedirectNavigation) {
net::EmbeddedTestServer origin_one;
net::EmbeddedTestServer origin_two;
ASSERT_TRUE(origin_one.InitializeAndListen());
ASSERT_TRUE(origin_two.InitializeAndListen());
// The download-attribute.html page contains an anchor element whose href is
// set to the value of the query parameter (specified as |target| in the URL
// below). The suggested filename for the anchor is 'suggested-filename'. When
// the page is loaded, a script simulates a click on the anchor, triggering a
// download of the target URL.
//
// We construct two test servers; origin_one and origin_two. Once started, the
// server URLs will differ by the port number. Therefore they will be in
// different origins.
GURL download_url = origin_one.GetURL("/ping");
GURL referrer_url = origin_one.GetURL(
std::string("/download-attribute.html?target=") + download_url.spec());
origin_one.ServeFilesFromDirectory(GetTestFilePath("download", ""));
// <origin_one>/download-attribute.html initiates a download of
// <origin_one>/ping, which redirects to <origin_two>/download. The latter
// serves an HTML document.
origin_one.RegisterRequestHandler(
CreateRedirectHandler("/ping", origin_two.GetURL("/download")));
origin_two.RegisterRequestHandler(
CreateBasicResponseHandler("/download", net::HTTP_OK, base::StringPairs(),
"text/html", "<title>hello</title>"));
origin_one.StartAcceptingConnections();
origin_two.StartAcceptingConnections();
std::u16string expected_title(u"hello");
TitleWatcher observer(shell()->web_contents(), expected_title);
EXPECT_TRUE(
NavigateToURL(shell(), referrer_url,
origin_two.GetURL("/download") /* expected_commit_url */));
ASSERT_EQ(expected_title, observer.WaitAndGetTitle());
std::vector<raw_ptr<download::DownloadItem, VectorExperimental>> downloads;
DownloadManagerForShell(shell())->GetAllDownloads(&downloads);
ASSERT_EQ(0u, downloads.size());
ASSERT_TRUE(origin_one.ShutdownAndWaitUntilComplete());
ASSERT_TRUE(origin_two.ShutdownAndWaitUntilComplete());
}
// Tests that if a renderer initiated download triggers cross origin in the
// redirect chain, the visible URL of the current tab shouldn't change.
IN_PROC_BROWSER_TEST_F(DownloadContentTest,
DownloadAttributeSameOriginRedirectNavigationTimeOut) {
net::EmbeddedTestServer origin_one;
net::EmbeddedTestServer origin_two;
ASSERT_TRUE(origin_one.InitializeAndListen());
ASSERT_TRUE(origin_two.InitializeAndListen());
// The download-attribute.html page contains an anchor element whose href is
// set to the value of the query parameter (specified as |target| in the URL
// below). The suggested filename for the anchor is 'suggested-filename'. When
// the page is loaded, a script simulates a click on the anchor, triggering a
// download of the target URL.
//
// We construct two test servers; origin_one and origin_two. Once started, the
// server URLs will differ by the port number. Therefore they will be in
// different origins.
GURL download_url = origin_one.GetURL("/ping");
GURL referrer_url = origin_one.GetURL(
std::string("/download-attribute.html?target=") + download_url.spec());
origin_one.ServeFilesFromDirectory(GetTestFilePath("download", ""));
// <origin_one>/download-attribute.html initiates a download of
// <origin_one>/ping, which redirects to <origin_two>/download. The latter
// will time out.
origin_one.RegisterRequestHandler(
CreateRedirectHandler("/ping", origin_two.GetURL("/download")));
origin_one.StartAcceptingConnections();
NavigationStartObserver obs(shell()->web_contents());
NavigationController::LoadURLParams params(referrer_url);
params.transition_type = ui::PageTransitionFromInt(
ui::PAGE_TRANSITION_TYPED | ui::PAGE_TRANSITION_FROM_ADDRESS_BAR);
shell()->web_contents()->GetController().LoadURLWithParams(params);
shell()->web_contents()->Focus();
// Waiting for 2 navigation to happen, one for the original request, one for
// the redirect.
obs.WaitForFinished(2);
EXPECT_EQ(referrer_url, shell()->web_contents()->GetVisibleURL());
ASSERT_TRUE(origin_one.ShutdownAndWaitUntilComplete());
origin_two.StartAcceptingConnections();
ASSERT_TRUE(origin_two.ShutdownAndWaitUntilComplete());
}
// A download initiated by the user via alt-click on a link should download,
// even when redirected cross origin.
//
// Alt-click doesn't make sense on Android, and download a HTML file results
// in an intent, so just skip.
#if !BUILDFLAG(IS_ANDROID)
IN_PROC_BROWSER_TEST_F(DownloadContentTest,
DownloadAttributeSameOriginRedirectAltClick) {
net::EmbeddedTestServer origin_one;
net::EmbeddedTestServer origin_two;
ASSERT_TRUE(origin_one.InitializeAndListen());
ASSERT_TRUE(origin_two.InitializeAndListen());
// The download-attribute.html page contains an anchor element whose href is
// set to the value of the query parameter (specified as |target| in the URL
// below). The suggested filename for the anchor is 'suggested-filename'. We
// will later send a "real" click to the anchor, triggering a download of the
// target URL.
//
// We construct two test servers; origin_one and origin_two. Once started, the
// server URLs will differ by the port number. Therefore they will be in
// different origins.
GURL download_url = origin_one.GetURL("/ping");
GURL referrer_url = origin_one.GetURL(
std::string("/download-attribute.html?noclick=") + download_url.spec());
origin_one.ServeFilesFromDirectory(GetTestFilePath("download", ""));
// <origin_one>/download-attribute.html initiates a download of
// <origin_one>/ping, which redirects to <origin_two>/download. The latter
// serves an HTML document.
origin_one.RegisterRequestHandler(
CreateRedirectHandler("/ping", origin_two.GetURL("/download")));
origin_two.RegisterRequestHandler(
CreateBasicResponseHandler("/download", net::HTTP_OK, base::StringPairs(),
"text/html", "<title>hello</title>"));
origin_one.StartAcceptingConnections();
origin_two.StartAcceptingConnections();
std::unique_ptr<DownloadTestObserver> observer(CreateWaiter(shell(), 1));
EXPECT_TRUE(NavigateToURL(shell(), referrer_url));
SimulateEndOfPaintHoldingOnPrimaryMainFrame(shell()->web_contents());
// Alt-click the link.
blink::WebMouseEvent mouse_event(
blink::WebInputEvent::Type::kMouseDown, blink::WebInputEvent::kAltKey,
blink::WebInputEvent::GetStaticTimeStampForTests());
mouse_event.button = blink::WebMouseEvent::Button::kLeft;
mouse_event.SetPositionInWidget(15, 15);
mouse_event.click_count = 1;
shell()
->web_contents()
->GetPrimaryMainFrame()
->GetRenderViewHost()
->GetWidget()
->ForwardMouseEvent(mouse_event);
mouse_event.SetType(blink::WebInputEvent::Type::kMouseUp);
shell()
->web_contents()
->GetPrimaryMainFrame()
->GetRenderViewHost()
->GetWidget()
->ForwardMouseEvent(mouse_event);
observer->WaitForFinished();
EXPECT_EQ(
1u, observer->NumDownloadsSeenInState(download::DownloadItem::COMPLETE));
std::vector<raw_ptr<download::DownloadItem, VectorExperimental>> downloads;
DownloadManagerForShell(shell())->GetAllDownloads(&downloads);
ASSERT_EQ(1u, downloads.size());
base::FilePath file_name = downloads[0]->GetTargetFilePath().BaseName();
#if BUILDFLAG(IS_WIN)
// Windows file extension depends on system registry.
EXPECT_TRUE(file_name.value() == FILE_PATH_LITERAL("download.htm") ||
file_name.value() == FILE_PATH_LITERAL("download.html"));
#else
EXPECT_EQ(FILE_PATH_LITERAL("download.html"), file_name.value());
#endif
ASSERT_TRUE(origin_one.ShutdownAndWaitUntilComplete());
ASSERT_TRUE(origin_two.ShutdownAndWaitUntilComplete());
}
#endif // !BUILDFLAG(IS_ANDROID)
// Test that the suggested filename for data: URLs works.
IN_PROC_BROWSER_TEST_F(DownloadContentTest, DownloadAttributeDataUrl) {
net::EmbeddedTestServer server;
ASSERT_TRUE(server.InitializeAndListen());
GURL url = server.GetURL(std::string(
"/download-attribute.html?target=data:application/octet-stream, ..."));
server.ServeFilesFromDirectory(GetTestFilePath("download", ""));
server.StartAcceptingConnections();
NavigateToCommittedURLAndWaitForDownload(shell(), url,
download::DownloadItem::COMPLETE);
std::vector<raw_ptr<download::DownloadItem, VectorExperimental>> downloads;
DownloadManagerForShell(shell())->GetAllDownloads(&downloads);
ASSERT_EQ(1u, downloads.size());
EXPECT_EQ(FILE_PATH_LITERAL("suggested-filename"),
downloads[0]->GetTargetFilePath().BaseName().value());
// A link clicked by JavaScript should not have a gesture.
EXPECT_FALSE(downloads[0]->HasUserGesture());
ASSERT_TRUE(server.ShutdownAndWaitUntilComplete());
}
// A request for a non-existent same-origin resource should result in a
// DownloadItem that's created in an interrupted state.
IN_PROC_BROWSER_TEST_F(DownloadContentTest, DownloadAttributeServerError) {
GURL download_url =
embedded_test_server()->GetURL("/download/does-not-exist");
GURL document_url = embedded_test_server()->GetURL(
std::string("/download/download-attribute.html?target=") +
download_url.spec());
download::DownloadItem* download =
StartDownloadAndReturnItem(shell(), document_url);
WaitForInterrupt(download);
EXPECT_EQ(download::DOWNLOAD_INTERRUPT_REASON_SERVER_BAD_CONTENT,
download->GetLastReason());
}
// A cross-origin request that fails before it gets a response from the server
// should result in a network error page.
IN_PROC_BROWSER_TEST_F(DownloadContentTest, DownloadAttributeNetworkError) {
SetupErrorInjectionDownloads();
WebContents* content = shell()->web_contents();
GURL url = TestDownloadHttpResponse::GetNextURLForDownload();
GURL server_url = embedded_test_server()->GetURL(url.host(), url.path());
GURL document_url = embedded_test_server()->GetURL(
std::string("/download/download-attribute.html?target=") +
server_url.spec());
// Simulate a network failure by injecting an error before the response
// header.
TestDownloadHttpResponse::Parameters parameters;
parameters.injected_errors.push(-1);
parameters.inject_error_cb = inject_error_callback();
TestDownloadHttpResponse::StartServing(parameters, server_url);
content::TestNavigationManager navigation_document(content, document_url);
content::TestNavigationManager navigation_download(content, server_url);
shell()->LoadURL(document_url);
ASSERT_TRUE(navigation_document.WaitForNavigationFinished());
ASSERT_TRUE(navigation_download.WaitForNavigationFinished());
EXPECT_TRUE(navigation_document.was_successful());
EXPECT_FALSE(navigation_download.was_successful());
NavigationEntry* navigation_entry =
shell()->web_contents()->GetController().GetLastCommittedEntry();
EXPECT_EQ(PAGE_TYPE_ERROR, navigation_entry->GetPageType());
EXPECT_EQ(server_url, navigation_entry->GetURL());
}
// A request that fails due to it being rejected by policy should result in a
// corresponding navigation.
IN_PROC_BROWSER_TEST_F(DownloadContentTest, DownloadAttributeInvalidURL) {
GURL url = embedded_test_server()->GetURL(
"/download/download-attribute.html?target=about:version");
auto observer =
std::make_unique<content::TestNavigationObserver>(GURL(kBlockedURL));
observer->WatchExistingWebContents();
observer->StartWatchingNewWebContents();
shell()->LoadURL(url);
observer->WaitForNavigationFinished();
}
IN_PROC_BROWSER_TEST_F(DownloadContentTest, DownloadAttributeBlobURL) {
GURL document_url =
embedded_test_server()->GetURL("/download/download-attribute-blob.html");
download::DownloadItem* download =
StartDownloadAndReturnItem(shell(), document_url);
WaitForCompletion(download);
EXPECT_STREQ(FILE_PATH_LITERAL("suggested-filename.txt"),
download->GetTargetFilePath().BaseName().value().c_str());
}
class DownloadContentSameSiteCookieTest
: public DownloadContentTest,
public ::testing::WithParamInterface<bool> {
public:
DownloadContentSameSiteCookieTest() {
inner_feature_list_.InitWithFeatureState(
net::features::kCookieSameSiteConsidersRedirectChain,
DoesCookieSameSiteConsiderRedirectChain());
}
bool DoesCookieSameSiteConsiderRedirectChain() { return GetParam(); }
private:
base::test::ScopedFeatureList inner_feature_list_;
};
IN_PROC_BROWSER_TEST_P(DownloadContentSameSiteCookieTest,
DownloadAttributeSameSiteCookie) {
base::ScopedAllowBlockingForTesting allow_blocking;
net::EmbeddedTestServer test_server;
ASSERT_TRUE(test_server.InitializeAndListen());
test_server.ServeFilesFromDirectory(GetTestFilePath("download", ""));
test_server.RegisterRequestHandler(
CreateEchoCookieHandler("/downloadcookies"));
GURL echo_cookie_url = test_server.GetURL(kOriginOne, "/downloadcookies");
test_server.RegisterRequestHandler(
CreateRedirectHandler("/server-redirect", echo_cookie_url));
test_server.StartAcceptingConnections();
// download-attribute-same-site-cookie sets two cookies. One "A=B" is set with
// SameSite=Strict. The other one "B=C" doesn't have this flag. In general
// a[download] should behave the same as a top level navigation.
//
// The page then simulates a click on an <a download> link whose target is the
// /echoheader handler on the same origin.
download::DownloadItem* download = StartDownloadAndReturnItem(
shell(),
test_server.GetURL(
kOriginOne,
std::string("/download-attribute-same-site-cookie.html?target=") +
echo_cookie_url.spec()));
WaitForCompletion(download);
std::string file_contents;
ASSERT_TRUE(
base::ReadFileToString(download->GetTargetFilePath(), &file_contents));
// Initiator and target are same-origin. Both cookies should have been
// included in the request.
EXPECT_STREQ("A=B; B=C", file_contents.c_str());
// The test isn't complete without verifying that the initiator isn't being
// incorrectly set to be the same as the resource origin. The
// download-attribute test page doesn't set any cookies but creates a download
// via a <a download> link to the target URL. In this case:
//
// Initiator origin: kOriginTwo
// Resource origin: kOriginOne
// First-party origin: kOriginOne
download = StartDownloadAndReturnItem(
shell(), test_server.GetURL(
kOriginTwo, std::string("/download-attribute.html?target=") +
echo_cookie_url.spec()));
WaitForCompletion(download);
ASSERT_TRUE(
base::ReadFileToString(download->GetTargetFilePath(), &file_contents));
// The initiator and the target are not same-origin. Only the second cookie
// should be sent along with the request.
EXPECT_STREQ("B=C", file_contents.c_str());
// OriginOne redirects through OriginTwo. Because the redirect chain contains
// a cross-site redirect, SameSite=Strict cookies are not sent (if redirect
// chains are considered).
//
// Initiator origin: kOriginOne
// Redirect chain contains: kOriginTwo
// Resource origin: kOriginOne
// First-party origin: kOriginOne
GURL redirect_url = test_server.GetURL(kOriginTwo, "/server-redirect");
download = StartDownloadAndReturnItem(
shell(), test_server.GetURL(
kOriginOne, std::string("/download-attribute.html?target=") +
redirect_url.spec()));
WaitForCompletion(download);
ASSERT_TRUE(
base::ReadFileToString(download->GetTargetFilePath(), &file_contents));
if (DoesCookieSameSiteConsiderRedirectChain()) {
EXPECT_STREQ("B=C", file_contents.c_str());
} else {
EXPECT_STREQ("A=B; B=C", file_contents.c_str());
}
}
INSTANTIATE_TEST_SUITE_P(/* no label */,
DownloadContentSameSiteCookieTest,
::testing::Bool());
// The file empty.bin is served with a MIME type of application/octet-stream.
// The content body is empty. Make sure this case is handled properly and we
// don't regress on http://crbug.com/320394.
IN_PROC_BROWSER_TEST_F(DownloadContentTest, DownloadGZipWithNoContent) {
NavigateToURLAndWaitForDownload(
shell(), embedded_test_server()->GetURL("/download/empty.bin"),
download::DownloadItem::COMPLETE);
// That's it. This should work without crashing.
}
// Make sure that sniffed MIME types are correctly passed through to the
// download item.
IN_PROC_BROWSER_TEST_F(DownloadContentTest, SniffedMimeType) {
download::DownloadItem* item = StartDownloadAndReturnItem(
shell(), embedded_test_server()->GetURL("/download/gzip-content.gz"));
WaitForCompletion(item);
EXPECT_STREQ("application/x-gzip", item->GetMimeType().c_str());
EXPECT_TRUE(item->GetOriginalMimeType().empty());
}
// Verify that for download that is not triggered by navigation, MIME sniffing
// is working.
IN_PROC_BROWSER_TEST_F(DownloadContentTest, SniffedMimeTypeForDownloadURL) {
GURL download_url =
embedded_test_server()->GetURL("/download/gzip-content.gz");
std::unique_ptr<DownloadTestObserver> observer(CreateWaiter(shell(), 1));
auto download_parameters = std::make_unique<download::DownloadUrlParameters>(
download_url, TRAFFIC_ANNOTATION_FOR_TESTS);
// Download URL without navigation.
DownloadManagerForShell(shell())->DownloadUrl(std::move(download_parameters));
observer->WaitForFinished();
// Verify download failed.
std::vector<raw_ptr<download::DownloadItem, VectorExperimental>> downloads;
DownloadManagerForShell(shell())->GetAllDownloads(&downloads);
EXPECT_EQ(1u, downloads.size());
EXPECT_EQ(download::DownloadItem::COMPLETE, downloads[0]->GetState());
EXPECT_STREQ("application/x-gzip", downloads[0]->GetMimeType().c_str());
}
IN_PROC_BROWSER_TEST_F(DownloadContentTest, DuplicateContentDisposition) {
// double-content-disposition.txt is served with two Content-Disposition
// headers, both of which are identical.
NavigateToURLAndWaitForDownload(
shell(),
embedded_test_server()->GetURL(
"/download/double-content-disposition.txt"),
download::DownloadItem::COMPLETE);
std::vector<raw_ptr<download::DownloadItem, VectorExperimental>> downloads;
DownloadManagerForShell(shell())->GetAllDownloads(&downloads);
ASSERT_EQ(1u, downloads.size());
EXPECT_EQ(FILE_PATH_LITERAL("Jumboshrimp.txt"),
downloads[0]->GetTargetFilePath().BaseName().value());
}
// Test fixture for forcing RendererSideContentDecoding feature.
class DownloadContentRendererSideContentDecodingTest
: public DownloadContentTest,
public ::testing::WithParamInterface<bool> {
public:
DownloadContentRendererSideContentDecodingTest() {
if (GetParam()) {
features_.InitWithFeatures(
{network::features::kRendererSideContentDecoding}, {});
} else {
features_.InitWithFeatures(
{}, {network::features::kRendererSideContentDecoding});
}
}
~DownloadContentRendererSideContentDecodingTest() override = default;
static std::string DescribeParams(
const testing::TestParamInfo<ParamType>& info) {
return info.param ? "FeatureEnabled" : "FeatureDisabled";
}
private:
base::test::ScopedFeatureList features_;
};
INSTANTIATE_TEST_SUITE_P(
,
DownloadContentRendererSideContentDecodingTest,
::testing::Bool(),
&DownloadContentRendererSideContentDecodingTest::DescribeParams);
IN_PROC_BROWSER_TEST_P(DownloadContentRendererSideContentDecodingTest,
CompressedResponseWithContentDisposition) {
// gzip-content-with-content-disposition.gz is served with Content-Disposition
// headers, and `Content-Encoding: gzip`.
NavigateToURLAndWaitForDownload(
shell(),
embedded_test_server()->GetURL(
"/download/gzip-content-with-content-disposition.gz"),
download::DownloadItem::COMPLETE);
std::vector<raw_ptr<download::DownloadItem, VectorExperimental>> downloads;
DownloadManagerForShell(shell())->GetAllDownloads(&downloads);
ASSERT_EQ(1u, downloads.size());
EXPECT_EQ(FILE_PATH_LITERAL("hello.txt"),
downloads[0]->GetTargetFilePath().BaseName().value());
// Verify the file is downloaded correctly.
{
base::ScopedAllowBlockingForTesting allow_blocking;
std::string downloaded_content;
ASSERT_TRUE(base::ReadFileToString(downloads[0]->GetTargetFilePath(),
&downloaded_content));
EXPECT_EQ(downloaded_content, "Hello World!\n");
}
}
// Test fixture for forcing RendererSideContentDecoding feature failure.
class DownloadContentRendererSideContentDecodingFailureTest
: public DownloadContentTest {
public:
DownloadContentRendererSideContentDecodingFailureTest() {
features_.InitWithFeaturesAndParameters(
{{network::features::kRendererSideContentDecoding,
{{"RendererSideContentDecodingForceMojoFailureForTesting", "true"}}}},
{});
}
~DownloadContentRendererSideContentDecodingFailureTest() override = default;
protected:
class FinishNavigationObserver : public WebContentsObserver {
public:
FinishNavigationObserver(WebContents* contents,
base::OnceClosure done_closure)
: WebContentsObserver(contents),
done_closure_(std::move(done_closure)) {}
void DidFinishNavigation(NavigationHandle* navigation_handle) override {
error_code_ = navigation_handle->GetNetErrorCode();
std::move(done_closure_).Run();
}
const std::optional<net::Error>& error_code() const { return error_code_; }
private:
base::OnceClosure done_closure_;
std::optional<net::Error> error_code_;
};
private:
base::test::ScopedFeatureList features_;
};
IN_PROC_BROWSER_TEST_F(
DownloadContentRendererSideContentDecodingFailureTest,
CompressedResponseWithContentDispositionInsufficientResources) {
base::RunLoop run_loop;
FinishNavigationObserver finish_navigation_observer(shell()->web_contents(),
run_loop.QuitClosure());
// gzip-content-with-content-disposition.gz is served with Content-Disposition
// headers, and `Content-Encoding: gzip`.
EXPECT_TRUE(NavigateToURLAndExpectNoCommit(
shell(), embedded_test_server()->GetURL(
"/download/gzip-content-with-content-disposition.gz")));
run_loop.Run();
EXPECT_THAT(finish_navigation_observer.error_code(), net::ERR_ABORTED);
}
// Test that the network isolation key is populated for:
// (1) <a download> triggered download request that doesn't go through the
// navigation path
// (2) the request resuming an interrupted download.
IN_PROC_BROWSER_TEST_F(DownloadContentTest,
AnchorDownload_Resume_IsolationInfoPopulated) {
SetupEnsureNoPendingDownloads();
GURL slow_download_url = embedded_test_server()->GetURL(
kOriginTwo, SlowDownloadHttpResponse::kKnownSizeUrl);
url::Origin download_origin = url::Origin::Create(slow_download_url);
net::IsolationInfo expected_isolation_info = net::IsolationInfo::Create(
net::IsolationInfo::RequestType::kMainFrame, download_origin,
download_origin, net::SiteForCookies::FromOrigin(download_origin));
GURL frame_url = embedded_test_server()->GetURL(
kOriginTwo,
"/download/download-attribute.html?noclick=" + slow_download_url.spec());
GURL document_url = embedded_test_server()->GetURL(
kOriginOne, "/download/iframe-host.html?target=" + frame_url.spec());
// Load a page that contains a cross-origin iframe, where the iframe contains
// a <a download> link same-origin to the iframe's origin.
TestNavigationObserver same_tab_observer(shell()->web_contents(), 1);
shell()->LoadURL(document_url);
same_tab_observer.Wait();
// Click the <a download> link in the child frame.
download::DownloadItem* download_item = nullptr;
ExpectRequestIsolationInfo(
slow_download_url, expected_isolation_info,
base::BindLambdaForTesting([&]() {
DownloadInProgressObserver observer(DownloadManagerForShell(shell()));
EXPECT_TRUE(
ExecJs(ChildFrameAt(shell()->web_contents(), 0),
"var anchorElement = document.querySelector('a[download]'); "
"anchorElement.click();"));
download_item = observer.WaitAndGetInProgressDownload();
}));
download_item->SimulateErrorForTesting(
download::DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED);
EXPECT_EQ(download::DownloadItem::INTERRUPTED, download_item->GetState());
ExpectRequestIsolationInfo(
slow_download_url, expected_isolation_info,
base::BindLambdaForTesting([&]() { download_item->Resume(true); }));
EXPECT_EQ(download::DownloadItem::IN_PROGRESS, download_item->GetState());
download_item->Cancel(true);
}
IN_PROC_BROWSER_TEST_F(DownloadContentTest, DownloadAttributeSameOriginIFrame) {
GURL frame_url = embedded_test_server()->GetURL(
"/download/download-attribute.html?target=/download/download-test.lib");
GURL document_url = embedded_test_server()->GetURL(
"/download/iframe-host.html?target=" + frame_url.spec());
download::DownloadItem* download =
StartDownloadAndReturnItem(shell(), document_url);
WaitForCompletion(download);
EXPECT_STREQ(FILE_PATH_LITERAL("suggested-filename"),
download->GetTargetFilePath().BaseName().value().c_str());
}
IN_PROC_BROWSER_TEST_F(DownloadContentTest,
DownloadAttributeCrossOriginIFrame) {
net::EmbeddedTestServer origin_one;
net::EmbeddedTestServer origin_two;
origin_one.ServeFilesFromDirectory(GetTestFilePath("download", ""));
origin_two.ServeFilesFromDirectory(GetTestFilePath("download", ""));
ASSERT_TRUE(origin_one.Start());
ASSERT_TRUE(origin_two.Start());
GURL download_url = origin_two.GetURL("/download-test.lib");
url::Origin download_origin = url::Origin::Create(download_url);
// The IsolationInfo of the download should be the same as that of a top-level
// navigation to the download.
net::IsolationInfo expected_isolation_info = net::IsolationInfo::Create(
net::IsolationInfo::RequestType::kSubFrame, download_origin,
download_origin, net::SiteForCookies::FromOrigin(download_origin));
GURL frame_url = origin_one.GetURL("/download-attribute.html?target=" +
download_url.spec());
GURL::Replacements replacements;
replacements.SetHostStr("localhost");
frame_url = frame_url.ReplaceComponents(replacements);
GURL document_url =
origin_two.GetURL("/iframe-host.html?target=" + frame_url.spec());
download::DownloadItem* download = nullptr;
ExpectRequestIsolationInfo(
download_url, expected_isolation_info, base::BindLambdaForTesting([&]() {
download = StartDownloadAndReturnItem(shell(), document_url);
}));
WaitForCompletion(download);
EXPECT_STREQ(FILE_PATH_LITERAL("download-test.lib"),
download->GetTargetFilePath().BaseName().value().c_str());
}
// Verify parallel download in normal case.
IN_PROC_BROWSER_TEST_F(ParallelDownloadTest, ParallelDownloadComplete) {
TestDownloadHttpResponse::Parameters parameters;
parameters.etag = "ABC";
parameters.size = 5097152;
RunCompletionTest(parameters);
}
// When the last request is rejected by the server, other parallel requests
// should take over and complete the download.
IN_PROC_BROWSER_TEST_F(ParallelDownloadTest, LastRequestRejected) {
TestDownloadHttpResponse::Parameters parameters;
parameters.etag = "ABC";
parameters.size = 5097152;
// The 3rd request will always fail. Other requests should take over.
parameters.SetResponseForRangeRequest(3398000, -1, k404Response);
RunCompletionTest(parameters);
}
// When the second request is rejected by the server, other parallel requests
// should take over and complete the download.
IN_PROC_BROWSER_TEST_F(ParallelDownloadTest, SecondRequestRejected) {
TestDownloadHttpResponse::Parameters parameters;
parameters.etag = "ABC";
parameters.size = 5097152;
// The 2nd request will always fail. Other requests should take over.
parameters.SetResponseForRangeRequest(1699000, 2000000, k404Response);
RunCompletionTest(parameters);
}
// The server will only accept the original request, and reject all other
// requests. The original request should complete the whole download.
IN_PROC_BROWSER_TEST_F(ParallelDownloadTest, OnlyFirstRequestValid) {
TestDownloadHttpResponse::Parameters parameters;
parameters.etag = "ABC";
parameters.size = 5097152;
// 2nd and 3rd request will fail, the original request should complete the
// download.
parameters.SetResponseForRangeRequest(1000, -1, k404Response);
RunCompletionTest(parameters);
}
// The server will send Accept-Ranges header without partial response.
IN_PROC_BROWSER_TEST_F(ParallelDownloadTest, NoPartialResponse) {
TestDownloadHttpResponse::Parameters parameters;
parameters.etag = "ABC";
parameters.size = 5097152;
parameters.support_byte_ranges = true;
parameters.support_partial_response = false;
RunCompletionTest(parameters);
}
// Verify parallel download resumption.
IN_PROC_BROWSER_TEST_F(ParallelDownloadTest, Resumption) {
// Create the received slices data, the last request is not finished and the
// server will send more data to finish the last slice.
std::vector<download::DownloadItem::ReceivedSlice> received_slices = {
download::DownloadItem::ReceivedSlice(0, 1000),
download::DownloadItem::ReceivedSlice(1000000, 1000),
download::DownloadItem::ReceivedSlice(2000000, 1000,
false /* finished */)};
RunResumptionTest(received_slices, 3000000, kTestRequestCount,
true /* support_partial_response */);
}
// Verifies that if the last slice is finished, parallel download resumption
// can complete.
IN_PROC_BROWSER_TEST_F(ParallelDownloadTest, ResumptionLastSliceFinished) {
// Create the received slices data, last slice is actually finished.
std::vector<download::DownloadItem::ReceivedSlice> received_slices = {
download::DownloadItem::ReceivedSlice(0, 1000),
download::DownloadItem::ReceivedSlice(1000000, 1000),
download::DownloadItem::ReceivedSlice(2000000, 1000000,
true /* finished */)};
// The server shouldn't receive an additional request, since the last slice
// is marked as finished.
RunResumptionTest(received_slices, 3000000, kTestRequestCount - 1,
true /* support_partial_response */);
}
// Verify parallel download resumption when only 1 slice was created in previous
// attempt.
IN_PROC_BROWSER_TEST_F(ParallelDownloadTest, ResumptionWithOnlyOneSlice) {
// Create the received slices data with only 1 slice.
std::vector<download::DownloadItem::ReceivedSlice> received_slices = {
download::DownloadItem::ReceivedSlice(0, 1000, false /* finished */)};
// Only 1 request should be sent.
RunResumptionTest(received_slices, 3000000, 1,
true /* support_partial_response */);
}
// Verifies that if the last slice is finished, but the database record is not
// finished, which may happen in database migration.
// When the server sends HTTP range not satisfied, the download can complete.
IN_PROC_BROWSER_TEST_F(ParallelDownloadTest, ResumptionLastSliceUnfinished) {
// Create the received slices data, last slice is actually finished.
std::vector<download::DownloadItem::ReceivedSlice> received_slices = {
download::DownloadItem::ReceivedSlice(0, 1000),
download::DownloadItem::ReceivedSlice(1000000, 1000),
download::DownloadItem::ReceivedSlice(2000000, 1000000,
false /* finished */)};
// Client will send an out of range request where server will send back HTTP
// range not satisfied, and download can complete.
RunResumptionTest(received_slices, 3000000, kTestRequestCount,
true /* support_partial_response */);
}
// Verify that if server doesn't support partial response, resuming a parallel
// download should complete the download.
IN_PROC_BROWSER_TEST_F(ParallelDownloadTest, ResumptionNoPartialResponse) {
// Create the received slices data, the last request is not finished and the
// server will send more data to finish the last slice.
std::vector<download::DownloadItem::ReceivedSlice> received_slices = {
download::DownloadItem::ReceivedSlice(0, 1000),
download::DownloadItem::ReceivedSlice(1000000, 1000),
download::DownloadItem::ReceivedSlice(2000000, 1000,
false /* finished */)};
RunResumptionTest(received_slices, 3000000, kTestRequestCount,
false /* support_partial_response */);
}
// Verify that if a temporary error happens to one of the parallel request,
// resuming a parallel download should still complete.
// Flaky on fuchsia: https://crbug.com/1492656
#if BUILDFLAG(IS_FUCHSIA)
#define MAYBE_ResumptionMiddleSliceTemporaryError \
DISABLED_ResumptionMiddleSliceTemporaryError
#else
#define MAYBE_ResumptionMiddleSliceTemporaryError \
ResumptionMiddleSliceTemporaryError
#endif
IN_PROC_BROWSER_TEST_F(ParallelDownloadTest,
MAYBE_ResumptionMiddleSliceTemporaryError) {
// Create the received slices data.
std::vector<download::DownloadItem::ReceivedSlice> received_slices = {
download::DownloadItem::ReceivedSlice(0, 1000),
download::DownloadItem::ReceivedSlice(1000000, 1000),
download::DownloadItem::ReceivedSlice(2000000, 1000,
false /* finished */)};
TestDownloadHttpResponse::Parameters parameters;
parameters.etag = "ABC";
parameters.size = 3000000;
parameters.connection_type = net::HttpConnectionInfo::kHTTP1_1;
// The 2nd slice will fail. Once the first and the third slices
// complete, download will resume on the 2nd slice.
parameters.SetResponseForRangeRequest(1000000, 1010000, k404Response,
true /* is_transient */);
// A total of 4 requests will be sent, 3 during the initial attempt, and 1
// for the retry attempt on the 2nd slice.
RunResumptionTestWithParameters(received_slices, kTestRequestCount + 1,
parameters);
}
// Verify that if the second request fails after the beginning request takes
// over and completes its slice, download should complete.
IN_PROC_BROWSER_TEST_F(ParallelDownloadTest, MiddleSliceDelayedError) {
const int64_t kFileSize = 5097152;
scoped_refptr<TestFileErrorInjector> injector(
TestFileErrorInjector::Create(DownloadManagerForShell(shell())));
TestFileErrorInjector::FileErrorInfo err = {
TestFileErrorInjector::FILE_OPERATION_WRITE, 1,
download::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE};
err.data_write_offset = 1699050;
injector->InjectError(err);
TestDownloadHttpResponse::Parameters parameters;
parameters.etag = "ABC";
parameters.size = kFileSize;
parameters.connection_type = net::HttpConnectionInfo::kHTTP1_1;
// The 2nd response will be dalyed.
parameters.SetResponseForRangeRequest(1699000, 2000000, k404Response,
true /* is_transient */,
true /* delay_response */);
GURL url = TestDownloadHttpResponse::GetNextURLForDownload();
GURL server_url = embedded_test_server()->GetURL(url.host(), url.path());
TestRequestPauseHandler request_pause_handler;
parameters.on_pause_handler = request_pause_handler.GetOnPauseHandler();
// Send some data for the first request and pause it so download won't
// complete before other parallel requests are created.
parameters.pause_offset = kPauseOffset;
TestDownloadHttpResponse::StartServing(parameters, server_url);
download::DownloadItem* download =
StartDownloadAndReturnItem(shell(), server_url);
// Wait for the 3rd request to complete first.
test_response_handler()->WaitUntilCompletion(1);
ReceivedSlicesCountingObserver slices_counting_observer;
slices_counting_observer.WaitForFinished(download, 2);
std::vector<download::DownloadItem::ReceivedSlice> received_slices =
download->GetReceivedSlices();
EXPECT_EQ(received_slices[1].offset + received_slices[1].received_bytes,
kFileSize);
// Now resume the first request and wait for it to complete, including writing
// the whole file.
request_pause_handler.Resume();
ReceivedBytesCountingObserver bytes_counting_observer;
bytes_counting_observer.WaitForFinished(download, kFileSize);
// Note that download is not yet completed even though the whole file is
// downloaded - second request is not yet processed.
EXPECT_EQ(download->GetState(),
download::DownloadItem::DownloadState::IN_PROGRESS);
// Dispatch the delayed response, and wait for download to complete.
test_response_handler()->DispatchDelayedResponses();
WaitForCompletion(download);
test_response_handler()->WaitUntilCompletion(3u);
const TestDownloadResponseHandler::CompletedRequests& completed_requests =
test_response_handler()->completed_requests();
EXPECT_EQ(3u, completed_requests.size());
WaitForCompletion(download);
ReadAndVerifyFileContents(parameters.pattern_generator_seed, parameters.size,
download->GetTargetFilePath());
}
// Test to verify that the browser-side enforcement of X-Frame-Options does
// not impact downloads. Since XFO is only checked for subframes, this test
// initiates a download in an iframe and expects it to succeed.
// See https://crbug.com/717971.
IN_PROC_BROWSER_TEST_F(DownloadContentTest, DownloadIgnoresXFO) {
GURL main_url(embedded_test_server()->GetURL(
"a.test", "/cross_site_iframe_factory.html?a.test(b.test)"));
GURL download_url(
embedded_test_server()->GetURL("/download/download-with-xfo-deny.html"));
WebContentsImpl* web_contents =
static_cast<WebContentsImpl*>(shell()->web_contents());
EXPECT_TRUE(NavigateToURL(shell(), main_url));
std::unique_ptr<DownloadTestObserver> observer(CreateWaiter(shell(), 1));
NavigateFrameToURL(web_contents->GetPrimaryFrameTree().root()->child_at(0),
download_url);
observer->WaitForFinished();
EXPECT_EQ(
1u, observer->NumDownloadsSeenInState(download::DownloadItem::COMPLETE));
std::vector<raw_ptr<download::DownloadItem, VectorExperimental>> downloads;
DownloadManagerForShell(shell())->GetAllDownloads(&downloads);
ASSERT_EQ(1u, downloads.size());
EXPECT_EQ(FILE_PATH_LITERAL("foo"),
downloads[0]->GetTargetFilePath().BaseName().value());
}
// Verify that the response body of non-successful server response can be
// downloaded to a file, when |fetch_error_body| sets to true.
IN_PROC_BROWSER_TEST_F(DownloadContentTest, FetchErrorResponseBody) {
net::EmbeddedTestServer server;
const std::string kNotFoundURL = "/404notfound";
const std::string kNotFoundResponseBody = "This is response body.";
server.RegisterRequestHandler(CreateBasicResponseHandler(
kNotFoundURL, net::HTTP_NOT_FOUND, base::StringPairs(), "text/html",
kNotFoundResponseBody));
ASSERT_TRUE(server.Start());
GURL url = server.GetURL(kNotFoundURL);
std::unique_ptr<download::DownloadUrlParameters> download_parameters(
DownloadRequestUtils::CreateDownloadForWebContentsMainFrame(
shell()->web_contents(), url, TRAFFIC_ANNOTATION_FOR_TESTS));
// Fetch non-successful response body.
download_parameters->set_fetch_error_body(true);
DownloadManager* download_manager = DownloadManagerForShell(shell());
std::unique_ptr<DownloadTestObserver> observer(CreateWaiter(shell(), 1));
download_manager->DownloadUrl(std::move(download_parameters));
observer->WaitForFinished();
std::vector<raw_ptr<download::DownloadItem, VectorExperimental>> items;
download_manager->GetAllDownloads(&items);
EXPECT_EQ(1u, items.size());
// Verify the error response body in the file.
{
base::ScopedAllowBlockingForTesting allow_blocking;
std::string file_content;
ASSERT_TRUE(
base::ReadFileToString(items[0]->GetTargetFilePath(), &file_content));
EXPECT_EQ(kNotFoundResponseBody, file_content);
}
}
// Verify that the upload body of a request is received correctly by the server.
IN_PROC_BROWSER_TEST_F(DownloadContentTest, UploadBytes) {
net::EmbeddedTestServer server;
const std::string kUploadURL = "/upload";
std::string kUploadString = "Test upload body";
server.RegisterRequestHandler(base::BindRepeating(&HandleUploadRequest));
ASSERT_TRUE(server.Start());
GURL url = server.GetURL(kUploadURL);
std::unique_ptr<download::DownloadUrlParameters> download_parameters(
DownloadRequestUtils::CreateDownloadForWebContentsMainFrame(
shell()->web_contents(), url, TRAFFIC_ANNOTATION_FOR_TESTS));
download_parameters->set_post_body(
network::ResourceRequestBody::CreateFromCopyOfBytes(
base::as_byte_span(kUploadString)));
DownloadManager* download_manager = DownloadManagerForShell(shell());
std::unique_ptr<DownloadTestObserver> observer(CreateWaiter(shell(), 1));
download_manager->DownloadUrl(std::move(download_parameters));
observer->WaitForFinished();
std::vector<raw_ptr<download::DownloadItem, VectorExperimental>> items;
download_manager->GetAllDownloads(&items);
EXPECT_EQ(1u, items.size());
// Verify the response body in the file. It should match the request content.
{
base::ScopedAllowBlockingForTesting allow_blocking;
std::string file_content;
ASSERT_TRUE(
base::ReadFileToString(items[0]->GetTargetFilePath(), &file_content));
EXPECT_EQ(kUploadString, file_content);
}
}
// Verify the case that the first response is HTTP 200, and then interrupted,
// and the second response is HTTP 404, the response body of 404 should be
// fetched.
// Also verify the request header is correctly piped to download item.
IN_PROC_BROWSER_TEST_F(DownloadContentTest, FetchErrorResponseBodyResumption) {
SetupErrorInjectionDownloads();
GURL url = TestDownloadHttpResponse::GetNextURLForDownload();
GURL server_url = embedded_test_server()->GetURL(url.host(), url.path());
TestDownloadHttpResponse::Parameters parameters =
TestDownloadHttpResponse::Parameters::WithSingleInterruption(
inject_error_callback());
TestDownloadHttpResponse::StartServing(parameters, server_url);
// Wait for an interrupted download.
std::unique_ptr<download::DownloadUrlParameters> download_parameters(
DownloadRequestUtils::CreateDownloadForWebContentsMainFrame(
shell()->web_contents(), server_url, TRAFFIC_ANNOTATION_FOR_TESTS));
download_parameters->set_fetch_error_body(true);
download_parameters->add_request_header("header_key", "header_value");
DownloadManager* download_manager = DownloadManagerForShell(shell());
auto observer = std::make_unique<content::DownloadTestObserverInterrupted>(
download_manager, 1,
content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL);
download_manager->DownloadUrl(std::move(download_parameters));
observer->WaitForFinished();
std::vector<raw_ptr<download::DownloadItem, VectorExperimental>> items;
download_manager->GetAllDownloads(&items);
EXPECT_EQ(1u, items.size());
// Now server will start to response 404 with empty body.
TestDownloadHttpResponse::StartServingStaticResponse(k404Response,
server_url);
download::DownloadItem* download = items[0];
// The fetch error body should be cached in download item. The download should
// start from beginning.
download->Resume(false);
WaitForCompletion(download);
// The file should be empty.
{
base::ScopedAllowBlockingForTesting allow_blocking;
std::string file_content;
ASSERT_TRUE(
base::ReadFileToString(items[0]->GetTargetFilePath(), &file_content));
EXPECT_EQ(std::string(), file_content);
}
// Additional request header should be sent.
test_response_handler()->WaitUntilCompletion(2u);
const auto& request = test_response_handler()->completed_requests().back();
auto it = request->http_request.headers.find("header_key");
EXPECT_TRUE(it != request->http_request.headers.end());
EXPECT_EQ(request->http_request.headers["header_key"],
std::string("header_value"));
}
// Verify WebUI download will success with an associated renderer process.
IN_PROC_BROWSER_TEST_F(DownloadContentTest, DownloadFromWebUI) {
GURL webui_url(GetWebUIURL("resources/images/error.svg"));
EXPECT_TRUE(NavigateToURL(shell(), webui_url));
SetupEnsureNoPendingDownloads();
// Creates download parameters with renderer process information.
std::unique_ptr<download::DownloadUrlParameters> download_parameters(
DownloadRequestUtils::CreateDownloadForWebContentsMainFrame(
shell()->web_contents(), webui_url, TRAFFIC_ANNOTATION_FOR_TESTS));
std::unique_ptr<DownloadTestObserver> observer(CreateWaiter(shell(), 1));
DownloadManagerForShell(shell())->DownloadUrl(std::move(download_parameters));
observer->WaitForFinished();
EXPECT_TRUE(EnsureNoPendingDownloads());
std::vector<raw_ptr<download::DownloadItem, VectorExperimental>> downloads;
DownloadManagerForShell(shell())->GetAllDownloads(&downloads);
ASSERT_EQ(1u, downloads.size());
ASSERT_EQ(download::DownloadItem::COMPLETE, downloads[0]->GetState());
}
// Verify WebUI download will gracefully fail without an associated renderer
// process.
IN_PROC_BROWSER_TEST_F(DownloadContentTest, DownloadFromWebUIWithoutRenderer) {
GURL webui_url("chrome://resources/images/error.svg");
EXPECT_TRUE(NavigateToURL(shell(), webui_url));
SetupEnsureNoPendingDownloads();
// Creates download parameters without any renderer process information.
auto download_parameters = std::make_unique<download::DownloadUrlParameters>(
webui_url, TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<DownloadTestObserver> observer(CreateWaiter(shell(), 1));
DownloadManagerForShell(shell())->DownloadUrl(std::move(download_parameters));
observer->WaitForFinished();
EXPECT_TRUE(EnsureNoPendingDownloads());
std::vector<raw_ptr<download::DownloadItem, VectorExperimental>> downloads;
DownloadManagerForShell(shell())->GetAllDownloads(&downloads);
ASSERT_EQ(1u, downloads.size());
// WebUI or other UrlLoaderFacotry will not handle request without a valid
// RenderFrameHost, download should gracefully fail without triggering
// crash.
ASSERT_EQ(download::DownloadItem::INTERRUPTED, downloads[0]->GetState());
}
IN_PROC_BROWSER_TEST_F(DownloadContentTest, SaveImageAt) {
// Navigate to a page containing a data-URL image in the top-left corner.
GURL main_url(
embedded_test_server()->GetURL("/download/page_with_data_image.html"));
EXPECT_TRUE(NavigateToURL(shell(), main_url));
// Ask the frame to save a data-URL image at the given coordinates.
std::unique_ptr<DownloadTestObserver> observer(CreateWaiter(shell(), 1));
shell()->web_contents()->GetPrimaryMainFrame()->SaveImageAt(100, 100);
observer->WaitForFinished();
EXPECT_EQ(
1u, observer->NumDownloadsSeenInState(download::DownloadItem::COMPLETE));
// Verify that there was one, appropriately named download.
std::vector<raw_ptr<download::DownloadItem, VectorExperimental>> downloads;
DownloadManagerForShell(shell())->GetAllDownloads(&downloads);
ASSERT_EQ(1u, downloads.size());
EXPECT_EQ(FILE_PATH_LITERAL("download.png"),
downloads[0]->GetTargetFilePath().BaseName().value());
// Verify file contents.
std::string expected_content;
{
base::ScopedAllowBlockingForTesting allow_blocking;
ASSERT_TRUE(ReadFileToString(GetTestFilePath("media", "blackwhite.png"),
&expected_content));
}
ASSERT_TRUE(VerifyFile(downloads[0]->GetFullPath(), expected_content,
expected_content.size()));
}
// Test fixture for forcing MHTML download.
class MhtmlDownloadTest : public DownloadContentTest {
protected:
void SetUpOnMainThread() override {
DownloadContentTest::SetUpOnMainThread();
browser_client_ = std::make_unique<DownloadTestContentBrowserClient>();
// Force downloading the MHTML.
browser_client_->set_allowed_rendering_mhtml_over_http(false);
// Enable RegisterNonNetworkNavigationURLLoaderFactories for
// test white list for non http shemes which should not trigger
// download.
browser_client_->enable_register_non_network_url_loader(true);
}
void TearDownOnMainThread() override {
browser_client_.reset();
DownloadContentTest::TearDownOnMainThread();
}
private:
std::unique_ptr<DownloadTestContentBrowserClient> browser_client_;
};
// Test allow list for non http schemes which should not trigger
// download for mhtml.
IN_PROC_BROWSER_TEST_F(MhtmlDownloadTest,
AllowListForNonHTTPNotTriggerDownload) {
#if BUILDFLAG(IS_ANDROID)
// "content://" is an protocol on Android.
GURL content_url("content://non_download.mhtml");
NavigateToCommittedURLAndExpectNoDownload(shell(), content_url);
#endif
GURL file_url("file:///non_download.mhtml");
NavigateToCommittedURLAndExpectNoDownload(shell(), file_url);
}
#if defined(THREAD_SANITIZER)
// Flaky on TSAN https://crbug.com/932092
#define MAYBE_ForceDownloadMultipartRelatedPage \
DISABLED_ForceDownloadMultipartRelatedPage
#else
#define MAYBE_ForceDownloadMultipartRelatedPage \
ForceDownloadMultipartRelatedPage
#endif
IN_PROC_BROWSER_TEST_F(MhtmlDownloadTest,
MAYBE_ForceDownloadMultipartRelatedPage) {
NavigateToURLAndWaitForDownload(
shell(),
// .mhtml file is mapped to "multipart/related" by the test server.
embedded_test_server()->GetURL("/download/hello.mhtml"),
download::DownloadItem::COMPLETE);
}
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || defined(ADDRESS_SANITIZER)
// Flaky https://crbug.com/852073
#define MAYBE_ForceDownloadMessageRfc822Page \
DISABLED_ForceDownloadMessageRfc822Page
#else
#define MAYBE_ForceDownloadMessageRfc822Page ForceDownloadMessageRfc822Page
#endif
IN_PROC_BROWSER_TEST_F(MhtmlDownloadTest,
MAYBE_ForceDownloadMessageRfc822Page) {
NavigateToURLAndWaitForDownload(
shell(),
// .mht file is mapped to "message/rfc822" by the test server.
embedded_test_server()->GetURL("/download/test.mht"),
download::DownloadItem::COMPLETE);
}
// Test fixture for loading MHTML.
class MhtmlLoadingTest : public DownloadContentTest {
protected:
// Return an URL for loading a local test file.
GURL GetFileURL(const base::FilePath::CharType* file_path) {
base::FilePath path;
CHECK(base::PathService::Get(base::DIR_SRC_TEST_DATA_ROOT, &path));
path = path.Append(GetTestDataFilePath());
path = path.Append(file_path);
return GURL("file:" + path.AsUTF8Unsafe());
}
};
IN_PROC_BROWSER_TEST_F(MhtmlLoadingTest,
AllowRenderMultipartRelatedPageFromFile) {
GURL url = GetFileURL(FILE_PATH_LITERAL("download/hello.mhtml"));
auto observer = std::make_unique<content::TestNavigationObserver>(url);
observer->WatchExistingWebContents();
observer->StartWatchingNewWebContents();
EXPECT_TRUE(NavigateToURL(shell(), url));
observer->WaitForNavigationFinished();
}
IN_PROC_BROWSER_TEST_F(MhtmlLoadingTest, AllowRenderMessageRfc822PageFromFile) {
GURL url = GetFileURL(FILE_PATH_LITERAL("download/test.mht"));
auto observer = std::make_unique<content::TestNavigationObserver>(url);
observer->WatchExistingWebContents();
observer->StartWatchingNewWebContents();
EXPECT_TRUE(NavigateToURL(shell(), url));
observer->WaitForNavigationFinished();
}
IN_PROC_BROWSER_TEST_F(MhtmlLoadingTest,
DisallowRenderMultipartRelatedPageFromHTTP) {
net::EmbeddedTestServer server;
net::test_server::ControllableHttpResponse response(&server, "/");
EXPECT_TRUE(server.Start());
std::unique_ptr<DownloadTestObserver> observer(CreateWaiter(shell(), 1));
GURL url = server.GetURL(kOrigin, "/");
shell()->LoadURL(url);
response.WaitForRequest();
response.Send(net::HTTP_OK, "multipart/related");
response.Done();
observer->WaitForFinished();
EXPECT_EQ(
1u, observer->NumDownloadsSeenInState(download::DownloadItem::COMPLETE));
}
IN_PROC_BROWSER_TEST_F(MhtmlLoadingTest,
DisallowRenderMessageRfc822PageFromHTTP) {
net::EmbeddedTestServer server;
net::test_server::ControllableHttpResponse response(&server, "/");
EXPECT_TRUE(server.Start());
std::unique_ptr<DownloadTestObserver> observer(CreateWaiter(shell(), 1));
GURL url = server.GetURL(kOrigin, "/");
shell()->LoadURL(url);
response.WaitForRequest();
response.Send(net::HTTP_OK, "message/rfc822");
response.Done();
observer->WaitForFinished();
EXPECT_EQ(
1u, observer->NumDownloadsSeenInState(download::DownloadItem::COMPLETE));
}
// Regression test for https://crbug.com/1171765
IN_PROC_BROWSER_TEST_F(MhtmlLoadingTest, DisallowRenderMessageRfc822Iframe) {
net::EmbeddedTestServer server;
net::test_server::ControllableHttpResponse main_response(&server, "/main");
net::test_server::ControllableHttpResponse sub_response(&server, "/sub");
EXPECT_TRUE(server.Start());
std::unique_ptr<DownloadTestObserver> observer(CreateWaiter(shell(), 1));
GURL main_url = server.GetURL(kOrigin, "/main");
GURL sub_url = server.GetURL(kOrigin, "/sub");
shell()->LoadURL(main_url);
main_response.WaitForRequest();
main_response.Send(net::HTTP_OK, "text/html",
"<iframe src='./sub'></iframe>");
main_response.Done();
sub_response.WaitForRequest();
sub_response.Send(net::HTTP_OK, "message/rfc822");
sub_response.Done();
observer->WaitForFinished();
EXPECT_EQ(
1u, observer->NumDownloadsSeenInState(download::DownloadItem::COMPLETE));
}
// MhtmlLoadingTest with `kMHTML_Improvements` enabled.
class MHTMLImprovementsLoadingTest : public MhtmlLoadingTest {
protected:
void SetUpOnMainThread() override {
MhtmlLoadingTest::SetUpOnMainThread();
browser_client_ = std::make_unique<DownloadTestContentBrowserClient>();
browser_client_->set_allowed_rendering_mhtml_over_http(true);
}
void TearDownOnMainThread() override {
browser_client_.reset();
MhtmlLoadingTest::TearDownOnMainThread();
}
private:
base::test::ScopedFeatureList features_ =
base::test::ScopedFeatureList({blink::features::kMHTML_Improvements});
std::unique_ptr<DownloadTestContentBrowserClient> browser_client_;
};
IN_PROC_BROWSER_TEST_F(MHTMLImprovementsLoadingTest,
FormsDisabledWhenRenderedFromHttp) {
// Note that normally Chrome will not load MHTML over HTTP(s), and instead
// will download the file. On Android, Chrome supports loading 'trusted'
// offline pages, which are loaded through `OfflinePageURLLoader`, and are
// simulated as loading from the original URL. For these trusted MHTML files,
// forms are disabled.
// This test forces loading MHTML over HTTP to trigger the form disabling
// functionality.
net::EmbeddedTestServer server;
net::test_server::ControllableHttpResponse response(&server, "/");
EXPECT_TRUE(server.Start());
GURL url = server.GetURL(kOrigin, "/");
std::string mhtml_content;
{
base::ScopedAllowBlockingForTesting allow_blocking;
ASSERT_TRUE(base::ReadFileToString(
GetTestFilePath("download", "forms.mhtml"), &mhtml_content));
}
auto observer = std::make_unique<content::TestNavigationObserver>(url);
observer->WatchExistingWebContents();
observer->StartWatchingNewWebContents();
shell()->LoadURL(url);
response.WaitForRequest();
response.Send(net::HTTP_OK, "multipart/related", mhtml_content);
response.Done();
observer->WaitForNavigationFinished();
ASSERT_TRUE(WaitForLoadStop(shell()->web_contents()));
// <input> is disabled. It won't have the disabled property set, but it will
// have the effects. One effect is changing the cursor.
EXPECT_EQ(
"default",
EvalJs(
shell(),
"window.getComputedStyle(document.querySelector('input')).cursor"));
}
IN_PROC_BROWSER_TEST_F(MHTMLImprovementsLoadingTest,
FormsNotDisabledWhenRenderedFromFile) {
GURL url = GetFileURL(FILE_PATH_LITERAL("download/forms.mhtml"));
auto observer = std::make_unique<content::TestNavigationObserver>(url);
observer->WatchExistingWebContents();
observer->StartWatchingNewWebContents();
EXPECT_TRUE(NavigateToURL(shell(), url));
observer->WaitForNavigationFinished();
ASSERT_TRUE(WaitForLoadStop(shell()->web_contents()));
// <input> is not disabled.
EXPECT_EQ(
"text",
EvalJs(
shell(),
"window.getComputedStyle(document.querySelector('input')).cursor"));
}
// Verify that downloads not triggered by navigation are discarded when
// initiated from a non-active page.
// Navigation downloads won't reach the DownloadManager. That is tested in
// PrerenderBrowserTest.{DownloadInMainFrame,DownloadInSubframe}.
IN_PROC_BROWSER_TEST_F(DownloadPrerenderTest, DiscardNonNavigationDownload) {
const GURL kInitialUrl = embedded_test_server()->GetURL("/empty.html");
const GURL kPrerenderingUrl =
embedded_test_server()->GetURL("/empty.html?prerendering");
const GURL kDownloadUrl =
embedded_test_server()->GetURL("/download/download-test.lib");
EXPECT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Create a prerendered page.
FrameTreeNodeId host_id = prerender_helper()->AddPrerender(kPrerenderingUrl);
auto* render_frame_host =
prerender_helper()->GetPrerenderedMainFrameHost(host_id);
auto* web_contents = shell()->web_contents();
test::PrerenderHostObserver host_observer(*web_contents, host_id);
// Do a download without navigation from the prerendered RenderFrameHost. The
// download should not reach the download manager.
auto* download_manager = DownloadManagerForShell(shell());
MockDownloadManagerObserver dm_observer(download_manager);
EXPECT_CALL(dm_observer, OnDownloadCreated(_, _)).Times(0);
EXPECT_CALL(dm_observer, OnDownloadDropped(_)).Times(0);
auto params = blink::mojom::DownloadURLParams::New();
params->url = kDownloadUrl;
static_cast<RenderFrameHostImpl*>(render_frame_host)
->DownloadURL(std::move(params));
// Do a download without navigation, from the download manager. In this
// case, the download will be dropped.
EXPECT_CALL(dm_observer, OnDownloadCreated(_, _)).Times(0);
EXPECT_CALL(dm_observer, OnDownloadDropped(_)).Times(1);
// Create download parameters with the renderer process information from the
// prerendered page and mark it as rendered-initiated, otherwise the download
// won't be checked.
auto download_parameters = std::make_unique<download::DownloadUrlParameters>(
kDownloadUrl, render_frame_host->GetProcess()->GetDeprecatedID(),
render_frame_host->GetRoutingID(), TRAFFIC_ANNOTATION_FOR_TESTS);
download_parameters->set_content_initiated(true);
download_manager->DownloadUrl(std::move(download_parameters));
// No navigations were done, so the prerendered page wasn't activated.
EXPECT_FALSE(host_observer.was_activated());
// Verify there were no downloads.
EXPECT_TRUE(EnsureNoPendingDownloads());
std::vector<raw_ptr<download::DownloadItem, VectorExperimental>> downloads;
download_manager->GetAllDownloads(&downloads);
EXPECT_TRUE(downloads.empty());
}
// Verify that downloads not triggered by navigation are discarded when
// initiated from a fenced frame.
IN_PROC_BROWSER_TEST_F(DownloadFencedFrameTest, DiscardNonNavigationDownload) {
const GURL kInitialUrl = embedded_test_server()->GetURL("/empty.html");
const GURL kFencedFrameUrl =
embedded_test_server()->GetURL("/fenced_frames/title1.html");
const GURL kDownloadUrl =
embedded_test_server()->GetURL("/download/download-test.lib");
// Create fenced frame
EXPECT_TRUE(NavigateToURL(shell(), kInitialUrl));
RenderFrameHost* fenced_frame_host = CreateFencedFrame(
shell()->web_contents()->GetPrimaryMainFrame(), kFencedFrameUrl);
// Do a download without navigation from the fenced frame RenderFrameHost.
// The download will be dropped.
auto* download_manager =
fenced_frame_host->GetBrowserContext()->GetDownloadManager();
MockDownloadManagerObserver dm_observer(download_manager);
EXPECT_CALL(dm_observer, OnDownloadCreated(_, _)).Times(0);
EXPECT_CALL(dm_observer, OnDownloadDropped(_)).Times(1);
auto params = blink::mojom::DownloadURLParams::New();
params->url = kDownloadUrl;
static_cast<RenderFrameHostImpl*>(fenced_frame_host)
->DownloadURL(std::move(params));
// Verify there were no downloads.
EXPECT_TRUE(EnsureNoPendingDownloads());
std::vector<raw_ptr<download::DownloadItem, VectorExperimental>> downloads;
download_manager->GetAllDownloads(&downloads);
EXPECT_TRUE(downloads.empty());
}
// An interrupted download will be created if fenced frame has revoked its
// untrusted network access.
// NOTE: Normally a download cannot be initiated from a network revoked fenced
// frame. In case there are download entry points that are not properly
// disabled, the network status check during the creation of download should
// catch these and create an interrupted download.
IN_PROC_BROWSER_TEST_F(DownloadFencedFrameTest,
CreateInterruptedDownloadIfNetworkRevoked) {
ASSERT_TRUE(embedded_https_test_server().Start());
const GURL kInitialUrl = embedded_https_test_server().GetURL(
"a.test", "/cross_site_iframe_factory.html?a.test(a.test{fenced})");
const GURL kDownloadUrl =
embedded_https_test_server().GetURL("/download/download-test.lib");
// Create the fenced frame.
EXPECT_TRUE(NavigateToURL(shell(), kInitialUrl));
std::vector<content::RenderFrameHost*> child_frames =
fenced_frame_helper()->GetChildFencedFrameHosts(
shell()->web_contents()->GetPrimaryMainFrame());
EXPECT_EQ(child_frames.size(), 1u);
content::RenderFrameHost* fenced_frame_host = child_frames[0];
// Create a download with the fenced frame untrusted network revoked. An
// interrupted download should be created.
auto* download_manager =
fenced_frame_host->GetBrowserContext()->GetDownloadManager();
MockDownloadManagerObserver dm_observer(download_manager);
EXPECT_CALL(dm_observer, OnDownloadCreated(_, _)).Times(1);
EXPECT_CALL(dm_observer, OnDownloadDropped(_)).Times(0);
auto params = blink::mojom::DownloadURLParams::New();
// Set this to be a context menu save so that it is not considered as content
// initiated. Otherwise no download item will be created.
params->is_context_menu_save = true;
params->url = kDownloadUrl;
std::unique_ptr<DownloadTestObserverInterrupted> observer =
std::make_unique<DownloadTestObserverInterrupted>(
download_manager, 1,
DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL);
content::test::RevokeFencedFrameUntrustedNetwork(fenced_frame_host);
// Download the URL.
static_cast<RenderFrameHostImpl*>(fenced_frame_host)
->DownloadURL(std::move(params));
// Verify that an interrupted download has been created.
observer->WaitForFinished();
std::vector<raw_ptr<download::DownloadItem, VectorExperimental>> downloads;
DownloadManagerForShell(shell())->GetAllDownloads(&downloads);
EXPECT_EQ(1u, downloads.size());
download::DownloadItem* download = downloads[0];
ASSERT_EQ(download->GetState(), download::DownloadItem::INTERRUPTED);
EXPECT_EQ(download->GetLastReason(),
download::DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED);
}
// A download triggered by clicking on a link with a |download| attribute should
// have the user-gesture flag set.
IN_PROC_BROWSER_TEST_F(DownloadContentTest,
DownloadAttributePreservesUserGesture) {
net::EmbeddedTestServer server;
ASSERT_TRUE(server.InitializeAndListen());
// The download-attribute.html page contains an anchor element whose href is
// set to the value of the query parameter (specified as |target| in the URL
// below). When the page is loaded, a script simulates a click on the anchor,
// triggering a download of the target URL.
GURL download_url = server.GetURL("/download");
GURL referrer_url =
server.GetURL(std::string("/download-attribute.html?noclick&target=") +
download_url.spec());
server.ServeFilesFromDirectory(GetTestFilePath("download", ""));
// download-attribute.html initiates a download of /download.
server.RegisterRequestHandler(
CreateBasicResponseHandler("/download", net::HTTP_OK, base::StringPairs(),
"application/octet-stream", "Hello"));
server.StartAcceptingConnections();
std::unique_ptr<DownloadTestObserver> observer(
CreateInProgressWaiter(shell(), 1));
// Load the download page and click on the link.
EXPECT_TRUE(NavigateToURL(shell(), referrer_url));
SimulateEndOfPaintHoldingOnPrimaryMainFrame(shell()->web_contents());
content::SimulateMouseClickOrTapElementWithId(shell()->web_contents(),
"downloadlink");
// Wait for the download.
observer->WaitForFinished();
std::vector<raw_ptr<download::DownloadItem, VectorExperimental>> downloads;
DownloadManagerForShell(shell())->GetAllDownloads(&downloads);
ASSERT_EQ(1u, downloads.size());
// Ensure that the download is treated as having a user-gesture.
EXPECT_EQ(FILE_PATH_LITERAL("suggested-filename"),
downloads[0]->GetTargetFilePath().BaseName().value());
EXPECT_TRUE(downloads[0]->HasUserGesture());
ASSERT_TRUE(server.ShutdownAndWaitUntilComplete());
}
using DownloadRangeTestParams =
std::tuple<int64_t /*starting byte in range request*/,
int64_t /*ending byte in range request*/,
int64_t /*starting byte in download file*/,
int64_t /*expected length*/>;
// Browser test for arbitrary range download. This is for download system
// caller to explicitly ask for range request, not for parallel download and
// resumption that internally use range requests.
class DownloadRangeTest
: public DownloadContentTest,
public ::testing::WithParamInterface<DownloadRangeTestParams> {
public:
DownloadRangeTest() = default;
~DownloadRangeTest() override = default;
};
INSTANTIATE_TEST_SUITE_P(
All,
DownloadRangeTest,
testing::Values(/*bytes=10-19, fetch 10 bytes*/
std::make_tuple(10, 19, 10, 10),
/*bytes=10-, fetch starting from 10th byte to the end*/
std::make_tuple(10, download::kInvalidRange, 10, 136),
/*bytes=-5*, fetch the last 5 bytes*/
std::make_tuple(download::kInvalidRange, 5, 141, 5)));
// Test to download with range request with
// |DownloadUrlParameters::set_range_request_offset|.
IN_PROC_BROWSER_TEST_P(DownloadRangeTest, ArbitraryDownloadRangeTest) {
GURL download_url =
embedded_test_server()->GetURL("/download/download-test.lib");
std::unique_ptr<DownloadTestObserver> observer(CreateWaiter(shell(), 1));
auto download_parameters = std::make_unique<download::DownloadUrlParameters>(
download_url, TRAFFIC_ANNOTATION_FOR_TESTS);
// Perform a range download.
download_parameters->set_use_if_range(false);
download_parameters->set_range_request_offset(std::get<0>(GetParam()),
std::get<1>(GetParam()));
DownloadManagerForShell(shell())->DownloadUrl(std::move(download_parameters));
observer->WaitForFinished();
// Verify download completed.
std::vector<raw_ptr<download::DownloadItem, VectorExperimental>> downloads;
DownloadManagerForShell(shell())->GetAllDownloads(&downloads);
EXPECT_EQ(1u, downloads.size());
EXPECT_EQ(download::DownloadItem::COMPLETE, downloads[0]->GetState());
// Verify the partial file is downloaded correctly.
{
base::ScopedAllowBlockingForTesting allow_blocking;
std::string whole_file, partial_file;
ASSERT_TRUE(base::ReadFileToString(
GetTestFilePath("download", "download-test.lib"), &whole_file));
ASSERT_TRUE(base::ReadFileToString(downloads[0]->GetTargetFilePath(),
&partial_file));
EXPECT_EQ(
whole_file.substr(std::get<2>(GetParam()), std::get<3>(GetParam())),
partial_file);
}
}
class DownloadRangeResumptionTest : public DownloadContentTest {
public:
DownloadRangeResumptionTest() = default;
~DownloadRangeResumptionTest() override = default;
};
// Test to download resumption from a partially downloaded file with range
// request with |DownloadUrlParameters::set_range_request_offset|.
IN_PROC_BROWSER_TEST_F(DownloadRangeResumptionTest,
ArbitraryDownloadRangeResumptionTest) {
// Make range download interrupted at certain position.
SetupErrorInjectionDownloads();
GURL url = TestDownloadHttpResponse::GetNextURLForDownload();
GURL server_url = embedded_test_server()->GetURL(url.host(), url.path());
TestDownloadHttpResponse::Parameters parameters =
TestDownloadHttpResponse::Parameters::WithSingleInterruption(
inject_error_callback());
EXPECT_EQ(51200, parameters.injected_errors.front());
// Make sure when auto resume from failure point, the server can response
// correctly.
parameters.SetResponseForRangeRequest(
51200, 100000,
"HTTP/1.1 206 Partial Content\r\n"
"Content-Range: bytes 51200-100000/48801\r\n"
"\r\n");
TestDownloadHttpResponse::StartServing(parameters, server_url);
// Perform a range download.
auto download_parameters = std::make_unique<download::DownloadUrlParameters>(
server_url, TRAFFIC_ANNOTATION_FOR_TESTS);
download_parameters->set_use_if_range(false);
download_parameters->set_range_request_offset(10, 100000);
DownloadManager* download_manager = DownloadManagerForShell(shell());
std::unique_ptr<DownloadTestObserverInterrupted> observer =
std::make_unique<DownloadTestObserverInterrupted>(
download_manager, 1,
DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL);
download_manager->DownloadUrl(std::move(download_parameters));
observer->WaitForFinished();
// Now clear the error and resume it.
parameters.ClearInjectedErrors();
TestDownloadHttpResponse::StartServing(parameters, server_url);
std::vector<raw_ptr<download::DownloadItem, VectorExperimental>> downloads;
DownloadManagerForShell(shell())->GetAllDownloads(&downloads);
EXPECT_EQ(1u, downloads.size());
download::DownloadItem* download = downloads[0];
EXPECT_EQ(download::DownloadItem::INTERRUPTED, download->GetState());
download->Resume(false);
WaitForCompletion(download);
{
base::ScopedAllowBlockingForTesting allow_blocking;
std::string partial_file;
ASSERT_TRUE(
base::ReadFileToString(download->GetTargetFilePath(), &partial_file));
EXPECT_EQ(partial_file, TestDownloadHttpResponse::GetPatternBytes(
parameters.pattern_generator_seed, 10, 99991));
}
}
} // namespace content
|