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
|
//------------------------------------------------------------------------------
// <copyright file="HttpRuntime.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
/*
* The ASP.NET runtime services
*
* Copyright (c) 1998 Microsoft Corporation
*/
namespace System.Web {
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Net;
using System.Reflection;
using System.Resources;
using System.Runtime;
using System.Runtime.InteropServices;
using System.Runtime.Remoting.Messaging;
using System.Security;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Security.Policy;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.Caching;
using System.Web.Compilation;
using System.Web.Configuration;
using System.Web.Hosting;
using System.Web.Management;
using System.Web.Security;
using System.Web.UI;
using System.Web.Util;
using System.Xml;
using Microsoft.Win32;
/// <devdoc>
/// <para>Provides a set of ASP.NET runtime services.</para>
/// </devdoc>
public sealed class HttpRuntime {
internal const string codegenDirName = "Temporary ASP.NET Files";
internal const string profileFileName = "profileoptimization.prof";
private static HttpRuntime _theRuntime; // single instance of the class
internal static byte[] s_autogenKeys = new byte[1024];
//
// Names of special ASP.NET directories
//
internal const string BinDirectoryName = "bin";
internal const string CodeDirectoryName = "App_Code";
internal const string WebRefDirectoryName = "App_WebReferences";
internal const string ResourcesDirectoryName = "App_GlobalResources";
internal const string LocalResourcesDirectoryName = "App_LocalResources";
internal const string DataDirectoryName = "App_Data";
internal const string ThemesDirectoryName = "App_Themes";
internal const string GlobalThemesDirectoryName = "Themes";
internal const string BrowsersDirectoryName = "App_Browsers";
private static string DirectorySeparatorString = new string(Path.DirectorySeparatorChar, 1);
private static string DoubleDirectorySeparatorString = new string(Path.DirectorySeparatorChar, 2);
private static char[] s_InvalidPhysicalPathChars = { '/', '?', '*', '<', '>', '|', '"' };
#if OLD
// For s_forbiddenDirs and s_forbiddenDirsConstant, see
// ndll.h, and RestrictIISFolders in regiis.cxx
internal static string[] s_forbiddenDirs = {
BinDirectoryName,
CodeDirectoryName,
DataDirectoryName,
ResourcesDirectoryName,
WebRefDirectoryName,
};
internal static Int32[] s_forbiddenDirsConstant = {
UnsafeNativeMethods.RESTRICT_BIN,
UnsafeNativeMethods.RESTRICT_CODE,
UnsafeNativeMethods.RESTRICT_DATA,
UnsafeNativeMethods.RESTRICT_RESOURCES,
UnsafeNativeMethods.RESTRICT_WEBREFERENCES,
};
#endif
static HttpRuntime() {
AddAppDomainTraceMessage("*HttpRuntime::cctor");
StaticInit();
_theRuntime = new HttpRuntime();
_theRuntime.Init();
AddAppDomainTraceMessage("HttpRuntime::cctor*");
}
[SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)]
public HttpRuntime() {
}
//
// static initialization to get hooked up to the unmanaged code
// get installation directory, etc.
//
private static bool s_initialized = false;
private static String s_installDirectory;
private static bool s_isEngineLoaded = false;
// Force the static initialization of this class.
internal static void ForceStaticInit() { }
private static void StaticInit() {
if (s_initialized) {
// already initialized
return;
}
bool isEngineLoaded = false;
bool wasEngineLoadedHere = false;
String installDir = null;
// load webengine.dll if it is not loaded already
#if !FEATURE_PAL // FEATURE_PAL does not enable IIS-based hosting features
installDir = RuntimeEnvironment.GetRuntimeDirectory();
if (UnsafeNativeMethods.GetModuleHandle(ModName.ENGINE_FULL_NAME) != IntPtr.Zero) {
isEngineLoaded = true;
}
// Load webengine.dll if not loaded already
if (!isEngineLoaded) {
String fullPath = installDir + Path.DirectorySeparatorChar + ModName.ENGINE_FULL_NAME;
if (UnsafeNativeMethods.LoadLibrary(fullPath) != IntPtr.Zero) {
isEngineLoaded = true;
wasEngineLoadedHere = true;
}
}
if (isEngineLoaded) {
UnsafeNativeMethods.InitializeLibrary(false);
if (wasEngineLoadedHere) {
UnsafeNativeMethods.PerfCounterInitialize();
}
}
#else // !FEATURE_PAL
string p = typeof(object).Module.FullyQualifiedName;
installDir = Path.GetDirectoryName(p);
#endif // !FEATURE_PAL
s_installDirectory = installDir;
s_isEngineLoaded = isEngineLoaded;
s_initialized = true;
PopulateIISVersionInformation();
AddAppDomainTraceMessage("Initialize");
}
//
// Runtime services
//
private NamedPermissionSet _namedPermissionSet;
private PolicyLevel _policyLevel;
private string _hostSecurityPolicyResolverType = null;
private FileChangesMonitor _fcm;
private Cache _cachePublic;
private bool _isOnUNCShare;
private Profiler _profiler;
private RequestTimeoutManager _timeoutManager;
private RequestQueue _requestQueue;
private bool _apartmentThreading;
private bool _processRequestInApplicationTrust;
private bool _disableProcessRequestInApplicationTrust;
private bool _isLegacyCas;
//
// Counters
//
private bool _beforeFirstRequest = true;
private DateTime _firstRequestStartTime;
private bool _firstRequestCompleted;
private bool _userForcedShutdown;
private bool _configInited;
private bool _fusionInited;
private int _activeRequestCount;
private volatile bool _disposingHttpRuntime;
private DateTime _lastShutdownAttemptTime;
private bool _shutdownInProgress;
private String _shutDownStack;
private String _shutDownMessage;
private ApplicationShutdownReason _shutdownReason = ApplicationShutdownReason.None;
private string _trustLevel;
private string _wpUserId;
private bool _shutdownWebEventRaised;
//
// Header Newlines
//
private bool _enableHeaderChecking;
//
// Callbacks
//
private AsyncCallback _requestNotificationCompletionCallback;
private AsyncCallback _handlerCompletionCallback;
private HttpWorkerRequest.EndOfSendNotification _asyncEndOfSendCallback;
private WaitCallback _appDomainUnloadallback;
//
// Initialization error (to be reported on subsequent requests)
//
private Exception _initializationError;
private bool _hostingInitFailed; // make such errors non-sticky
private Timer _appDomainShutdownTimer = null;
//
// App domain related
//
private String _tempDir;
private String _codegenDir;
private String _appDomainAppId;
private String _appDomainAppPath;
private VirtualPath _appDomainAppVPath;
private String _appDomainId;
//
// Debugging support
//
private bool _debuggingEnabled = false;
//
// App_Offline.htm support
//
private const string AppOfflineFileName = "App_Offline.htm";
private const long MaxAppOfflineFileLength = 1024 * 1024;
private byte[] _appOfflineMessage;
//
// Client script support
//
private const string AspNetClientFilesSubDirectory = "asp.netclientfiles";
private const string AspNetClientFilesParentVirtualPath = "/aspnet_client/system_web/";
private string _clientScriptVirtualPath;
private string _clientScriptPhysicalPath;
//
// IIS version and whether we're using the integrated pipeline
//
private static Version _iisVersion;
private static bool _useIntegratedPipeline;
//
// Prefetch
//
private static bool _enablePrefetchOptimization;
/////////////////////////////////////////////////////////////////////////
// 3 steps of initialization:
// Init() is called from HttpRuntime cctor
// HostingInit() is called by the Hosting Environment
// FirstRequestInit() is called on first HTTP request
//
/*
* Context-less initialization (on app domain creation)
*/
private void Init() {
try {
#if !FEATURE_PAL
if (Environment.OSVersion.Platform != PlatformID.Win32NT)
throw new PlatformNotSupportedException(SR.GetString(SR.RequiresNT));
#else // !FEATURE_PAL
// ROTORTODO
// Do nothing: FEATURE_PAL environment will always support ASP.NET hosting
#endif // !FEATURE_PAL
_profiler = new Profiler();
_timeoutManager = new RequestTimeoutManager();
_wpUserId = GetCurrentUserName();
_requestNotificationCompletionCallback = new AsyncCallback(this.OnRequestNotificationCompletion);
_handlerCompletionCallback = new AsyncCallback(this.OnHandlerCompletion);
_asyncEndOfSendCallback = new HttpWorkerRequest.EndOfSendNotification(this.EndOfSendCallback);
_appDomainUnloadallback = new WaitCallback(this.ReleaseResourcesAndUnloadAppDomain);
// appdomain values
if (GetAppDomainString(".appDomain") != null) {
Debug.Assert(HostingEnvironment.IsHosted);
_appDomainAppId = GetAppDomainString(".appId");
_appDomainAppPath = GetAppDomainString(".appPath");
_appDomainAppVPath = VirtualPath.CreateNonRelativeTrailingSlash(GetAppDomainString(".appVPath"));
_appDomainId = GetAppDomainString(".domainId");
_isOnUNCShare = StringUtil.StringStartsWith(_appDomainAppPath, "\\\\");
// init perf counters for this appdomain
PerfCounters.Open(_appDomainAppId);
}
else {
Debug.Assert(!HostingEnvironment.IsHosted);
}
// _appDomainAppPath should be set before file change notifications are initialized
// DevDiv 248126: Check httpRuntime fcnMode first before we use the registry key
_fcm = new FileChangesMonitor(HostingEnvironment.FcnMode);
}
catch (Exception e) {
// remember static initalization error
InitializationException = e;
}
}
private void SetUpDataDirectory() {
// Set the DataDirectory (see VSWhidbey 226834) with permission (DevDiv 29614)
string dataDirectory = Path.Combine(_appDomainAppPath, DataDirectoryName);
AppDomain.CurrentDomain.SetData("DataDirectory", dataDirectory,
new FileIOPermission(FileIOPermissionAccess.PathDiscovery, dataDirectory));
}
private void DisposeAppDomainShutdownTimer() {
Timer timer = _appDomainShutdownTimer;
if (timer != null && Interlocked.CompareExchange(ref _appDomainShutdownTimer, null, timer) == timer) {
timer.Dispose();
}
}
private void AppDomainShutdownTimerCallback(Object state) {
try {
DisposeAppDomainShutdownTimer();
ShutdownAppDomain(ApplicationShutdownReason.InitializationError, "Initialization Error");
}
catch { } // ignore exceptions
}
/*
* Restart the AppDomain in 10 seconds
*/
private void StartAppDomainShutdownTimer() {
if (_appDomainShutdownTimer == null && !_shutdownInProgress) {
lock (this) {
if (_appDomainShutdownTimer == null && !_shutdownInProgress) {
_appDomainShutdownTimer = new Timer(
new TimerCallback(this.AppDomainShutdownTimerCallback),
null,
10 * 1000,
0);
}
}
}
}
/*
* Initialization from HostingEnvironment of HTTP independent features
*/
private void HostingInit(HostingEnvironmentFlags hostingFlags, PolicyLevel policyLevel, Exception appDomainCreationException) {
using (new ApplicationImpersonationContext()) {
try {
// To ignore FCN during initialization
_firstRequestStartTime = DateTime.UtcNow;
SetUpDataDirectory();
// Throw an exception about lack of access to app directory early on
EnsureAccessToApplicationDirectory();
// Monitor renames to directories we are watching, and notifications on the bin directory
//
// Note that this must be the first monitoring that we do of the application directory.
// There is a bug in Windows 2000 Server where notifications on UNC shares do not
// happen correctly if:
// 1. the directory is monitored for regular notifications
// 2. the directory is then monitored for directory renames
// 3. the directory is monitored again for regular notifications
StartMonitoringDirectoryRenamesAndBinDirectory();
// Initialize ObjectCacheHost before config is read, since config relies on the cache
if (InitializationException == null) {
HostingEnvironment.InitializeObjectCacheHost();
}
//
// Get the configuration needed to minimally initialize
// the components required for a complete configuration system,
// especially SetTrustLevel.
//
// We want to do this before calling SetUpCodegenDirectory(),
// to remove the risk of the config system loading
// codegen assemblies in full trust (VSWhidbey 460506)
//
CacheSection cacheSection;
TrustSection trustSection;
SecurityPolicySection securityPolicySection;
CompilationSection compilationSection;
HostingEnvironmentSection hostingEnvironmentSection;
Exception configInitException;
GetInitConfigSections(
out cacheSection,
out trustSection,
out securityPolicySection,
out compilationSection,
out hostingEnvironmentSection,
out configInitException);
// Once the configuration system is initialized, we can read
// the cache configuration settings.
//
// Note that we must do this after we start monitoring directory renames,
// as reading config will cause file monitoring on the application directory
// to occur.
// Set up the codegen directory for the app. This needs to be done before we process
// the policy file, because it needs to replace the $CodeGen$ token.
SetUpCodegenDirectory(compilationSection);
if(compilationSection != null) {
_enablePrefetchOptimization = compilationSection.EnablePrefetchOptimization;
if(_enablePrefetchOptimization) {
UnsafeNativeMethods.StartPrefetchActivity((uint)StringUtil.GetStringHashCode(_appDomainAppId));
}
}
// NOTE: after calling SetUpCodegenDirectory(), and until we call SetTrustLevel(), we are at
// risk of codegen assemblies being loaded in full trust. No code that might cause
// assembly loading should be added here! This is only valid if the legacyCasModel is set
// to true in <trust> section.
// Throw the original configuration exception from ApplicationManager if configuration is broken.
if (appDomainCreationException != null) {
throw appDomainCreationException;
}
if (trustSection == null || String.IsNullOrEmpty(trustSection.Level)) {
throw new ConfigurationErrorsException(SR.GetString(SR.Config_section_not_present, "trust"));
}
if (trustSection.LegacyCasModel) {
try {
_disableProcessRequestInApplicationTrust = false;
_isLegacyCas = true;
// Set code access policy on the app domain
SetTrustLevel(trustSection, securityPolicySection);
}
catch {
// throw the original config exception if it exists
if (configInitException != null)
throw configInitException;
throw;
}
}
else if ((hostingFlags & HostingEnvironmentFlags.ClientBuildManager) != 0) {
_trustLevel = "Full";
}
else {
_disableProcessRequestInApplicationTrust = true;
// Set code access policy properties of the runtime object
SetTrustParameters(trustSection, securityPolicySection, policyLevel);
}
// Configure fusion to use directories set in the app config
InitFusion(hostingEnvironmentSection);
// set the sliding expiration for URL metadata
CachedPathData.InitializeUrlMetadataSlidingExpiration(hostingEnvironmentSection);
// Complete initialization of configuration.
// Note that this needs to be called after SetTrustLevel,
// as it indicates that we have the permission set needed
// to correctly run configuration section handlers.
// As little config should be read before CompleteInit() as possible.
// No section that runs before CompleteInit() should demand permissions,
// as the permissions set has not yet determined until SetTrustLevel()
// is called.
HttpConfigurationSystem.CompleteInit();
//
// If an exception occurred loading configuration,
// we are now ready to handle exception processing
// with the correct trust level set.
//
if (configInitException != null) {
throw configInitException;
}
SetThreadPoolLimits();
SetAutogenKeys();
// Initialize the build manager
BuildManager.InitializeBuildManager();
if(compilationSection != null && compilationSection.ProfileGuidedOptimizations == ProfileGuidedOptimizationsFlags.All) {
ProfileOptimization.SetProfileRoot(_codegenDir);
ProfileOptimization.StartProfile(profileFileName);
}
// Determine apartment threading setting
InitApartmentThreading();
// Init debugging
InitDebuggingSupport();
_processRequestInApplicationTrust = trustSection.ProcessRequestInApplicationTrust;
// Init AppDomain Resource Perf Counters
AppDomainResourcePerfCounters.Init();
RelaxMapPathIfRequired();
}
catch (Exception e) {
_hostingInitFailed = true;
InitializationException = e;
Debug.Trace("AppDomainFactory", "HostingInit failed. " + e.ToString());
if ((hostingFlags & HostingEnvironmentFlags.ThrowHostingInitErrors) != 0)
throw;
}
}
}
internal static Exception InitializationException {
get {
return _theRuntime._initializationError;
}
// The exception is "cached" for 10 seconds, then the AppDomain is restarted.
set {
_theRuntime._initializationError = value;
// In v2.0, we shutdown immediately if hostingInitFailed...so we don't need the timer
if (!HostingInitFailed) {
_theRuntime.StartAppDomainShutdownTimer();
}
}
}
internal static bool HostingInitFailed {
get {
return _theRuntime._hostingInitFailed;
}
}
internal static void InitializeHostingFeatures(HostingEnvironmentFlags hostingFlags, PolicyLevel policyLevel, Exception appDomainCreationException) {
_theRuntime.HostingInit(hostingFlags, policyLevel, appDomainCreationException);
}
internal static bool EnableHeaderChecking {
get {
return _theRuntime._enableHeaderChecking;
}
}
internal static bool ProcessRequestInApplicationTrust {
get {
return _theRuntime._processRequestInApplicationTrust;
}
}
internal static bool DisableProcessRequestInApplicationTrust {
get {
return _theRuntime._disableProcessRequestInApplicationTrust;
}
}
internal static bool IsLegacyCas {
get {
return _theRuntime._isLegacyCas;
}
}
internal static byte[] AppOfflineMessage {
get {
return _theRuntime._appOfflineMessage;
}
}
/*
* Initialization on first request (context available)
*/
private void FirstRequestInit(HttpContext context) {
Exception error = null;
if (InitializationException == null && _appDomainId != null) {
#if DBG
HttpContext.SetDebugAssertOnAccessToCurrent(true);
#endif
try {
using (new ApplicationImpersonationContext()) {
// Is this necessary? See InitHttpConfiguration
CultureInfo savedCulture = Thread.CurrentThread.CurrentCulture;
CultureInfo savedUICulture = Thread.CurrentThread.CurrentUICulture;
try {
// Ensure config system is initialized
InitHttpConfiguration(); // be sure config system is set
// Check if applicaton is enabled
CheckApplicationEnabled();
// Check access to temp compilation directory (under hosting identity)
CheckAccessToTempDirectory();
// Initialize health monitoring
InitializeHealthMonitoring();
// Init request queue (after reading config)
InitRequestQueue();
// configure the profiler according to config
InitTrace(context);
// Start heatbeat for Web Event Health Monitoring
HealthMonitoringManager.StartHealthMonitoringHeartbeat();
// Remove read and browse access of the bin directory
RestrictIISFolders(context);
// Preload all assemblies from bin (only if required). ASURT 114486
PreloadAssembliesFromBin();
// Decide whether or not to encode headers. VsWhidbey 257154
InitHeaderEncoding();
// Force the current encoder + validator to load so that there's a deterministic
// place (here) for an exception to occur if there's a load error
HttpEncoder.InitializeOnFirstRequest();
RequestValidator.InitializeOnFirstRequest();
if (context.WorkerRequest is ISAPIWorkerRequestOutOfProc) {
// Make sure that the <processModel> section has no errors
ProcessModelSection processModel = RuntimeConfig.GetMachineConfig().ProcessModel;
}
}
finally {
Thread.CurrentThread.CurrentUICulture = savedUICulture;
SetCurrentThreadCultureWithAssert(savedCulture);
}
}
}
catch (ConfigurationException e) {
error = e;
}
catch (Exception e) {
// remember second-phase initialization error
error = new HttpException(SR.GetString(SR.XSP_init_error, e.Message), e);
}
finally {
#if DBG
HttpContext.SetDebugAssertOnAccessToCurrent(false);
#endif
}
}
if (InitializationException != null) {
// throw cached exception. We need to wrap it in a new exception, otherwise
// we lose the original stack.
throw new HttpException(InitializationException.Message, InitializationException);
}
else if (error != null) {
InitializationException = error;
// throw new exception
throw error;
}
AddAppDomainTraceMessage("FirstRequestInit");
}
[SecurityPermission(SecurityAction.Assert, ControlThread = true)]
internal static void SetCurrentThreadCultureWithAssert(CultureInfo cultureInfo) {
Thread.CurrentThread.CurrentCulture = cultureInfo;
}
private void EnsureFirstRequestInit(HttpContext context) {
if (_beforeFirstRequest) {
lock (this) {
if (_beforeFirstRequest) {
_firstRequestStartTime = DateTime.UtcNow;
FirstRequestInit(context);
_beforeFirstRequest = false;
context.FirstRequest = true;
}
}
}
}
private void EnsureAccessToApplicationDirectory() {
if (!FileUtil.DirectoryAccessible(_appDomainAppPath)) {
//
if (_appDomainAppPath.IndexOf('?') >= 0) {
// Possible Unicode when not supported
throw new HttpException(SR.GetString(SR.Access_denied_to_unicode_app_dir, _appDomainAppPath));
}
else {
throw new HttpException(SR.GetString(SR.Access_denied_to_app_dir, _appDomainAppPath));
}
}
}
private void StartMonitoringDirectoryRenamesAndBinDirectory() {
_fcm.StartMonitoringDirectoryRenamesAndBinDirectory(AppDomainAppPathInternal, new FileChangeEventHandler(this.OnCriticalDirectoryChange));
}
//
// Monitor a local resources subdirectory and unload appdomain when it changes
//
internal static void StartListeningToLocalResourcesDirectory(VirtualPath virtualDir) {
#if !FEATURE_PAL // FEATURE_PAL does not enable file change notification
_theRuntime._fcm.StartListeningToLocalResourcesDirectory(virtualDir);
#endif // !FEATURE_PAL
}
//
// Get the configuration needed to minimally initialize
// the components required for a complete configuration system,
//
// Note that if the application configuration file has an error,
// AppLKGConfig will still retreive any valid configuration from
// that file, or from location directives that apply to the
// application path. This implies that an administrator can
// lock down an application's trust level in root web.config,
// and it will still take effect if the application's web.config
// has errors.
//
private void GetInitConfigSections(
out CacheSection cacheSection,
out TrustSection trustSection,
out SecurityPolicySection securityPolicySection,
out CompilationSection compilationSection,
out HostingEnvironmentSection hostingEnvironmentSection,
out Exception initException) {
cacheSection = null;
trustSection = null;
securityPolicySection = null;
compilationSection = null;
hostingEnvironmentSection = null;
initException = null;
// AppLKGConfig is guaranteed to not throw an exception.
RuntimeConfig appLKGConfig = RuntimeConfig.GetAppLKGConfig();
// AppConfig may throw an exception.
RuntimeConfig appConfig = null;
try {
appConfig = RuntimeConfig.GetAppConfig();
}
catch (Exception e) {
initException = e;
}
// Cache section
if (appConfig != null) {
try {
cacheSection = appConfig.Cache;
}
catch (Exception e) {
if (initException == null) {
initException = e;
}
}
}
if (cacheSection == null) {
cacheSection = appLKGConfig.Cache;
}
// Trust section
if (appConfig != null) {
try {
trustSection = appConfig.Trust;
}
catch (Exception e) {
if (initException == null) {
initException = e;
}
}
}
if (trustSection == null) {
trustSection = appLKGConfig.Trust;
}
// SecurityPolicy section
if (appConfig != null) {
try {
securityPolicySection = appConfig.SecurityPolicy;
}
catch (Exception e) {
if (initException == null) {
initException = e;
}
}
}
if (securityPolicySection == null) {
securityPolicySection = appLKGConfig.SecurityPolicy;
}
// Compilation section
if (appConfig != null) {
try {
compilationSection = appConfig.Compilation;
}
catch (Exception e) {
if (initException == null) {
initException = e;
}
}
}
if (compilationSection == null) {
compilationSection = appLKGConfig.Compilation;
}
// HostingEnvironment section
if (appConfig != null) {
try {
hostingEnvironmentSection = appConfig.HostingEnvironment;
}
catch (Exception e) {
if (initException == null) {
initException = e;
}
}
}
if (hostingEnvironmentSection == null) {
hostingEnvironmentSection = appLKGConfig.HostingEnvironment;
}
}
// Set up the codegen directory for the app
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "This call site is trusted.")]
private void SetUpCodegenDirectory(CompilationSection compilationSection) {
AppDomain appDomain = Thread.GetDomain();
string codegenBase;
// devdiv 1038337. Passing the corresponding IsDevelopmentEnvironment flag to ConstructSimpleAppName
string simpleAppName = System.Web.Hosting.AppManagerAppDomainFactory.ConstructSimpleAppName(
AppDomainAppVirtualPath, HostingEnvironment.IsDevelopmentEnvironment);
string tempDirectory = null;
// These variables are used for error handling
string tempDirAttribName = null;
string configFileName = null;
int configLineNumber = 0;
if (compilationSection != null && !String.IsNullOrEmpty(compilationSection.TempDirectory)) {
tempDirectory = compilationSection.TempDirectory;
compilationSection.GetTempDirectoryErrorInfo(out tempDirAttribName,
out configFileName, out configLineNumber);
}
if (tempDirectory != null) {
tempDirectory = tempDirectory.Trim();
if (!Path.IsPathRooted(tempDirectory)) {
// Make sure the path is not relative (VSWhidbey 260075)
tempDirectory = null;
}
else {
try {
// Canonicalize it to avoid problems with spaces (VSWhidbey 229873)
tempDirectory = new DirectoryInfo(tempDirectory).FullName;
}
catch {
tempDirectory = null;
}
}
if (tempDirectory == null) {
throw new ConfigurationErrorsException(
SR.GetString(SR.Invalid_temp_directory, tempDirAttribName),
configFileName, configLineNumber);
}
#if FEATURE_PAL
} else {
System.UInt32 length = 0;
StringBuilder sb = null;
bool bRet;
// Get the required length
bRet = UnsafeNativeMethods.GetUserTempDirectory(
UnsafeNativeMethods.DeploymentDirectoryType.ddtInstallationDependentDirectory,
null, ref length);
if (true == bRet) {
// now, allocate the string
sb = new StringBuilder ((int)length);
// call again to get the value
bRet = UnsafeNativeMethods.GetUserTempDirectory(
UnsafeNativeMethods.DeploymentDirectoryType.ddtInstallationDependentDirectory,
sb, ref length);
}
if (false == bRet) {
throw new ConfigurationException(
HttpRuntime.FormatResourceString(SR.Invalid_temp_directory, tempDirAttribName));
}
tempDirectory = Path.Combine(sb.ToString(), codegenDirName);
}
// Always try to create the ASP.Net temp directory for FEATURE_PAL
#endif // FEATURE_PAL
// Create the config-specified directory if needed
try {
Directory.CreateDirectory(tempDirectory);
}
catch (Exception e) {
throw new ConfigurationErrorsException(
SR.GetString(SR.Invalid_temp_directory, tempDirAttribName),
e,
configFileName, configLineNumber);
}
#if !FEATURE_PAL
}
else {
tempDirectory = Path.Combine(s_installDirectory, codegenDirName);
}
#endif // !FEATURE_PAL
// If we don't have write access to the codegen dir, use the TEMP dir instead.
// This will allow non-admin users to work in hosting scenarios (e.g. Venus, aspnet_compiler)
if (!System.Web.UI.Util.HasWriteAccessToDirectory(tempDirectory)) {
// Don't do this if we are not in a CBM scenario and we're in a service (!UserInteractive),
// as TEMP could point to unwanted places.
#if !FEATURE_PAL // always fail here
if ((!BuildManagerHost.InClientBuildManager) && (!Environment.UserInteractive))
#endif // !FEATURE_PAL
{
throw new HttpException(SR.GetString(SR.No_codegen_access,
System.Web.UI.Util.GetCurrentAccountName(), tempDirectory));
}
tempDirectory = Path.GetTempPath();
Debug.Assert(System.Web.UI.Util.HasWriteAccessToDirectory(tempDirectory));
tempDirectory = Path.Combine(tempDirectory, codegenDirName);
}
_tempDir = tempDirectory;
codegenBase = Path.Combine(tempDirectory, simpleAppName);
#pragma warning disable 0618 // To avoid deprecation warning
appDomain.SetDynamicBase(codegenBase);
#pragma warning restore 0618
_codegenDir = Thread.GetDomain().DynamicDirectory;
// Create the codegen directory if needed
Directory.CreateDirectory(_codegenDir);
}
private void InitFusion(HostingEnvironmentSection hostingEnvironmentSection) {
AppDomain appDomain = Thread.GetDomain();
// If there is a double backslash in the string, get rid of it (ASURT 122191)
// Make sure to skip the first char, to avoid breaking the UNC case
string appDomainAppPath = _appDomainAppPath;
if (appDomainAppPath.IndexOf(DoubleDirectorySeparatorString, 1, StringComparison.Ordinal) >= 1) {
appDomainAppPath = appDomainAppPath[0] + appDomainAppPath.Substring(1).Replace(DoubleDirectorySeparatorString,
DirectorySeparatorString);
}
#pragma warning disable 0618 // To avoid deprecation warning
// Allow assemblies from 'bin' to be loaded
appDomain.AppendPrivatePath(appDomainAppPath + BinDirectoryName);
#pragma warning restore 0618
// If shadow copying was disabled via config, turn it off (DevDiv 30864)
if (hostingEnvironmentSection != null && !hostingEnvironmentSection.ShadowCopyBinAssemblies) {
#pragma warning disable 0618 // To avoid deprecation warning
appDomain.ClearShadowCopyPath();
#pragma warning restore 0618
}
else {
// enable shadow-copying from bin
#pragma warning disable 0618 // To avoid deprecation warning
appDomain.SetShadowCopyPath(appDomainAppPath + BinDirectoryName);
#pragma warning restore 0618
}
// Get rid of the last part of the directory (the app name), since it will
// be re-appended.
string parentDir = Directory.GetParent(_codegenDir).FullName;
#pragma warning disable 0618 // To avoid deprecation warning
appDomain.SetCachePath(parentDir);
#pragma warning restore 0618
_fusionInited = true;
}
private void InitRequestQueue() {
RuntimeConfig config = RuntimeConfig.GetAppConfig();
HttpRuntimeSection runtimeConfig = config.HttpRuntime;
ProcessModelSection processConfig = config.ProcessModel;
if (processConfig.AutoConfig) {
_requestQueue = new RequestQueue(
88 * processConfig.CpuCount,
76 * processConfig.CpuCount,
runtimeConfig.AppRequestQueueLimit,
processConfig.ClientConnectedCheck);
}
else {
// Configuration section handlers cannot validate values based on values
// in other configuration sections, so we validate minFreeThreads and
// minLocalRequestFreeThreads here.
int maxThreads = (processConfig.MaxWorkerThreadsTimesCpuCount < processConfig.MaxIoThreadsTimesCpuCount) ? processConfig.MaxWorkerThreadsTimesCpuCount : processConfig.MaxIoThreadsTimesCpuCount;
// validate minFreeThreads
if (runtimeConfig.MinFreeThreads >= maxThreads) {
if (runtimeConfig.ElementInformation.Properties["minFreeThreads"].LineNumber == 0) {
if (processConfig.ElementInformation.Properties["maxWorkerThreads"].LineNumber != 0) {
throw new ConfigurationErrorsException(SR.GetString(SR.Thread_pool_limit_must_be_greater_than_minFreeThreads, runtimeConfig.MinFreeThreads.ToString(CultureInfo.InvariantCulture)),
processConfig.ElementInformation.Properties["maxWorkerThreads"].Source,
processConfig.ElementInformation.Properties["maxWorkerThreads"].LineNumber);
}
else {
throw new ConfigurationErrorsException(SR.GetString(SR.Thread_pool_limit_must_be_greater_than_minFreeThreads, runtimeConfig.MinFreeThreads.ToString(CultureInfo.InvariantCulture)),
processConfig.ElementInformation.Properties["maxIoThreads"].Source,
processConfig.ElementInformation.Properties["maxIoThreads"].LineNumber);
}
}
else {
throw new ConfigurationErrorsException(SR.GetString(SR.Min_free_threads_must_be_under_thread_pool_limits, maxThreads.ToString(CultureInfo.InvariantCulture)),
runtimeConfig.ElementInformation.Properties["minFreeThreads"].Source,
runtimeConfig.ElementInformation.Properties["minFreeThreads"].LineNumber);
}
}
// validate minLocalRequestFreeThreads
if (runtimeConfig.MinLocalRequestFreeThreads > runtimeConfig.MinFreeThreads) {
if (runtimeConfig.ElementInformation.Properties["minLocalRequestFreeThreads"].LineNumber == 0) {
throw new ConfigurationErrorsException(SR.GetString(SR.Local_free_threads_cannot_exceed_free_threads),
processConfig.ElementInformation.Properties["minFreeThreads"].Source,
processConfig.ElementInformation.Properties["minFreeThreads"].LineNumber);
}
else {
throw new ConfigurationErrorsException(SR.GetString(SR.Local_free_threads_cannot_exceed_free_threads),
runtimeConfig.ElementInformation.Properties["minLocalRequestFreeThreads"].Source,
runtimeConfig.ElementInformation.Properties["minLocalRequestFreeThreads"].LineNumber);
}
}
_requestQueue = new RequestQueue(
runtimeConfig.MinFreeThreads,
runtimeConfig.MinLocalRequestFreeThreads,
runtimeConfig.AppRequestQueueLimit,
processConfig.ClientConnectedCheck);
}
}
private void InitApartmentThreading() {
HttpRuntimeSection runtimeConfig = RuntimeConfig.GetAppConfig().HttpRuntime;
if (runtimeConfig != null) {
_apartmentThreading = runtimeConfig.ApartmentThreading;
}
else {
_apartmentThreading = false;
}
}
private void InitTrace(HttpContext context) {
TraceSection traceConfig = RuntimeConfig.GetAppConfig().Trace;
Profile.RequestsToProfile = traceConfig.RequestLimit;
Profile.PageOutput = traceConfig.PageOutput;
Profile.OutputMode = TraceMode.SortByTime;
if (traceConfig.TraceMode == TraceDisplayMode.SortByCategory)
Profile.OutputMode = TraceMode.SortByCategory;
Profile.LocalOnly = traceConfig.LocalOnly;
Profile.IsEnabled = traceConfig.Enabled;
Profile.MostRecent = traceConfig.MostRecent;
Profile.Reset();
// the first request's context is created before InitTrace, so
// we need to set this manually. (ASURT 93730)
context.TraceIsEnabled = traceConfig.Enabled;
TraceContext.SetWriteToDiagnosticsTrace(traceConfig.WriteToDiagnosticsTrace);
}
private void InitDebuggingSupport() {
CompilationSection compConfig = RuntimeConfig.GetAppConfig().Compilation;
_debuggingEnabled = compConfig.Debug;
}
/*
* Pre-load all the bin assemblies if we're impersonated. This way, if user code
* calls Assembly.Load while impersonated, the assembly will already be loaded, and
* we won't fail due to lack of permissions on the codegen dir (see ASURT 114486)
*/
[PermissionSet(SecurityAction.Assert, Unrestricted = true)]
private void PreloadAssembliesFromBin() {
bool appClientImpersonationEnabled = false;
if (!_isOnUNCShare) {
// if not on UNC share check if config has impersonation enabled (without userName)
IdentitySection c = RuntimeConfig.GetAppConfig().Identity;
if (c.Impersonate && c.ImpersonateToken == IntPtr.Zero)
appClientImpersonationEnabled = true;
}
if (!appClientImpersonationEnabled)
return;
// Get the path to the bin directory
string binPath = HttpRuntime.BinDirectoryInternal;
DirectoryInfo binPathDirectory = new DirectoryInfo(binPath);
if (!binPathDirectory.Exists)
return;
PreloadAssembliesFromBinRecursive(binPathDirectory);
}
private void PreloadAssembliesFromBinRecursive(DirectoryInfo dirInfo) {
FileInfo[] binDlls = dirInfo.GetFiles("*.dll");
// Pre-load all the assemblies, ignoring all exceptions
foreach (FileInfo fi in binDlls) {
try { Assembly.Load(System.Web.UI.Util.GetAssemblyNameFromFileName(fi.Name)); }
catch (FileNotFoundException) {
// If Load failed, try LoadFrom (VSWhidbey 493725)
try { Assembly.LoadFrom(fi.FullName); }
catch { }
}
catch { }
}
// Recurse on the subdirectories
DirectoryInfo[] subDirs = dirInfo.GetDirectories();
foreach (DirectoryInfo di in subDirs) {
PreloadAssembliesFromBinRecursive(di);
}
}
private void SetAutoConfigLimits(ProcessModelSection pmConfig) {
// check if the current limits are ok
int workerMax, ioMax;
ThreadPool.GetMaxThreads(out workerMax, out ioMax);
// only set if different
if (pmConfig.DefaultMaxWorkerThreadsForAutoConfig != workerMax || pmConfig.DefaultMaxIoThreadsForAutoConfig != ioMax) {
Debug.Trace("ThreadPool", "SetThreadLimit: from " + workerMax + "," + ioMax + " to " + pmConfig.DefaultMaxWorkerThreadsForAutoConfig + "," + pmConfig.DefaultMaxIoThreadsForAutoConfig);
UnsafeNativeMethods.SetClrThreadPoolLimits(pmConfig.DefaultMaxWorkerThreadsForAutoConfig, pmConfig.DefaultMaxIoThreadsForAutoConfig, true);
}
// this is the code equivalent of setting maxconnection
// Dev11 141729: Make autoConfig scale by default
// Dev11 144842: PERF: Consider removing Max connection limit or changing the default value
System.Net.ServicePointManager.DefaultConnectionLimit = Int32.MaxValue;
// we call InitRequestQueue later, from FirstRequestInit, and set minFreeThreads and minLocalRequestFreeThreads
}
private void SetThreadPoolLimits() {
try {
ProcessModelSection pmConfig = RuntimeConfig.GetMachineConfig().ProcessModel;
if (pmConfig.AutoConfig) {
// use recommendation in http://support.microsoft.com/?id=821268
SetAutoConfigLimits(pmConfig);
}
else if (pmConfig.MaxWorkerThreadsTimesCpuCount > 0 && pmConfig.MaxIoThreadsTimesCpuCount > 0) {
// check if the current limits are ok
int workerMax, ioMax;
ThreadPool.GetMaxThreads(out workerMax, out ioMax);
// only set if different
if (pmConfig.MaxWorkerThreadsTimesCpuCount != workerMax || pmConfig.MaxIoThreadsTimesCpuCount != ioMax) {
Debug.Trace("ThreadPool", "SetThreadLimit: from " + workerMax + "," + ioMax + " to " + pmConfig.MaxWorkerThreadsTimesCpuCount + "," + pmConfig.MaxIoThreadsTimesCpuCount);
UnsafeNativeMethods.SetClrThreadPoolLimits(pmConfig.MaxWorkerThreadsTimesCpuCount, pmConfig.MaxIoThreadsTimesCpuCount, false);
}
}
if (pmConfig.MinWorkerThreadsTimesCpuCount > 0 || pmConfig.MinIoThreadsTimesCpuCount > 0) {
int currentMinWorkerThreads, currentMinIoThreads;
ThreadPool.GetMinThreads(out currentMinWorkerThreads, out currentMinIoThreads);
int newMinWorkerThreads = pmConfig.MinWorkerThreadsTimesCpuCount > 0 ? pmConfig.MinWorkerThreadsTimesCpuCount : currentMinWorkerThreads;
int newMinIoThreads = pmConfig.MinIoThreadsTimesCpuCount > 0 ? pmConfig.MinIoThreadsTimesCpuCount : currentMinIoThreads;
if (newMinWorkerThreads > 0 && newMinIoThreads > 0
&& (newMinWorkerThreads != currentMinWorkerThreads || newMinIoThreads != currentMinIoThreads))
ThreadPool.SetMinThreads(newMinWorkerThreads, newMinIoThreads);
}
}
catch {
}
}
internal static void CheckApplicationEnabled() {
// process App_Offline.htm file
string appOfflineFile = Path.Combine(_theRuntime._appDomainAppPath, AppOfflineFileName);
bool appOfflineFileFound = false;
// monitor even if doesn't exist
_theRuntime._fcm.StartMonitoringFile(appOfflineFile, new FileChangeEventHandler(_theRuntime.OnAppOfflineFileChange));
// read the file into memory
try {
if (File.Exists(appOfflineFile)) {
Debug.Trace("AppOffline", "File " + appOfflineFile + " exists. Using it.");
using (FileStream fs = new FileStream(appOfflineFile, FileMode.Open, FileAccess.Read, FileShare.Read)) {
if (fs.Length <= MaxAppOfflineFileLength) {
int length = (int)fs.Length;
if (length > 0) {
byte[] message = new byte[length];
if (fs.Read(message, 0, length) == length) {
// remember the message
_theRuntime._appOfflineMessage = message;
appOfflineFileFound = true;
}
}
else {
// empty file
appOfflineFileFound = true;
_theRuntime._appOfflineMessage = new byte[0];
}
}
}
}
}
catch {
// ignore any IO errors reading the file
}
// throw if there is a valid App_Offline file
if (appOfflineFileFound) {
throw new HttpException(503, String.Empty);
}
// process the config setting
HttpRuntimeSection runtimeConfig = RuntimeConfig.GetAppConfig().HttpRuntime;
if (!runtimeConfig.Enable) {
// throw 404 on first request init -- this will get cached until config changes
throw new HttpException(404, String.Empty);
}
}
[FileIOPermission(SecurityAction.Assert, Unrestricted = true)]
private void CheckAccessToTempDirectory() {
// The original check (in HostingInit) was done under process identity
// this time we do it under hosting identity
if (HostingEnvironment.HasHostingIdentity) {
using (new ApplicationImpersonationContext()) {
if (!System.Web.UI.Util.HasWriteAccessToDirectory(_tempDir)) {
throw new HttpException(SR.GetString(SR.No_codegen_access,
System.Web.UI.Util.GetCurrentAccountName(), _tempDir));
}
}
}
}
private void InitializeHealthMonitoring() {
#if !FEATURE_PAL // FEATURE_PAL does not enable IIS-based hosting features
ProcessModelSection pmConfig = RuntimeConfig.GetMachineConfig().ProcessModel;
int deadLockInterval = (int)pmConfig.ResponseDeadlockInterval.TotalSeconds;
int requestQueueLimit = pmConfig.RequestQueueLimit;
Debug.Trace("HealthMonitor", "Initalizing: ResponseDeadlockInterval=" + deadLockInterval);
UnsafeNativeMethods.InitializeHealthMonitor(deadLockInterval, requestQueueLimit);
#endif // !FEATURE_PAL
}
private static void InitHttpConfiguration() {
if (!_theRuntime._configInited) {
_theRuntime._configInited = true;
HttpConfigurationSystem.EnsureInit(null, true, true);
// whenever possible report errors in the user's culture (from machine.config)
// Note: this thread's culture is saved/restored during FirstRequestInit, so this is safe
// see ASURT 81655
GlobalizationSection globConfig = RuntimeConfig.GetAppLKGConfig().Globalization;
if (globConfig != null) {
if (!String.IsNullOrEmpty(globConfig.Culture) &&
!StringUtil.StringStartsWithIgnoreCase(globConfig.Culture, "auto"))
SetCurrentThreadCultureWithAssert(HttpServerUtility.CreateReadOnlyCultureInfo(globConfig.Culture));
if (!String.IsNullOrEmpty(globConfig.UICulture) &&
!StringUtil.StringStartsWithIgnoreCase(globConfig.UICulture, "auto"))
Thread.CurrentThread.CurrentUICulture = HttpServerUtility.CreateReadOnlyCultureInfo(globConfig.UICulture);
}
// check for errors in <processModel> section
RuntimeConfig appConfig = RuntimeConfig.GetAppConfig();
object section = appConfig.ProcessModel;
// check for errors in <hostingEnvironment> section
section = appConfig.HostingEnvironment;
}
}
private void InitHeaderEncoding() {
HttpRuntimeSection runtimeConfig = RuntimeConfig.GetAppConfig().HttpRuntime;
_enableHeaderChecking = runtimeConfig.EnableHeaderChecking;
}
private static void SetAutogenKeys() {
#if !FEATURE_PAL // FEATURE_PAL does not enable cryptography
byte[] bKeysRandom = new byte[s_autogenKeys.Length];
byte[] bKeysStored = new byte[s_autogenKeys.Length];
bool fGetStoredKeys = false;
RNGCryptoServiceProvider randgen = new RNGCryptoServiceProvider();
// Gernerate random keys
randgen.GetBytes(bKeysRandom);
// If getting stored keys via WorkerRequest object failed, get it directly
if (!fGetStoredKeys)
fGetStoredKeys = (UnsafeNativeMethods.EcbCallISAPI(IntPtr.Zero, UnsafeNativeMethods.CallISAPIFunc.GetAutogenKeys,
bKeysRandom, bKeysRandom.Length, bKeysStored, bKeysStored.Length) == 1);
// If we managed to get stored keys, copy them in; else use random keys
if (fGetStoredKeys)
Buffer.BlockCopy(bKeysStored, 0, s_autogenKeys, 0, s_autogenKeys.Length);
else
Buffer.BlockCopy(bKeysRandom, 0, s_autogenKeys, 0, s_autogenKeys.Length);
#endif // !FEATURE_PAL
}
internal static void IncrementActivePipelineCount() {
Interlocked.Increment(ref _theRuntime._activeRequestCount);
HostingEnvironment.IncrementBusyCount();
}
internal static void DecrementActivePipelineCount() {
HostingEnvironment.DecrementBusyCount();
Interlocked.Decrement(ref _theRuntime._activeRequestCount);
}
internal static void PopulateIISVersionInformation() {
if (IsEngineLoaded) {
uint dwVersion;
bool fIsIntegratedMode;
UnsafeIISMethods.MgdGetIISVersionInformation(out dwVersion, out fIsIntegratedMode);
if (dwVersion != 0) {
// High word is the major version; low word is the minor version (this is MAKELONG format)
_iisVersion = new Version((int)(dwVersion >> 16), (int)(dwVersion & 0xffff));
_useIntegratedPipeline = fIsIntegratedMode;
}
}
}
// Gets the version of IIS (7.0, 7.5, 8.0, etc.) that is hosting this application, or null if this application isn't IIS-hosted.
// Should also return the correct version for IIS Express.
public static Version IISVersion {
get {
return _iisVersion;
}
}
// DevDivBugs 190952: public method for querying runtime pipeline mode
public static bool UsingIntegratedPipeline {
get {
return UseIntegratedPipeline;
}
}
internal static bool UseIntegratedPipeline {
get {
return _useIntegratedPipeline;
}
}
internal static bool EnablePrefetchOptimization {
get {
return _enablePrefetchOptimization;
}
}
/*
* Process one step of the integrated pipeline
*
*/
internal static RequestNotificationStatus ProcessRequestNotification(IIS7WorkerRequest wr, HttpContext context)
{
return _theRuntime.ProcessRequestNotificationPrivate(wr, context);
}
private RequestNotificationStatus ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) {
RequestNotificationStatus status = RequestNotificationStatus.Pending;
try {
int currentModuleIndex;
bool isPostNotification;
int currentNotification;
// setup the HttpContext for this event/module combo
UnsafeIISMethods.MgdGetCurrentNotificationInfo(wr.RequestContext, out currentModuleIndex, out isPostNotification, out currentNotification);
context.CurrentModuleIndex = currentModuleIndex;
context.IsPostNotification = isPostNotification;
context.CurrentNotification = (RequestNotification) currentNotification;
#if DBG
Debug.Trace("PipelineRuntime", "HttpRuntime::ProcessRequestNotificationPrivate: notification=" + context.CurrentNotification.ToString()
+ ", isPost=" + context.IsPostNotification
+ ", moduleIndex=" + context.CurrentModuleIndex);
#endif
IHttpHandler handler = null;
if (context.NeedToInitializeApp()) {
#if DBG
Debug.Trace("FileChangesMonitorIgnoreSubdirChange",
"*** FirstNotification " + DateTime.Now.ToString("hh:mm:ss.fff", CultureInfo.InvariantCulture)
+ ": _appDomainAppId=" + _appDomainAppId);
#endif
// First request initialization
try {
EnsureFirstRequestInit(context);
}
catch {
// If we are handling a DEBUG request, ignore the FirstRequestInit exception.
// This allows the HttpDebugHandler to execute, and lets the debugger attach to
// the process (VSWhidbey 358135)
if (!context.Request.IsDebuggingRequest) {
throw;
}
}
context.Response.InitResponseWriter();
handler = HttpApplicationFactory.GetApplicationInstance(context);
if (handler == null)
throw new HttpException(SR.GetString(SR.Unable_create_app_object));
if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Infrastructure)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_START_HANDLER, context.WorkerRequest, handler.GetType().FullName, "Start");
HttpApplication app = handler as HttpApplication;
if (app != null) {
// associate the context with an application instance
app.AssignContext(context);
}
}
// this may throw, and should be called after app initialization
wr.SynchronizeVariables(context);
if (context.ApplicationInstance != null) {
// process request
IAsyncResult ar = context.ApplicationInstance.BeginProcessRequestNotification(context, _requestNotificationCompletionCallback);
if (ar.CompletedSynchronously) {
status = RequestNotificationStatus.Continue;
}
}
else if (handler != null) {
// HttpDebugHandler is processed here
handler.ProcessRequest(context);
status = RequestNotificationStatus.FinishRequest;
}
else {
status = RequestNotificationStatus.Continue;
}
}
catch (Exception e) {
status = RequestNotificationStatus.FinishRequest;
context.Response.InitResponseWriter();
// errors are handled in HttpRuntime::FinishRequestNotification
context.AddError(e);
}
if (status != RequestNotificationStatus.Pending) {
// we completed synchronously
FinishRequestNotification(wr, context, ref status);
}
#if DBG
Debug.Trace("PipelineRuntime", "HttpRuntime::ProcessRequestNotificationPrivate: status=" + status.ToString());
#endif
return status;
}
private void FinishRequestNotification(IIS7WorkerRequest wr, HttpContext context, ref RequestNotificationStatus status) {
Debug.Assert(status != RequestNotificationStatus.Pending, "status != RequestNotificationStatus.Pending");
HttpApplication app = context.ApplicationInstance;
if (context.NotificationContext.RequestCompleted) {
status = RequestNotificationStatus.FinishRequest;
}
// check if the app offline or whether an error has occurred, and report the condition
context.ReportRuntimeErrorIfExists(ref status);
// we do not return FinishRequest for LogRequest or EndRequest
if (status == RequestNotificationStatus.FinishRequest
&& (context.CurrentNotification == RequestNotification.LogRequest
|| context.CurrentNotification == RequestNotification.EndRequest)) {
status = RequestNotificationStatus.Continue;
}
IntPtr requestContext = wr.RequestContext;
bool sendHeaders = UnsafeIISMethods.MgdIsLastNotification(requestContext, status);
try {
context.Response.UpdateNativeResponse(sendHeaders);
}
catch(Exception e) {
// if we catch an exception here then
// i) clear cached response body bytes on the worker request
// ii) clear the managed headers, the IIS native headers, the mangaged httpwriter response buffers, and the native IIS response buffers
// iii) attempt to format the exception and write it to the response
wr.UnlockCachedResponseBytes();
context.AddError(e);
context.ReportRuntimeErrorIfExists(ref status);
try {
context.Response.UpdateNativeResponse(sendHeaders);
}
catch {
}
}
if (sendHeaders) {
context.FinishPipelineRequest();
}
// Perf optimization: dispose managed context if possible (no need to try if status is pending)
if (status != RequestNotificationStatus.Pending) {
PipelineRuntime.DisposeHandler(context, requestContext, status);
}
}
internal static void FinishPipelineRequest(HttpContext context) {
// Remember that first request is done
_theRuntime._firstRequestCompleted = true;
// need to raise OnRequestCompleted while within the ThreadContext so that things like User, CurrentCulture, etc. are available
context.RaiseOnRequestCompleted();
context.Request.Dispose();
context.Response.Dispose();
HttpApplication app = context.ApplicationInstance;
if(null != app) {
ThreadContext threadContext = context.IndicateCompletionContext;
if (threadContext != null) {
if (!threadContext.HasBeenDisassociatedFromThread) {
lock (threadContext) {
if (!threadContext.HasBeenDisassociatedFromThread) {
threadContext.DisassociateFromCurrentThread();
context.IndicateCompletionContext = null;
context.InIndicateCompletion = false;
}
}
}
}
app.ReleaseAppInstance();
}
SetExecutionTimePerformanceCounter(context);
UpdatePerfCounters(context.Response.StatusCode);
if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Infrastructure)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_END_HANDLER, context.WorkerRequest);
// In case of a HostingInit() error, app domain should not stick around
if (HostingInitFailed) {
Debug.Trace("AppDomainFactory", "Shutting down appdomain because of HostingInit error");
ShutdownAppDomain(ApplicationShutdownReason.HostingEnvironment, "HostingInit error");
}
}
/*
* Process one request
*/
private void ProcessRequestInternal(HttpWorkerRequest wr) {
// Count active requests
Interlocked.Increment(ref _activeRequestCount);
if (_disposingHttpRuntime) {
// Dev11 333176: An appdomain is unloaded before all requests are served, resulting in System.AppDomainUnloadedException during isapi completion callback
//
// HttpRuntim.Dispose could have already finished on a different thread when we had no active requests
// In this case we are about to start or already started unloading the appdomain so we will reject the request the safest way possible
try {
wr.SendStatus(503, "Server Too Busy");
wr.SendKnownResponseHeader(HttpWorkerRequest.HeaderContentType, "text/html; charset=utf-8");
byte[] body = Encoding.ASCII.GetBytes("<html><body>Server Too Busy</body></html>");
wr.SendResponseFromMemory(body, body.Length);
// this will flush synchronously because of HttpRuntime.ShutdownInProgress
wr.FlushResponse(true);
wr.EndOfRequest();
} finally {
Interlocked.Decrement(ref _activeRequestCount);
}
return;
}
// Construct the Context on HttpWorkerRequest, hook everything together
HttpContext context;
try {
context = new HttpContext(wr, false /* initResponseWriter */);
}
catch {
try {
// If we fail to create the context for any reason, send back a 400 to make sure
// the request is correctly closed (relates to VSUQFE3962)
wr.SendStatus(400, "Bad Request");
wr.SendKnownResponseHeader(HttpWorkerRequest.HeaderContentType, "text/html; charset=utf-8");
byte[] body = Encoding.ASCII.GetBytes("<html><body>Bad Request</body></html>");
wr.SendResponseFromMemory(body, body.Length);
wr.FlushResponse(true);
wr.EndOfRequest();
return;
} finally {
Interlocked.Decrement(ref _activeRequestCount);
}
}
wr.SetEndOfSendNotification(_asyncEndOfSendCallback, context);
HostingEnvironment.IncrementBusyCount();
try {
// First request initialization
try {
EnsureFirstRequestInit(context);
}
catch {
// If we are handling a DEBUG request, ignore the FirstRequestInit exception.
// This allows the HttpDebugHandler to execute, and lets the debugger attach to
// the process (VSWhidbey 358135)
if (!context.Request.IsDebuggingRequest) {
throw;
}
}
// Init response writer (after we have config in first request init)
// no need for impersonation as it is handled in config system
context.Response.InitResponseWriter();
// Get application instance
IHttpHandler app = HttpApplicationFactory.GetApplicationInstance(context);
if (app == null)
throw new HttpException(SR.GetString(SR.Unable_create_app_object));
if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Infrastructure)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_START_HANDLER, context.WorkerRequest, app.GetType().FullName, "Start");
if (app is IHttpAsyncHandler) {
// asynchronous handler
IHttpAsyncHandler asyncHandler = (IHttpAsyncHandler)app;
context.AsyncAppHandler = asyncHandler;
asyncHandler.BeginProcessRequest(context, _handlerCompletionCallback, context);
}
else {
// synchronous handler
app.ProcessRequest(context);
FinishRequest(context.WorkerRequest, context, null);
}
}
catch (Exception e) {
context.Response.InitResponseWriter();
FinishRequest(wr, context, e);
}
}
private void RejectRequestInternal(HttpWorkerRequest wr, bool silent) {
// Construct the Context on HttpWorkerRequest, hook everything together
HttpContext context = new HttpContext(wr, false /* initResponseWriter */);
wr.SetEndOfSendNotification(_asyncEndOfSendCallback, context);
// Count active requests
Interlocked.Increment(ref _activeRequestCount);
HostingEnvironment.IncrementBusyCount();
if (silent) {
context.Response.InitResponseWriter();
FinishRequest(wr, context, null);
}
else {
PerfCounters.IncrementGlobalCounter(GlobalPerfCounter.REQUESTS_REJECTED);
PerfCounters.IncrementCounter(AppPerfCounter.APP_REQUESTS_REJECTED);
try {
throw new HttpException(503, SR.GetString(SR.Server_too_busy));
}
catch (Exception e) {
context.Response.InitResponseWriter();
FinishRequest(wr, context, e);
}
}
}
internal static void ReportAppOfflineErrorMessage(HttpResponse response, byte[] appOfflineMessage) {
response.StatusCode = 503;
response.ContentType = "text/html";
response.AddHeader("Retry-After", "3600");
response.OutputStream.Write(appOfflineMessage, 0, appOfflineMessage.Length);
}
/*
* Finish processing request, sync or async
*/
private void FinishRequest(HttpWorkerRequest wr, HttpContext context, Exception e) {
HttpResponse response = context.Response;
if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Infrastructure)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_END_HANDLER, context.WorkerRequest);
SetExecutionTimePerformanceCounter(context);
// Flush in case of no error
if (e == null) {
// impersonate around PreSendHeaders / PreSendContent
using (new ClientImpersonationContext(context, false)) {
try {
// this sends the actual content in most cases
response.FinalFlushAtTheEndOfRequestProcessing();
}
catch (Exception eFlush) {
e = eFlush;
}
}
}
// Report error if any
if (e != null) {
using (new DisposableHttpContextWrapper(context)) {
// if the custom encoder throws, it might interfere with returning error information
// to the client, so we force use of the default encoder
context.DisableCustomHttpEncoder = true;
if (_appOfflineMessage != null) {
try {
ReportAppOfflineErrorMessage(response, _appOfflineMessage);
response.FinalFlushAtTheEndOfRequestProcessing();
}
catch {
}
}
else {
// when application is on UNC share the code below must
// be run while impersonating the token given by IIS
using (new ApplicationImpersonationContext()) {
try {
try {
// try to report error in a way that could possibly throw (a config exception)
response.ReportRuntimeError(e, true /*canThrow*/, false);
}
catch (Exception eReport) {
// report the config error in a way that would not throw
response.ReportRuntimeError(eReport, false /*canThrow*/, false);
}
response.FinalFlushAtTheEndOfRequestProcessing();
}
catch {
}
}
}
}
}
// Remember that first request is done
_firstRequestCompleted = true;
// In case we reporting HostingInit() error, app domain should not stick around
if (_hostingInitFailed) {
Debug.Trace("AppDomainFactory", "Shutting down appdomain because of HostingInit error");
ShutdownAppDomain(ApplicationShutdownReason.HostingEnvironment, "HostingInit error");
}
// Check status code and increment proper counter
// If it's an error status code (i.e. 400 or higher), increment the proper perf counters
int statusCode = response.StatusCode;
UpdatePerfCounters(statusCode);
context.FinishRequestForCachedPathData(statusCode);
// ---- exceptions from EndOfRequest as they will prevent proper request cleanup
// Since the exceptions are not expected here we want to log them
try {
wr.EndOfRequest();
}
catch (Exception ex) {
WebBaseEvent.RaiseRuntimeError(ex, this);
}
// Count active requests
HostingEnvironment.DecrementBusyCount();
Interlocked.Decrement(ref _activeRequestCount);
// Schedule more work if some requests are queued
if (_requestQueue != null)
_requestQueue.ScheduleMoreWorkIfNeeded();
}
//
// Make sure shutdown happens only once
//
private bool InitiateShutdownOnce() {
if (_shutdownInProgress)
return false;
lock (this) {
if (_shutdownInProgress)
return false;
_shutdownInProgress = true;
}
return true;
}
//
// Shutdown this and restart new app domain
//
[PermissionSet(SecurityAction.Assert, Unrestricted = true)]
private void ReleaseResourcesAndUnloadAppDomain(Object state /*not used*/) {
#if DBG
Debug.Trace("FileChangesMonitorIgnoreSubdirChange",
"*** ReleaseResourcesAndUnloadAppDomain " + DateTime.Now.ToString("hh:mm:ss.fff", CultureInfo.InvariantCulture)
+ ": _appDomainAppId=" + _appDomainAppId);
#endif
Debug.Trace("AppDomainFactory", "ReleaseResourcesAndUnloadAppDomain, Id=" + _appDomainAppId
+ " DomainId = " + _appDomainId
+ " Stack = " + Environment.StackTrace );
try {
PerfCounters.IncrementGlobalCounter(GlobalPerfCounter.APPLICATION_RESTARTS);
}
catch {
}
// Release all resources
try {
Dispose();
}
catch {
}
Thread.Sleep(250);
AddAppDomainTraceMessage("before Unload");
for (; ; ) {
try {
AppDomain.Unload(Thread.GetDomain());
}
catch (CannotUnloadAppDomainException) {
Debug.Assert(false);
}
catch (Exception e) {
Debug.Trace("AppDomainFactory", "AppDomain.Unload exception: " + e + "; Id=" + _appDomainAppId);
if (!BuildManagerHost.InClientBuildManager) {
// Avoid calling Exception.ToString if we are in the ClientBuildManager (Dev10 bug 824659)
AddAppDomainTraceMessage("Unload Exception: " + e);
}
throw;
}
}
}
private static void SetExecutionTimePerformanceCounter(HttpContext context) {
// Set the Request Execution time perf counter
TimeSpan elapsed = DateTime.UtcNow.Subtract(context.WorkerRequest.GetStartTime());
long milli = elapsed.Ticks / TimeSpan.TicksPerMillisecond;
if (milli > Int32.MaxValue)
milli = Int32.MaxValue;
PerfCounters.SetGlobalCounter(GlobalPerfCounter.REQUEST_EXECUTION_TIME, (int)milli);
PerfCounters.SetCounter(AppPerfCounter.APP_REQUEST_EXEC_TIME, (int)milli);
}
private static void UpdatePerfCounters(int statusCode) {
if (400 <= statusCode) {
PerfCounters.IncrementCounter(AppPerfCounter.REQUESTS_FAILED);
switch (statusCode) {
case 401: // Not authorized
PerfCounters.IncrementCounter(AppPerfCounter.REQUESTS_NOT_AUTHORIZED);
break;
case 404: // Not found
case 414: // Not found
PerfCounters.IncrementCounter(AppPerfCounter.REQUESTS_NOT_FOUND);
break;
}
}
else {
// If status code is not in the 400-599 range (i.e. 200-299 success or 300-399 redirection),
// count it as a successful request.
PerfCounters.IncrementCounter(AppPerfCounter.REQUESTS_SUCCEDED);
}
}
private void WaitForRequestsToFinish(int waitTimeoutMs) {
DateTime waitLimit = DateTime.UtcNow.AddMilliseconds(waitTimeoutMs);
for (; ; ) {
if (_activeRequestCount == 0 && (_requestQueue == null || _requestQueue.IsEmpty))
break;
Thread.Sleep(250);
// only apply timeout if a managed debugger is not attached
if (!System.Diagnostics.Debugger.IsAttached && DateTime.UtcNow > waitLimit) {
break; // give it up
}
}
}
/*
* Cleanup of all unmananged state
*/
private void Dispose() {
// get shutdown timeout from config
int drainTimeoutSec = HttpRuntimeSection.DefaultShutdownTimeout;
try {
HttpRuntimeSection runtimeConfig = RuntimeConfig.GetAppLKGConfig().HttpRuntime;
if (runtimeConfig != null) {
drainTimeoutSec = (int)runtimeConfig.ShutdownTimeout.TotalSeconds;
}
// before aborting compilation give time to drain (new requests are no longer coming at this point)
WaitForRequestsToFinish(drainTimeoutSec * 1000);
// reject remaining queued requests
if (_requestQueue != null)
_requestQueue.Drain();
} finally {
// By this time all new requests should be directed to a newly created app domain
// But there might be requests that got dispatched to this old app domain but have not reached ProcessRequestInternal yet
// Signal ProcessRequestInternal to reject them immediately without initiating async operations
_disposingHttpRuntime = true;
}
// give it a little more time to drain
WaitForRequestsToFinish((drainTimeoutSec * 1000) / 6);
// wait for pending async io to complete, prior to aborting requests
// this isn't necessary for IIS 7, where the async sends are always done
// from native code with native buffers
System.Web.Hosting.ISAPIWorkerRequestInProcForIIS6.WaitForPendingAsyncIo();
// For IIS7 integrated pipeline, wait until GL_APPLICATION_STOP fires and
// there are no active calls to IndicateCompletion before unloading the AppDomain
if (HttpRuntime.UseIntegratedPipeline) {
PipelineRuntime.WaitForRequestsToDrain();
}
else {
// wait for all active requests to complete
while (_activeRequestCount != 0) {
Thread.Sleep(250);
}
}
// Dispose AppDomainShutdownTimer
DisposeAppDomainShutdownTimer();
// kill all remaining requests (and the timeout timer)
_timeoutManager.Stop();
AppDomainResourcePerfCounters.Stop();
#if !FEATURE_PAL // FEATURE_PAL does not enable IIS-based hosting features
// double check for pending async io
System.Web.Hosting.ISAPIWorkerRequestInProcForIIS6.WaitForPendingAsyncIo();
// stop sqlcachedependency polling
SqlCacheDependencyManager.Dispose((drainTimeoutSec * 1000) / 2);
#endif // !FEATURE_PAL
// cleanup cache (this ends all sessions)
HealthMonitoringManager.IsCacheDisposed = true; // HMM is the only place internally where we care if the Cache is disposed or not.
if (_cachePublic != null) {
var oCache = HttpRuntime.Cache.GetObjectCache(createIfDoesNotExist: false);
var iCache = HttpRuntime.Cache.GetInternalCache(createIfDoesNotExist: false);
if (oCache != null) {
oCache.Dispose();
}
if (iCache != null) {
iCache.Dispose();
}
}
// app on end, cleanup app instances
HttpApplicationFactory.EndApplication(); // call app_onEnd
// stop file changes monitor
_fcm.Stop();
// stop health monitoring timer
HealthMonitoringManager.Shutdown();
}
/*
* Async completion of IIS7 pipeline (unlike OnHandlerCompletion, this may fire more than once).
*/
private void OnRequestNotificationCompletion(IAsyncResult ar) {
try {
OnRequestNotificationCompletionHelper(ar);
}
catch(Exception e) {
ApplicationManager.RecordFatalException(e);
throw;
}
}
private void OnRequestNotificationCompletionHelper(IAsyncResult ar) {
if (ar.CompletedSynchronously) {
Debug.Trace("PipelineRuntime", "OnRequestNotificationCompletion: completed synchronously");
return;
}
Debug.Trace("PipelineRuntime", "OnRequestNotificationCompletion: completed asynchronously");
RequestNotificationStatus status = RequestNotificationStatus.Continue;
HttpContext context = (HttpContext) ar.AsyncState;
IIS7WorkerRequest wr = context.WorkerRequest as IIS7WorkerRequest;
try {
context.ApplicationInstance.EndProcessRequestNotification(ar);
}
catch (Exception e) {
status = RequestNotificationStatus.FinishRequest;
context.AddError(e);
}
// RequestContext is set to null if this is the last notification, so we need to save it
// for the call to PostCompletion
IntPtr requestContext = wr.RequestContext;
FinishRequestNotification(wr, context, ref status);
// set the notification context to null since we are exiting this notification
context.NotificationContext = null;
// Indicate completion to IIS, so that it can resume
// request processing on an IIS thread
Debug.Trace("PipelineRuntime", "OnRequestNotificationCompletion(" + status + ")");
int result = UnsafeIISMethods.MgdPostCompletion(requestContext, status);
Misc.ThrowIfFailedHr(result);
}
/*
* Async completion of managed pipeline (called at most one time).
*/
private void OnHandlerCompletion(IAsyncResult ar) {
HttpContext context = (HttpContext)ar.AsyncState;
try {
context.AsyncAppHandler.EndProcessRequest(ar);
}
catch (Exception e) {
context.AddError(e);
}
finally {
// no longer keep AsyncAppHandler poiting to the application
// is only needed to call EndProcessRequest
context.AsyncAppHandler = null;
}
FinishRequest(context.WorkerRequest, context, context.Error);
}
/*
* Notification from worker request that it is done writing from buffer
* so that the buffers can be recycled
*/
private void EndOfSendCallback(HttpWorkerRequest wr, Object arg) {
Debug.Trace("PipelineRuntime", "HttpRuntime.EndOfSendCallback");
HttpContext context = (HttpContext)arg;
context.Request.Dispose();
context.Response.Dispose();
}
/*
* Notification when something in the bin directory changed
*/
private void OnCriticalDirectoryChange(Object sender, FileChangeEvent e) {
// shutdown the app domain
Debug.Trace("AppDomainFactory", "Shutting down appdomain because of bin dir change or directory rename." +
" FileName=" + e.FileName + " Action=" + e.Action);
ApplicationShutdownReason reason = ApplicationShutdownReason.None;
string directoryName = new DirectoryInfo(e.FileName).Name;
string message = FileChangesMonitor.GenerateErrorMessage(e.Action);
message = (message != null) ? message + directoryName : directoryName + " dir change or directory rename";
if (StringUtil.EqualsIgnoreCase(directoryName, CodeDirectoryName)) {
reason = ApplicationShutdownReason.CodeDirChangeOrDirectoryRename;
}
else if (StringUtil.EqualsIgnoreCase(directoryName, ResourcesDirectoryName)) {
reason = ApplicationShutdownReason.ResourcesDirChangeOrDirectoryRename;
}
else if (StringUtil.EqualsIgnoreCase(directoryName, BrowsersDirectoryName)) {
reason = ApplicationShutdownReason.BrowsersDirChangeOrDirectoryRename;
}
else if (StringUtil.EqualsIgnoreCase(directoryName, BinDirectoryName)) {
reason = ApplicationShutdownReason.BinDirChangeOrDirectoryRename;
}
if (e.Action == FileAction.Added) {
// Make sure HttpRuntime does not ignore the appdomain shutdown if a file is added (VSWhidbey 363481)
HttpRuntime.SetUserForcedShutdown();
Debug.Trace("AppDomainFactorySpecial", "Call SetUserForcedShutdown: FileName=" + e.FileName + "; now=" + DateTime.Now);
}
ShutdownAppDomain(reason, message);
}
/**
* Coalesce file change notifications to minimize sharing violations and AppDomain restarts (ASURT 147492)
*/
internal static void CoalesceNotifications() {
int waitChangeNotification = HttpRuntimeSection.DefaultWaitChangeNotification;
int maxWaitChangeNotification = HttpRuntimeSection.DefaultMaxWaitChangeNotification;
try {
HttpRuntimeSection config = RuntimeConfig.GetAppLKGConfig().HttpRuntime;
if (config != null) {
waitChangeNotification = config.WaitChangeNotification;
maxWaitChangeNotification = config.MaxWaitChangeNotification;
}
}
catch {
}
if (waitChangeNotification == 0 || maxWaitChangeNotification == 0)
return;
DateTime maxWait = DateTime.UtcNow.AddSeconds(maxWaitChangeNotification);
// Coalesce file change notifications
try {
while (DateTime.UtcNow < maxWait) {
if (DateTime.UtcNow > _theRuntime.LastShutdownAttemptTime.AddSeconds(waitChangeNotification))
break;
Thread.Sleep(250);
}
}
catch {
}
}
// appdomain shutdown eventhandler
internal static event BuildManagerHostUnloadEventHandler AppDomainShutdown;
internal static void OnAppDomainShutdown(BuildManagerHostUnloadEventArgs e) {
if (AppDomainShutdown != null) {
AppDomainShutdown(_theRuntime, e);
}
}
internal static void SetUserForcedShutdown() {
_theRuntime._userForcedShutdown = true;
}
/*
* Shutdown the current app domain
*/
internal static bool ShutdownAppDomain(ApplicationShutdownReason reason, string message) {
return ShutdownAppDomainWithStackTrace(reason, message, null /*stackTrace*/);
}
/*
* Shutdown the current app domain with a stack trace. This is useful for callers that are running
* on a QUWI callback, and wouldn't provide a meaningful stack trace by default.
*/
internal static bool ShutdownAppDomainWithStackTrace(ApplicationShutdownReason reason, string message, string stackTrace) {
SetShutdownReason(reason, message);
return ShutdownAppDomain(stackTrace);
}
private static bool ShutdownAppDomain(string stackTrace) {
#if DBG
Debug.Trace("FileChangesMonitorIgnoreSubdirChange",
"*** ShutdownAppDomain " + DateTime.Now.ToString("hh:mm:ss.fff", CultureInfo.InvariantCulture)
+ ": _appDomainAppId=" + HttpRuntime.AppDomainAppId);
#endif
// Ignore notifications during the processing of the first request (ASURT 100335)
// skip this if LastShutdownAttemptTime has been set
if (_theRuntime.LastShutdownAttemptTime == DateTime.MinValue && !_theRuntime._firstRequestCompleted && !_theRuntime._userForcedShutdown) {
// check the timeout (don't disable notifications forever
int delayTimeoutSec = HttpRuntimeSection.DefaultDelayNotificationTimeout;
try {
RuntimeConfig runtimeConfig = RuntimeConfig.GetAppLKGConfig();
if (runtimeConfig != null) {
HttpRuntimeSection runtimeSection = runtimeConfig.HttpRuntime;
if (runtimeSection != null) {
delayTimeoutSec = (int)runtimeSection.DelayNotificationTimeout.TotalSeconds;
if (DateTime.UtcNow < _theRuntime._firstRequestStartTime.AddSeconds(delayTimeoutSec)) {
Debug.Trace("AppDomainFactory", "ShutdownAppDomain IGNORED (1st request is not done yet), Id = " + AppDomainAppId);
return false;
}
}
}
}
catch {
}
}
try {
_theRuntime.RaiseShutdownWebEventOnce();
}
catch {
// VSWhidbey 444472: if an exception is thrown, we consume it and continue executing the following code.
}
// Update last time ShutdownAppDomain was called
_theRuntime.LastShutdownAttemptTime = DateTime.UtcNow;
if (!HostingEnvironment.ShutdownInitiated) {
// This shutdown is not triggered by hosting environment - let it do the job
HostingEnvironment.InitiateShutdownWithoutDemand();
return true;
}
//WOS 1400290: CantUnloadAppDomainException in ISAPI mode, wait until HostingEnvironment.ShutdownThisAppDomainOnce completes
if (HostingEnvironment.ShutdownInProgress) {
return false;
}
// Make sure we don't go through shutdown logic many times
if (!_theRuntime.InitiateShutdownOnce())
return false;
Debug.Trace("AppDomainFactory", "ShutdownAppDomain, Id = " + AppDomainAppId + ", ShutdownInProgress=" + ShutdownInProgress
+ ", ShutdownMessage=" + _theRuntime._shutDownMessage);
if (String.IsNullOrEmpty(stackTrace) && !BuildManagerHost.InClientBuildManager) {
// Avoid calling Environment.StackTrace if we are in the ClientBuildManager (Dev10 bug 824659)
// Instrument to be able to see what's causing a shutdown
new EnvironmentPermission(PermissionState.Unrestricted).Assert();
try {
_theRuntime._shutDownStack = Environment.StackTrace;
}
finally {
CodeAccessPermission.RevertAssert();
}
}
else {
_theRuntime._shutDownStack = stackTrace;
}
// Notify when appdomain is about to shutdown.
OnAppDomainShutdown(new BuildManagerHostUnloadEventArgs(_theRuntime._shutdownReason));
// unload app domain from another CLR thread
ThreadPool.QueueUserWorkItem(_theRuntime._appDomainUnloadallback);
return true;
}
internal static void RecoverFromUnexceptedAppDomainUnload() {
if (_theRuntime._shutdownInProgress)
return;
// someone unloaded app domain directly - tell unmanaged code
Debug.Trace("AppDomainFactory", "Unexpected AppDomainUnload");
_theRuntime._shutdownInProgress = true;
// tell unmanaged code not to dispatch requests to this app domain
try {
ISAPIRuntime.RemoveThisAppDomainFromUnmanagedTable();
PipelineRuntime.RemoveThisAppDomainFromUnmanagedTable();
AddAppDomainTraceMessage("AppDomainRestart");
}
finally {
// release all resources
_theRuntime.Dispose();
}
}
/*
* Notification when app-level Config changed
*/
internal static void OnConfigChange(String message) {
Debug.Trace("AppDomainFactory", "Shutting down appdomain because of config change");
ShutdownAppDomain(ApplicationShutdownReason.ConfigurationChange, (message != null) ? message : "CONFIG change");
}
// Intrumentation to remember the overwhelming file change
internal static void SetShutdownReason(ApplicationShutdownReason reason, String message) {
if (_theRuntime._shutdownReason == ApplicationShutdownReason.None) {
_theRuntime._shutdownReason = reason;
}
SetShutdownMessage(message);
}
internal static void SetShutdownMessage(String message) {
if (message != null) {
if (_theRuntime._shutDownMessage == null)
_theRuntime._shutDownMessage = message;
else
_theRuntime._shutDownMessage += "\r\n" + message;
}
}
// public method is on HostingEnvironment
internal static ApplicationShutdownReason ShutdownReason {
get { return _theRuntime._shutdownReason; }
}
//
// public static APIs
//
/*
* Process one request
*/
/// <devdoc>
/// <para><SPAN>The method that drives
/// all ASP.NET web processing execution.</SPAN></para>
/// </devdoc>
[AspNetHostingPermission(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Medium)]
public static void ProcessRequest(HttpWorkerRequest wr) {
if (wr == null)
throw new ArgumentNullException("wr");
if (HttpRuntime.UseIntegratedPipeline) {
throw new PlatformNotSupportedException(SR.GetString(SR.Method_Not_Supported_By_Iis_Integrated_Mode, "HttpRuntime.ProcessRequest"));
}
ProcessRequestNoDemand(wr);
}
internal static void ProcessRequestNoDemand(HttpWorkerRequest wr) {
RequestQueue rq = _theRuntime._requestQueue;
wr.UpdateInitialCounters();
if (rq != null) // could be null before first request
wr = rq.GetRequestToExecute(wr);
if (wr != null) {
CalculateWaitTimeAndUpdatePerfCounter(wr);
wr.ResetStartTime();
ProcessRequestNow(wr);
}
}
private static void CalculateWaitTimeAndUpdatePerfCounter(HttpWorkerRequest wr) {
DateTime begin = wr.GetStartTime();
TimeSpan elapsed = DateTime.UtcNow.Subtract(begin);
long milli = elapsed.Ticks / TimeSpan.TicksPerMillisecond;
if (milli > Int32.MaxValue)
milli = Int32.MaxValue;
PerfCounters.SetGlobalCounter(GlobalPerfCounter.REQUEST_WAIT_TIME, (int)milli);
PerfCounters.SetCounter(AppPerfCounter.APP_REQUEST_WAIT_TIME, (int)milli);
}
internal static void ProcessRequestNow(HttpWorkerRequest wr) {
_theRuntime.ProcessRequestInternal(wr);
}
internal static void RejectRequestNow(HttpWorkerRequest wr, bool silent) {
_theRuntime.RejectRequestInternal(wr, silent);
}
/// <devdoc>
/// <para>Removes all items from the cache and shuts down the runtime.</para>
/// </devdoc>
[SecurityPermission(SecurityAction.Demand, Unrestricted = true)]
public static void Close() {
Debug.Trace("AppDomainFactory", "HttpRuntime.Close, ShutdownInProgress=" + ShutdownInProgress);
if (_theRuntime.InitiateShutdownOnce()) {
SetShutdownReason(ApplicationShutdownReason.HttpRuntimeClose, "HttpRuntime.Close is called");
if (HostingEnvironment.IsHosted) {
// go throw initiate shutdown for hosted scenarios
HostingEnvironment.InitiateShutdownWithoutDemand();
}
else {
_theRuntime.Dispose();
}
}
}
/// <devdoc>
/// <para>Unloads the current app domain.</para>
/// </devdoc>
public static void UnloadAppDomain() {
_theRuntime._userForcedShutdown = true;
ShutdownAppDomain(ApplicationShutdownReason.UnloadAppDomainCalled, "User code called UnloadAppDomain");
}
private DateTime LastShutdownAttemptTime {
get {
DateTime dt;
lock (this) {
dt = _lastShutdownAttemptTime;
}
return dt;
}
set {
lock (this) {
_lastShutdownAttemptTime = value;
}
}
}
internal static Profiler Profile {
get {
return _theRuntime._profiler;
}
}
internal static bool IsTrustLevelInitialized {
get {
return !HostingEnvironment.IsHosted || TrustLevel != null;
}
}
internal static NamedPermissionSet NamedPermissionSet {
get {
// Make sure we have already initialized the trust level
//
return _theRuntime._namedPermissionSet;
}
}
internal static PolicyLevel PolicyLevel {
get {
return _theRuntime._policyLevel;
}
}
internal static string HostSecurityPolicyResolverType {
get {
return _theRuntime._hostSecurityPolicyResolverType;
}
}
[AspNetHostingPermission(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Unrestricted)]
public static NamedPermissionSet GetNamedPermissionSet() {
NamedPermissionSet namedPermissionSet = _theRuntime._namedPermissionSet;
if (namedPermissionSet == null) {
return null;
}
else {
return new NamedPermissionSet(namedPermissionSet);
}
}
internal static bool IsFullTrust {
get {
// Make sure we have already initialized the trust level
Debug.Assert(IsTrustLevelInitialized);
return (_theRuntime._namedPermissionSet == null);
}
}
/*
* Check that the current trust level allows access to a virtual path. Throw if it doesn't,
*/
internal static void CheckVirtualFilePermission(string virtualPath) {
string physicalPath = HostingEnvironment.MapPath(virtualPath);
CheckFilePermission(physicalPath);
}
/*
* Check that the current trust level allows access to a path. Throw if it doesn't,
*/
internal static void CheckFilePermission(string path) {
CheckFilePermission(path, false);
}
internal static void CheckFilePermission(string path, bool writePermissions) {
if (!HasFilePermission(path, writePermissions)) {
throw new HttpException(SR.GetString(SR.Access_denied_to_path, GetSafePath(path)));
}
}
internal static bool HasFilePermission(string path) {
return HasFilePermission(path, false);
}
internal static bool HasFilePermission(string path, bool writePermissions) {
// WOS #1523618: need to skip this check for HttpResponse.ReportRuntimeError when reporting an
// InitializationException (e.g., necessary to display line info for ConfigurationException).
if (TrustLevel == null && InitializationException != null) {
return true;
}
// Make sure we have already initialized the trust level
Debug.Assert(TrustLevel != null || !HostingEnvironment.IsHosted, "TrustLevel != null || !HostingEnvironment.IsHosted");
// If we don't have a NamedPermissionSet, we're in full trust
if (NamedPermissionSet == null)
return true;
bool fAccess = false;
// Check that the user has permission to the path
IPermission allowedPermission = NamedPermissionSet.GetPermission(typeof(FileIOPermission));
if (allowedPermission != null) {
IPermission askedPermission = null;
try {
if (!writePermissions)
askedPermission = new FileIOPermission(FileIOPermissionAccess.Read, path);
else
askedPermission = new FileIOPermission(FileIOPermissionAccess.AllAccess, path);
}
catch {
// This could happen if the path is not absolute
return false;
}
fAccess = askedPermission.IsSubsetOf(allowedPermission);
}
return fAccess;
}
internal static bool HasWebPermission(Uri uri) {
// Make sure we have already initialized the trust level
Debug.Assert(TrustLevel != null || !HostingEnvironment.IsHosted);
// If we don't have a NamedPermissionSet, we're in full trust
if (NamedPermissionSet == null)
return true;
bool fAccess = false;
// Check that the user has permission to the URI
IPermission allowedPermission = NamedPermissionSet.GetPermission(typeof(WebPermission));
if (allowedPermission != null) {
IPermission askedPermission = null;
try {
askedPermission = new WebPermission(NetworkAccess.Connect, uri.ToString());
}
catch {
return false;
}
fAccess = askedPermission.IsSubsetOf(allowedPermission);
}
return fAccess;
}
internal static bool HasDbPermission(DbProviderFactory factory) {
// Make sure we have already initialized the trust level
Debug.Assert(TrustLevel != null || !HostingEnvironment.IsHosted);
// If we don't have a NamedPermissionSet, we're in full trust
if (NamedPermissionSet == null)
return true;
bool fAccess = false;
// Check that the user has permission to the provider
CodeAccessPermission askedPermission = factory.CreatePermission(PermissionState.Unrestricted);
if (askedPermission != null) {
IPermission allowedPermission = NamedPermissionSet.GetPermission(askedPermission.GetType());
if (allowedPermission != null) {
fAccess = askedPermission.IsSubsetOf(allowedPermission);
}
}
return fAccess;
}
internal static bool HasPathDiscoveryPermission(string path) {
// WOS #1523618: need to skip this check for HttpResponse.ReportRuntimeError when reporting an
// InitializationException (e.g., necessary to display line info for ConfigurationException).
if (TrustLevel == null && InitializationException != null) {
return true;
}
// Make sure we have already initialized the trust level
Debug.Assert(TrustLevel != null || !HostingEnvironment.IsHosted);
// If we don't have a NamedPermissionSet, we're in full trust
if (NamedPermissionSet == null)
return true;
bool fAccess = false;
// Check that the user has permission to the path
IPermission allowedPermission = NamedPermissionSet.GetPermission(typeof(FileIOPermission));
if (allowedPermission != null) {
IPermission askedPermission = new FileIOPermission(FileIOPermissionAccess.PathDiscovery, path);
fAccess = askedPermission.IsSubsetOf(allowedPermission);
}
return fAccess;
}
internal static bool HasAppPathDiscoveryPermission() {
return HasPathDiscoveryPermission(HttpRuntime.AppDomainAppPathInternal);
}
internal static string GetSafePath(string path) {
if (String.IsNullOrEmpty(path))
return path;
try {
if (HasPathDiscoveryPermission(path)) // could throw on bad filenames
return path;
}
catch {
}
return Path.GetFileName(path);
}
/*
* Check that the current trust level allows Unmanaged access
*/
internal static bool HasUnmanagedPermission() {
// Make sure we have already initialized the trust level
Debug.Assert(TrustLevel != null || !HostingEnvironment.IsHosted);
// If we don't have a NamedPermissionSet, we're in full trust
if (NamedPermissionSet == null)
return true;
SecurityPermission securityPermission = (SecurityPermission)NamedPermissionSet.GetPermission(
typeof(SecurityPermission));
if (securityPermission == null)
return false;
return (securityPermission.Flags & SecurityPermissionFlag.UnmanagedCode) != 0;
}
internal static bool HasAspNetHostingPermission(AspNetHostingPermissionLevel level) {
// Make sure we have already initialized the trust level
//
// If we don't have a NamedPermissionSet, we're in full trust
if (NamedPermissionSet == null)
return true;
AspNetHostingPermission permission = (AspNetHostingPermission)NamedPermissionSet.GetPermission(
typeof(AspNetHostingPermission));
if (permission == null)
return false;
return (permission.Level >= level);
}
internal static void CheckAspNetHostingPermission(AspNetHostingPermissionLevel level, String errorMessageId) {
if (!HasAspNetHostingPermission(level)) {
throw new HttpException(SR.GetString(errorMessageId));
}
}
// If we're not in full trust, fail if the passed in type doesn't have the APTCA bit
internal static void FailIfNoAPTCABit(Type t, ElementInformation elemInfo, string propertyName) {
if (!IsTypeAllowedInConfig(t)) {
if (null != elemInfo) {
PropertyInformation propInfo = elemInfo.Properties[propertyName];
throw new ConfigurationErrorsException(SR.GetString(SR.Type_from_untrusted_assembly, t.FullName),
propInfo.Source, propInfo.LineNumber);
}
else {
throw new ConfigurationErrorsException(SR.GetString(SR.Type_from_untrusted_assembly, t.FullName));
}
}
}
// If we're not in full trust, fail if the passed in type doesn't have the APTCA bit
internal static void FailIfNoAPTCABit(Type t, XmlNode node) {
if (!IsTypeAllowedInConfig(t)) {
throw new ConfigurationErrorsException(SR.GetString(SR.Type_from_untrusted_assembly, t.FullName),
node);
}
}
private static bool HasAPTCABit(Assembly assembly) {
return assembly.IsDefined(typeof(AllowPartiallyTrustedCallersAttribute), inherit: false);
}
// Check if the type is allowed to be used in config by checking the APTCA bit
internal static bool IsTypeAllowedInConfig(Type t) {
// Allow everything in full trust
if (HttpRuntime.HasAspNetHostingPermission(AspNetHostingPermissionLevel.Unrestricted))
return true;
return IsTypeAccessibleFromPartialTrust(t);
}
internal static bool IsTypeAccessibleFromPartialTrust(Type t) {
Assembly assembly = t.Assembly;
if (assembly.SecurityRuleSet == SecurityRuleSet.Level1) {
// Level 1 CAS uses transparency as an auditing mechanism rather than an enforcement mechanism, so we can't
// perform a transparency check. Instead, allow the call to go through if:
// (a) the referenced assembly is partially trusted, hence it cannot do anything dangerous; or
// (b) the assembly is fully trusted and has APTCA.
return (!assembly.IsFullyTrusted || HasAPTCABit(assembly));
}
else {
// ** TEMPORARY **
// Some GACed assemblies register critical modules / handlers. We can't break these scenarios for .NET 4.5, but we should
// remove this APTCA check when we fix DevDiv #85358 and use only the transparency check defined below.
if (HasAPTCABit(assembly)) {
return true;
}
// ** END TEMPORARY **
// Level 2 CAS uses transparency as an enforcement mechanism, so we can perform a transparency check.
// Transparent and SafeCritical types are safe to use from partial trust code.
return (t.IsSecurityTransparent || t.IsSecuritySafeCritical);
}
}
internal static FileChangesMonitor FileChangesMonitor {
get { return _theRuntime._fcm; }
}
internal static RequestTimeoutManager RequestTimeoutManager {
get { return _theRuntime._timeoutManager; }
}
/// <devdoc>
/// <para>Provides access to the cache.</para>
/// </devdoc>
public static Cache Cache {
get {
if (HttpRuntime.AspInstallDirectoryInternal == null) {
throw new HttpException(SR.GetString(SR.Aspnet_not_installed, VersionInfo.SystemWebVersion));
}
Cache cachePublic = _theRuntime._cachePublic;
if (cachePublic == null) {
lock (_theRuntime) {
cachePublic = _theRuntime._cachePublic;
if (cachePublic == null) {
// Create the CACHE object
cachePublic = new Caching.Cache(0);
_theRuntime._cachePublic = cachePublic;
}
}
}
return cachePublic;
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static string AspInstallDirectory {
get {
String path = AspInstallDirectoryInternal;
if (path == null) {
throw new HttpException(SR.GetString(SR.Aspnet_not_installed, VersionInfo.SystemWebVersion));
}
InternalSecurityPermissions.PathDiscovery(path).Demand();
return path;
}
}
internal static string AspInstallDirectoryInternal {
get { return s_installDirectory; }
}
//
// Return the client script virtual path, e.g. "/aspnet_client/system_web/2_0_50217"
//
public static string AspClientScriptVirtualPath {
get {
if (_theRuntime._clientScriptVirtualPath == null) {
string aspNetVersion = VersionInfo.SystemWebVersion;
string clientScriptVirtualPath = AspNetClientFilesParentVirtualPath + aspNetVersion.Substring(0, aspNetVersion.LastIndexOf('.')).Replace('.', '_');
_theRuntime._clientScriptVirtualPath = clientScriptVirtualPath;
}
return _theRuntime._clientScriptVirtualPath;
}
}
public static string AspClientScriptPhysicalPath {
get {
String path = AspClientScriptPhysicalPathInternal;
if (path == null) {
throw new HttpException(SR.GetString(SR.Aspnet_not_installed, VersionInfo.SystemWebVersion));
}
return path;
}
}
//
// Return the client script physical path, e.g. @"c:\windows\microsoft.net\framework\v2.0.50217.0\asp.netclientfiles"
//
internal static string AspClientScriptPhysicalPathInternal {
get {
if (_theRuntime._clientScriptPhysicalPath == null) {
string clientScriptPhysicalPath = System.IO.Path.Combine(AspInstallDirectoryInternal, AspNetClientFilesSubDirectory);
_theRuntime._clientScriptPhysicalPath = clientScriptPhysicalPath;
}
return _theRuntime._clientScriptPhysicalPath;
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static string ClrInstallDirectory {
get {
String path = ClrInstallDirectoryInternal;
InternalSecurityPermissions.PathDiscovery(path).Demand();
return path;
}
}
internal static string ClrInstallDirectoryInternal {
get { return HttpConfigurationSystem.MsCorLibDirectory; }
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static string MachineConfigurationDirectory {
get {
String path = MachineConfigurationDirectoryInternal;
InternalSecurityPermissions.PathDiscovery(path).Demand();
return path;
}
}
internal static string MachineConfigurationDirectoryInternal {
get { return HttpConfigurationSystem.MachineConfigurationDirectory; }
}
internal static bool IsEngineLoaded {
get { return s_isEngineLoaded; }
}
//
// Static app domain related properties
//
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static String CodegenDir {
get {
String path = CodegenDirInternal;
InternalSecurityPermissions.PathDiscovery(path).Demand();
return path;
}
}
internal static string CodegenDirInternal {
get { return _theRuntime._codegenDir; }
}
internal static string TempDirInternal {
get { return _theRuntime._tempDir; }
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static String AppDomainAppId {
get {
return _theRuntime._appDomainAppId;
}
}
internal static bool IsAspNetAppDomain {
get { return AppDomainAppId != null; }
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static String AppDomainAppPath {
get {
InternalSecurityPermissions.AppPathDiscovery.Demand();
return AppDomainAppPathInternal;
}
}
internal static string AppDomainAppPathInternal {
get { return _theRuntime._appDomainAppPath; }
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static String AppDomainAppVirtualPath {
get {
return VirtualPath.GetVirtualPathStringNoTrailingSlash(_theRuntime._appDomainAppVPath);
}
}
// Save as AppDomainAppVirtualPath, but includes the trailng slash. We can't change
// AppDomainAppVirtualPath since it's public.
internal static String AppDomainAppVirtualPathString {
get {
return VirtualPath.GetVirtualPathString(_theRuntime._appDomainAppVPath);
}
}
internal static VirtualPath AppDomainAppVirtualPathObject {
get {
return _theRuntime._appDomainAppVPath;
}
}
internal static bool IsPathWithinAppRoot(String path) {
if (AppDomainIdInternal == null)
return true; // app domain not initialized
return UrlPath.IsEqualOrSubpath(AppDomainAppVirtualPathString, path);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static String AppDomainId {
[AspNetHostingPermission(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.High)]
get {
return AppDomainIdInternal;
}
}
internal static string AppDomainIdInternal {
get { return _theRuntime._appDomainId; }
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static String BinDirectory {
get {
String path = BinDirectoryInternal;
InternalSecurityPermissions.PathDiscovery(path).Demand();
return path;
}
}
internal static string BinDirectoryInternal {
get { return Path.Combine(_theRuntime._appDomainAppPath, BinDirectoryName) + Path.DirectorySeparatorChar; }
}
internal static VirtualPath CodeDirectoryVirtualPath {
get { return _theRuntime._appDomainAppVPath.SimpleCombineWithDir(CodeDirectoryName); }
}
internal static VirtualPath ResourcesDirectoryVirtualPath {
get { return _theRuntime._appDomainAppVPath.SimpleCombineWithDir(ResourcesDirectoryName); }
}
internal static VirtualPath WebRefDirectoryVirtualPath {
get { return _theRuntime._appDomainAppVPath.SimpleCombineWithDir(WebRefDirectoryName); }
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static bool IsOnUNCShare {
[AspNetHostingPermission(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Low)]
get {
return IsOnUNCShareInternal;
}
}
internal static bool IsOnUNCShareInternal {
get { return _theRuntime._isOnUNCShare; }
}
//
// Static helper to retrieve app domain values
//
private static String GetAppDomainString(String key) {
Object x = Thread.GetDomain().GetData(key);
return x as String;
}
internal static void AddAppDomainTraceMessage(String message) {
const String appDomainTraceKey = "ASP.NET Domain Trace";
AppDomain d = Thread.GetDomain();
String m = d.GetData(appDomainTraceKey) as String;
d.SetData(appDomainTraceKey, (m != null) ? m + " ... " + message : message);
}
// Gets the version of the ASP.NET framework the current web applications is targeting.
// This property is normally set via the <httpRuntime> element's "targetFramework"
// attribute. The property is not guaranteed to return a correct value if the current
// AppDomain is not an ASP.NET web application AppDomain.
public static Version TargetFramework {
get {
return BinaryCompatibility.Current.TargetFramework;
}
}
//
// Flags
//
internal static bool DebuggingEnabled {
get { return _theRuntime._debuggingEnabled; }
}
internal static bool ConfigInited {
get { return _theRuntime._configInited; }
}
internal static bool FusionInited {
get { return _theRuntime._fusionInited; }
}
internal static bool ApartmentThreading {
get { return _theRuntime._apartmentThreading; }
}
internal static bool ShutdownInProgress {
get { return _theRuntime._shutdownInProgress; }
}
internal static string TrustLevel {
get { return _theRuntime._trustLevel; }
}
internal static string WpUserId {
get { return _theRuntime._wpUserId; }
}
private void SetTrustLevel(TrustSection trustSection, SecurityPolicySection securityPolicySection) {
// Use a temporary variable, since we use the field as a signal that the trust has really
// been set, which is not the case until later in this method.
string trustLevel = trustSection.Level;
if (trustSection.Level == "Full") {
_trustLevel = trustLevel;
return;
}
if (securityPolicySection == null || securityPolicySection.TrustLevels[trustSection.Level] == null) {
throw new ConfigurationErrorsException(SR.GetString(SR.Unable_to_get_policy_file, trustSection.Level), String.Empty, 0);
// Do not give out configuration information since we don't know what trust level we are
// supposed to be running at. If the information below is added to the error it might expose
// part of the config file that the users does not have permissions to see. VS261145
// ,trustSection.ElementInformation.Properties["level"].Source,
// trustSection.ElementInformation.Properties["level"].LineNumber);
}
String file = null;
if (trustSection.Level == "Minimal" || trustSection.Level == "Low" ||
trustSection.Level == "Medium" || trustSection.Level == "High") {
file = (String)securityPolicySection.TrustLevels[trustSection.Level].LegacyPolicyFileExpanded;
}
else {
file = (String)securityPolicySection.TrustLevels[trustSection.Level].PolicyFileExpanded;
}
if (file == null || !FileUtil.FileExists(file)) {
//if HttpContext.Current.IsCustomErrorEnabled
throw new HttpException(SR.GetString(SR.Unable_to_get_policy_file, trustSection.Level));
//else
// throw new ConfigurationErrorsException(SR.GetString(SR.Unable_to_get_policy_file, trustSection.Level),
// trustSection.Filename, trustSection.LineNumber);
}
bool foundGacToken = false;
#pragma warning disable 618
PolicyLevel policyLevel = CreatePolicyLevel(file, AppDomainAppPathInternal, CodegenDirInternal, trustSection.OriginUrl, out foundGacToken);
// see if the policy file contained a v1.x UrlMembershipCondition containing
// a GAC token. If so, let's upgrade it by adding a code group granting
// full trust to code from the GAC
if (foundGacToken) {
// walk the code groups at the app domain level and look for one that grants
// access to the GAC with an UrlMembershipCondition.
CodeGroup rootGroup = policyLevel.RootCodeGroup;
bool foundGacCondition = false;
foreach (CodeGroup childGroup in rootGroup.Children) {
if (childGroup.MembershipCondition is GacMembershipCondition) {
foundGacCondition = true;
// if we found the GAC token and also have the GacMembershipCondition
// the policy file needs to be upgraded to just include the GacMembershipCondition
Debug.Assert(!foundGacCondition);
break;
}
}
// add one as a child of the toplevel group after
// some sanity checking to make sure it's an ASP.NET policy file
// which always begins with a FirstMatchCodeGroup granting nothing
// this might not upgrade some custom policy files
if (!foundGacCondition) {
if (rootGroup is FirstMatchCodeGroup) {
FirstMatchCodeGroup firstMatch = (FirstMatchCodeGroup)rootGroup;
if (firstMatch.MembershipCondition is AllMembershipCondition &&
firstMatch.PermissionSetName == "Nothing") {
PermissionSet fullTrust = new PermissionSet(PermissionState.Unrestricted);
CodeGroup gacGroup = new UnionCodeGroup(new GacMembershipCondition(),
new PolicyStatement(fullTrust));
// now, walk the current groups and insert our new group
// immediately before the old Gac group
// we'll need to use heuristics for this:
// it will be an UrlMembershipCondition group with full trust
CodeGroup newRoot = new FirstMatchCodeGroup(rootGroup.MembershipCondition, rootGroup.PolicyStatement);
foreach (CodeGroup childGroup in rootGroup.Children) {
// is this the target old $Gac$ group?
// insert our new GacMembershipCondition group ahead of it
if ((childGroup is UnionCodeGroup) &&
(childGroup.MembershipCondition is UrlMembershipCondition) &&
childGroup.PolicyStatement.PermissionSet.IsUnrestricted()) {
if (null != gacGroup) {
newRoot.AddChild(gacGroup);
gacGroup = null;
}
}
// append this group to the root group
// AddChild itself does a deep Copy to get any
// child groups so we don't need one here
newRoot.AddChild(childGroup);
}
policyLevel.RootCodeGroup = newRoot;
//Debug.Trace("internal", "PolicyLevel: " + policyLevel.ToXml());
}
}
}
#pragma warning restore 618
}
#pragma warning disable 618
AppDomain.CurrentDomain.SetAppDomainPolicy(policyLevel);
_namedPermissionSet = policyLevel.GetNamedPermissionSet(trustSection.PermissionSetName);
#pragma warning restore 618
_trustLevel = trustLevel;
_fcm.StartMonitoringFile(file, new FileChangeEventHandler(this.OnSecurityPolicyFileChange));
}
#pragma warning disable 618
private static PolicyLevel CreatePolicyLevel(String configFile, String appDir, String binDir, String strOriginUrl, out bool foundGacToken) {
// Read in the config file to a string.
FileStream file = new FileStream(configFile, FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(file, Encoding.UTF8);
String strFileData = reader.ReadToEnd();
reader.Close();
appDir = FileUtil.RemoveTrailingDirectoryBackSlash(appDir);
binDir = FileUtil.RemoveTrailingDirectoryBackSlash(binDir);
strFileData = strFileData.Replace("$AppDir$", appDir);
strFileData = strFileData.Replace("$AppDirUrl$", MakeFileUrl(appDir));
strFileData = strFileData.Replace("$CodeGen$", MakeFileUrl(binDir));
if (strOriginUrl == null)
strOriginUrl = String.Empty;
strFileData = strFileData.Replace("$OriginHost$", strOriginUrl);
// see if the file contains a GAC token
// if so, do the replacement and record the
// fact so that we later add a GacMembershipCondition
// codegroup to the PolicyLevel
int ndx = strFileData.IndexOf("$Gac$", StringComparison.Ordinal);
if (ndx != -1) {
string gacLocation = GetGacLocation();
if (gacLocation != null)
gacLocation = MakeFileUrl(gacLocation);
if (gacLocation == null)
gacLocation = String.Empty;
strFileData = strFileData.Replace("$Gac$", gacLocation);
foundGacToken = true;
}
else {
foundGacToken = false;
}
return SecurityManager.LoadPolicyLevelFromString(strFileData, PolicyLevelType.AppDomain);
}
#pragma warning restore 618
private void SetTrustParameters(TrustSection trustSection, SecurityPolicySection securityPolicySection, PolicyLevel policyLevel) {
_trustLevel = trustSection.Level;
if (_trustLevel != "Full") {
// if we are in partial trust, HostingEnvironment should init HttpRuntime with a non-null PolicyLevel object
Debug.Assert(policyLevel != null);
_namedPermissionSet = policyLevel.GetNamedPermissionSet(trustSection.PermissionSetName);
_policyLevel = policyLevel;
_hostSecurityPolicyResolverType = trustSection.HostSecurityPolicyResolverType;
String file = (String)securityPolicySection.TrustLevels[trustSection.Level].PolicyFileExpanded;
_fcm.StartMonitoringFile(file, new FileChangeEventHandler(this.OnSecurityPolicyFileChange));
}
}
/*
* Notification when something in the code-access security policy file changed
*/
private void OnSecurityPolicyFileChange(Object sender, FileChangeEvent e) {
// shutdown the app domain
Debug.Trace("AppDomainFactory", "Shutting down appdomain because code-access security policy file changed");
string message = FileChangesMonitor.GenerateErrorMessage(e.Action, e.FileName);
if (message == null) {
message = "Change in code-access security policy file";
}
ShutdownAppDomain(ApplicationShutdownReason.ChangeInSecurityPolicyFile,
message);
}
// notification when app_offline.htm file changed or created
private void OnAppOfflineFileChange(Object sender, FileChangeEvent e) {
// shutdown the app domain
Debug.Trace("AppOffline", AppOfflineFileName + " changed - shutting down the app domain");
Debug.Trace("AppDomainFactory", "Shutting down appdomain because " + AppOfflineFileName + " file changed");
// WOS 1948399: set _userForcedShutdown to avoid DelayNotificationTimeout, since first request has not completed yet in integrated mode;
SetUserForcedShutdown();
string message = FileChangesMonitor.GenerateErrorMessage(e.Action, AppOfflineFileName);
if (message == null) {
message = "Change in " + AppOfflineFileName;
}
ShutdownAppDomain(ApplicationShutdownReason.ConfigurationChange, message);
}
internal static String MakeFileUrl(String path) {
Uri uri = new Uri(path);
return uri.ToString();
}
internal static String GetGacLocation() {
StringBuilder buf = new StringBuilder(262);
int iSize = 260;
//
if (UnsafeNativeMethods.GetCachePath(2, buf, ref iSize) >= 0)
return buf.ToString();
throw new HttpException(SR.GetString(SR.GetGacLocaltion_failed));
}
/*
* Remove from metabase all read/write/browse permission from certain subdirs
*
*/
internal static void RestrictIISFolders(HttpContext context) {
int ret;
HttpWorkerRequest wr = context.WorkerRequest;
Debug.Assert(AppDomainAppId != null);
// Don't do it if we are not running on IIS
if (wr == null || !(wr is System.Web.Hosting.ISAPIWorkerRequest)) {
return;
}
// Do it only for IIS 5
#if !FEATURE_PAL // FEATURE_PAL does not enable IIS-based hosting features
if (!(wr is System.Web.Hosting.ISAPIWorkerRequestInProcForIIS6))
#endif // !FEATURE_PAL
{
byte[] bufin;
byte[] bufout = new byte[1]; // Just to keep EcbCallISAPI happy
bufin = BitConverter.GetBytes(UnsafeNativeMethods.RESTRICT_BIN);
ret = context.CallISAPI(UnsafeNativeMethods.CallISAPIFunc.RestrictIISFolders, bufin, bufout);
if (ret != 1) {
// Cannot pass back any HR from inetinfo.exe because CSyncPipeManager::GetDataFromIIS
// does not support passing back any value when there is an error.
Debug.Trace("RestrictIISFolders", "Cannot restrict folder access for '" + AppDomainAppId + "'.");
}
}
}
//
// Helper to create instances (public vs. internal/private ctors, see 89781)
//
internal static Object CreateNonPublicInstance(Type type) {
return CreateNonPublicInstance(type, null);
}
[PermissionSet(SecurityAction.Assert, Unrestricted = true)]
internal static Object CreateNonPublicInstance(Type type, Object[] args) {
return Activator.CreateInstance(
type,
BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.CreateInstance,
null,
args,
null);
}
internal static Object CreatePublicInstance(Type type) {
return Activator.CreateInstance(type);
}
#if !DONTUSEFACTORYGENERATOR
// Cache instances of IWebObjectFactory for each Type, which allow us
// to instantiate the objects very efficiently, compared to calling
// Activator.CreateInstance on every call.
private static FactoryGenerator s_factoryGenerator;
private static Hashtable s_factoryCache;
private static bool s_initializedFactory;
private static object s_factoryLock = new Object();
#endif // DONTUSEFACTORYGENERATOR
/*
* Faster implementation of CreatePublicInstance. It generates bits of IL
* on the fly to achieve the improve performance. this should only be used
* in cases where the number of different types to be created is well bounded.
* Otherwise, we would create too much IL, which can bloat the process.
*/
internal static Object FastCreatePublicInstance(Type type) {
#if DONTUSEFACTORYGENERATOR
return CreatePublicInstance(type);
#else
// Only use the factory logic if the assembly is in the GAC, to avoid getting
// assembly conflicts (VSWhidbey 405086)
if (!type.Assembly.GlobalAssemblyCache) {
return CreatePublicInstance(type);
}
// Create the factory generator on demand
if (!s_initializedFactory) {
// Devdiv 90810 - Synchronize to avoid race condition
lock (s_factoryLock) {
if (!s_initializedFactory) {
s_factoryGenerator = new FactoryGenerator();
// Create the factory cache
s_factoryCache = Hashtable.Synchronized(new Hashtable());
s_initializedFactory = true;
}
}
}
// First, check if it's cached
IWebObjectFactory factory = (IWebObjectFactory)s_factoryCache[type];
if (factory == null) {
Debug.Trace("FastCreatePublicInstance", "Creating generator for type " + type.FullName);
// Create the object factory
factory = s_factoryGenerator.CreateFactory(type);
// Cache the factory
s_factoryCache[type] = factory;
}
return factory.CreateInstance();
#endif // DONTUSEFACTORYGENERATOR
}
internal static Object CreatePublicInstance(Type type, Object[] args) {
if (args == null)
return Activator.CreateInstance(type);
return Activator.CreateInstance(type, args);
}
static string GetCurrentUserName() {
try {
return WindowsIdentity.GetCurrent().Name;
}
catch {
return null;
}
}
void RaiseShutdownWebEventOnce() {
if (!_shutdownWebEventRaised) {
lock (this) {
if (!_shutdownWebEventRaised) {
// Raise Web Event
WebBaseEvent.RaiseSystemEvent(this, WebEventCodes.ApplicationShutdown,
WebApplicationLifetimeEvent.DetailCodeFromShutdownReason(ShutdownReason));
_shutdownWebEventRaised = true;
}
}
}
}
private static string _DefaultPhysicalPathOnMapPathFailure;
private void RelaxMapPathIfRequired() {
try {
RuntimeConfig config = RuntimeConfig.GetAppConfig();
if (config != null && config.HttpRuntime != null && config.HttpRuntime.RelaxedUrlToFileSystemMapping) {
_DefaultPhysicalPathOnMapPathFailure = Path.Combine(_appDomainAppPath, "NOT_A_VALID_FILESYSTEM_PATH");
}
} catch {}
}
internal static bool IsMapPathRelaxed {
get {
return _DefaultPhysicalPathOnMapPathFailure != null;
}
}
internal static string GetRelaxedMapPathResult(string originalResult) {
if (!IsMapPathRelaxed) // Feature not enabled?
return originalResult;
if (originalResult == null) // null is never valid: Return the hard coded default physical path
return _DefaultPhysicalPathOnMapPathFailure;
// Does it contain an invalid file-path char?
if (originalResult.IndexOfAny(s_InvalidPhysicalPathChars) >= 0)
return _DefaultPhysicalPathOnMapPathFailure;
// Final check: do the full check to ensure it is valid
try {
bool pathTooLong;
if (FileUtil.IsSuspiciousPhysicalPath(originalResult, out pathTooLong) || pathTooLong)
return _DefaultPhysicalPathOnMapPathFailure;
} catch {
return _DefaultPhysicalPathOnMapPathFailure;
}
// it is valid
return originalResult;
}
}
public enum ApplicationShutdownReason {
None = 0,
HostingEnvironment = 1,
ChangeInGlobalAsax = 2,
ConfigurationChange = 3,
UnloadAppDomainCalled = 4,
ChangeInSecurityPolicyFile = 5,
BinDirChangeOrDirectoryRename = 6,
BrowsersDirChangeOrDirectoryRename = 7,
CodeDirChangeOrDirectoryRename = 8,
ResourcesDirChangeOrDirectoryRename = 9,
IdleTimeout = 10,
PhysicalApplicationPathChanged = 11,
HttpRuntimeClose = 12,
InitializationError = 13,
MaxRecompilationsReached = 14,
BuildManagerChange = 15,
};
}
|