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
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <stddef.h>
#include <memory>
#include <utility>
#include <vector>
#include "base/bind.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/location.h"
#include "base/macros.h"
#include "base/memory/scoped_vector.h"
#include "base/memory/shared_memory.h"
#include "base/pickle.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/test/scoped_feature_list.h"
#include "base/threading/thread_task_runner_handle.h"
#include "content/browser/browser_thread_impl.h"
#include "content/browser/child_process_security_policy_impl.h"
#include "content/browser/download/download_manager_impl.h"
#include "content/browser/download/download_resource_handler.h"
#include "content/browser/frame_host/navigation_request_info.h"
#include "content/browser/loader/detachable_resource_handler.h"
#include "content/browser/loader/navigation_resource_throttle.h"
#include "content/browser/loader/navigation_url_loader.h"
#include "content/browser/loader/resource_dispatcher_host_impl.h"
#include "content/browser/loader/resource_loader.h"
#include "content/browser/loader/resource_message_filter.h"
#include "content/browser/loader/resource_request_info_impl.h"
#include "content/browser/loader_delegate_impl.h"
#include "content/common/appcache_interfaces.h"
#include "content/common/child_process_host_impl.h"
#include "content/common/navigation_params.h"
#include "content/common/resource_messages.h"
#include "content/common/resource_request.h"
#include "content/common/view_messages.h"
#include "content/public/browser/global_request_id.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/resource_context.h"
#include "content/public/browser/resource_dispatcher_host_delegate.h"
#include "content/public/browser/resource_request_info.h"
#include "content/public/browser/resource_throttle.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_observer.h"
#include "content/public/common/browser_side_navigation_policy.h"
#include "content/public/common/child_process_host.h"
#include "content/public/common/content_features.h"
#include "content/public/common/process_type.h"
#include "content/public/common/resource_response.h"
#include "content/public/test/test_browser_context.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "content/public/test/test_renderer_host.h"
#include "content/test/test_content_browser_client.h"
#include "content/test/test_navigation_url_loader_delegate.h"
#include "net/base/chunked_upload_data_stream.h"
#include "net/base/elements_upload_data_stream.h"
#include "net/base/load_flags.h"
#include "net/base/net_errors.h"
#include "net/base/request_priority.h"
#include "net/base/upload_bytes_element_reader.h"
#include "net/http/http_util.h"
#include "net/test/cert_test_util.h"
#include "net/test/test_data_directory.h"
#include "net/test/url_request/url_request_failed_job.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_job.h"
#include "net/url_request/url_request_job_factory.h"
#include "net/url_request/url_request_simple_job.h"
#include "net/url_request/url_request_test_job.h"
#include "net/url_request/url_request_test_util.h"
#include "storage/browser/blob/shareable_file_reference.h"
#include "testing/gtest/include/gtest/gtest.h"
// TODO(eroman): Write unit tests for SafeBrowsing that exercise
// SafeBrowsingResourceHandler.
using storage::ShareableFileReference;
namespace content {
namespace {
// Returns the resource response header structure for this request.
void GetResponseHead(const std::vector<IPC::Message>& messages,
ResourceResponseHead* response_head) {
ASSERT_GE(messages.size(), 2U);
// The first messages should be received response.
ASSERT_EQ(ResourceMsg_ReceivedResponse::ID, messages[0].type());
base::PickleIterator iter(messages[0]);
int request_id;
ASSERT_TRUE(IPC::ReadParam(&messages[0], &iter, &request_id));
ASSERT_TRUE(IPC::ReadParam(&messages[0], &iter, response_head));
}
void GenerateIPCMessage(scoped_refptr<ResourceMessageFilter> filter,
std::unique_ptr<IPC::Message> message) {
ResourceDispatcherHostImpl::Get()->OnMessageReceived(
*message, filter.get());
}
// On Windows, ResourceMsg_SetDataBuffer supplies a HANDLE which is not
// automatically released.
//
// See ResourceDispatcher::ReleaseResourcesInDataMessage.
//
// TODO(davidben): It would be nice if the behavior for base::SharedMemoryHandle
// were more like it is in POSIX where the received fds are tracked in a
// ref-counted core that closes them if not extracted.
void ReleaseHandlesInMessage(const IPC::Message& message) {
if (message.type() == ResourceMsg_SetDataBuffer::ID) {
base::PickleIterator iter(message);
int request_id;
CHECK(iter.ReadInt(&request_id));
base::SharedMemoryHandle shm_handle;
if (IPC::ParamTraits<base::SharedMemoryHandle>::Read(&message,
&iter,
&shm_handle)) {
if (base::SharedMemory::IsHandleValid(shm_handle))
base::SharedMemory::CloseHandle(shm_handle);
}
}
}
} // namespace
static int RequestIDForMessage(const IPC::Message& msg) {
int request_id = -1;
switch (msg.type()) {
case ResourceMsg_UploadProgress::ID:
case ResourceMsg_ReceivedResponse::ID:
case ResourceMsg_ReceivedRedirect::ID:
case ResourceMsg_SetDataBuffer::ID:
case ResourceMsg_DataReceived::ID:
case ResourceMsg_InlinedDataChunkReceived::ID:
case ResourceMsg_DataDownloaded::ID:
case ResourceMsg_RequestComplete::ID: {
bool result = base::PickleIterator(msg).ReadInt(&request_id);
DCHECK(result);
break;
}
}
return request_id;
}
static ResourceRequest CreateResourceRequest(const char* method,
ResourceType type,
const GURL& url) {
ResourceRequest request;
request.method = std::string(method);
request.url = url;
request.first_party_for_cookies = url; // bypass third-party cookie blocking
request.request_initiator = url::Origin(url); // ensure initiator is set
request.referrer_policy = blink::WebReferrerPolicyDefault;
request.load_flags = 0;
request.origin_pid = 0;
request.resource_type = type;
request.request_context = 0;
request.appcache_host_id = kAppCacheNoHostId;
request.download_to_file = false;
request.should_reset_appcache = false;
request.is_main_frame = true;
request.parent_is_main_frame = false;
request.transition_type = ui::PAGE_TRANSITION_LINK;
request.allow_download = true;
return request;
}
// Spin up the message loop to kick off the request.
static void KickOffRequest() {
base::RunLoop().RunUntilIdle();
}
// We may want to move this to a shared space if it is useful for something else
class ResourceIPCAccumulator {
public:
~ResourceIPCAccumulator() {
for (size_t i = 0; i < messages_.size(); i++) {
ReleaseHandlesInMessage(messages_[i]);
}
}
// On Windows, takes ownership of SharedMemoryHandles in |msg|.
void AddMessage(const IPC::Message& msg) {
messages_.push_back(msg);
}
// This groups the messages by their request ID. The groups will be in order
// that the first message for each request ID was received, and the messages
// within the groups will be in the order that they appeared.
// Note that this clears messages_. The caller takes ownership of any
// SharedMemoryHandles in messages placed into |msgs|.
// TODO(mmenke): This seems really fragile. Consider reworking ownership.
typedef std::vector< std::vector<IPC::Message> > ClassifiedMessages;
void GetClassifiedMessages(ClassifiedMessages* msgs);
// Returns the reply of |msg|, which is a synchronous IPC message.
const IPC::Message* GetReply(const IPC::Message& msg);
private:
std::vector<IPC::Message> messages_;
};
// This is very inefficient as a result of repeatedly extracting the ID, use
// only for tests!
void ResourceIPCAccumulator::GetClassifiedMessages(ClassifiedMessages* msgs) {
while (!messages_.empty()) {
// Ignore unknown message types as it is valid for code to generated other
// IPCs as side-effects that we are not testing here.
int cur_id = RequestIDForMessage(messages_[0]);
if (cur_id != -1) {
std::vector<IPC::Message> cur_requests;
cur_requests.push_back(messages_[0]);
// find all other messages with this ID
for (int i = 1; i < static_cast<int>(messages_.size()); i++) {
int id = RequestIDForMessage(messages_[i]);
if (id == cur_id) {
cur_requests.push_back(messages_[i]);
messages_.erase(messages_.begin() + i);
i--;
}
}
msgs->push_back(cur_requests);
}
messages_.erase(messages_.begin());
}
}
const IPC::Message* ResourceIPCAccumulator::GetReply(const IPC::Message& msg) {
for (auto& reply : messages_) {
if (!reply.is_reply())
continue;
if (IPC::SyncMessage::GetMessageId(reply) ==
IPC::SyncMessage::GetMessageId(msg))
return &reply;
}
return nullptr;
}
// This is used to create a filter matching a specified child id.
class TestFilterSpecifyingChild : public ResourceMessageFilter {
public:
explicit TestFilterSpecifyingChild(ResourceContext* resource_context,
int process_id)
: ResourceMessageFilter(
process_id,
PROCESS_TYPE_RENDERER,
NULL,
NULL,
NULL,
NULL,
base::Bind(&TestFilterSpecifyingChild::GetContexts,
base::Unretained(this))),
resource_context_(resource_context),
canceled_(false),
received_after_canceled_(0) {
set_peer_process_for_testing(base::Process::Current());
}
void set_canceled(bool canceled) { canceled_ = canceled; }
int received_after_canceled() const { return received_after_canceled_; }
// ResourceMessageFilter override
bool Send(IPC::Message* msg) override {
// No messages should be received when the process has been canceled.
if (canceled_)
received_after_canceled_++;
ReleaseHandlesInMessage(*msg);
delete msg;
return true;
}
ResourceContext* resource_context() { return resource_context_; }
protected:
~TestFilterSpecifyingChild() override {}
private:
void GetContexts(ResourceType resource_type,
ResourceContext** resource_context,
net::URLRequestContext** request_context) {
*resource_context = resource_context_;
*request_context = resource_context_->GetRequestContext();
}
ResourceContext* resource_context_;
bool canceled_;
int received_after_canceled_;
DISALLOW_COPY_AND_ASSIGN(TestFilterSpecifyingChild);
};
class TestFilter : public TestFilterSpecifyingChild {
public:
explicit TestFilter(ResourceContext* resource_context)
: TestFilterSpecifyingChild(
resource_context,
ChildProcessHostImpl::GenerateChildProcessUniqueId()) {
ChildProcessSecurityPolicyImpl::GetInstance()->Add(child_id());
}
protected:
~TestFilter() override {
ChildProcessSecurityPolicyImpl::GetInstance()->Remove(child_id());
}
};
// This class forwards the incoming messages to the ResourceDispatcherHostTest.
// For the test, we want all the incoming messages to go to the same place,
// which is why this forwards.
class ForwardingFilter : public TestFilter {
public:
explicit ForwardingFilter(IPC::Sender* dest,
ResourceContext* resource_context)
: TestFilter(resource_context),
dest_(dest) {
}
// TestFilter override
bool Send(IPC::Message* msg) override { return dest_->Send(msg); }
private:
~ForwardingFilter() override {}
IPC::Sender* dest_;
DISALLOW_COPY_AND_ASSIGN(ForwardingFilter);
};
// This class is a variation on URLRequestTestJob in that it does
// not complete start upon entry, only when specifically told to.
class URLRequestTestDelayedStartJob : public net::URLRequestTestJob {
public:
URLRequestTestDelayedStartJob(net::URLRequest* request,
net::NetworkDelegate* network_delegate)
: net::URLRequestTestJob(request, network_delegate) {
Init();
}
URLRequestTestDelayedStartJob(net::URLRequest* request,
net::NetworkDelegate* network_delegate,
const std::string& response_headers,
const std::string& response_data,
bool auto_advance)
: net::URLRequestTestJob(request,
network_delegate,
response_headers,
response_data,
auto_advance) {
Init();
}
// Do nothing until you're told to.
void Start() override {}
// Finish starting a URL request whose job is an instance of
// URLRequestTestDelayedStartJob. It is illegal to call this routine
// with a URLRequest that does not use URLRequestTestDelayedStartJob.
static void CompleteStart(net::URLRequest* request) {
for (URLRequestTestDelayedStartJob* job = list_head_;
job;
job = job->next_) {
if (job->request() == request) {
job->net::URLRequestTestJob::Start();
return;
}
}
NOTREACHED();
}
static bool DelayedStartQueueEmpty() {
return !list_head_;
}
static void ClearQueue() {
if (list_head_) {
LOG(ERROR)
<< "Unreleased entries on URLRequestTestDelayedStartJob delay queue"
<< "; may result in leaks.";
list_head_ = NULL;
}
}
protected:
~URLRequestTestDelayedStartJob() override {
for (URLRequestTestDelayedStartJob** job = &list_head_; *job;
job = &(*job)->next_) {
if (*job == this) {
*job = (*job)->next_;
return;
}
}
NOTREACHED();
}
private:
void Init() {
next_ = list_head_;
list_head_ = this;
}
static URLRequestTestDelayedStartJob* list_head_;
URLRequestTestDelayedStartJob* next_;
};
URLRequestTestDelayedStartJob*
URLRequestTestDelayedStartJob::list_head_ = NULL;
// This class is a variation on URLRequestTestJob in that it
// returns IO_pending errors before every read, not just the first one.
class URLRequestTestDelayedCompletionJob : public net::URLRequestTestJob {
public:
URLRequestTestDelayedCompletionJob(net::URLRequest* request,
net::NetworkDelegate* network_delegate)
: net::URLRequestTestJob(request, network_delegate) {}
URLRequestTestDelayedCompletionJob(net::URLRequest* request,
net::NetworkDelegate* network_delegate,
bool auto_advance)
: net::URLRequestTestJob(request, network_delegate, auto_advance) {}
URLRequestTestDelayedCompletionJob(net::URLRequest* request,
net::NetworkDelegate* network_delegate,
const std::string& response_headers,
const std::string& response_data,
bool auto_advance)
: net::URLRequestTestJob(request,
network_delegate,
response_headers,
response_data,
auto_advance) {}
protected:
~URLRequestTestDelayedCompletionJob() override {}
private:
bool NextReadAsync() override { return true; }
};
// This class is a variation on URLRequestTestJob that ensures that no read is
// asked of this job.
class URLRequestMustNotReadTestJob : public net::URLRequestTestJob {
public:
URLRequestMustNotReadTestJob(net::URLRequest* request,
net::NetworkDelegate* network_delegate,
const std::string& response_headers,
const std::string& response_data)
: net::URLRequestTestJob(request,
network_delegate,
response_headers,
response_data,
false) {}
int ReadRawData(net::IOBuffer* buf, int buf_size) override {
EXPECT_TRUE(false) << "The job should have been cancelled before trying to "
"read the response body.";
return 0;
}
};
class URLRequestBigJob : public net::URLRequestSimpleJob {
public:
URLRequestBigJob(net::URLRequest* request,
net::NetworkDelegate* network_delegate)
: net::URLRequestSimpleJob(request, network_delegate) {
}
// URLRequestSimpleJob implementation:
int GetData(std::string* mime_type,
std::string* charset,
std::string* data,
const net::CompletionCallback& callback) const override {
*mime_type = "text/plain";
*charset = "UTF-8";
std::string text;
int count;
if (!ParseURL(request_->url(), &text, &count))
return net::ERR_INVALID_URL;
data->reserve(text.size() * count);
for (int i = 0; i < count; ++i)
data->append(text);
return net::OK;
}
base::TaskRunner* GetTaskRunner() const override {
return base::ThreadTaskRunnerHandle::Get().get();
}
private:
~URLRequestBigJob() override {}
// big-job:substring,N
static bool ParseURL(const GURL& url, std::string* text, int* count) {
std::vector<std::string> parts = base::SplitString(
url.path(), ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
if (parts.size() != 2)
return false;
*text = parts[0];
return base::StringToInt(parts[1], count);
}
};
// URLRequestJob used to test GetLoadInfoForAllRoutes. The LoadState and
// UploadProgress values are set for the jobs at the time of creation, and
// the jobs will never actually do anything.
class URLRequestLoadInfoJob : public net::URLRequestJob {
public:
URLRequestLoadInfoJob(net::URLRequest* request,
net::NetworkDelegate* network_delegate,
const net::LoadState& load_state)
: net::URLRequestJob(request, network_delegate),
load_state_(load_state) {}
// net::URLRequestJob implementation:
void Start() override {}
net::LoadState GetLoadState() const override { return load_state_; }
private:
~URLRequestLoadInfoJob() override {}
// big-job:substring,N
static bool ParseURL(const GURL& url, std::string* text, int* count) {
std::vector<std::string> parts = base::SplitString(
url.path(), ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
if (parts.size() != 2)
return false;
*text = parts[0];
return base::StringToInt(parts[1], count);
}
const net::LoadState load_state_;
};
class ResourceDispatcherHostTest;
class TestURLRequestJobFactory : public net::URLRequestJobFactory {
public:
explicit TestURLRequestJobFactory(ResourceDispatcherHostTest* test_fixture)
: test_fixture_(test_fixture),
hang_after_start_(false),
delay_start_(false),
delay_complete_(false),
must_not_read_(false),
url_request_jobs_created_count_(0) {}
void HandleScheme(const std::string& scheme) {
supported_schemes_.insert(scheme);
}
int url_request_jobs_created_count() const {
return url_request_jobs_created_count_;
}
// When set, jobs will hang eternally once started.
void SetHangAfterStartJobGeneration(bool hang_after_start) {
hang_after_start_ = hang_after_start;
}
void SetDelayedStartJobGeneration(bool delay_job_start) {
delay_start_ = delay_job_start;
}
void SetDelayedCompleteJobGeneration(bool delay_job_complete) {
delay_complete_ = delay_job_complete;
}
void SetMustNotReadJobGeneration(bool must_not_read) {
must_not_read_ = must_not_read;
}
net::URLRequestJob* MaybeCreateJobWithProtocolHandler(
const std::string& scheme,
net::URLRequest* request,
net::NetworkDelegate* network_delegate) const override;
net::URLRequestJob* MaybeInterceptRedirect(
net::URLRequest* request,
net::NetworkDelegate* network_delegate,
const GURL& location) const override;
net::URLRequestJob* MaybeInterceptResponse(
net::URLRequest* request,
net::NetworkDelegate* network_delegate) const override;
bool IsHandledProtocol(const std::string& scheme) const override {
return supported_schemes_.count(scheme) > 0;
}
bool IsHandledURL(const GURL& url) const override {
return supported_schemes_.count(url.scheme()) > 0;
}
bool IsSafeRedirectTarget(const GURL& location) const override {
return false;
}
private:
ResourceDispatcherHostTest* test_fixture_;
bool hang_after_start_;
bool delay_start_;
bool delay_complete_;
bool must_not_read_;
mutable int url_request_jobs_created_count_;
std::set<std::string> supported_schemes_;
DISALLOW_COPY_AND_ASSIGN(TestURLRequestJobFactory);
};
// Associated with an URLRequest to determine if the URLRequest gets deleted.
class TestUserData : public base::SupportsUserData::Data {
public:
explicit TestUserData(bool* was_deleted)
: was_deleted_(was_deleted) {
}
~TestUserData() override { *was_deleted_ = true; }
private:
bool* was_deleted_;
};
enum GenericResourceThrottleFlags {
NONE = 0,
DEFER_STARTING_REQUEST = 1 << 0,
DEFER_PROCESSING_RESPONSE = 1 << 1,
CANCEL_BEFORE_START = 1 << 2,
CANCEL_PROCESSING_RESPONSE = 1 << 3,
MUST_NOT_CACHE_BODY = 1 << 4,
};
// Throttle that tracks the current throttle blocking a request. Only one
// can throttle any request at a time.
class GenericResourceThrottle : public ResourceThrottle {
public:
// The value is used to indicate that the throttle should not provide
// a error code when cancelling a request. net::OK is used, because this
// is not an error code.
static const int USE_DEFAULT_CANCEL_ERROR_CODE = net::OK;
GenericResourceThrottle(int flags, int code)
: flags_(flags),
error_code_for_cancellation_(code) {
}
~GenericResourceThrottle() override {
if (active_throttle_ == this)
active_throttle_ = NULL;
}
// ResourceThrottle implementation:
void WillStartRequest(bool* defer) override {
ASSERT_EQ(NULL, active_throttle_);
if (flags_ & DEFER_STARTING_REQUEST) {
active_throttle_ = this;
*defer = true;
}
if (flags_ & CANCEL_BEFORE_START) {
if (error_code_for_cancellation_ == USE_DEFAULT_CANCEL_ERROR_CODE) {
controller()->Cancel();
} else {
controller()->CancelWithError(error_code_for_cancellation_);
}
}
}
void WillProcessResponse(bool* defer) override {
ASSERT_EQ(NULL, active_throttle_);
if (flags_ & DEFER_PROCESSING_RESPONSE) {
active_throttle_ = this;
*defer = true;
}
if (flags_ & CANCEL_PROCESSING_RESPONSE) {
if (error_code_for_cancellation_ == USE_DEFAULT_CANCEL_ERROR_CODE) {
controller()->Cancel();
} else {
controller()->CancelWithError(error_code_for_cancellation_);
}
}
}
const char* GetNameForLogging() const override {
return "GenericResourceThrottle";
}
void Resume() {
ASSERT_TRUE(this == active_throttle_);
active_throttle_ = NULL;
controller()->Resume();
}
static GenericResourceThrottle* active_throttle() {
return active_throttle_;
}
bool MustProcessResponseBeforeReadingBody() override {
return flags_ & MUST_NOT_CACHE_BODY;
}
private:
int flags_; // bit-wise union of GenericResourceThrottleFlags.
int error_code_for_cancellation_;
// The currently active throttle, if any.
static GenericResourceThrottle* active_throttle_;
};
// static
GenericResourceThrottle* GenericResourceThrottle::active_throttle_ = NULL;
class TestResourceDispatcherHostDelegate
: public ResourceDispatcherHostDelegate {
public:
TestResourceDispatcherHostDelegate()
: create_two_throttles_(false),
flags_(NONE),
error_code_for_cancellation_(
GenericResourceThrottle::USE_DEFAULT_CANCEL_ERROR_CODE) {
}
void set_url_request_user_data(base::SupportsUserData::Data* user_data) {
user_data_.reset(user_data);
}
void set_flags(int value) {
flags_ = value;
}
void set_error_code_for_cancellation(int code) {
error_code_for_cancellation_ = code;
}
void set_create_two_throttles(bool create_two_throttles) {
create_two_throttles_ = create_two_throttles;
}
// ResourceDispatcherHostDelegate implementation:
void RequestBeginning(net::URLRequest* request,
ResourceContext* resource_context,
AppCacheService* appcache_service,
ResourceType resource_type,
ScopedVector<ResourceThrottle>* throttles) override {
if (user_data_) {
const void* key = user_data_.get();
request->SetUserData(key, user_data_.release());
}
if (flags_ != NONE) {
throttles->push_back(new GenericResourceThrottle(
flags_, error_code_for_cancellation_));
if (create_two_throttles_)
throttles->push_back(new GenericResourceThrottle(
flags_, error_code_for_cancellation_));
}
}
private:
bool create_two_throttles_;
int flags_;
int error_code_for_cancellation_;
std::unique_ptr<base::SupportsUserData::Data> user_data_;
};
// Waits for a ShareableFileReference to be released.
class ShareableFileReleaseWaiter {
public:
explicit ShareableFileReleaseWaiter(const base::FilePath& path) {
scoped_refptr<ShareableFileReference> file =
ShareableFileReference::Get(path);
file->AddFinalReleaseCallback(
base::Bind(&ShareableFileReleaseWaiter::Released,
base::Unretained(this)));
}
void Wait() {
loop_.Run();
}
private:
void Released(const base::FilePath& path) {
loop_.Quit();
}
base::RunLoop loop_;
DISALLOW_COPY_AND_ASSIGN(ShareableFileReleaseWaiter);
};
// For verifying notifications sent to the WebContents by the
// ResourceDispatcherHostImpl.
class TestWebContentsObserver : public WebContentsObserver {
public:
explicit TestWebContentsObserver(WebContents* web_contents)
: WebContentsObserver(web_contents),
resource_request_redirect_count_(0),
resource_response_start_count_(0) {}
void DidGetRedirectForResourceRequest(
const ResourceRedirectDetails& details) override {
++resource_request_redirect_count_;
}
void DidGetResourceResponseStart(
const ResourceRequestDetails& details) override {
++resource_response_start_count_;
}
int resource_response_start_count() { return resource_response_start_count_; }
int resource_request_redirect_count() {
return resource_request_redirect_count_;
}
private:
int resource_request_redirect_count_;
int resource_response_start_count_;
};
enum class TestConfig {
kDefault,
kOptimizeIPCForSmallResourceEnabled,
};
void CheckRequestCompleteErrorCode(const IPC::Message& message,
int expected_error_code) {
// Verify the expected error code was received.
int request_id;
int error_code;
ASSERT_EQ(ResourceMsg_RequestComplete::ID, message.type());
base::PickleIterator iter(message);
ASSERT_TRUE(IPC::ReadParam(&message, &iter, &request_id));
ASSERT_TRUE(IPC::ReadParam(&message, &iter, &error_code));
ASSERT_EQ(expected_error_code, error_code);
}
class ResourceDispatcherHostTest : public testing::TestWithParam<TestConfig>,
public IPC::Sender {
public:
typedef ResourceDispatcherHostImpl::LoadInfo LoadInfo;
typedef ResourceDispatcherHostImpl::LoadInfoList LoadInfoList;
typedef ResourceDispatcherHostImpl::LoadInfoMap LoadInfoMap;
ResourceDispatcherHostTest()
: thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP),
host_(base::Bind(&DownloadResourceHandler::Create)),
use_test_ssl_certificate_(false),
send_data_received_acks_(false),
auto_advance_(false) {
host_.SetLoaderDelegate(&loader_delegate_);
browser_context_.reset(new TestBrowserContext());
BrowserContext::EnsureResourceContextInitialized(browser_context_.get());
base::RunLoop().RunUntilIdle();
filter_ = MakeForwardingFilter();
// TODO(cbentzel): Better way to get URLRequestContext?
net::URLRequestContext* request_context =
browser_context_->GetResourceContext()->GetRequestContext();
job_factory_.reset(new TestURLRequestJobFactory(this));
request_context->set_job_factory(job_factory_.get());
request_context->set_network_delegate(&network_delegate_);
}
~ResourceDispatcherHostTest() override {
filter_->OnChannelClosing();
}
// IPC::Sender implementation
bool Send(IPC::Message* msg) override {
accum_.AddMessage(*msg);
if (send_data_received_acks_ &&
msg->type() == ResourceMsg_DataReceived::ID) {
GenerateDataReceivedACK(*msg);
}
if (wait_for_request_complete_loop_ &&
msg->type() == ResourceMsg_RequestComplete::ID) {
wait_for_request_complete_loop_->Quit();
}
// Do not release handles in it yet; the accumulator owns them now.
delete msg;
return true;
}
protected:
friend class TestURLRequestJobFactory;
// testing::Test
void SetUp() override {
ChildProcessSecurityPolicyImpl::GetInstance()->Add(0);
HandleScheme("test");
scoped_refptr<SiteInstance> site_instance =
SiteInstance::Create(browser_context_.get());
web_contents_.reset(
WebContents::Create(WebContents::CreateParams(browser_context_.get())));
web_contents_observer_.reset(
new TestWebContentsObserver(web_contents_.get()));
web_contents_filter_ = new TestFilterSpecifyingChild(
browser_context_->GetResourceContext(),
web_contents_->GetRenderProcessHost()->GetID());
child_ids_.insert(web_contents_->GetRenderProcessHost()->GetID());
switch (GetParam()) {
case TestConfig::kDefault:
break;
case TestConfig::kOptimizeIPCForSmallResourceEnabled: {
scoped_feature_list_.InitAndEnableFeature(
features::kOptimizeLoadingIPCForSmallResources);
ASSERT_TRUE(base::FeatureList::IsEnabled(
features::kOptimizeLoadingIPCForSmallResources));
break;
}
}
}
void TearDown() override {
web_contents_filter_->OnChannelClosing();
web_contents_observer_.reset();
web_contents_.reset();
EXPECT_TRUE(URLRequestTestDelayedStartJob::DelayedStartQueueEmpty());
URLRequestTestDelayedStartJob::ClearQueue();
for (std::set<int>::iterator it = child_ids_.begin();
it != child_ids_.end(); ++it) {
host_.CancelRequestsForProcess(*it);
}
host_.Shutdown();
ChildProcessSecurityPolicyImpl::GetInstance()->Remove(0);
// Flush the message loop to make application verifiers happy.
if (ResourceDispatcherHostImpl::Get())
ResourceDispatcherHostImpl::Get()->CancelRequestsForContext(
browser_context_->GetResourceContext());
browser_context_.reset();
base::RunLoop().RunUntilIdle();
}
// Creates a new ForwardingFilter and registers it with |child_ids_| so as not
// to leak per-child state on test shutdown.
ForwardingFilter* MakeForwardingFilter() {
ForwardingFilter* filter =
new ForwardingFilter(this, browser_context_->GetResourceContext());
child_ids_.insert(filter->child_id());
return filter;
}
// Creates a request using the current test object as the filter and
// SubResource as the resource type.
void MakeTestRequest(int render_view_id,
int request_id,
const GURL& url);
void MakeTestRequestWithRenderFrame(int render_view_id,
int render_frame_id,
int request_id,
const GURL& url,
ResourceType type);
// Generates a request using the given filter and resource type.
void MakeTestRequestWithResourceType(ResourceMessageFilter* filter,
int render_view_id,
int request_id,
const GURL& url,
ResourceType type);
void MakeWebContentsAssociatedTestRequest(int request_id, const GURL& url);
void MakeWebContentsAssociatedTestRequestWithResourceType(int request_id,
const GURL& url,
ResourceType type);
// Generates a request with the given priority.
void MakeTestRequestWithPriority(int render_view_id,
int request_id,
net::RequestPriority priority);
void MakeTestRequestWithPriorityAndRenderFrame(int render_view_id,
int render_frame_id,
int request_id,
net::RequestPriority priority);
void MakeWebContentsAssociatedDownloadRequest(int request_id,
const GURL& url);
void CancelRequest(int request_id);
void RendererCancelRequest(int request_id) {
ResourceMessageFilter* old_filter = SetFilter(filter_.get());
host_.OnCancelRequest(request_id);
SetFilter(old_filter);
}
void CompleteStartRequest(int request_id);
void CompleteStartRequest(ResourceMessageFilter* filter, int request_id);
net::TestNetworkDelegate* network_delegate() { return &network_delegate_; }
void EnsureSchemeIsAllowed(const std::string& scheme) {
ChildProcessSecurityPolicyImpl* policy =
ChildProcessSecurityPolicyImpl::GetInstance();
if (!policy->IsWebSafeScheme(scheme))
policy->RegisterWebSafeScheme(scheme);
}
// Sets a particular response for any request from now on. To switch back to
// the default bahavior, pass an empty |headers|. |headers| should be CR[LF]
// terminated.
void SetResponse(const std::string& headers, const std::string& data) {
response_headers_ = headers;
response_data_ = data;
}
void SetResponse(const std::string& headers) {
SetResponse(headers, std::string());
}
// If called, requests called from now on will be created as
// TestHTTPSURLRequestJobs: that is, a test certificate will be set on
// the |ssl_info| field of the response.
void SetTestSSLCertificate() { use_test_ssl_certificate_ = true; }
void SendDataReceivedACKs(bool send_acks) {
send_data_received_acks_ = send_acks;
}
// Intercepts requests for the given protocol.
void HandleScheme(const std::string& scheme) {
job_factory_->HandleScheme(scheme);
EnsureSchemeIsAllowed(scheme);
}
void GenerateDataReceivedACK(const IPC::Message& msg) {
EXPECT_EQ(ResourceMsg_DataReceived::ID, msg.type());
int request_id = -1;
bool result = base::PickleIterator(msg).ReadInt(&request_id);
DCHECK(result);
std::unique_ptr<IPC::Message> ack(
new ResourceHostMsg_DataReceived_ACK(request_id));
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(&GenerateIPCMessage, filter_, base::Passed(&ack)));
}
// Setting filters for testing renderer messages.
// Returns the previous filter.
ResourceMessageFilter* SetFilter(ResourceMessageFilter* new_filter) {
ResourceMessageFilter* old_filter = host_.filter_;
host_.filter_ = new_filter;
return old_filter;
}
void WaitForRequestComplete() {
DCHECK(!wait_for_request_complete_loop_);
wait_for_request_complete_loop_.reset(new base::RunLoop);
wait_for_request_complete_loop_->Run();
wait_for_request_complete_loop_.reset();
}
void DeleteRenderFrame(const GlobalFrameRoutingId& global_routing_id) {
host_.OnRenderFrameDeleted(global_routing_id);
}
// Creates and drives a main resource request until completion. Then asserts
// that the expected_error_code has been emitted for the request.
void CompleteFailingMainResourceRequest(const GURL& url,
int expected_error_code) {
if (IsBrowserSideNavigationEnabled()) {
auto_advance_ = true;
// Make a navigation request.
TestNavigationURLLoaderDelegate delegate;
BeginNavigationParams begin_params(std::string(), net::LOAD_NORMAL, false,
false, REQUEST_CONTEXT_TYPE_LOCATION);
CommonNavigationParams common_params;
common_params.url = url;
std::unique_ptr<NavigationRequestInfo> request_info(
new NavigationRequestInfo(common_params, begin_params, url,
url::Origin(url), true, false, false, -1,
false, false));
std::unique_ptr<NavigationURLLoader> test_loader =
NavigationURLLoader::Create(browser_context_.get(),
std::move(request_info), nullptr, nullptr,
&delegate);
// The navigation should fail with the expected error code.
delegate.WaitForRequestFailed();
ASSERT_EQ(expected_error_code, delegate.net_error());
return;
}
MakeTestRequestWithResourceType(filter_.get(), 0, 1, url,
RESOURCE_TYPE_MAIN_FRAME);
// Flush all pending requests.
while (net::URLRequestTestJob::ProcessOnePendingMessage()) {
}
base::RunLoop().RunUntilIdle();
// Sorts out all the messages we saw by request.
ResourceIPCAccumulator::ClassifiedMessages msgs;
accum_.GetClassifiedMessages(&msgs);
// We should have gotten one RequestComplete message.
ASSERT_EQ(1U, msgs.size());
ASSERT_EQ(1U, msgs[0].size());
EXPECT_EQ(ResourceMsg_RequestComplete::ID, msgs[0][0].type());
// The RequestComplete message should have had the expected error code.
CheckRequestCompleteErrorCode(msgs[0][0], expected_error_code);
}
content::TestBrowserThreadBundle thread_bundle_;
std::unique_ptr<TestBrowserContext> browser_context_;
std::unique_ptr<TestURLRequestJobFactory> job_factory_;
std::unique_ptr<WebContents> web_contents_;
std::unique_ptr<TestWebContentsObserver> web_contents_observer_;
scoped_refptr<ForwardingFilter> filter_;
scoped_refptr<TestFilterSpecifyingChild> web_contents_filter_;
net::TestNetworkDelegate network_delegate_;
LoaderDelegateImpl loader_delegate_;
ResourceDispatcherHostImpl host_;
ResourceIPCAccumulator accum_;
std::string response_headers_;
std::string response_data_;
bool use_test_ssl_certificate_;
std::string scheme_;
bool send_data_received_acks_;
std::set<int> child_ids_;
std::unique_ptr<base::RunLoop> wait_for_request_complete_loop_;
RenderViewHostTestEnabler render_view_host_test_enabler_;
bool auto_advance_;
base::test::ScopedFeatureList scoped_feature_list_;
};
void ResourceDispatcherHostTest::MakeTestRequest(int render_view_id,
int request_id,
const GURL& url) {
MakeTestRequestWithResourceType(filter_.get(), render_view_id, request_id,
url, RESOURCE_TYPE_SUB_RESOURCE);
}
void ResourceDispatcherHostTest::MakeTestRequestWithRenderFrame(
int render_view_id,
int render_frame_id,
int request_id,
const GURL& url,
ResourceType type) {
ResourceRequest request = CreateResourceRequest("GET", type, url);
request.render_frame_id = render_frame_id;
ResourceHostMsg_RequestResource msg(render_view_id, request_id, request);
host_.OnMessageReceived(msg, filter_.get());
KickOffRequest();
}
void ResourceDispatcherHostTest::MakeTestRequestWithResourceType(
ResourceMessageFilter* filter,
int render_view_id,
int request_id,
const GURL& url,
ResourceType type) {
ResourceRequest request = CreateResourceRequest("GET", type, url);
ResourceHostMsg_RequestResource msg(render_view_id, request_id, request);
host_.OnMessageReceived(msg, filter);
KickOffRequest();
}
void ResourceDispatcherHostTest::MakeWebContentsAssociatedTestRequest(
int request_id,
const GURL& url) {
MakeWebContentsAssociatedTestRequestWithResourceType(
request_id, url, RESOURCE_TYPE_SUB_RESOURCE);
}
void ResourceDispatcherHostTest::
MakeWebContentsAssociatedTestRequestWithResourceType(int request_id,
const GURL& url,
ResourceType type) {
ResourceRequest request = CreateResourceRequest("GET", type, url);
request.origin_pid = web_contents_->GetRenderProcessHost()->GetID();
request.render_frame_id = web_contents_->GetMainFrame()->GetRoutingID();
ResourceHostMsg_RequestResource msg(web_contents_->GetRoutingID(), request_id,
request);
host_.OnMessageReceived(msg, web_contents_filter_.get());
KickOffRequest();
}
void ResourceDispatcherHostTest::MakeTestRequestWithPriority(
int render_view_id,
int request_id,
net::RequestPriority priority) {
MakeTestRequestWithPriorityAndRenderFrame(render_view_id, -1, request_id,
priority);
}
void ResourceDispatcherHostTest::MakeTestRequestWithPriorityAndRenderFrame(
int render_view_id,
int render_frame_id,
int request_id,
net::RequestPriority priority) {
ResourceRequest request = CreateResourceRequest(
"GET", RESOURCE_TYPE_SUB_RESOURCE, GURL("http://example.com/priority"));
request.render_frame_id = render_frame_id;
request.priority = priority;
ResourceHostMsg_RequestResource msg(render_view_id, request_id, request);
host_.OnMessageReceived(msg, filter_.get());
}
void ResourceDispatcherHostTest::MakeWebContentsAssociatedDownloadRequest(
int request_id,
const GURL& url) {
net::URLRequestContext* request_context =
browser_context_->GetResourceContext()->GetRequestContext();
std::unique_ptr<net::URLRequest> request(
request_context->CreateRequest(url, net::DEFAULT_PRIORITY, NULL));
DownloadManagerImpl::BeginDownloadRequest(
std::move(request), Referrer(), browser_context_->GetResourceContext(),
false, // is_content_initiated
web_contents_->GetRenderProcessHost()->GetID(),
web_contents_->GetRoutingID(),
web_contents_->GetMainFrame()->GetRoutingID(), false);
}
void ResourceDispatcherHostTest::CancelRequest(int request_id) {
host_.CancelRequest(filter_->child_id(), request_id);
}
void ResourceDispatcherHostTest::CompleteStartRequest(int request_id) {
CompleteStartRequest(filter_.get(), request_id);
}
void ResourceDispatcherHostTest::CompleteStartRequest(
ResourceMessageFilter* filter,
int request_id) {
GlobalRequestID gid(filter->child_id(), request_id);
net::URLRequest* req = host_.GetURLRequest(gid);
EXPECT_TRUE(req);
if (req)
URLRequestTestDelayedStartJob::CompleteStart(req);
}
testing::AssertionResult ExtractInlinedChunkData(
const IPC::Message& message,
std::string* leading_chunk_data) {
base::PickleIterator iter(message);
int request_id;
if (!IPC::ReadParam(&message, &iter, &request_id))
return testing::AssertionFailure() << "Could not read request_id";
std::vector<char> data;
if (!IPC::ReadParam(&message, &iter, &data))
return testing::AssertionFailure() << "Could not read data";
leading_chunk_data->assign(data.begin(), data.end());
return testing::AssertionSuccess();
}
testing::AssertionResult ExtractDataOffsetAndLength(const IPC::Message& message,
int* data_offset,
int* data_length) {
base::PickleIterator iter(message);
int request_id;
if (!IPC::ReadParam(&message, &iter, &request_id))
return testing::AssertionFailure() << "Could not read request_id";
if (!IPC::ReadParam(&message, &iter, data_offset))
return testing::AssertionFailure() << "Could not read data_offset";
if (!IPC::ReadParam(&message, &iter, data_length))
return testing::AssertionFailure() << "Could not read data_length";
return testing::AssertionSuccess();
}
void CheckSuccessfulRequestWithErrorCodeForInlinedCase(
const std::vector<IPC::Message>& messages,
const std::string& reference_data,
int expected_error) {
// A successful request on the inlined case will have received 3 messages:
// ReceivedResponse (indicates headers received)
// InlinedDataChunkReceived (contains the content)
// RequestComplete (request is done)
ASSERT_EQ(3U, messages.size());
// The first messages should be received response
ASSERT_EQ(ResourceMsg_ReceivedResponse::ID, messages[0].type());
ASSERT_EQ(ResourceMsg_InlinedDataChunkReceived::ID, messages[1].type());
std::string leading_chunk_data;
ASSERT_TRUE(ExtractInlinedChunkData(messages[1], &leading_chunk_data));
ASSERT_EQ(reference_data, leading_chunk_data);
CheckRequestCompleteErrorCode(messages[2], expected_error);
}
void CheckSuccessfulRequestWithErrorCode(
const std::vector<IPC::Message>& messages,
const std::string& reference_data,
int expected_error) {
ASSERT_LT(2U, messages.size());
if (base::FeatureList::IsEnabled(
features::kOptimizeLoadingIPCForSmallResources) &&
messages[1].type() == ResourceMsg_InlinedDataChunkReceived::ID) {
CheckSuccessfulRequestWithErrorCodeForInlinedCase(
messages, reference_data, expected_error);
return;
}
// A successful request will have received 4 messages:
// ReceivedResponse (indicates headers received)
// SetDataBuffer (contains shared memory handle)
// DataReceived (data offset and length into shared memory)
// RequestComplete (request is done)
//
// This function verifies that we received 4 messages and that they are
// appropriate. It allows for an error code other than net::OK if the request
// should successfully receive data and then abort, e.g., on cancel.
ASSERT_EQ(4U, messages.size());
// The first messages should be received response
ASSERT_EQ(ResourceMsg_ReceivedResponse::ID, messages[0].type());
ASSERT_EQ(ResourceMsg_SetDataBuffer::ID, messages[1].type());
base::PickleIterator iter(messages[1]);
int request_id;
ASSERT_TRUE(IPC::ReadParam(&messages[1], &iter, &request_id));
base::SharedMemoryHandle shm_handle;
ASSERT_TRUE(IPC::ReadParam(&messages[1], &iter, &shm_handle));
int shm_size;
ASSERT_TRUE(IPC::ReadParam(&messages[1], &iter, &shm_size));
// Followed by the data, currently we only do the data in one chunk, but
// should probably test multiple chunks later
ASSERT_EQ(ResourceMsg_DataReceived::ID, messages[2].type());
int data_offset;
int data_length;
ASSERT_TRUE(
ExtractDataOffsetAndLength(messages[2], &data_offset, &data_length));
ASSERT_EQ(reference_data.size(), static_cast<size_t>(data_length));
ASSERT_GE(shm_size, data_length);
base::SharedMemory shared_mem(shm_handle, true); // read only
shared_mem.Map(data_length);
const char* data = static_cast<char*>(shared_mem.memory()) + data_offset;
ASSERT_EQ(0, memcmp(reference_data.c_str(), data, data_length));
// The last message should be all data received.
CheckRequestCompleteErrorCode(messages[3], expected_error);
}
void CheckSuccessfulRequest(const std::vector<IPC::Message>& messages,
const std::string& reference_data) {
CheckSuccessfulRequestWithErrorCode(messages, reference_data, net::OK);
}
void CheckSuccessfulRedirect(const std::vector<IPC::Message>& messages,
const std::string& reference_data) {
ASSERT_EQ(5U, messages.size());
ASSERT_EQ(ResourceMsg_ReceivedRedirect::ID, messages[0].type());
const std::vector<IPC::Message> second_req_msgs =
std::vector<IPC::Message>(messages.begin() + 1, messages.end());
CheckSuccessfulRequest(second_req_msgs, reference_data);
}
void CheckFailedRequest(const std::vector<IPC::Message>& messages,
const std::string& reference_data,
int expected_error) {
ASSERT_LT(0U, messages.size());
ASSERT_GE(2U, messages.size());
size_t failure_index = messages.size() - 1;
if (messages.size() == 2) {
EXPECT_EQ(ResourceMsg_ReceivedResponse::ID, messages[0].type());
}
CheckRequestCompleteErrorCode(messages[failure_index], expected_error);
}
// Tests whether many messages get dispatched properly.
TEST_P(ResourceDispatcherHostTest, TestMany) {
MakeTestRequest(0, 1, net::URLRequestTestJob::test_url_1());
MakeTestRequest(0, 2, net::URLRequestTestJob::test_url_2());
MakeTestRequest(0, 3, net::URLRequestTestJob::test_url_3());
MakeTestRequestWithResourceType(filter_.get(), 0, 4,
net::URLRequestTestJob::test_url_4(),
RESOURCE_TYPE_PREFETCH); // detachable type
MakeTestRequest(0, 5, net::URLRequestTestJob::test_url_redirect_to_url_2());
// Finish the redirection
ResourceHostMsg_FollowRedirect redirect_msg(5);
host_.OnMessageReceived(redirect_msg, filter_.get());
base::RunLoop().RunUntilIdle();
// flush all the pending requests
while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
// sorts out all the messages we saw by request
ResourceIPCAccumulator::ClassifiedMessages msgs;
accum_.GetClassifiedMessages(&msgs);
// there are five requests, so we should have gotten them classified as such
ASSERT_EQ(5U, msgs.size());
CheckSuccessfulRequest(msgs[0], net::URLRequestTestJob::test_data_1());
CheckSuccessfulRequest(msgs[1], net::URLRequestTestJob::test_data_2());
CheckSuccessfulRequest(msgs[2], net::URLRequestTestJob::test_data_3());
CheckSuccessfulRequest(msgs[3], net::URLRequestTestJob::test_data_4());
CheckSuccessfulRedirect(msgs[4], net::URLRequestTestJob::test_data_2());
}
// Tests whether messages get canceled properly. We issue four requests,
// cancel two of them, and make sure that each sent the proper notifications.
TEST_P(ResourceDispatcherHostTest, Cancel) {
MakeTestRequest(0, 1, net::URLRequestTestJob::test_url_1());
MakeTestRequest(0, 2, net::URLRequestTestJob::test_url_2());
MakeTestRequest(0, 3, net::URLRequestTestJob::test_url_3());
MakeTestRequestWithResourceType(filter_.get(), 0, 4,
net::URLRequestTestJob::test_url_4(),
RESOURCE_TYPE_PREFETCH); // detachable type
CancelRequest(2);
// Cancel request must come from the renderer for a detachable resource to
// delay.
RendererCancelRequest(4);
// The handler should have been detached now.
GlobalRequestID global_request_id(filter_->child_id(), 4);
ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(
host_.GetURLRequest(global_request_id));
ASSERT_TRUE(info->detachable_handler()->is_detached());
// flush all the pending requests
while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
base::RunLoop().RunUntilIdle();
// Everything should be out now.
EXPECT_EQ(0, host_.pending_requests());
ResourceIPCAccumulator::ClassifiedMessages msgs;
accum_.GetClassifiedMessages(&msgs);
// there are four requests, so we should have gotten them classified as such
ASSERT_EQ(4U, msgs.size());
CheckSuccessfulRequest(msgs[0], net::URLRequestTestJob::test_data_1());
CheckSuccessfulRequest(msgs[2], net::URLRequestTestJob::test_data_3());
// Check that request 2 and 4 got canceled, as far as the renderer is
// concerned. Request 2 will have been deleted.
ASSERT_EQ(1U, msgs[1].size());
ASSERT_EQ(ResourceMsg_ReceivedResponse::ID, msgs[1][0].type());
ASSERT_EQ(2U, msgs[3].size());
ASSERT_EQ(ResourceMsg_ReceivedResponse::ID, msgs[3][0].type());
CheckRequestCompleteErrorCode(msgs[3][1], net::ERR_ABORTED);
// However, request 4 should have actually gone to completion. (Only request 2
// was canceled.)
EXPECT_EQ(4, network_delegate()->completed_requests());
EXPECT_EQ(1, network_delegate()->canceled_requests());
EXPECT_EQ(0, network_delegate()->error_count());
}
TEST_P(ResourceDispatcherHostTest, DownloadToNetworkCache) {
// Normal request.
MakeTestRequest(0, 1, net::URLRequestTestJob::test_url_2());
// Cache-only request.
ResourceRequest request_to_cache = CreateResourceRequest(
"GET", RESOURCE_TYPE_IMAGE, net::URLRequestTestJob::test_url_3());
request_to_cache.download_to_network_cache_only = true;
ResourceHostMsg_RequestResource msg_to_cache(0, 2, request_to_cache);
host_.OnMessageReceived(msg_to_cache, filter_.get());
KickOffRequest();
// The handler for the cache-only request should have been detached now.
GlobalRequestID global_request_id(filter_->child_id(), 2);
ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(
host_.GetURLRequest(global_request_id));
ASSERT_TRUE(info->detachable_handler()->is_detached());
// Flush all the pending requests.
while (net::URLRequestTestJob::ProcessOnePendingMessage()) {
}
base::RunLoop().RunUntilIdle();
// Everything should be out now.
EXPECT_EQ(0, host_.pending_requests());
ResourceIPCAccumulator::ClassifiedMessages msgs;
accum_.GetClassifiedMessages(&msgs);
// There are two requests, so we should have gotten them classified as such.
ASSERT_EQ(2U, msgs.size());
// The normal request succeeded.
CheckSuccessfulRequest(msgs[0], net::URLRequestTestJob::test_data_2());
// The cache-only request got canceled, as far as the renderer is concerned.
ASSERT_EQ(1U, msgs[1].size());
CheckRequestCompleteErrorCode(msgs[1][0], net::ERR_ABORTED);
// However, all requests should have actually gone to completion.
EXPECT_EQ(2, network_delegate()->completed_requests());
EXPECT_EQ(0, network_delegate()->canceled_requests());
EXPECT_EQ(0, network_delegate()->error_count());
}
// Shows that detachable requests will timeout if the request takes too long to
// complete.
TEST_P(ResourceDispatcherHostTest, DetachedResourceTimesOut) {
MakeTestRequestWithResourceType(filter_.get(), 0, 1,
net::URLRequestTestJob::test_url_2(),
RESOURCE_TYPE_PREFETCH); // detachable type
GlobalRequestID global_request_id(filter_->child_id(), 1);
ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(
host_.GetURLRequest(global_request_id));
ASSERT_TRUE(info->detachable_handler());
info->detachable_handler()->set_cancel_delay(
base::TimeDelta::FromMilliseconds(200));
base::RunLoop().RunUntilIdle();
RendererCancelRequest(1);
// From the renderer's perspective, the request was cancelled.
ResourceIPCAccumulator::ClassifiedMessages msgs;
accum_.GetClassifiedMessages(&msgs);
ASSERT_EQ(1U, msgs.size());
ASSERT_EQ(2U, msgs[0].size());
ASSERT_EQ(ResourceMsg_ReceivedResponse::ID, msgs[0][0].type());
CheckRequestCompleteErrorCode(msgs[0][1], net::ERR_ABORTED);
// But it continues detached.
EXPECT_EQ(1, host_.pending_requests());
EXPECT_TRUE(info->detachable_handler()->is_detached());
// Wait until after the delay timer times out before we start processing any
// messages.
base::OneShotTimer timer;
timer.Start(FROM_HERE, base::TimeDelta::FromMilliseconds(210),
base::MessageLoop::current(), &base::MessageLoop::QuitWhenIdle);
base::RunLoop().Run();
// The prefetch should be cancelled by now.
EXPECT_EQ(0, host_.pending_requests());
EXPECT_EQ(1, network_delegate()->completed_requests());
EXPECT_EQ(1, network_delegate()->canceled_requests());
EXPECT_EQ(0, network_delegate()->error_count());
}
TEST_P(ResourceDispatcherHostTest, SyncLoadSuccess) {
ResourceRequest request = CreateResourceRequest(
"GET", RESOURCE_TYPE_XHR, net::URLRequestTestJob::test_url_1());
request.priority = net::MAXIMUM_PRIORITY;
// Successful sync load.
std::tuple<SyncLoadResult> result;
ResourceHostMsg_SyncLoad sync_load_msg(0, 1, request, &std::get<0>(result));
host_.OnMessageReceived(sync_load_msg, filter_.get());
base::RunLoop().RunUntilIdle();
const IPC::Message* reply = accum_.GetReply(sync_load_msg);
ASSERT_TRUE(reply);
ASSERT_TRUE(ResourceHostMsg_SyncLoad::ReadReplyParam(reply, &result));
EXPECT_EQ(net::OK, std::get<0>(result).error_code);
}
TEST_P(ResourceDispatcherHostTest, SyncLoadError) {
ResourceRequest request = CreateResourceRequest(
"GET", RESOURCE_TYPE_XHR, net::URLRequestTestJob::test_url_error());
request.priority = net::MAXIMUM_PRIORITY;
// Failued sync load.
std::tuple<SyncLoadResult> result;
ResourceHostMsg_SyncLoad sync_load_msg(0, 1, request, &std::get<0>(result));
host_.OnMessageReceived(sync_load_msg, filter_.get());
base::RunLoop().RunUntilIdle();
const IPC::Message* reply = accum_.GetReply(sync_load_msg);
ASSERT_TRUE(reply);
ASSERT_TRUE(ResourceHostMsg_SyncLoad::ReadReplyParam(reply, &result));
EXPECT_EQ(net::ERR_INVALID_URL, std::get<0>(result).error_code);
}
TEST_P(ResourceDispatcherHostTest, SyncLoadCancel) {
ResourceRequest request = CreateResourceRequest(
"GET", RESOURCE_TYPE_XHR, net::URLRequestTestJob::test_url_1());
request.priority = net::MAXIMUM_PRIORITY;
// Cancelled sync load.
SyncLoadResult result;
ResourceHostMsg_SyncLoad sync_load_msg(0, 1, request, &result);
host_.OnMessageReceived(sync_load_msg, filter_.get());
host_.CancelRequestsForProcess(filter_->child_id());
base::RunLoop().RunUntilIdle();
const IPC::Message* reply = accum_.GetReply(sync_load_msg);
ASSERT_TRUE(reply);
ASSERT_TRUE(reply->is_reply_error());
}
// If the filter has disappeared then detachable resources should continue to
// load.
TEST_P(ResourceDispatcherHostTest, DeletedFilterDetached) {
// test_url_1's data is available synchronously, so use 2 and 3.
ResourceRequest request_prefetch = CreateResourceRequest(
"GET", RESOURCE_TYPE_PREFETCH, net::URLRequestTestJob::test_url_2());
ResourceRequest request_ping = CreateResourceRequest(
"GET", RESOURCE_TYPE_PING, net::URLRequestTestJob::test_url_3());
ResourceHostMsg_RequestResource msg_prefetch(0, 1, request_prefetch);
host_.OnMessageReceived(msg_prefetch, filter_.get());
ResourceHostMsg_RequestResource msg_ping(0, 2, request_ping);
host_.OnMessageReceived(msg_ping, filter_.get());
// Remove the filter before processing the requests by simulating channel
// closure.
ResourceRequestInfoImpl* info_prefetch = ResourceRequestInfoImpl::ForRequest(
host_.GetURLRequest(GlobalRequestID(filter_->child_id(), 1)));
ResourceRequestInfoImpl* info_ping = ResourceRequestInfoImpl::ForRequest(
host_.GetURLRequest(GlobalRequestID(filter_->child_id(), 2)));
DCHECK_EQ(filter_.get(), info_prefetch->filter());
DCHECK_EQ(filter_.get(), info_ping->filter());
filter_->OnChannelClosing();
info_prefetch->filter_.reset();
info_ping->filter_.reset();
// From the renderer's perspective, the requests were cancelled.
ResourceIPCAccumulator::ClassifiedMessages msgs;
accum_.GetClassifiedMessages(&msgs);
ASSERT_EQ(2U, msgs.size());
CheckRequestCompleteErrorCode(msgs[0][0], net::ERR_ABORTED);
CheckRequestCompleteErrorCode(msgs[1][0], net::ERR_ABORTED);
// But it continues detached.
EXPECT_EQ(2, host_.pending_requests());
EXPECT_TRUE(info_prefetch->detachable_handler()->is_detached());
EXPECT_TRUE(info_ping->detachable_handler()->is_detached());
KickOffRequest();
// Make sure the requests weren't canceled early.
EXPECT_EQ(2, host_.pending_requests());
while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
base::RunLoop().RunUntilIdle();
EXPECT_EQ(0, host_.pending_requests());
EXPECT_EQ(2, network_delegate()->completed_requests());
EXPECT_EQ(0, network_delegate()->canceled_requests());
EXPECT_EQ(0, network_delegate()->error_count());
}
// If the filter has disappeared (original process dies) then detachable
// resources should continue to load, even when redirected.
TEST_P(ResourceDispatcherHostTest, DeletedFilterDetachedRedirect) {
ResourceRequest request = CreateResourceRequest(
"GET", RESOURCE_TYPE_PREFETCH,
net::URLRequestTestJob::test_url_redirect_to_url_2());
ResourceHostMsg_RequestResource msg(0, 1, request);
host_.OnMessageReceived(msg, filter_.get());
// Remove the filter before processing the request by simulating channel
// closure.
GlobalRequestID global_request_id(filter_->child_id(), 1);
ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(
host_.GetURLRequest(global_request_id));
info->filter_->OnChannelClosing();
info->filter_.reset();
// From the renderer's perspective, the request was cancelled.
ResourceIPCAccumulator::ClassifiedMessages msgs;
accum_.GetClassifiedMessages(&msgs);
ASSERT_EQ(1U, msgs.size());
CheckRequestCompleteErrorCode(msgs[0][0], net::ERR_ABORTED);
// But it continues detached.
EXPECT_EQ(1, host_.pending_requests());
EXPECT_TRUE(info->detachable_handler()->is_detached());
// Verify no redirects before resetting the filter.
net::URLRequest* url_request = host_.GetURLRequest(global_request_id);
EXPECT_EQ(1u, url_request->url_chain().size());
KickOffRequest();
// Verify that a redirect was followed.
EXPECT_EQ(2u, url_request->url_chain().size());
// Make sure the request wasn't canceled early.
EXPECT_EQ(1, host_.pending_requests());
// Finish up the request.
while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
base::RunLoop().RunUntilIdle();
EXPECT_EQ(0, host_.pending_requests());
EXPECT_EQ(1, network_delegate()->completed_requests());
EXPECT_EQ(0, network_delegate()->canceled_requests());
EXPECT_EQ(0, network_delegate()->error_count());
}
TEST_P(ResourceDispatcherHostTest, CancelWhileStartIsDeferred) {
bool was_deleted = false;
// Arrange to have requests deferred before starting.
TestResourceDispatcherHostDelegate delegate;
delegate.set_flags(DEFER_STARTING_REQUEST);
delegate.set_url_request_user_data(new TestUserData(&was_deleted));
host_.SetDelegate(&delegate);
MakeTestRequest(0, 1, net::URLRequestTestJob::test_url_1());
// We cancel from the renderer because all non-renderer cancels delete
// the request synchronously.
RendererCancelRequest(1);
// Our TestResourceThrottle should not have been deleted yet. This is to
// ensure that destruction of the URLRequest happens asynchronously to
// calling CancelRequest.
EXPECT_FALSE(was_deleted);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(was_deleted);
}
TEST_P(ResourceDispatcherHostTest, DetachWhileStartIsDeferred) {
bool was_deleted = false;
// Arrange to have requests deferred before starting.
TestResourceDispatcherHostDelegate delegate;
delegate.set_flags(DEFER_STARTING_REQUEST);
delegate.set_url_request_user_data(new TestUserData(&was_deleted));
host_.SetDelegate(&delegate);
MakeTestRequestWithResourceType(filter_.get(), 0, 1,
net::URLRequestTestJob::test_url_1(),
RESOURCE_TYPE_PREFETCH); // detachable type
// Cancel request must come from the renderer for a detachable resource to
// detach.
RendererCancelRequest(1);
// Even after driving the event loop, the request has not been deleted.
EXPECT_FALSE(was_deleted);
// However, it is still throttled because the defer happened above the
// DetachableResourceHandler.
while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(was_deleted);
// Resume the request.
GenericResourceThrottle* throttle =
GenericResourceThrottle::active_throttle();
ASSERT_TRUE(throttle);
throttle->Resume();
// Now, the request completes.
while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(was_deleted);
EXPECT_EQ(1, network_delegate()->completed_requests());
EXPECT_EQ(0, network_delegate()->canceled_requests());
EXPECT_EQ(0, network_delegate()->error_count());
}
// Tests if cancel is called in ResourceThrottle::WillStartRequest, then the
// URLRequest will not be started.
TEST_P(ResourceDispatcherHostTest, CancelInResourceThrottleWillStartRequest) {
TestResourceDispatcherHostDelegate delegate;
delegate.set_flags(CANCEL_BEFORE_START);
host_.SetDelegate(&delegate);
MakeTestRequest(0, 1, net::URLRequestTestJob::test_url_1());
// flush all the pending requests
while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
base::RunLoop().RunUntilIdle();
ResourceIPCAccumulator::ClassifiedMessages msgs;
accum_.GetClassifiedMessages(&msgs);
// Check that request got canceled.
ASSERT_EQ(1U, msgs[0].size());
CheckRequestCompleteErrorCode(msgs[0][0], net::ERR_ABORTED);
// Make sure URLRequest is never started.
EXPECT_EQ(0, job_factory_->url_request_jobs_created_count());
}
TEST_P(ResourceDispatcherHostTest, PausedStartError) {
// Arrange to have requests deferred before processing response headers.
TestResourceDispatcherHostDelegate delegate;
delegate.set_flags(DEFER_PROCESSING_RESPONSE);
host_.SetDelegate(&delegate);
job_factory_->SetDelayedStartJobGeneration(true);
MakeTestRequest(0, 1, net::URLRequestTestJob::test_url_error());
CompleteStartRequest(1);
// flush all the pending requests
while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
base::RunLoop().RunUntilIdle();
EXPECT_EQ(0, host_.pending_requests());
}
TEST_P(ResourceDispatcherHostTest, ThrottleAndResumeTwice) {
// Arrange to have requests deferred before starting.
TestResourceDispatcherHostDelegate delegate;
delegate.set_flags(DEFER_STARTING_REQUEST);
delegate.set_create_two_throttles(true);
host_.SetDelegate(&delegate);
// Make sure the first throttle blocked the request, and then resume.
MakeTestRequest(0, 1, net::URLRequestTestJob::test_url_1());
GenericResourceThrottle* first_throttle =
GenericResourceThrottle::active_throttle();
ASSERT_TRUE(first_throttle);
first_throttle->Resume();
// Make sure the second throttle blocked the request, and then resume.
ASSERT_TRUE(GenericResourceThrottle::active_throttle());
ASSERT_NE(first_throttle, GenericResourceThrottle::active_throttle());
GenericResourceThrottle::active_throttle()->Resume();
ASSERT_FALSE(GenericResourceThrottle::active_throttle());
// The request is started asynchronously.
base::RunLoop().RunUntilIdle();
// Flush all the pending requests.
while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
EXPECT_EQ(0, host_.pending_requests());
// Make sure the request completed successfully.
ResourceIPCAccumulator::ClassifiedMessages msgs;
accum_.GetClassifiedMessages(&msgs);
ASSERT_EQ(1U, msgs.size());
CheckSuccessfulRequest(msgs[0], net::URLRequestTestJob::test_data_1());
}
// Tests that the delegate can cancel a request and provide a error code.
TEST_P(ResourceDispatcherHostTest, CancelInDelegate) {
TestResourceDispatcherHostDelegate delegate;
delegate.set_flags(CANCEL_BEFORE_START);
delegate.set_error_code_for_cancellation(net::ERR_ACCESS_DENIED);
host_.SetDelegate(&delegate);
MakeTestRequest(0, 1, net::URLRequestTestJob::test_url_1());
// The request will get cancelled by the throttle.
// flush all the pending requests
while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
base::RunLoop().RunUntilIdle();
ResourceIPCAccumulator::ClassifiedMessages msgs;
accum_.GetClassifiedMessages(&msgs);
// Check the cancellation
ASSERT_EQ(1U, msgs.size());
ASSERT_EQ(1U, msgs[0].size());
CheckRequestCompleteErrorCode(msgs[0][0], net::ERR_ACCESS_DENIED);
}
// Tests CancelRequestsForProcess
TEST_P(ResourceDispatcherHostTest, TestProcessCancel) {
scoped_refptr<TestFilter> test_filter = new TestFilter(
browser_context_->GetResourceContext());
child_ids_.insert(test_filter->child_id());
// request 1 goes to the test delegate
MakeTestRequestWithResourceType(test_filter.get(), 0, 1,
net::URLRequestTestJob::test_url_1(),
RESOURCE_TYPE_SUB_RESOURCE);
// request 2 goes to us
MakeTestRequest(0, 2, net::URLRequestTestJob::test_url_2());
// request 3 goes to the test delegate
MakeTestRequestWithResourceType(test_filter.get(), 0, 3,
net::URLRequestTestJob::test_url_3(),
RESOURCE_TYPE_SUB_RESOURCE);
// request 4 goes to us
MakeTestRequestWithResourceType(filter_.get(), 0, 4,
net::URLRequestTestJob::test_url_4(),
RESOURCE_TYPE_PREFETCH); // detachable type
// Make sure all requests have finished stage one. test_url_1 will have
// finished.
base::RunLoop().RunUntilIdle();
// TODO(mbelshe):
// Now that the async IO path is in place, the IO always completes on the
// initial call; so the requests have already completed. This basically
// breaks the whole test.
// EXPECT_EQ(3, host_.pending_requests());
// Process test_url_2 and test_url_3 for one level so one callback is called.
// We'll cancel test_url_4 (detachable) before processing it to verify that it
// delays the cancel.
for (int i = 0; i < 2; i++)
EXPECT_TRUE(net::URLRequestTestJob::ProcessOnePendingMessage());
// Cancel the requests to the test process.
host_.CancelRequestsForProcess(filter_->child_id());
test_filter->set_canceled(true);
// The requests should all be cancelled, except request 4, which is detached.
EXPECT_EQ(1, host_.pending_requests());
GlobalRequestID global_request_id(filter_->child_id(), 4);
ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(
host_.GetURLRequest(global_request_id));
ASSERT_TRUE(info->detachable_handler()->is_detached());
// Flush all the pending requests.
while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
EXPECT_EQ(0, host_.pending_requests());
// The test delegate should not have gotten any messages after being canceled.
ASSERT_EQ(0, test_filter->received_after_canceled());
// There should be two results.
ResourceIPCAccumulator::ClassifiedMessages msgs;
accum_.GetClassifiedMessages(&msgs);
ASSERT_EQ(2U, msgs.size());
CheckSuccessfulRequest(msgs[0], net::URLRequestTestJob::test_data_2());
// The detachable request was cancelled by the renderer before it
// finished. From the perspective of the renderer, it should have cancelled.
ASSERT_EQ(2U, msgs[1].size());
ASSERT_EQ(ResourceMsg_ReceivedResponse::ID, msgs[1][0].type());
CheckRequestCompleteErrorCode(msgs[1][1], net::ERR_ABORTED);
// But it completed anyway. For the network stack, no requests were canceled.
EXPECT_EQ(4, network_delegate()->completed_requests());
EXPECT_EQ(0, network_delegate()->canceled_requests());
EXPECT_EQ(0, network_delegate()->error_count());
test_filter->OnChannelClosing();
}
// Tests whether the correct requests get canceled when a RenderViewHost is
// deleted.
TEST_P(ResourceDispatcherHostTest, CancelRequestsOnRenderFrameDeleted) {
// Requests all hang once started. This prevents requests from being
// destroyed due to completion.
job_factory_->SetHangAfterStartJobGeneration(true);
HandleScheme("http");
TestResourceDispatcherHostDelegate delegate;
host_.SetDelegate(&delegate);
host_.OnRenderViewHostCreated(filter_->child_id(), 0);
// One RenderView issues a high priority request and a low priority one. Both
// should be started.
MakeTestRequestWithPriorityAndRenderFrame(0, 10, 1, net::HIGHEST);
MakeTestRequestWithPriorityAndRenderFrame(0, 11, 2, net::LOWEST);
KickOffRequest();
EXPECT_EQ(2, network_delegate_.created_requests());
EXPECT_EQ(0, network_delegate_.canceled_requests());
// The same RenderView issues two more low priority requests. The
// ResourceScheduler shouldn't let them start immediately.
MakeTestRequestWithPriorityAndRenderFrame(0, 10, 3, net::LOWEST);
MakeTestRequestWithPriorityAndRenderFrame(0, 11, 4, net::LOWEST);
KickOffRequest();
EXPECT_EQ(2, network_delegate_.created_requests());
EXPECT_EQ(0, network_delegate_.canceled_requests());
// Another RenderView in the same process as the old one issues a request,
// which is then started.
MakeTestRequestWithPriorityAndRenderFrame(1, 12, 5, net::LOWEST);
KickOffRequest();
EXPECT_EQ(3, network_delegate_.created_requests());
EXPECT_EQ(0, network_delegate_.canceled_requests());
// The first two RenderFrameHosts are destroyed. All 4 of their requests
// should be cancelled, and none of the two deferred requests should be
// started.
DeleteRenderFrame(GlobalFrameRoutingId(filter_->child_id(), 10));
DeleteRenderFrame(GlobalFrameRoutingId(filter_->child_id(), 11));
host_.OnRenderViewHostDeleted(filter_->child_id(), 0);
base::RunLoop().RunUntilIdle();
EXPECT_EQ(3, network_delegate_.created_requests());
EXPECT_EQ(4, network_delegate_.canceled_requests());
// No messages should have been sent, since none of the jobs made any
// progress.
ResourceIPCAccumulator::ClassifiedMessages msgs;
accum_.GetClassifiedMessages(&msgs);
EXPECT_EQ(0U, msgs.size());
}
TEST_P(ResourceDispatcherHostTest, TestProcessCancelDetachedTimesOut) {
MakeTestRequestWithResourceType(filter_.get(), 0, 1,
net::URLRequestTestJob::test_url_4(),
RESOURCE_TYPE_PREFETCH); // detachable type
GlobalRequestID global_request_id(filter_->child_id(), 1);
ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(
host_.GetURLRequest(global_request_id));
ASSERT_TRUE(info->detachable_handler());
info->detachable_handler()->set_cancel_delay(
base::TimeDelta::FromMilliseconds(200));
base::RunLoop().RunUntilIdle();
// Cancel the requests to the test process.
host_.CancelRequestsForProcess(filter_->child_id());
EXPECT_EQ(1, host_.pending_requests());
// Wait until after the delay timer times out before we start processing any
// messages.
base::OneShotTimer timer;
timer.Start(FROM_HERE, base::TimeDelta::FromMilliseconds(210),
base::MessageLoop::current(), &base::MessageLoop::QuitWhenIdle);
base::RunLoop().Run();
// The prefetch should be cancelled by now.
EXPECT_EQ(0, host_.pending_requests());
// In case any messages are still to be processed.
while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
base::RunLoop().RunUntilIdle();
ResourceIPCAccumulator::ClassifiedMessages msgs;
accum_.GetClassifiedMessages(&msgs);
ASSERT_EQ(1U, msgs.size());
// The request should have cancelled.
ASSERT_EQ(2U, msgs[0].size());
ASSERT_EQ(ResourceMsg_ReceivedResponse::ID, msgs[0][0].type());
CheckRequestCompleteErrorCode(msgs[0][1], net::ERR_ABORTED);
// And not run to completion.
EXPECT_EQ(1, network_delegate()->completed_requests());
EXPECT_EQ(1, network_delegate()->canceled_requests());
EXPECT_EQ(0, network_delegate()->error_count());
}
// Tests blocking and resuming requests.
TEST_P(ResourceDispatcherHostTest, TestBlockingResumingRequests) {
host_.BlockRequestsForRoute(GlobalFrameRoutingId(filter_->child_id(), 11));
host_.BlockRequestsForRoute(GlobalFrameRoutingId(filter_->child_id(), 12));
host_.BlockRequestsForRoute(GlobalFrameRoutingId(filter_->child_id(), 13));
MakeTestRequestWithRenderFrame(0, 10, 1, net::URLRequestTestJob::test_url_1(),
RESOURCE_TYPE_SUB_RESOURCE);
MakeTestRequestWithRenderFrame(1, 11, 2, net::URLRequestTestJob::test_url_2(),
RESOURCE_TYPE_SUB_RESOURCE);
MakeTestRequestWithRenderFrame(0, 10, 3, net::URLRequestTestJob::test_url_3(),
RESOURCE_TYPE_SUB_RESOURCE);
MakeTestRequestWithRenderFrame(1, 11, 4, net::URLRequestTestJob::test_url_1(),
RESOURCE_TYPE_SUB_RESOURCE);
MakeTestRequestWithRenderFrame(2, 12, 5, net::URLRequestTestJob::test_url_2(),
RESOURCE_TYPE_SUB_RESOURCE);
MakeTestRequestWithRenderFrame(3, 13, 6, net::URLRequestTestJob::test_url_3(),
RESOURCE_TYPE_SUB_RESOURCE);
// Flush all the pending requests
while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
// Sort out all the messages we saw by request
ResourceIPCAccumulator::ClassifiedMessages msgs;
accum_.GetClassifiedMessages(&msgs);
// All requests but the 2 for the RFH 0 should have been blocked.
ASSERT_EQ(2U, msgs.size());
CheckSuccessfulRequest(msgs[0], net::URLRequestTestJob::test_data_1());
CheckSuccessfulRequest(msgs[1], net::URLRequestTestJob::test_data_3());
// Resume requests for RFH 11 and flush pending requests.
host_.ResumeBlockedRequestsForRoute(
GlobalFrameRoutingId(filter_->child_id(), 11));
KickOffRequest();
while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
msgs.clear();
accum_.GetClassifiedMessages(&msgs);
ASSERT_EQ(2U, msgs.size());
CheckSuccessfulRequest(msgs[0], net::URLRequestTestJob::test_data_2());
CheckSuccessfulRequest(msgs[1], net::URLRequestTestJob::test_data_1());
// Test that new requests are not blocked for RFH 11.
MakeTestRequestWithRenderFrame(1, 11, 7, net::URLRequestTestJob::test_url_1(),
RESOURCE_TYPE_SUB_RESOURCE);
while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
msgs.clear();
accum_.GetClassifiedMessages(&msgs);
ASSERT_EQ(1U, msgs.size());
CheckSuccessfulRequest(msgs[0], net::URLRequestTestJob::test_data_1());
// Now resumes requests for all RFH (12 and 13).
host_.ResumeBlockedRequestsForRoute(
GlobalFrameRoutingId(filter_->child_id(), 12));
host_.ResumeBlockedRequestsForRoute(
GlobalFrameRoutingId(filter_->child_id(), 13));
KickOffRequest();
while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
msgs.clear();
accum_.GetClassifiedMessages(&msgs);
ASSERT_EQ(2U, msgs.size());
CheckSuccessfulRequest(msgs[0], net::URLRequestTestJob::test_data_2());
CheckSuccessfulRequest(msgs[1], net::URLRequestTestJob::test_data_3());
}
// Tests blocking and canceling requests.
TEST_P(ResourceDispatcherHostTest, TestBlockingCancelingRequests) {
host_.BlockRequestsForRoute(GlobalFrameRoutingId(filter_->child_id(), 11));
MakeTestRequestWithRenderFrame(0, 10, 1, net::URLRequestTestJob::test_url_1(),
RESOURCE_TYPE_SUB_RESOURCE);
MakeTestRequestWithRenderFrame(1, 11, 2, net::URLRequestTestJob::test_url_2(),
RESOURCE_TYPE_SUB_RESOURCE);
MakeTestRequestWithRenderFrame(0, 10, 3, net::URLRequestTestJob::test_url_3(),
RESOURCE_TYPE_SUB_RESOURCE);
MakeTestRequestWithRenderFrame(1, 11, 4, net::URLRequestTestJob::test_url_1(),
RESOURCE_TYPE_SUB_RESOURCE);
// Blocked detachable resources should not delay cancellation.
//
MakeTestRequestWithRenderFrame(1, 11, 5, net::URLRequestTestJob::test_url_4(),
RESOURCE_TYPE_PREFETCH); // detachable type
// Flush all the pending requests.
while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
// Sort out all the messages we saw by request.
ResourceIPCAccumulator::ClassifiedMessages msgs;
accum_.GetClassifiedMessages(&msgs);
// The 2 requests for the RFH 10 should have been processed.
ASSERT_EQ(2U, msgs.size());
CheckSuccessfulRequest(msgs[0], net::URLRequestTestJob::test_data_1());
CheckSuccessfulRequest(msgs[1], net::URLRequestTestJob::test_data_3());
// Cancel requests for RFH 11.
host_.CancelBlockedRequestsForRoute(
GlobalFrameRoutingId(filter_->child_id(), 11));
KickOffRequest();
while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
msgs.clear();
accum_.GetClassifiedMessages(&msgs);
ASSERT_EQ(0U, msgs.size());
}
// Tests that blocked requests are canceled if their associated process dies.
TEST_P(ResourceDispatcherHostTest, TestBlockedRequestsProcessDies) {
// This second filter is used to emulate a second process.
scoped_refptr<ForwardingFilter> second_filter = MakeForwardingFilter();
host_.BlockRequestsForRoute(
GlobalFrameRoutingId(second_filter->child_id(), 0));
MakeTestRequestWithResourceType(filter_.get(), 0, 1,
net::URLRequestTestJob::test_url_1(),
RESOURCE_TYPE_SUB_RESOURCE);
MakeTestRequestWithResourceType(second_filter.get(), 0, 2,
net::URLRequestTestJob::test_url_2(),
RESOURCE_TYPE_SUB_RESOURCE);
MakeTestRequestWithResourceType(filter_.get(), 0, 3,
net::URLRequestTestJob::test_url_3(),
RESOURCE_TYPE_SUB_RESOURCE);
MakeTestRequestWithResourceType(second_filter.get(), 0, 4,
net::URLRequestTestJob::test_url_1(),
RESOURCE_TYPE_SUB_RESOURCE);
MakeTestRequestWithResourceType(second_filter.get(), 0, 5,
net::URLRequestTestJob::test_url_4(),
RESOURCE_TYPE_PREFETCH); // detachable type
// Simulate process death.
host_.CancelRequestsForProcess(second_filter->child_id());
// Flush all the pending requests.
while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
// Sort out all the messages we saw by request.
ResourceIPCAccumulator::ClassifiedMessages msgs;
accum_.GetClassifiedMessages(&msgs);
// The 2 requests for the RVH 0 should have been processed. Note that
// blocked detachable requests are canceled without delay.
ASSERT_EQ(2U, msgs.size());
CheckSuccessfulRequest(msgs[0], net::URLRequestTestJob::test_data_1());
CheckSuccessfulRequest(msgs[1], net::URLRequestTestJob::test_data_3());
EXPECT_TRUE(host_.blocked_loaders_map_.empty());
second_filter->OnChannelClosing();
}
// Tests that blocked requests don't leak when the ResourceDispatcherHost goes
// away. Note that we rely on Purify for finding the leaks if any.
// If this test turns the Purify bot red, check the ResourceDispatcherHost
// destructor to make sure the blocked requests are deleted.
TEST_P(ResourceDispatcherHostTest, TestBlockedRequestsDontLeak) {
// This second filter is used to emulate a second process.
scoped_refptr<ForwardingFilter> second_filter = MakeForwardingFilter();
host_.BlockRequestsForRoute(GlobalFrameRoutingId(filter_->child_id(), 1));
host_.BlockRequestsForRoute(GlobalFrameRoutingId(filter_->child_id(), 2));
host_.BlockRequestsForRoute(
GlobalFrameRoutingId(second_filter->child_id(), 1));
MakeTestRequestWithResourceType(filter_.get(), 0, 1,
net::URLRequestTestJob::test_url_1(),
RESOURCE_TYPE_SUB_RESOURCE);
MakeTestRequestWithResourceType(filter_.get(), 1, 2,
net::URLRequestTestJob::test_url_2(),
RESOURCE_TYPE_SUB_RESOURCE);
MakeTestRequestWithResourceType(filter_.get(), 0, 3,
net::URLRequestTestJob::test_url_3(),
RESOURCE_TYPE_SUB_RESOURCE);
MakeTestRequestWithResourceType(second_filter.get(), 1, 4,
net::URLRequestTestJob::test_url_1(),
RESOURCE_TYPE_SUB_RESOURCE);
MakeTestRequestWithResourceType(filter_.get(), 2, 5,
net::URLRequestTestJob::test_url_2(),
RESOURCE_TYPE_SUB_RESOURCE);
MakeTestRequestWithResourceType(filter_.get(), 2, 6,
net::URLRequestTestJob::test_url_3(),
RESOURCE_TYPE_SUB_RESOURCE);
MakeTestRequestWithResourceType(filter_.get(), 0, 7,
net::URLRequestTestJob::test_url_4(),
RESOURCE_TYPE_PREFETCH); // detachable type
MakeTestRequestWithResourceType(second_filter.get(), 1, 8,
net::URLRequestTestJob::test_url_4(),
RESOURCE_TYPE_PREFETCH); // detachable type
host_.CancelRequestsForProcess(filter_->child_id());
host_.CancelRequestsForProcess(second_filter->child_id());
// Flush all the pending requests.
while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
second_filter->OnChannelClosing();
}
// Test the private helper method "CalculateApproximateMemoryCost()".
TEST_P(ResourceDispatcherHostTest, CalculateApproximateMemoryCost) {
net::URLRequestContext context;
std::unique_ptr<net::URLRequest> req(context.CreateRequest(
GURL("http://www.google.com"), net::DEFAULT_PRIORITY, NULL));
EXPECT_EQ(4425, ResourceDispatcherHostImpl::CalculateApproximateMemoryCost(
req.get()));
// Add 9 bytes of referrer.
req->SetReferrer("123456789");
EXPECT_EQ(4434, ResourceDispatcherHostImpl::CalculateApproximateMemoryCost(
req.get()));
// Add 33 bytes of upload content.
std::string upload_content;
upload_content.resize(33);
std::fill(upload_content.begin(), upload_content.end(), 'x');
std::unique_ptr<net::UploadElementReader> reader(
new net::UploadBytesElementReader(upload_content.data(),
upload_content.size()));
req->set_upload(
net::ElementsUploadDataStream::CreateWithReader(std::move(reader), 0));
// Since the upload throttling is disabled, this has no effect on the cost.
EXPECT_EQ(4434, ResourceDispatcherHostImpl::CalculateApproximateMemoryCost(
req.get()));
}
// Test that too much memory for outstanding requests for a particular
// render_process_host_id causes requests to fail.
TEST_P(ResourceDispatcherHostTest, TooMuchOutstandingRequestsMemory) {
// Expected cost of each request as measured by
// ResourceDispatcherHost::CalculateApproximateMemoryCost().
int kMemoryCostOfTest2Req =
ResourceDispatcherHostImpl::kAvgBytesPerOutstandingRequest +
net::URLRequestTestJob::test_url_2().spec().size() + sizeof("GET") - 1;
// Tighten the bound on the ResourceDispatcherHost, to speed things up.
int kMaxCostPerProcess = 440000;
host_.set_max_outstanding_requests_cost_per_process(kMaxCostPerProcess);
// Determine how many instance of test_url_2() we can request before
// throttling kicks in.
size_t kMaxRequests = kMaxCostPerProcess / kMemoryCostOfTest2Req;
// This second filter is used to emulate a second process.
scoped_refptr<ForwardingFilter> second_filter = MakeForwardingFilter();
// Saturate the number of outstanding requests for our process.
for (size_t i = 0; i < kMaxRequests; ++i) {
MakeTestRequestWithResourceType(filter_.get(), 0, i + 1,
net::URLRequestTestJob::test_url_2(),
RESOURCE_TYPE_SUB_RESOURCE);
}
// Issue two more requests for our process -- these should fail immediately.
MakeTestRequestWithResourceType(filter_.get(), 0, kMaxRequests + 1,
net::URLRequestTestJob::test_url_2(),
RESOURCE_TYPE_SUB_RESOURCE);
MakeTestRequestWithResourceType(filter_.get(), 0, kMaxRequests + 2,
net::URLRequestTestJob::test_url_2(),
RESOURCE_TYPE_SUB_RESOURCE);
// Issue two requests for the second process -- these should succeed since
// it is just process 0 that is saturated.
MakeTestRequestWithResourceType(second_filter.get(), 0, kMaxRequests + 3,
net::URLRequestTestJob::test_url_2(),
RESOURCE_TYPE_SUB_RESOURCE);
MakeTestRequestWithResourceType(second_filter.get(), 0, kMaxRequests + 4,
net::URLRequestTestJob::test_url_2(),
RESOURCE_TYPE_SUB_RESOURCE);
// Flush all the pending requests.
while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
base::RunLoop().RunUntilIdle();
// Sorts out all the messages we saw by request.
ResourceIPCAccumulator::ClassifiedMessages msgs;
accum_.GetClassifiedMessages(&msgs);
// We issued (kMaxRequests + 4) total requests.
ASSERT_EQ(kMaxRequests + 4, msgs.size());
// Check that the first kMaxRequests succeeded.
for (size_t i = 0; i < kMaxRequests; ++i)
CheckSuccessfulRequest(msgs[i], net::URLRequestTestJob::test_data_2());
// Check that the subsequent two requests (kMaxRequests + 1) and
// (kMaxRequests + 2) were failed, since the per-process bound was reached.
for (int i = 0; i < 2; ++i) {
// Should have sent a single RequestComplete message.
int index = kMaxRequests + i;
CheckFailedRequest(msgs[index], net::URLRequestTestJob::test_data_2(),
net::ERR_INSUFFICIENT_RESOURCES);
}
// The final 2 requests should have succeeded.
CheckSuccessfulRequest(msgs[kMaxRequests + 2],
net::URLRequestTestJob::test_data_2());
CheckSuccessfulRequest(msgs[kMaxRequests + 3],
net::URLRequestTestJob::test_data_2());
second_filter->OnChannelClosing();
}
// Test that when too many requests are outstanding for a particular
// render_process_host_id, any subsequent request from it fails. Also verify
// that the global limit is honored.
TEST_P(ResourceDispatcherHostTest, TooManyOutstandingRequests) {
// Tighten the bound on the ResourceDispatcherHost, to speed things up.
const size_t kMaxRequestsPerProcess = 2;
host_.set_max_num_in_flight_requests_per_process(kMaxRequestsPerProcess);
const size_t kMaxRequests = 3;
host_.set_max_num_in_flight_requests(kMaxRequests);
// Needed to emulate additional processes.
scoped_refptr<ForwardingFilter> second_filter = MakeForwardingFilter();
scoped_refptr<ForwardingFilter> third_filter = MakeForwardingFilter();
// Saturate the number of outstanding requests for our process.
for (size_t i = 0; i < kMaxRequestsPerProcess; ++i) {
MakeTestRequestWithResourceType(filter_.get(), 0, i + 1,
net::URLRequestTestJob::test_url_2(),
RESOURCE_TYPE_SUB_RESOURCE);
}
// Issue another request for our process -- this should fail immediately.
MakeTestRequestWithResourceType(filter_.get(), 0, kMaxRequestsPerProcess + 1,
net::URLRequestTestJob::test_url_2(),
RESOURCE_TYPE_SUB_RESOURCE);
// Issue a request for the second process -- this should succeed, because it
// is just process 0 that is saturated.
MakeTestRequestWithResourceType(
second_filter.get(), 0, kMaxRequestsPerProcess + 2,
net::URLRequestTestJob::test_url_2(), RESOURCE_TYPE_SUB_RESOURCE);
// Issue a request for the third process -- this should fail, because the
// global limit has been reached.
MakeTestRequestWithResourceType(
third_filter.get(), 0, kMaxRequestsPerProcess + 3,
net::URLRequestTestJob::test_url_2(), RESOURCE_TYPE_SUB_RESOURCE);
// Flush all the pending requests.
while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
base::RunLoop().RunUntilIdle();
// Sorts out all the messages we saw by request.
ResourceIPCAccumulator::ClassifiedMessages msgs;
accum_.GetClassifiedMessages(&msgs);
// The processes issued the following requests:
// #1 issued kMaxRequestsPerProcess that passed + 1 that failed
// #2 issued 1 request that passed
// #3 issued 1 request that failed
ASSERT_EQ((kMaxRequestsPerProcess + 1) + 1 + 1, msgs.size());
for (size_t i = 0; i < kMaxRequestsPerProcess; ++i)
CheckSuccessfulRequest(msgs[i], net::URLRequestTestJob::test_data_2());
CheckFailedRequest(msgs[kMaxRequestsPerProcess + 0],
net::URLRequestTestJob::test_data_2(),
net::ERR_INSUFFICIENT_RESOURCES);
CheckSuccessfulRequest(msgs[kMaxRequestsPerProcess + 1],
net::URLRequestTestJob::test_data_2());
CheckFailedRequest(msgs[kMaxRequestsPerProcess + 2],
net::URLRequestTestJob::test_data_2(),
net::ERR_INSUFFICIENT_RESOURCES);
second_filter->OnChannelClosing();
third_filter->OnChannelClosing();
}
// Tests that we sniff the mime type for a simple request.
TEST_P(ResourceDispatcherHostTest, MimeSniffed) {
std::string raw_headers("HTTP/1.1 200 OK\n\n");
std::string response_data("<html><title>Test One</title></html>");
SetResponse(raw_headers, response_data);
HandleScheme("http");
MakeTestRequest(0, 1, GURL("http:bla"));
// Flush all pending requests.
while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
// Sorts out all the messages we saw by request.
ResourceIPCAccumulator::ClassifiedMessages msgs;
accum_.GetClassifiedMessages(&msgs);
ASSERT_EQ(1U, msgs.size());
ResourceResponseHead response_head;
GetResponseHead(msgs[0], &response_head);
ASSERT_EQ("text/html", response_head.mime_type);
}
// Tests that we don't sniff the mime type when the server provides one.
TEST_P(ResourceDispatcherHostTest, MimeNotSniffed) {
std::string raw_headers("HTTP/1.1 200 OK\n"
"Content-type: image/jpeg\n\n");
std::string response_data("<html><title>Test One</title></html>");
SetResponse(raw_headers, response_data);
HandleScheme("http");
MakeTestRequest(0, 1, GURL("http:bla"));
// Flush all pending requests.
while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
// Sorts out all the messages we saw by request.
ResourceIPCAccumulator::ClassifiedMessages msgs;
accum_.GetClassifiedMessages(&msgs);
ASSERT_EQ(1U, msgs.size());
ResourceResponseHead response_head;
GetResponseHead(msgs[0], &response_head);
ASSERT_EQ("image/jpeg", response_head.mime_type);
}
// Tests that we don't sniff the mime type when there is no message body.
TEST_P(ResourceDispatcherHostTest, MimeNotSniffed2) {
SetResponse("HTTP/1.1 304 Not Modified\n\n");
HandleScheme("http");
MakeTestRequest(0, 1, GURL("http:bla"));
// Flush all pending requests.
while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
// Sorts out all the messages we saw by request.
ResourceIPCAccumulator::ClassifiedMessages msgs;
accum_.GetClassifiedMessages(&msgs);
ASSERT_EQ(1U, msgs.size());
ResourceResponseHead response_head;
GetResponseHead(msgs[0], &response_head);
ASSERT_EQ("", response_head.mime_type);
}
TEST_P(ResourceDispatcherHostTest, MimeSniff204) {
SetResponse("HTTP/1.1 204 No Content\n\n");
HandleScheme("http");
MakeTestRequest(0, 1, GURL("http:bla"));
// Flush all pending requests.
while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
// Sorts out all the messages we saw by request.
ResourceIPCAccumulator::ClassifiedMessages msgs;
accum_.GetClassifiedMessages(&msgs);
ASSERT_EQ(1U, msgs.size());
ResourceResponseHead response_head;
GetResponseHead(msgs[0], &response_head);
ASSERT_EQ("text/plain", response_head.mime_type);
}
TEST_P(ResourceDispatcherHostTest, MimeSniffEmpty) {
SetResponse("HTTP/1.1 200 OK\n\n");
HandleScheme("http");
MakeTestRequest(0, 1, GURL("http:bla"));
// Flush all pending requests.
while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
// Sorts out all the messages we saw by request.
ResourceIPCAccumulator::ClassifiedMessages msgs;
accum_.GetClassifiedMessages(&msgs);
ASSERT_EQ(1U, msgs.size());
ResourceResponseHead response_head;
GetResponseHead(msgs[0], &response_head);
ASSERT_EQ("text/plain", response_head.mime_type);
}
// Tests for crbug.com/31266 (Non-2xx + application/octet-stream).
TEST_P(ResourceDispatcherHostTest, ForbiddenDownload) {
NavigationResourceThrottle::set_ui_checks_always_succeed_for_testing(true);
std::string raw_headers("HTTP/1.1 403 Forbidden\n"
"Content-disposition: attachment; filename=blah\n"
"Content-type: application/octet-stream\n\n");
std::string response_data("<html><title>Test One</title></html>");
SetResponse(raw_headers, response_data);
HandleScheme("http");
int expected_error_code = net::ERR_INVALID_RESPONSE;
GURL forbidden_download_url = GURL("http:bla");
CompleteFailingMainResourceRequest(forbidden_download_url,
expected_error_code);
}
// Test for http://crbug.com/76202 . We don't want to destroy a
// download request prematurely when processing a cancellation from
// the renderer.
TEST_P(ResourceDispatcherHostTest, IgnoreCancelForDownloads) {
// PlzNavigate: A request that ends up being a download is a main resource
// request. Hence, it has been initiated by the browser and is not associated
// with a renderer. Therefore, it cannot be canceled by a renderer IPC.
if (IsBrowserSideNavigationEnabled()) {
SUCCEED() << "Not applicable with --enable-browser-side-navigation.";
return;
}
NavigationResourceThrottle::set_ui_checks_always_succeed_for_testing(true);
EXPECT_EQ(0, host_.pending_requests());
int render_view_id = 0;
int request_id = 1;
std::string raw_headers("HTTP\n"
"Content-disposition: attachment; filename=foo\n\n");
std::string response_data("01234567890123456789\x01foobar");
// Get past sniffing metrics in the MimeTypeResourceHandler. Note that
// if we don't get past the sniffing metrics, the result will be that
// the MimeTypeResourceHandler won't have figured out that it's a download,
// won't have constructed a DownloadResourceHandler, and and the request will
// be successfully canceled below, failing the test.
response_data.resize(1025, ' ');
SetResponse(raw_headers, response_data);
job_factory_->SetDelayedCompleteJobGeneration(true);
HandleScheme("http");
MakeTestRequestWithResourceType(filter_.get(), render_view_id, request_id,
GURL("http://example.com/blah"),
RESOURCE_TYPE_MAIN_FRAME);
// Return some data so that the request is identified as a download
// and the proper resource handlers are created.
EXPECT_TRUE(net::URLRequestTestJob::ProcessOnePendingMessage());
base::RunLoop().RunUntilIdle();
// And now simulate a cancellation coming from the renderer.
ResourceHostMsg_CancelRequest msg(request_id);
host_.OnMessageReceived(msg, filter_.get());
// Since the request had already started processing as a download,
// the cancellation above should have been ignored and the request
// should still be alive.
EXPECT_EQ(1, host_.pending_requests());
while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
base::RunLoop().RunUntilIdle();
}
TEST_P(ResourceDispatcherHostTest, CancelRequestsForContext) {
EXPECT_EQ(0, host_.pending_requests());
NavigationResourceThrottle::set_ui_checks_always_succeed_for_testing(true);
int render_view_id = 0;
int request_id = 1;
std::string raw_headers("HTTP\n"
"Content-disposition: attachment; filename=foo\n\n");
std::string response_data("01234567890123456789\x01foobar");
// Get past sniffing metrics.
response_data.resize(1025, ' ');
SetResponse(raw_headers, response_data);
job_factory_->SetDelayedCompleteJobGeneration(true);
HandleScheme("http");
const GURL download_url = GURL("http://example.com/blah");
if (IsBrowserSideNavigationEnabled()) {
// Create a NavigationRequest.
TestNavigationURLLoaderDelegate delegate;
BeginNavigationParams begin_params(std::string(), net::LOAD_NORMAL, false,
false, REQUEST_CONTEXT_TYPE_LOCATION);
CommonNavigationParams common_params;
common_params.url = download_url;
std::unique_ptr<NavigationRequestInfo> request_info(
new NavigationRequestInfo(common_params, begin_params, download_url,
url::Origin(download_url), true, false, false,
-1, false, false));
std::unique_ptr<NavigationURLLoader> loader = NavigationURLLoader::Create(
browser_context_.get(), std::move(request_info), nullptr, nullptr,
&delegate);
// Wait until a response has been received and proceed with the response.
KickOffRequest();
// Return some data so that the request is identified as a download
// and the proper resource handlers are created.
EXPECT_TRUE(net::URLRequestTestJob::ProcessOnePendingMessage());
base::RunLoop().RunUntilIdle();
// The UI thread will be informed that the navigation failed with an error
// code of ERR_ABORTED because the navigation turns out to be a download.
// The navigation is aborted, but the request goes on as a download.
EXPECT_EQ(delegate.net_error(), net::ERR_ABORTED);
EXPECT_EQ(1, host_.pending_requests());
// In PlzNavigate, the renderer cannot cancel the request directly.
// However, cancelling by context should work.
host_.CancelRequestsForContext(browser_context_->GetResourceContext());
EXPECT_EQ(0, host_.pending_requests());
base::RunLoop().RunUntilIdle();
} else {
MakeTestRequestWithResourceType(filter_.get(), render_view_id, request_id,
download_url, RESOURCE_TYPE_MAIN_FRAME);
// Return some data so that the request is identified as a download
// and the proper resource handlers are created.
EXPECT_TRUE(net::URLRequestTestJob::ProcessOnePendingMessage());
base::RunLoop().RunUntilIdle();
// And now simulate a cancellation coming from the renderer.
ResourceHostMsg_CancelRequest msg(request_id);
host_.OnMessageReceived(msg, filter_.get());
// Since the request had already started processing as a download,
// the cancellation above should have been ignored and the request
// should still be alive.
EXPECT_EQ(1, host_.pending_requests());
// Cancelling by other methods shouldn't work either.
host_.CancelRequestsForProcess(render_view_id);
EXPECT_EQ(1, host_.pending_requests());
// Cancelling by context should work.
host_.CancelRequestsForContext(filter_->resource_context());
EXPECT_EQ(0, host_.pending_requests());
while (net::URLRequestTestJob::ProcessOnePendingMessage()) {
}
base::RunLoop().RunUntilIdle();
}
}
TEST_P(ResourceDispatcherHostTest, CancelRequestsForContextDetached) {
EXPECT_EQ(0, host_.pending_requests());
int render_view_id = 0;
int request_id = 1;
MakeTestRequestWithResourceType(filter_.get(), render_view_id, request_id,
net::URLRequestTestJob::test_url_4(),
RESOURCE_TYPE_PREFETCH); // detachable type
// Simulate a cancel coming from the renderer.
RendererCancelRequest(request_id);
// Since the request had already started processing as detachable,
// the cancellation above should have been ignored and the request
// should have been detached.
EXPECT_EQ(1, host_.pending_requests());
// Cancelling by other methods should also leave it detached.
host_.CancelRequestsForProcess(render_view_id);
EXPECT_EQ(1, host_.pending_requests());
// Cancelling by context should work.
host_.CancelRequestsForContext(filter_->resource_context());
EXPECT_EQ(0, host_.pending_requests());
}
// Test the cancelling of requests that are being transferred to a new renderer
// due to a redirection.
TEST_P(ResourceDispatcherHostTest, CancelRequestsForContextTransferred) {
// PlzNavigate: there are no transferred requests in PlzNavigate.
if (IsBrowserSideNavigationEnabled())
return;
NavigationResourceThrottle::set_ui_checks_always_succeed_for_testing(true);
EXPECT_EQ(0, host_.pending_requests());
int request_id = 1;
std::string raw_headers("HTTP/1.1 200 OK\n"
"Content-Type: text/html; charset=utf-8\n\n");
std::string response_data("<html>foobar</html>");
SetResponse(raw_headers, response_data);
HandleScheme("http");
MakeWebContentsAssociatedTestRequestWithResourceType(
request_id, GURL("http://example.com/blah"), RESOURCE_TYPE_MAIN_FRAME);
GlobalRequestID global_request_id(web_contents_filter_->child_id(),
request_id);
host_.MarkAsTransferredNavigation(global_request_id, base::Closure());
// And now simulate a cancellation coming from the renderer.
ResourceHostMsg_CancelRequest msg(request_id);
host_.OnMessageReceived(msg, web_contents_filter_.get());
// Since the request is marked as being transferred,
// the cancellation above should have been ignored and the request
// should still be alive.
EXPECT_EQ(1, host_.pending_requests());
// Cancelling by other methods shouldn't work either.
host_.CancelRequestsForProcess(web_contents_->GetRoutingID());
EXPECT_EQ(1, host_.pending_requests());
// Cancelling by context should work.
host_.CancelRequestsForContext(web_contents_filter_->resource_context());
EXPECT_EQ(0, host_.pending_requests());
}
// Test transferred navigations with text/html, which doesn't trigger any
// content sniffing.
TEST_P(ResourceDispatcherHostTest, TransferNavigationHtml) {
if (IsBrowserSideNavigationEnabled()) {
SUCCEED() << "Test is not applicable with browser side navigation enabled";
return;
}
EXPECT_EQ(0, host_.pending_requests());
NavigationResourceThrottle::set_ui_checks_always_succeed_for_testing(true);
NavigationResourceThrottle::set_force_transfer_for_testing(true);
int render_view_id = 0;
int request_id = 1;
// Configure initial request.
SetResponse("HTTP/1.1 302 Found\n"
"Location: http://other.com/blech\n\n");
HandleScheme("http");
MakeTestRequestWithResourceType(filter_.get(), render_view_id, request_id,
GURL("http://example.com/blah"),
RESOURCE_TYPE_MAIN_FRAME);
// Now that we're blocked on the redirect, update the response and unblock by
// telling the AsyncResourceHandler to follow the redirect.
const std::string kResponseBody = "hello world";
SetResponse("HTTP/1.1 200 OK\n"
"Content-Type: text/html\n\n",
kResponseBody);
ResourceHostMsg_FollowRedirect redirect_msg(request_id);
host_.OnMessageReceived(redirect_msg, filter_.get());
base::RunLoop().RunUntilIdle();
// Flush all the pending requests to get the response through the
// MimeTypeResourceHandler.
while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
// This second filter is used to emulate a second process.
scoped_refptr<ForwardingFilter> second_filter = MakeForwardingFilter();
int new_render_view_id = 1;
int new_request_id = 2;
ResourceRequest request = CreateResourceRequest(
"GET", RESOURCE_TYPE_MAIN_FRAME, GURL("http://other.com/blech"));
request.transferred_request_child_id = filter_->child_id();
request.transferred_request_request_id = request_id;
ResourceHostMsg_RequestResource transfer_request_msg(
new_render_view_id, new_request_id, request);
host_.OnMessageReceived(transfer_request_msg, second_filter.get());
base::RunLoop().RunUntilIdle();
// Check generated messages.
ResourceIPCAccumulator::ClassifiedMessages msgs;
accum_.GetClassifiedMessages(&msgs);
ASSERT_EQ(2U, msgs.size());
EXPECT_EQ(ResourceMsg_ReceivedRedirect::ID, msgs[0][0].type());
CheckSuccessfulRequest(msgs[1], kResponseBody);
second_filter->OnChannelClosing();
}
// Test transferring two navigations with text/html, to ensure the resource
// accounting works.
TEST_P(ResourceDispatcherHostTest, TransferTwoNavigationsHtml) {
if (IsBrowserSideNavigationEnabled()) {
SUCCEED() << "Test is not applicable with browser side navigation enabled";
return;
}
NavigationResourceThrottle::set_force_transfer_for_testing(true);
NavigationResourceThrottle::set_ui_checks_always_succeed_for_testing(true);
EXPECT_EQ(0, host_.pending_requests());
int render_view_id = 0;
int request_id = 1;
// Configure initial request.
const std::string kResponseBody = "hello world";
SetResponse("HTTP/1.1 200 OK\n"
"Content-Type: text/html\n\n",
kResponseBody);
HandleScheme("http");
// Make the first request.
MakeTestRequestWithResourceType(filter_.get(), render_view_id, request_id,
GURL("http://example.com/blah"),
RESOURCE_TYPE_MAIN_FRAME);
// Make a second request from the same process.
int second_request_id = 2;
MakeTestRequestWithResourceType(filter_.get(), render_view_id,
second_request_id,
GURL("http://example.com/foo"),
RESOURCE_TYPE_MAIN_FRAME);
// Flush all the pending requests to get the response through the
// MimeTypeResourceHandler.
while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
NavigationResourceThrottle::set_force_transfer_for_testing(false);
// This second filter is used to emulate a second process.
scoped_refptr<ForwardingFilter> second_filter = MakeForwardingFilter();
// Transfer the first request.
int new_render_view_id = 1;
int new_request_id = 5;
ResourceRequest request = CreateResourceRequest(
"GET", RESOURCE_TYPE_MAIN_FRAME, GURL("http://example.com/blah"));
request.transferred_request_child_id = filter_->child_id();
request.transferred_request_request_id = request_id;
ResourceHostMsg_RequestResource transfer_request_msg(
new_render_view_id, new_request_id, request);
host_.OnMessageReceived(transfer_request_msg, second_filter.get());
base::RunLoop().RunUntilIdle();
// Transfer the second request.
int new_second_request_id = 6;
ResourceRequest second_request = CreateResourceRequest(
"GET", RESOURCE_TYPE_MAIN_FRAME, GURL("http://example.com/foo"));
request.transferred_request_child_id = filter_->child_id();
request.transferred_request_request_id = second_request_id;
ResourceHostMsg_RequestResource second_transfer_request_msg(
new_render_view_id, new_second_request_id, second_request);
host_.OnMessageReceived(second_transfer_request_msg, second_filter.get());
base::RunLoop().RunUntilIdle();
// Check generated messages.
ResourceIPCAccumulator::ClassifiedMessages msgs;
accum_.GetClassifiedMessages(&msgs);
ASSERT_EQ(2U, msgs.size());
CheckSuccessfulRequest(msgs[0], kResponseBody);
second_filter->OnChannelClosing();
}
// Test transferred navigations with text/plain, which causes
// MimeTypeResourceHandler to buffer the response to sniff the content before
// the transfer occurs.
TEST_P(ResourceDispatcherHostTest, TransferNavigationText) {
if (IsBrowserSideNavigationEnabled()) {
SUCCEED() << "Test is not applicable with browser side navigation enabled";
return;
}
NavigationResourceThrottle::set_force_transfer_for_testing(true);
NavigationResourceThrottle::set_ui_checks_always_succeed_for_testing(true);
EXPECT_EQ(0, host_.pending_requests());
int render_view_id = 0;
int request_id = 1;
// Configure initial request.
SetResponse("HTTP/1.1 302 Found\n"
"Location: http://other.com/blech\n\n");
HandleScheme("http");
MakeTestRequestWithResourceType(filter_.get(), render_view_id, request_id,
GURL("http://example.com/blah"),
RESOURCE_TYPE_MAIN_FRAME);
// Now that we're blocked on the redirect, update the response and unblock by
// telling the AsyncResourceHandler to follow the redirect. Use a text/plain
// MIME type, which causes MimeTypeResourceHandler to buffer it before the
// transfer occurs.
const std::string kResponseBody = "hello world";
SetResponse("HTTP/1.1 200 OK\n"
"Content-Type: text/plain\n\n",
kResponseBody);
ResourceHostMsg_FollowRedirect redirect_msg(request_id);
host_.OnMessageReceived(redirect_msg, filter_.get());
base::RunLoop().RunUntilIdle();
// Flush all the pending requests to get the response through the
// MimeTypeResourceHandler.
while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
base::RunLoop().RunUntilIdle();
// This second filter is used to emulate a second process.
scoped_refptr<ForwardingFilter> second_filter = MakeForwardingFilter();
int new_render_view_id = 1;
int new_request_id = 2;
ResourceRequest request = CreateResourceRequest(
"GET", RESOURCE_TYPE_MAIN_FRAME, GURL("http://other.com/blech"));
request.transferred_request_child_id = filter_->child_id();
request.transferred_request_request_id = request_id;
ResourceHostMsg_RequestResource transfer_request_msg(
new_render_view_id, new_request_id, request);
host_.OnMessageReceived(transfer_request_msg, second_filter.get());
base::RunLoop().RunUntilIdle();
// Check generated messages.
ResourceIPCAccumulator::ClassifiedMessages msgs;
accum_.GetClassifiedMessages(&msgs);
ASSERT_EQ(2U, msgs.size());
EXPECT_EQ(ResourceMsg_ReceivedRedirect::ID, msgs[0][0].type());
CheckSuccessfulRequest(msgs[1], kResponseBody);
second_filter->OnChannelClosing();
}
TEST_P(ResourceDispatcherHostTest, TransferNavigationWithProcessCrash) {
if (IsBrowserSideNavigationEnabled()) {
SUCCEED() << "Test is not applicable with browser side navigation enabled";
return;
}
NavigationResourceThrottle::set_force_transfer_for_testing(true);
NavigationResourceThrottle::set_ui_checks_always_succeed_for_testing(true);
EXPECT_EQ(0, host_.pending_requests());
int render_view_id = 0;
int request_id = 1;
int first_child_id = -1;
// Configure initial request.
SetResponse("HTTP/1.1 302 Found\n"
"Location: http://other.com/blech\n\n");
const std::string kResponseBody = "hello world";
HandleScheme("http");
// Create a first filter that can be deleted before the second one starts.
{
scoped_refptr<ForwardingFilter> first_filter = MakeForwardingFilter();
first_child_id = first_filter->child_id();
ResourceRequest first_request = CreateResourceRequest(
"GET", RESOURCE_TYPE_MAIN_FRAME, GURL("http://example.com/blah"));
ResourceHostMsg_RequestResource first_request_msg(
render_view_id, request_id, first_request);
host_.OnMessageReceived(first_request_msg, first_filter.get());
base::RunLoop().RunUntilIdle();
// Now that we're blocked on the redirect, update the response and unblock
// by telling the AsyncResourceHandler to follow the redirect.
SetResponse("HTTP/1.1 200 OK\n"
"Content-Type: text/html\n\n",
kResponseBody);
ResourceHostMsg_FollowRedirect redirect_msg(request_id);
host_.OnMessageReceived(redirect_msg, first_filter.get());
base::RunLoop().RunUntilIdle();
// Flush all the pending requests to get the response through the
// MimeTypeResourceHandler.
while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
first_filter->OnChannelClosing();
}
// The first filter is now deleted, as if the child process died.
// Make sure we don't hold onto the ResourceMessageFilter after it is deleted.
GlobalRequestID first_global_request_id(first_child_id, request_id);
// This second filter is used to emulate a second process.
scoped_refptr<ForwardingFilter> second_filter = MakeForwardingFilter();
int new_render_view_id = 1;
int new_request_id = 2;
ResourceRequest request = CreateResourceRequest(
"GET", RESOURCE_TYPE_MAIN_FRAME, GURL("http://other.com/blech"));
request.transferred_request_child_id = first_child_id;
request.transferred_request_request_id = request_id;
// For cleanup.
child_ids_.insert(second_filter->child_id());
ResourceHostMsg_RequestResource transfer_request_msg(
new_render_view_id, new_request_id, request);
host_.OnMessageReceived(transfer_request_msg, second_filter.get());
base::RunLoop().RunUntilIdle();
// Check generated messages.
ResourceIPCAccumulator::ClassifiedMessages msgs;
accum_.GetClassifiedMessages(&msgs);
ASSERT_EQ(2U, msgs.size());
EXPECT_EQ(ResourceMsg_ReceivedRedirect::ID, msgs[0][0].type());
CheckSuccessfulRequest(msgs[1], kResponseBody);
second_filter->OnChannelClosing();
}
TEST_P(ResourceDispatcherHostTest, TransferNavigationWithTwoRedirects) {
if (IsBrowserSideNavigationEnabled()) {
SUCCEED() << "Test is not applicable with browser side navigation enabled";
return;
}
NavigationResourceThrottle::set_force_transfer_for_testing(true);
NavigationResourceThrottle::set_ui_checks_always_succeed_for_testing(true);
EXPECT_EQ(0, host_.pending_requests());
int render_view_id = 0;
int request_id = 1;
// Configure initial request.
SetResponse("HTTP/1.1 302 Found\n"
"Location: http://other.com/blech\n\n");
HandleScheme("http");
MakeTestRequestWithResourceType(filter_.get(), render_view_id, request_id,
GURL("http://example.com/blah"),
RESOURCE_TYPE_MAIN_FRAME);
// Now that we're blocked on the redirect, simulate hitting another redirect.
SetResponse("HTTP/1.1 302 Found\n"
"Location: http://other.com/blerg\n\n");
ResourceHostMsg_FollowRedirect redirect_msg(request_id);
host_.OnMessageReceived(redirect_msg, filter_.get());
base::RunLoop().RunUntilIdle();
// Now that we're blocked on the second redirect, update the response and
// unblock by telling the AsyncResourceHandler to follow the redirect.
// Again, use text/plain to force MimeTypeResourceHandler to buffer before
// the transfer.
const std::string kResponseBody = "hello world";
SetResponse("HTTP/1.1 200 OK\n"
"Content-Type: text/plain\n\n",
kResponseBody);
ResourceHostMsg_FollowRedirect redirect_msg2(request_id);
host_.OnMessageReceived(redirect_msg2, filter_.get());
base::RunLoop().RunUntilIdle();
// Flush all the pending requests to get the response through the
// MimeTypeResourceHandler.
while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
base::RunLoop().RunUntilIdle();
// This second filter is used to emulate a second process.
scoped_refptr<ForwardingFilter> second_filter = MakeForwardingFilter();
int new_render_view_id = 1;
int new_request_id = 2;
ResourceRequest request = CreateResourceRequest(
"GET", RESOURCE_TYPE_MAIN_FRAME, GURL("http://other.com/blech"));
request.transferred_request_child_id = filter_->child_id();
request.transferred_request_request_id = request_id;
// For cleanup.
child_ids_.insert(second_filter->child_id());
ResourceHostMsg_RequestResource transfer_request_msg(
new_render_view_id, new_request_id, request);
host_.OnMessageReceived(transfer_request_msg, second_filter.get());
// Verify that we update the ResourceRequestInfo.
GlobalRequestID global_request_id(second_filter->child_id(), new_request_id);
const ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(
host_.GetURLRequest(global_request_id));
EXPECT_EQ(second_filter->child_id(), info->GetChildID());
EXPECT_EQ(new_render_view_id, info->GetRouteID());
EXPECT_EQ(new_request_id, info->GetRequestID());
EXPECT_EQ(second_filter.get(), info->filter());
// Let request complete.
base::RunLoop().RunUntilIdle();
// Check generated messages.
ResourceIPCAccumulator::ClassifiedMessages msgs;
accum_.GetClassifiedMessages(&msgs);
ASSERT_EQ(2U, msgs.size());
EXPECT_EQ(ResourceMsg_ReceivedRedirect::ID, msgs[0][0].type());
CheckSuccessfulRequest(msgs[1], kResponseBody);
second_filter->OnChannelClosing();
}
TEST_P(ResourceDispatcherHostTest, UnknownURLScheme) {
NavigationResourceThrottle::set_ui_checks_always_succeed_for_testing(true);
EXPECT_EQ(0, host_.pending_requests());
HandleScheme("http");
const GURL invalid_sheme_url = GURL("foo://bar");
const int expected_error_code = net::ERR_UNKNOWN_URL_SCHEME;
CompleteFailingMainResourceRequest(invalid_sheme_url, expected_error_code);
}
TEST_P(ResourceDispatcherHostTest, DataReceivedACKs) {
EXPECT_EQ(0, host_.pending_requests());
SendDataReceivedACKs(true);
HandleScheme("big-job");
MakeTestRequest(0, 1, GURL("big-job:0123456789,1000000"));
base::RunLoop().RunUntilIdle();
// Sort all the messages we saw by request.
ResourceIPCAccumulator::ClassifiedMessages msgs;
accum_.GetClassifiedMessages(&msgs);
size_t size = msgs[0].size();
EXPECT_EQ(ResourceMsg_ReceivedResponse::ID, msgs[0][0].type());
EXPECT_EQ(ResourceMsg_SetDataBuffer::ID, msgs[0][1].type());
for (size_t i = 2; i < size - 1; ++i)
EXPECT_EQ(ResourceMsg_DataReceived::ID, msgs[0][i].type());
EXPECT_EQ(ResourceMsg_RequestComplete::ID, msgs[0][size - 1].type());
}
// Request a very large detachable resource and cancel part way. Some of the
// data should have been sent to the renderer, but not all.
TEST_P(ResourceDispatcherHostTest, DataSentBeforeDetach) {
EXPECT_EQ(0, host_.pending_requests());
int render_view_id = 0;
int request_id = 1;
std::string raw_headers("HTTP\n"
"Content-type: image/jpeg\n\n");
std::string response_data("01234567890123456789\x01foobar");
// Create a response larger than kMaxAllocationSize (currently 32K). Note
// that if this increase beyond 512K we'll need to make the response longer.
const int kAllocSize = 1024*512;
response_data.resize(kAllocSize, ' ');
SetResponse(raw_headers, response_data);
job_factory_->SetDelayedCompleteJobGeneration(true);
HandleScheme("http");
MakeTestRequestWithResourceType(filter_.get(), render_view_id, request_id,
GURL("http://example.com/blah"),
RESOURCE_TYPE_PREFETCH);
// Get a bit of data before cancelling.
EXPECT_TRUE(net::URLRequestTestJob::ProcessOnePendingMessage());
// Simulate a cancellation coming from the renderer.
ResourceHostMsg_CancelRequest msg(request_id);
host_.OnMessageReceived(msg, filter_.get());
EXPECT_EQ(1, host_.pending_requests());
while (net::URLRequestTestJob::ProcessOnePendingMessage()) {}
// Sort all the messages we saw by request.
ResourceIPCAccumulator::ClassifiedMessages msgs;
accum_.GetClassifiedMessages(&msgs);
EXPECT_EQ(4U, msgs[0].size());
// Figure out how many bytes were received by the renderer.
int data_offset;
int data_length;
ASSERT_TRUE(
ExtractDataOffsetAndLength(msgs[0][2], &data_offset, &data_length));
EXPECT_LT(0, data_length);
EXPECT_GT(kAllocSize, data_length);
// Verify the data that was received before cancellation. The request should
// have appeared to cancel, however.
CheckSuccessfulRequestWithErrorCode(
msgs[0],
std::string(response_data.begin(), response_data.begin() + data_length),
net::ERR_ABORTED);
}
TEST_P(ResourceDispatcherHostTest, DelayedDataReceivedACKs) {
EXPECT_EQ(0, host_.pending_requests());
HandleScheme("big-job");
MakeTestRequest(0, 1, GURL("big-job:0123456789,1000000"));
base::RunLoop().RunUntilIdle();
// Sort all the messages we saw by request.
ResourceIPCAccumulator::ClassifiedMessages msgs;
accum_.GetClassifiedMessages(&msgs);
// We expect 1x ReceivedResponse, 1x SetDataBuffer, Nx ReceivedData messages.
EXPECT_EQ(ResourceMsg_ReceivedResponse::ID, msgs[0][0].type());
EXPECT_EQ(ResourceMsg_SetDataBuffer::ID, msgs[0][1].type());
for (size_t i = 2; i < msgs[0].size(); ++i)
EXPECT_EQ(ResourceMsg_DataReceived::ID, msgs[0][i].type());
// NOTE: If we fail the above checks then it means that we probably didn't
// load a big enough response to trigger the delay mechanism we are trying to
// test!
msgs[0].erase(msgs[0].begin());
msgs[0].erase(msgs[0].begin());
// ACK all DataReceived messages until we find a RequestComplete message.
bool complete = false;
while (!complete) {
for (size_t i = 0; i < msgs[0].size(); ++i) {
if (msgs[0][i].type() == ResourceMsg_RequestComplete::ID) {
complete = true;
break;
}
EXPECT_EQ(ResourceMsg_DataReceived::ID, msgs[0][i].type());
ResourceHostMsg_DataReceived_ACK msg(1);
host_.OnMessageReceived(msg, filter_.get());
}
base::RunLoop().RunUntilIdle();
msgs.clear();
accum_.GetClassifiedMessages(&msgs);
}
}
// Flakyness of this test might indicate memory corruption issues with
// for example the ResourceBuffer of AsyncResourceHandler.
TEST_P(ResourceDispatcherHostTest, DataReceivedUnexpectedACKs) {
EXPECT_EQ(0, host_.pending_requests());
HandleScheme("big-job");
MakeTestRequest(0, 1, GURL("big-job:0123456789,1000000"));
base::RunLoop().RunUntilIdle();
// Sort all the messages we saw by request.
ResourceIPCAccumulator::ClassifiedMessages msgs;
accum_.GetClassifiedMessages(&msgs);
// We expect 1x ReceivedResponse, 1x SetDataBuffer, Nx ReceivedData messages.
EXPECT_EQ(ResourceMsg_ReceivedResponse::ID, msgs[0][0].type());
EXPECT_EQ(ResourceMsg_SetDataBuffer::ID, msgs[0][1].type());
for (size_t i = 2; i < msgs[0].size(); ++i)
EXPECT_EQ(ResourceMsg_DataReceived::ID, msgs[0][i].type());
// NOTE: If we fail the above checks then it means that we probably didn't
// load a big enough response to trigger the delay mechanism.
// Send some unexpected ACKs.
for (size_t i = 0; i < 128; ++i) {
ResourceHostMsg_DataReceived_ACK msg(1);
host_.OnMessageReceived(msg, filter_.get());
}
msgs[0].erase(msgs[0].begin());
msgs[0].erase(msgs[0].begin());
// ACK all DataReceived messages until we find a RequestComplete message.
bool complete = false;
while (!complete) {
for (size_t i = 0; i < msgs[0].size(); ++i) {
if (msgs[0][i].type() == ResourceMsg_RequestComplete::ID) {
complete = true;
break;
}
EXPECT_EQ(ResourceMsg_DataReceived::ID, msgs[0][i].type());
ResourceHostMsg_DataReceived_ACK msg(1);
host_.OnMessageReceived(msg, filter_.get());
}
base::RunLoop().RunUntilIdle();
msgs.clear();
accum_.GetClassifiedMessages(&msgs);
}
}
// Tests the dispatcher host's temporary file management.
TEST_P(ResourceDispatcherHostTest, RegisterDownloadedTempFile) {
const int kRequestID = 1;
// Create a temporary file.
base::FilePath file_path;
ASSERT_TRUE(base::CreateTemporaryFile(&file_path));
scoped_refptr<ShareableFileReference> deletable_file =
ShareableFileReference::GetOrCreate(
file_path, ShareableFileReference::DELETE_ON_FINAL_RELEASE,
BrowserThread::GetTaskRunnerForThread(BrowserThread::FILE).get());
// Not readable.
EXPECT_FALSE(ChildProcessSecurityPolicyImpl::GetInstance()->CanReadFile(
filter_->child_id(), file_path));
// Register it for a resource request.
host_.RegisterDownloadedTempFile(filter_->child_id(), kRequestID, file_path);
// Should be readable now.
EXPECT_TRUE(ChildProcessSecurityPolicyImpl::GetInstance()->CanReadFile(
filter_->child_id(), file_path));
// The child releases from the request.
ResourceHostMsg_ReleaseDownloadedFile release_msg(kRequestID);
host_.OnMessageReceived(release_msg, filter_.get());
// Still readable because there is another reference to the file. (The child
// may take additional blob references.)
EXPECT_TRUE(ChildProcessSecurityPolicyImpl::GetInstance()->CanReadFile(
filter_->child_id(), file_path));
// Release extra references and wait for the file to be deleted. (This relies
// on the delete happening on the FILE thread which is mapped to main thread
// in this test.)
deletable_file = NULL;
base::RunLoop().RunUntilIdle();
// The file is no longer readable to the child and has been deleted.
EXPECT_FALSE(ChildProcessSecurityPolicyImpl::GetInstance()->CanReadFile(
filter_->child_id(), file_path));
EXPECT_FALSE(base::PathExists(file_path));
}
// Tests that temporary files held on behalf of child processes are released
// when the child process dies.
TEST_P(ResourceDispatcherHostTest, ReleaseTemporiesOnProcessExit) {
const int kRequestID = 1;
// Create a temporary file.
base::FilePath file_path;
ASSERT_TRUE(base::CreateTemporaryFile(&file_path));
scoped_refptr<ShareableFileReference> deletable_file =
ShareableFileReference::GetOrCreate(
file_path, ShareableFileReference::DELETE_ON_FINAL_RELEASE,
BrowserThread::GetTaskRunnerForThread(BrowserThread::FILE).get());
// Register it for a resource request.
host_.RegisterDownloadedTempFile(filter_->child_id(), kRequestID, file_path);
deletable_file = NULL;
// Should be readable now.
EXPECT_TRUE(ChildProcessSecurityPolicyImpl::GetInstance()->CanReadFile(
filter_->child_id(), file_path));
// Let the process die.
filter_->OnChannelClosing();
base::RunLoop().RunUntilIdle();
// The file is no longer readable to the child and has been deleted.
EXPECT_FALSE(ChildProcessSecurityPolicyImpl::GetInstance()->CanReadFile(
filter_->child_id(), file_path));
EXPECT_FALSE(base::PathExists(file_path));
}
TEST_P(ResourceDispatcherHostTest, DownloadToFile) {
// Make a request which downloads to file.
ResourceRequest request = CreateResourceRequest(
"GET", RESOURCE_TYPE_SUB_RESOURCE, net::URLRequestTestJob::test_url_1());
request.download_to_file = true;
ResourceHostMsg_RequestResource request_msg(0, 1, request);
host_.OnMessageReceived(request_msg, filter_.get());
// Running the message loop until idle does not work because
// RedirectToFileResourceHandler posts things to base::WorkerPool. Instead,
// wait for the ResourceMsg_RequestComplete to go out. Then run the event loop
// until idle so the loader is gone.
WaitForRequestComplete();
base::RunLoop().RunUntilIdle();
EXPECT_EQ(0, host_.pending_requests());
ResourceIPCAccumulator::ClassifiedMessages msgs;
accum_.GetClassifiedMessages(&msgs);
ASSERT_EQ(1U, msgs.size());
const std::vector<IPC::Message>& messages = msgs[0];
// The request should contain the following messages:
// ReceivedResponse (indicates headers received and filename)
// DataDownloaded* (bytes downloaded and total length)
// RequestComplete (request is done)
// ReceivedResponse
ResourceResponseHead response_head;
GetResponseHead(messages, &response_head);
ASSERT_FALSE(response_head.download_file_path.empty());
// DataDownloaded
size_t total_len = 0;
for (size_t i = 1; i < messages.size() - 1; i++) {
ASSERT_EQ(ResourceMsg_DataDownloaded::ID, messages[i].type());
base::PickleIterator iter(messages[i]);
int request_id, data_len;
ASSERT_TRUE(IPC::ReadParam(&messages[i], &iter, &request_id));
ASSERT_TRUE(IPC::ReadParam(&messages[i], &iter, &data_len));
total_len += data_len;
}
EXPECT_EQ(net::URLRequestTestJob::test_data_1().size(), total_len);
// RequestComplete
CheckRequestCompleteErrorCode(messages.back(), net::OK);
// Verify that the data ended up in the temporary file.
std::string contents;
ASSERT_TRUE(base::ReadFileToString(response_head.download_file_path,
&contents));
EXPECT_EQ(net::URLRequestTestJob::test_data_1(), contents);
// The file should be readable by the child.
EXPECT_TRUE(ChildProcessSecurityPolicyImpl::GetInstance()->CanReadFile(
filter_->child_id(), response_head.download_file_path));
// When the renderer releases the file, it should be deleted. Again,
// RunUntilIdle doesn't work because base::WorkerPool is involved.
ShareableFileReleaseWaiter waiter(response_head.download_file_path);
ResourceHostMsg_ReleaseDownloadedFile release_msg(1);
host_.OnMessageReceived(release_msg, filter_.get());
waiter.Wait();
// The release callback runs before the delete is scheduled, so pump the
// message loop for the delete itself. (This relies on the delete happening on
// the FILE thread which is mapped to main thread in this test.)
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(base::PathExists(response_head.download_file_path));
EXPECT_FALSE(ChildProcessSecurityPolicyImpl::GetInstance()->CanReadFile(
filter_->child_id(), response_head.download_file_path));
}
WebContents* WebContentsBinder(WebContents* rv) { return rv; }
// Tests GetLoadInfoForAllRoutes when there are 3 requests from the same
// RenderView. The second one is farthest along.
TEST_P(ResourceDispatcherHostTest, LoadInfo) {
std::unique_ptr<LoadInfoList> infos(new LoadInfoList);
LoadInfo info;
WebContents* wc1 = reinterpret_cast<WebContents*>(0x1);
info.web_contents_getter = base::Bind(WebContentsBinder, wc1);
info.load_state = net::LoadStateWithParam(net::LOAD_STATE_SENDING_REQUEST,
base::string16());
info.url = GURL("test://1/");
info.upload_position = 0;
info.upload_size = 0;
infos->push_back(info);
info.url = GURL("test://2/");
info.load_state = net::LoadStateWithParam(net::LOAD_STATE_READING_RESPONSE,
base::string16());
infos->push_back(info);
info.url = GURL("test://3/");
std::unique_ptr<LoadInfoMap> load_info_map =
ResourceDispatcherHostImpl::PickMoreInterestingLoadInfos(
std::move(infos));
ASSERT_EQ(1u, load_info_map->size());
ASSERT_TRUE(load_info_map->find(wc1) != load_info_map->end());
EXPECT_EQ(GURL("test://2/"), (*load_info_map)[wc1].url);
EXPECT_EQ(net::LOAD_STATE_READING_RESPONSE,
(*load_info_map)[wc1].load_state.state);
EXPECT_EQ(0u, (*load_info_map)[wc1].upload_position);
EXPECT_EQ(0u, (*load_info_map)[wc1].upload_size);
}
// Tests GetLoadInfoForAllRoutes when there are 2 requests with the same
// priority. The first one (Which will have the lowest ID) should be returned.
TEST_P(ResourceDispatcherHostTest, LoadInfoSamePriority) {
std::unique_ptr<LoadInfoList> infos(new LoadInfoList);
LoadInfo info;
WebContents* wc1 = reinterpret_cast<WebContents*>(0x1);
info.web_contents_getter = base::Bind(WebContentsBinder, wc1);
info.load_state = net::LoadStateWithParam(net::LOAD_STATE_IDLE,
base::string16());
info.url = GURL("test://1/");
info.upload_position = 0;
info.upload_size = 0;
infos->push_back(info);
info.url = GURL("test://2/");
infos->push_back(info);
std::unique_ptr<LoadInfoMap> load_info_map =
ResourceDispatcherHostImpl::PickMoreInterestingLoadInfos(
std::move(infos));
ASSERT_EQ(1u, load_info_map->size());
ASSERT_TRUE(load_info_map->find(wc1) != load_info_map->end());
EXPECT_EQ(GURL("test://1/"), (*load_info_map)[wc1].url);
EXPECT_EQ(net::LOAD_STATE_IDLE, (*load_info_map)[wc1].load_state.state);
EXPECT_EQ(0u, (*load_info_map)[wc1].upload_position);
EXPECT_EQ(0u, (*load_info_map)[wc1].upload_size);
}
// Tests GetLoadInfoForAllRoutes when a request is uploading a body.
TEST_P(ResourceDispatcherHostTest, LoadInfoUploadProgress) {
std::unique_ptr<LoadInfoList> infos(new LoadInfoList);
LoadInfo info;
WebContents* wc1 = reinterpret_cast<WebContents*>(0x1);
info.web_contents_getter = base::Bind(WebContentsBinder, wc1);
info.load_state = net::LoadStateWithParam(net::LOAD_STATE_READING_RESPONSE,
base::string16());
info.url = GURL("test://1/");
info.upload_position = 0;
info.upload_size = 0;
infos->push_back(info);
info.upload_position = 1000;
info.upload_size = 1000;
infos->push_back(info);
info.url = GURL("test://2/");
info.load_state = net::LoadStateWithParam(net::LOAD_STATE_SENDING_REQUEST,
base::string16());
info.upload_position = 50;
info.upload_size = 100;
infos->push_back(info);
info.url = GURL("test://1/");
info.load_state = net::LoadStateWithParam(net::LOAD_STATE_READING_RESPONSE,
base::string16());
info.upload_position = 1000;
info.upload_size = 1000;
infos->push_back(info);
info.url = GURL("test://3/");
info.upload_position = 0;
info.upload_size = 0;
infos->push_back(info);
std::unique_ptr<LoadInfoMap> load_info_map =
ResourceDispatcherHostImpl::PickMoreInterestingLoadInfos(
std::move(infos));
ASSERT_EQ(1u, load_info_map->size());
ASSERT_TRUE(load_info_map->find(wc1) != load_info_map->end());
EXPECT_EQ(GURL("test://2/"), (*load_info_map)[wc1].url);
EXPECT_EQ(net::LOAD_STATE_SENDING_REQUEST,
(*load_info_map)[wc1].load_state.state);
EXPECT_EQ(50u, (*load_info_map)[wc1].upload_position);
EXPECT_EQ(100u, (*load_info_map)[wc1].upload_size);
}
// Tests GetLoadInfoForAllRoutes when there are 4 requests from 2 different
// RenderViews. Also tests the case where the first / last requests are the
// most interesting ones.
TEST_P(ResourceDispatcherHostTest, LoadInfoTwoRenderViews) {
std::unique_ptr<LoadInfoList> infos(new LoadInfoList);
LoadInfo info;
WebContents* wc1 = reinterpret_cast<WebContents*>(0x1);
info.web_contents_getter = base::Bind(WebContentsBinder, wc1);
info.load_state = net::LoadStateWithParam(net::LOAD_STATE_CONNECTING,
base::string16());
info.url = GURL("test://1/");
info.upload_position = 0;
info.upload_size = 0;
infos->push_back(info);
WebContents* wc2 = reinterpret_cast<WebContents*>(0x2);
info.web_contents_getter = base::Bind(WebContentsBinder, wc2);
info.load_state = net::LoadStateWithParam(net::LOAD_STATE_IDLE,
base::string16());
info.url = GURL("test://2/");
infos->push_back(info);
info.web_contents_getter = base::Bind(WebContentsBinder, wc1);
info.url = GURL("test://3/");
infos->push_back(info);
info.web_contents_getter = base::Bind(WebContentsBinder, wc2);
info.load_state = net::LoadStateWithParam(net::LOAD_STATE_CONNECTING,
base::string16());
info.url = GURL("test://4/");
infos->push_back(info);
std::unique_ptr<LoadInfoMap> load_info_map =
ResourceDispatcherHostImpl::PickMoreInterestingLoadInfos(
std::move(infos));
ASSERT_EQ(2u, load_info_map->size());
ASSERT_TRUE(load_info_map->find(wc1) != load_info_map->end());
EXPECT_EQ(GURL("test://1/"), (*load_info_map)[wc1].url);
EXPECT_EQ(net::LOAD_STATE_CONNECTING,
(*load_info_map)[wc1].load_state.state);
EXPECT_EQ(0u, (*load_info_map)[wc1].upload_position);
EXPECT_EQ(0u, (*load_info_map)[wc1].upload_size);
ASSERT_TRUE(load_info_map->find(wc2) != load_info_map->end());
EXPECT_EQ(GURL("test://4/"), (*load_info_map)[wc2].url);
EXPECT_EQ(net::LOAD_STATE_CONNECTING,
(*load_info_map)[wc2].load_state.state);
EXPECT_EQ(0u, (*load_info_map)[wc2].upload_position);
EXPECT_EQ(0u, (*load_info_map)[wc2].upload_size);
}
// Confirm that resource response started notifications are correctly
// transmitted to the WebContents.
TEST_P(ResourceDispatcherHostTest, TransferResponseStarted) {
int initial_count = web_contents_observer_->resource_response_start_count();
MakeWebContentsAssociatedTestRequest(1, net::URLRequestTestJob::test_url_1());
base::RunLoop().RunUntilIdle();
EXPECT_EQ(initial_count + 1,
web_contents_observer_->resource_response_start_count());
}
// Confirm that request redirected notifications are correctly
// transmitted to the WebContents.
TEST_P(ResourceDispatcherHostTest, TransferRequestRedirected) {
int initial_count = web_contents_observer_->resource_request_redirect_count();
MakeWebContentsAssociatedTestRequest(
1, net::URLRequestTestJob::test_url_redirect_to_url_2());
base::RunLoop().RunUntilIdle();
EXPECT_EQ(initial_count + 1,
web_contents_observer_->resource_request_redirect_count());
}
// Confirm that DidChangePriority messages are respected.
TEST_P(ResourceDispatcherHostTest, DidChangePriority) {
// ResourceScheduler only throttles http and https requests.
HandleScheme("http");
// Needed to enable scheduling for this child.
host_.OnRenderViewHostCreated(filter_->child_id(), // child_id
0); // route_id
// Prevent any of these requests from completing.
job_factory_->SetDelayedCompleteJobGeneration(true);
SetResponse("HTTP/1.1 200 OK\n\n", "<title>Dummy body</title>");
// Only one idle priority request will run while a high-priority request
// exists.
MakeTestRequestWithPriority(0, 1, net::HIGHEST);
MakeTestRequestWithPriority(0, 2, net::IDLE);
MakeTestRequestWithPriority(0, 3, net::IDLE);
KickOffRequest();
EXPECT_EQ(2, job_factory_->url_request_jobs_created_count());
// Increase the priority of the second idle priority request. It was
// scheduled later, so it is not currently running.
ResourceHostMsg_DidChangePriority priority_msg(3, net::MAXIMUM_PRIORITY, 0);
host_.OnMessageReceived(priority_msg, filter_.get());
base::RunLoop().RunUntilIdle();
EXPECT_EQ(3, job_factory_->url_request_jobs_created_count());
// Cleanup.
host_.OnRenderViewHostDeleted(filter_->child_id(), // child_id
0); // route_id
}
// Confirm that resource response started notifications for downloads are not
// transmitted to the WebContents.
TEST_P(ResourceDispatcherHostTest, TransferResponseStartedDownload) {
int initial_count(web_contents_observer_->resource_response_start_count());
MakeWebContentsAssociatedDownloadRequest(
1, net::URLRequestTestJob::test_url_1());
base::RunLoop().RunUntilIdle();
EXPECT_EQ(initial_count,
web_contents_observer_->resource_response_start_count());
}
// Confirm that request redirected notifications for downloads are not
// transmitted to the WebContents.
TEST_P(ResourceDispatcherHostTest, TransferRequestRedirectedDownload) {
int initial_count(web_contents_observer_->resource_request_redirect_count());
MakeWebContentsAssociatedDownloadRequest(
1, net::URLRequestTestJob::test_url_redirect_to_url_2());
base::RunLoop().RunUntilIdle();
EXPECT_EQ(initial_count,
web_contents_observer_->resource_request_redirect_count());
}
// Tests that a ResourceThrottle that needs to process the response before any
// part of the body is read can do so.
TEST_P(ResourceDispatcherHostTest, ThrottleMustProcessResponseBeforeRead) {
// Ensure all jobs will check that no read operation is called.
job_factory_->SetMustNotReadJobGeneration(true);
HandleScheme("http");
// Create a ResourceThrottle that must process the response before any part of
// the body is read. This throttle will also cancel the request in
// WillProcessResponse.
TestResourceDispatcherHostDelegate delegate;
int throttle_flags = CANCEL_PROCESSING_RESPONSE | MUST_NOT_CACHE_BODY;
delegate.set_flags(throttle_flags);
host_.SetDelegate(&delegate);
// This response should normally result in the MIME type being sniffed, which
// requires reading the body.
std::string raw_headers(
"HTTP/1.1 200 OK\n"
"Content-Type: text/plain; charset=utf-8\n\n");
std::string response_data("p { text-align: center; }");
SetResponse(raw_headers, response_data);
MakeTestRequestWithResourceType(filter_.get(), filter_->child_id(), 1,
GURL("http://example.com/blah"),
RESOURCE_TYPE_STYLESHEET);
while (net::URLRequestTestJob::ProcessOnePendingMessage()) {
}
base::RunLoop().RunUntilIdle();
}
namespace {
void StoreSyncLoadResult(bool* called,
bool* was_null,
SyncLoadResult* result_out,
const SyncLoadResult* result) {
*called = true;
*was_null = !result;
if (result)
*result_out = *result;
}
} // namespace
TEST_P(ResourceDispatcherHostTest, SyncLoadWithMojoSuccess) {
ResourceRequest request = CreateResourceRequest(
"GET", RESOURCE_TYPE_XHR, net::URLRequestTestJob::test_url_1());
request.priority = net::MAXIMUM_PRIORITY;
bool called = false;
bool was_null = false;
SyncLoadResult result;
host_.OnSyncLoadWithMojo(0, 1, request, filter_.get(),
base::Bind(&StoreSyncLoadResult,
&called, &was_null, &result));
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(called);
EXPECT_FALSE(was_null);
EXPECT_EQ(net::OK, result.error_code);
}
TEST_P(ResourceDispatcherHostTest, SyncLoadWithMojoError) {
ResourceRequest request = CreateResourceRequest(
"GET", RESOURCE_TYPE_XHR, net::URLRequestTestJob::test_url_error());
request.priority = net::MAXIMUM_PRIORITY;
bool called = false;
bool was_null = false;
SyncLoadResult result;
host_.OnSyncLoadWithMojo(0, 1, request, filter_.get(),
base::Bind(&StoreSyncLoadResult,
&called, &was_null, &result));
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(called);
EXPECT_FALSE(was_null);
EXPECT_EQ(net::ERR_INVALID_URL, result.error_code);
}
TEST_P(ResourceDispatcherHostTest, SyncLoadWithMojoCancel) {
ResourceRequest request = CreateResourceRequest(
"GET", RESOURCE_TYPE_XHR, net::URLRequestTestJob::test_url_error());
request.priority = net::MAXIMUM_PRIORITY;
bool called = false;
bool was_null = false;
SyncLoadResult result;
host_.OnSyncLoadWithMojo(0, 1, request, filter_.get(),
base::Bind(&StoreSyncLoadResult,
&called, &was_null, &result));
host_.CancelRequestsForProcess(filter_->child_id());
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(called);
EXPECT_TRUE(was_null);
}
// A URLRequestTestJob that sets a test certificate on the |ssl_info|
// field of the response.
class TestHTTPSURLRequestJob : public net::URLRequestTestJob {
public:
TestHTTPSURLRequestJob(net::URLRequest* request,
net::NetworkDelegate* network_delegate,
const std::string& response_headers,
const std::string& response_data,
bool auto_advance)
: net::URLRequestTestJob(request,
network_delegate,
response_headers,
response_data,
auto_advance) {}
void GetResponseInfo(net::HttpResponseInfo* info) override {
net::URLRequestTestJob::GetResponseInfo(info);
info->ssl_info.cert =
net::ImportCertFromFile(net::GetTestCertsDirectory(), "ok_cert.pem");
}
};
net::URLRequestJob* TestURLRequestJobFactory::MaybeCreateJobWithProtocolHandler(
const std::string& scheme,
net::URLRequest* request,
net::NetworkDelegate* network_delegate) const {
url_request_jobs_created_count_++;
if (hang_after_start_) {
return new net::URLRequestFailedJob(request, network_delegate,
net::ERR_IO_PENDING);
}
if (test_fixture_->response_headers_.empty()) {
if (delay_start_) {
return new URLRequestTestDelayedStartJob(request, network_delegate);
} else if (delay_complete_) {
return new URLRequestTestDelayedCompletionJob(request,
network_delegate);
} else if (scheme == "big-job") {
return new URLRequestBigJob(request, network_delegate);
} else {
return new net::URLRequestTestJob(request, network_delegate,
test_fixture_->auto_advance_);
}
} else {
if (delay_start_) {
return new URLRequestTestDelayedStartJob(
request, network_delegate,
test_fixture_->response_headers_, test_fixture_->response_data_,
false);
} else if (delay_complete_) {
return new URLRequestTestDelayedCompletionJob(
request, network_delegate,
test_fixture_->response_headers_, test_fixture_->response_data_,
false);
} else if (must_not_read_) {
return new URLRequestMustNotReadTestJob(request, network_delegate,
test_fixture_->response_headers_,
test_fixture_->response_data_);
} else if (test_fixture_->use_test_ssl_certificate_) {
return new TestHTTPSURLRequestJob(request, network_delegate,
test_fixture_->response_headers_,
test_fixture_->response_data_, false);
} else {
return new net::URLRequestTestJob(
request, network_delegate, test_fixture_->response_headers_,
test_fixture_->response_data_, test_fixture_->auto_advance_);
}
}
}
net::URLRequestJob* TestURLRequestJobFactory::MaybeInterceptRedirect(
net::URLRequest* request,
net::NetworkDelegate* network_delegate,
const GURL& location) const {
return nullptr;
}
net::URLRequestJob* TestURLRequestJobFactory::MaybeInterceptResponse(
net::URLRequest* request,
net::NetworkDelegate* network_delegate) const {
return nullptr;
}
INSTANTIATE_TEST_CASE_P(
ResourceDispatcherHostTests,
ResourceDispatcherHostTest,
testing::Values(TestConfig::kDefault,
TestConfig::kOptimizeIPCForSmallResourceEnabled));
} // namespace content
|