1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522
|
//------------------------------------------------------------------------------
// <copyright file="BaseConfigurationRecord.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Configuration {
using System.Configuration.Internal;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Security;
using System.Text;
using System.Threading;
using System.Xml;
using System.Runtime.Versioning;
//
// This object represents the configuration for a request path, and is cached per-path.
//
[System.Diagnostics.DebuggerDisplay("ConfigPath = {ConfigPath}")]
abstract internal class BaseConfigurationRecord : IInternalConfigRecord {
protected const string NL = "\r\n";
internal const string KEYWORD_TRUE = "true";
internal const string KEYWORD_FALSE = "false";
protected const string KEYWORD_CONFIGURATION = "configuration";
protected const string KEYWORD_CONFIGURATION_NAMESPACE = "http://schemas.microsoft.com/.NetConfiguration/v2.0";
protected const string KEYWORD_CONFIGSECTIONS = "configSections";
protected const string KEYWORD_SECTION = "section";
protected const string KEYWORD_SECTION_NAME = "name";
protected const string KEYWORD_SECTION_TYPE = "type";
protected const string KEYWORD_SECTION_ALLOWLOCATION = "allowLocation";
protected const string KEYWORD_SECTION_ALLOWDEFINITION = "allowDefinition";
protected const string KEYWORD_SECTION_ALLOWDEFINITION_EVERYWHERE = "Everywhere";
protected const string KEYWORD_SECTION_ALLOWDEFINITION_MACHINEONLY = "MachineOnly";
protected const string KEYWORD_SECTION_ALLOWDEFINITION_MACHINETOAPPLICATION = "MachineToApplication";
protected const string KEYWORD_SECTION_ALLOWDEFINITION_MACHINETOWEBROOT = "MachineToWebRoot";
protected const string KEYWORD_SECTION_ALLOWEXEDEFINITION = "allowExeDefinition";
protected const string KEYWORD_SECTION_ALLOWEXEDEFINITION_MACHTOROAMING = "MachineToRoamingUser";
protected const string KEYWORD_SECTION_ALLOWEXEDEFINITION_MACHTOLOCAL = "MachineToLocalUser";
protected const string KEYWORD_SECTION_RESTARTONEXTERNALCHANGES = "restartOnExternalChanges";
protected const string KEYWORD_SECTION_REQUIREPERMISSION = "requirePermission";
protected const string KEYWORD_SECTIONGROUP = "sectionGroup";
protected const string KEYWORD_SECTIONGROUP_NAME = "name";
protected const string KEYWORD_SECTIONGROUP_TYPE = "type";
protected const string KEYWORD_REMOVE = "remove";
protected const string KEYWORD_CLEAR = "clear";
protected const string KEYWORD_LOCATION = "location";
protected const string KEYWORD_LOCATION_PATH = "path";
internal const string KEYWORD_LOCATION_ALLOWOVERRIDE = "allowOverride";
protected const string KEYWORD_LOCATION_INHERITINCHILDAPPLICATIONS = "inheritInChildApplications";
protected const string KEYWORD_CONFIGSOURCE = "configSource";
protected const string KEYWORD_XMLNS = "xmlns";
protected const string KEYWORD_CONFIG_BUILDER = "configBuilders";
internal const string KEYWORD_PROTECTION_PROVIDER = "configProtectionProvider";
protected const string FORMAT_NEWCONFIGFILE = "<?xml version=\"1.0\" encoding=\"{0}\"?>\r\n";
protected const string FORMAT_CONFIGURATION = "<configuration>\r\n";
protected const string FORMAT_CONFIGURATION_NAMESPACE = "<configuration xmlns=\"{0}\">\r\n";
protected const string FORMAT_CONFIGURATION_ENDELEMENT = "</configuration>";
internal const string KEYWORD_SECTION_OVERRIDEMODEDEFAULT = "overrideModeDefault";
internal const string KEYWORD_LOCATION_OVERRIDEMODE = "overrideMode";
internal const string KEYWORD_OVERRIDEMODE_INHERIT = "Inherit";
internal const string KEYWORD_OVERRIDEMODE_ALLOW = "Allow";
internal const string KEYWORD_OVERRIDEMODE_DENY = "Deny";
protected const string FORMAT_LOCATION_NOPATH = "<location {0} inheritInChildApplications=\"{1}\">\r\n";
protected const string FORMAT_LOCATION_PATH = "<location path=\"{2}\" {0} inheritInChildApplications=\"{1}\">\r\n";
protected const string FORMAT_LOCATION_ENDELEMENT = "</location>";
internal const string KEYWORD_LOCATION_OVERRIDEMODE_STRING = "{0}=\"{1}\"";
protected const string FORMAT_SECTION_CONFIGSOURCE = "<{0} configSource=\"{1}\" />";
protected const string FORMAT_CONFIGSOURCE_FILE = "<?xml version=\"1.0\" encoding=\"{0}\"?>\r\n";
protected const string FORMAT_SECTIONGROUP_ENDELEMENT = "</sectionGroup>";
// Class flags should only be used with the ClassFlags property.
protected const int ClassSupportsChangeNotifications = 0x00000001;
protected const int ClassSupportsRefresh = 0x00000002;
protected const int ClassSupportsImpersonation = 0x00000004;
protected const int ClassSupportsRestrictedPermissions = 0x00000008;
protected const int ClassSupportsKeepInputs = 0x00000010;
protected const int ClassSupportsDelayedInit = 0x00000020;
protected const int ClassIgnoreLocalErrors = 0x00000040;
// Flags to use with the _flags field.
protected const int ProtectedDataInitialized = 0x00000001;
protected const int Closed = 0x00000002;
protected const int PrefetchAll = 0x00000008;
protected const int IsAboveApplication = 0x00000020;
private const int ContextEvaluated = 0x00000080;
private const int IsLocationListResolved = 0x00000100;
protected const int NamespacePresentInFile = 0x00000200;
private const int RestrictedPermissionsResolved = 0x00000800;
protected const int IsTrusted = 0x00002000;
protected const int SupportsChangeNotifications = 0x00010000;
protected const int SupportsRefresh = 0x00020000;
protected const int SupportsPath = 0x00040000;
protected const int SupportsKeepInputs = 0x00080000;
protected const int SupportsLocation = 0x00100000;
// Flags for Mgmt Configuration Record
protected const int ForceLocationWritten = 0x01000000;
protected const int SuggestLocationRemoval = 0x02000000;
protected const int NamespacePresentCurrent = 0x04000000;
protected const int ConfigBuildersInitialized = 0x08000000;
internal const char ConfigPathSeparatorChar = '/';
internal const string ConfigPathSeparatorString = "/";
static internal readonly char[] ConfigPathSeparatorParams = new char[] {ConfigPathSeparatorChar};
private static volatile ConfigurationPermission s_unrestrictedConfigPermission; // cached ConfigurationPermission
protected SafeBitVector32 _flags; // state
protected BaseConfigurationRecord _parent; // parent record
protected Hashtable _children; // configName -> record
protected InternalConfigRoot _configRoot; // root of configuration
protected string _configName; // the last part of the config path
protected string _configPath; // the full config path
protected string _locationSubPath; // subPath for the config record when editing a location configuration
private ConfigRecordStreamInfo _configStreamInfo; // stream info for the config record
private object _configContext; // Context for config level
private ConfigurationBuildersSection _configBuilders; // section containing the general config builders
private ProtectedConfigurationSection _protectedConfig; // section containing the encryption providers
private PermissionSet _restrictedPermissions; // cached restricted permission set
private ConfigurationSchemaErrors _initErrors; // errors encountered during the parse of the configuration file
private BaseConfigurationRecord _initDelayedRoot; // root of delayed initialization
// Records information about <configSections> present in this web.config file.
// config key -> FactoryRecord
protected Hashtable _factoryRecords;
// Records information about sections that apply to this path,
// which may be found in this web.config file, in a parent through
// inheritance, or in a parent through <location>
// config key -> SectionRecord
protected Hashtable _sectionRecords;
// Records information about sections in a <location> directive
// that do not apply to this configPath (sections where path != ".")
protected ArrayList _locationSections;
// WOS 1955773: (Perf) 4,000 location sections in web.config file degrades working set
private static string s_appConfigPath;
// Comparer used in sorting IndirectInputs.
private static IComparer<SectionInput> s_indirectInputsComparer = new IndirectLocationInputComparer();
internal BaseConfigurationRecord() {
// not strictly necessary, but compiler spits out a warning without this initiailization
_flags = new SafeBitVector32();
}
// Class flags
protected abstract SimpleBitVector32 ClassFlags {get;}
// Create the factory that will evaluate configuration
protected abstract object CreateSectionFactory(FactoryRecord factoryRecord);
// Create the configuration object
protected abstract object CreateSection(bool inputIsTrusted, FactoryRecord factoryRecord, SectionRecord sectionRecord, SectionInput sectionInput, object parentConfig, ConfigXmlReader reader);
// Use the parent result in creating the child
protected abstract object UseParentResult(string configKey, object parentResult, SectionRecord sectionRecord);
// Return the runtime object from GetSection
protected abstract object GetRuntimeObject(object result);
//
// IInternalConfigRecord methods
//
public string ConfigPath {
get {return _configPath;}
}
public string StreamName {
get {return ConfigStreamInfo.StreamName;}
}
public bool HasInitErrors {
get {
return _initErrors.HasErrors(ClassFlags[ClassIgnoreLocalErrors]);
}
}
public void ThrowIfInitErrors() {
ThrowIfParseErrors(_initErrors);
}
public object GetSection(string configKey) {
#if DBG
// On debug builds, the config system depends on system.diagnostics,
// so we must always return a valid result and never throw.
if (configKey == "system.diagnostics" && !ClassFlags[ClassIgnoreLocalErrors]) {
return GetSection(configKey, true, true);
}
else {
return GetSection(configKey, false, true);
}
#else
return GetSection(configKey, false, true);
#endif
}
public object GetLkgSection(string configKey) {
return GetSection(configKey, true, true);
}
public void RefreshSection(string configKey) {
_configRoot.ClearResult(this, configKey, true);
}
public void Remove() {
_configRoot.RemoveConfigRecord(this);
}
//
// end of IInternalConfigRecord methods
//
internal bool HasStream {
get { return ConfigStreamInfo.HasStream; }
}
// Determine which sections should be prefetched during the first scan.
private bool ShouldPrefetchRawXml(FactoryRecord factoryRecord) {
if (_flags[PrefetchAll])
return true;
switch (factoryRecord.ConfigKey) {
case BaseConfigurationRecord.RESERVED_SECTION_PROTECTED_CONFIGURATION:
case "system.diagnostics":
case "appSettings":
case "connectionStrings":
return true;
}
return Host.PrefetchSection(factoryRecord.Group, factoryRecord.Name);
}
protected IDisposable Impersonate() {
IDisposable context = null;
if (ClassFlags[ClassSupportsImpersonation]) {
context = Host.Impersonate();
}
if (context == null) {
context = EmptyImpersonationContext.GetStaticInstance();
}
return context;
}
internal PermissionSet GetRestrictedPermissions()
{
if (!_flags[RestrictedPermissionsResolved])
{
lock (this)
{
if (!_flags[RestrictedPermissionsResolved])
{
if (AppDomain.CurrentDomain.IsHomogenous)
{
// in a homogenous domain, just call PermitOnly() on the AppDomain's existing permission set
_restrictedPermissions = AppDomain.CurrentDomain.PermissionSet;
_flags[RestrictedPermissionsResolved] = true;
}
else
{
// in a non-homogenous domain, use Evidence to calculate the current security policy
PermissionSet restrictedPermissions;
bool isHostReady;
GetRestrictedPermissionsWithAssert(out restrictedPermissions, out isHostReady);
if (isHostReady)
{
_restrictedPermissions = restrictedPermissions;
_flags[RestrictedPermissionsResolved] = true;
}
}
// calling PermitOnly() on an unrestricted PermissionSet is a no-op
if (_restrictedPermissions != null && _restrictedPermissions.IsUnrestricted())
{
_restrictedPermissions = null;
}
}
}
}
return _restrictedPermissions;
}
// Getting the PermissionSet object is a FullTrust operation; we can Assert since our callers are careful not to leak it
[PermissionSet(SecurityAction.Assert, Unrestricted = true)]
private void GetRestrictedPermissionsWithAssert(out PermissionSet permissionSet, out bool isHostReady) {
Host.GetRestrictedPermissions(this, out permissionSet, out isHostReady);
}
internal void Init(
IInternalConfigRoot configRoot,
BaseConfigurationRecord parent,
string configPath,
string locationSubPath) {
_initErrors = new ConfigurationSchemaErrors();
//
// try/catch here is only for unexpected exceptions due to errors in
// our own code, as we always want the configuration record to be
// usable
//
try {
_configRoot = (InternalConfigRoot) configRoot;
_parent = parent;
_configPath = configPath;
_locationSubPath = locationSubPath;
_configName = ConfigPathUtility.GetName(configPath);
if (IsLocationConfig) {
_configStreamInfo = _parent.ConfigStreamInfo;
}
else {
_configStreamInfo = new ConfigRecordStreamInfo();
}
// no more initialization in case of root config
if (IsRootConfig)
return;
// determine what features we support
_flags[SupportsChangeNotifications] = ClassFlags[ClassSupportsChangeNotifications] && Host.SupportsChangeNotifications;
_flags[SupportsRefresh] = ClassFlags[ClassSupportsRefresh] && Host.SupportsRefresh;
_flags[SupportsKeepInputs] = ClassFlags[ClassSupportsKeepInputs] || _flags[SupportsRefresh];
_flags[SupportsPath] = Host.SupportsPath;
_flags[SupportsLocation] = Host.SupportsLocation;
// get static state based on the configPath
if (_flags[SupportsLocation]) {
_flags[IsAboveApplication] = Host.IsAboveApplication(_configPath);
}
_flags[IsTrusted] = Host.IsTrustedConfigPath(_configPath);
ArrayList locationSubPathInputs = null;
if (_flags[SupportsLocation]) {
//
// Treat location inputs from parent record
// as though they were bonafide sections in this record.
//
if (IsLocationConfig && _parent._locationSections != null) {
// Resolve paths and check for errors in location sections.
_parent.ResolveLocationSections();
int i = 0;
while (i < _parent._locationSections.Count) {
LocationSectionRecord locationSectionRecord = (LocationSectionRecord) _parent._locationSections[i];
if (!StringUtil.EqualsIgnoreCase(locationSectionRecord.SectionXmlInfo.TargetConfigPath, this.ConfigPath)) {
i++;
}
else {
// remove the locationSectionRecord from the list
_parent._locationSections.RemoveAt(i);
if (locationSubPathInputs == null) {
locationSubPathInputs = new ArrayList();
}
locationSubPathInputs.Add(locationSectionRecord);
}
}
}
// Handle indirect inputs for location config record.
if (IsLocationConfig && Host.IsLocationApplicable(_configPath)) {
Dictionary<string, List<SectionInput>> indirectLocationInputs = null;
BaseConfigurationRecord current = _parent;
// Note that the code will also go thru all parents, just like what we did
// with the location inputs later. But perf-wise it's okay not to merge the two loops
// because a Configuration object will contain at most one location config record.
while (!current.IsRootConfig) {
if (current._locationSections != null) {
current.ResolveLocationSections();
foreach (LocationSectionRecord locationSectionRecord in current._locationSections) {
//
// VSWhidbey 540184
// If we're initializing a location config record, we will also use those location
// tags that apply to the directories between the parent and the location config
// record's ConfigPath.
//
// This way, the result will contain all the inputs (we've parsed so far) which
// affect the path specified by locationSubPath.
///
// To look for this kind of input, make sure that:
// 1. We are creating a location config
// 2. The location tag's target path lies between parent's config path and ConfigPath
// 2.1: ConfigPath must be a child of the location tag's target path
// 2.2: The target path must be a child of parent's config path
//
// One example of why we need 2.2:
// The root web.config has a location tag with path="1", and we open a configuration
// at "1" with locationSubPath="sub". If we don't have 2.2, then we will incorrectly set
// addInput to true for this location tag. It's incorrect because that location tag
// is already used by configRecord at level "1".
//
// 3. The location tag shouldn't be skipped due to inheritInChildApplications setting
//
if (
// Check #1
IsLocationConfig &&
// Check #2.1
UrlPath.IsSubpath(locationSectionRecord.SectionXmlInfo.TargetConfigPath, ConfigPath) &&
// Check #2.2
UrlPath.IsSubpath(parent.ConfigPath, locationSectionRecord.SectionXmlInfo.TargetConfigPath) &&
// Check #3
!ShouldSkipDueToInheritInChildApplications(locationSectionRecord.SectionXmlInfo.SkipInChildApps, locationSectionRecord.SectionXmlInfo.TargetConfigPath)
) {
//
// In order to separate these kinds of input from "file inputs" and "location inputs"
// we introduce a new kind of input called the "indirect location inputs".
//
// First add all indirect inputs per configKey to a local list.
// We will sort all lists after the while loop.
if (indirectLocationInputs == null) {
indirectLocationInputs = new Dictionary<string, List<SectionInput>>(1);
}
string configKey = locationSectionRecord.SectionXmlInfo.ConfigKey;
if (!((IDictionary)indirectLocationInputs).Contains(configKey)) {
indirectLocationInputs.Add(configKey, new List<SectionInput>(1));
}
indirectLocationInputs[configKey].Add(
new SectionInput(locationSectionRecord.SectionXmlInfo,
locationSectionRecord.ErrorsList));
// copy the initialization errors to the record
if (locationSectionRecord.HasErrors) {
this._initErrors.AddSavedLocalErrors(locationSectionRecord.Errors);
}
}
}
}
current = current._parent;
}
if (indirectLocationInputs != null) {
// Add indirect inputs per configKey
foreach(KeyValuePair<string, List<SectionInput>> keyValuePair in indirectLocationInputs) {
List<SectionInput> inputsPerConfigKey = keyValuePair.Value;
string configKey = keyValuePair.Key;
// We have to sort the indirect inputs
// 1. First by the location tag's target config path, and if they're the same,
// 2. Then by the location tag's definition config path.
inputsPerConfigKey.Sort(s_indirectInputsComparer);
// Add them to the section record.
// In the sorted list, the closest parent is at the beginning of the
// list, which is what we'll add first.
SectionRecord sectionRecord = EnsureSectionRecord(configKey, true);
Debug.Assert(inputsPerConfigKey.Count > 0, "We won't get here unless we have inputs.");
foreach(SectionInput sectionInput in inputsPerConfigKey) {
sectionRecord.AddIndirectLocationInput(sectionInput);
}
DebugValidateIndirectInputs(sectionRecord);
}
}
}
//
// Add location inputs that apply to this path, all the way up the parent hierarchy.
//
if (Host.IsLocationApplicable(_configPath)) {
BaseConfigurationRecord current = _parent;
while (!current.IsRootConfig) {
if (current._locationSections != null) {
current.ResolveLocationSections();
foreach (LocationSectionRecord locationSectionRecord in current._locationSections) {
// We use the location tag input if:
// - The path matches, and
// - It's not skipped due to inheritInChildApplications setting.
if (StringUtil.EqualsIgnoreCase(locationSectionRecord.SectionXmlInfo.TargetConfigPath, this._configPath) &&
!ShouldSkipDueToInheritInChildApplications(locationSectionRecord.SectionXmlInfo.SkipInChildApps)) {
// add the location input for this section
SectionRecord sectionRecord = EnsureSectionRecord(locationSectionRecord.ConfigKey, true);
SectionInput sectionInput = new SectionInput(
locationSectionRecord.SectionXmlInfo, locationSectionRecord.ErrorsList);
sectionRecord.AddLocationInput(sectionInput);
// copy the initialization errors to the record
if (locationSectionRecord.HasErrors) {
this._initErrors.AddSavedLocalErrors(locationSectionRecord.Errors);
}
}
}
}
current = current._parent;
}
}
}
if (!IsLocationConfig) {
//
// If config file exists, open it and parse it once so we can
// find what to evaluate later.
//
InitConfigFromFile();
}
else {
// Add location sections for this record as bonafide sections.
if (locationSubPathInputs != null) {
foreach (LocationSectionRecord locationSectionRecord in locationSubPathInputs) {
// add the file input
SectionRecord sectionRecord = EnsureSectionRecord(locationSectionRecord.ConfigKey, true);
SectionInput sectionInput = new SectionInput(locationSectionRecord.SectionXmlInfo, locationSectionRecord.ErrorsList);
sectionRecord.AddFileInput(sectionInput);
// copy the initialization errors to the record
if (locationSectionRecord.HasErrors) {
this._initErrors.AddSavedLocalErrors(locationSectionRecord.Errors);
}
}
}
}
}
//
// Capture all exceptions and include them in initialization errors.
//
catch (Exception e) {
string streamname = (ConfigStreamInfo != null) ? ConfigStreamInfo.StreamName : null;
_initErrors.AddError(
ExceptionUtil.WrapAsConfigException(SR.GetString(SR.Config_error_loading_XML_file), e, streamname, 0),
ExceptionAction.Global);
}
}
// InitConfigFromFile
//
// Init the Config From the File.
//
private void InitConfigFromFile() {
bool implicitSectionsAdded = false;
try {
// If initialization should be delayed, do not read the file.
if (ClassFlags[ClassSupportsDelayedInit] && Host.IsInitDelayed(this)) {
// determine the root of delayed initialization
if (_parent._initDelayedRoot == null) {
_initDelayedRoot = this;
}
else {
_initDelayedRoot = _parent._initDelayedRoot;
}
}
else {
//
// This parent of a record that is not initDelayed must also
// not be initDelayed.
//
Debug.Assert(!_parent.IsInitDelayed, "!_parent.IsInitDelayed");
using (Impersonate()) {
//
// Get the stream name. Note that this may be an expensive operation
// for the client configuration host, which is why it comes after the
// check for delayed init.
//
ConfigStreamInfo.StreamName = Host.GetStreamName(_configPath);
if (!String.IsNullOrEmpty(ConfigStreamInfo.StreamName)) {
// Lets listen to the stream
ConfigStreamInfo.StreamVersion = MonitorStream(null, null, ConfigStreamInfo.StreamName);
using (Stream stream = Host.OpenStreamForRead(ConfigStreamInfo.StreamName)) {
if (stream == null) {
// There is no stream to load from
return;
}
ConfigStreamInfo.HasStream = true;
// Determine whether or not to prefetch.
_flags[PrefetchAll] = Host.PrefetchAll(_configPath, ConfigStreamInfo.StreamName);
using (XmlUtil xmlUtil = new XmlUtil(stream, ConfigStreamInfo.StreamName, true, _initErrors)) {
ConfigStreamInfo.StreamEncoding = xmlUtil.Reader.Encoding;
// Read the factories
Hashtable factoryList = ScanFactories(xmlUtil);
_factoryRecords = factoryList;
// Add implicit sections before scanning sections
AddImplicitSections(null);
implicitSectionsAdded = true;
// Read the sections themselves
if (xmlUtil.Reader.Depth == 1) {
ScanSections(xmlUtil);
}
}
}
}
}
}
}
//
// Capture all exceptions and include them in _initErrors so execution in Init can continue.
//
catch (XmlException e) {
//
// Treat invalid XML as unrecoverable by replacing all errors with the XML error.
//
_initErrors.SetSingleGlobalError(
ExceptionUtil.WrapAsConfigException(SR.GetString(SR.Config_error_loading_XML_file), e, ConfigStreamInfo.StreamName, 0));
}
catch (Exception e) {
_initErrors.AddError(
ExceptionUtil.WrapAsConfigException(SR.GetString(SR.Config_error_loading_XML_file), e, ConfigStreamInfo.StreamName, 0),
ExceptionAction.Global);
}
//
// If there are global errors that make all input invalid,
// reset our state so that inherited configuration can still be used,
// including location sections that apply to this file.
//
if (_initErrors.HasGlobalErrors) {
//
// Parsing of a section may have been in progress when the exception
// was thrown, so clear any accumulated local errors.
//
_initErrors.ResetLocalErrors();
//
// Stop monitoring any configSource streams, but still continue
// to monitor the main config file if it was successfully monitored.
//
HybridDictionary streamInfos = null;
lock (this) {
if (ConfigStreamInfo.HasStreamInfos) {
streamInfos = ConfigStreamInfo.StreamInfos;
ConfigStreamInfo.ClearStreamInfos();
if (!String.IsNullOrEmpty(ConfigStreamInfo.StreamName)) {
StreamInfo fileStreamInfo = (StreamInfo) streamInfos[ConfigStreamInfo.StreamName];
// add this file's streaminfo to the now empty list
if (fileStreamInfo != null) {
streamInfos.Remove(ConfigStreamInfo.StreamName);
ConfigStreamInfo.StreamInfos.Add(ConfigStreamInfo.StreamName, fileStreamInfo);
}
}
}
}
// Stop monitoring streams outside the lock, to prevent deadlock.
if (streamInfos != null) {
foreach (StreamInfo streamInfo in streamInfos.Values) {
if (streamInfo.IsMonitored) {
Host.StopMonitoringStreamForChanges(streamInfo.StreamName, ConfigStreamInfo.CallbackDelegate);
}
}
}
// Remove file input
if (_sectionRecords != null) {
List<SectionRecord> removes = null;
foreach (SectionRecord sectionRecord in _sectionRecords.Values) {
Debug.Assert(!sectionRecord.HasIndirectLocationInputs,
"Don't expect to have any IndirectLocationInputs because location config record shouldn't call InitConfigFromFile");
if (sectionRecord.HasLocationInputs) {
// Remove any file input
sectionRecord.RemoveFileInput();
}
else {
// Remove the entire section record
if (removes == null) {
removes = new List<SectionRecord>();
}
removes.Add(sectionRecord);
}
}
if (removes != null) {
foreach (SectionRecord sectionRecord in removes) {
_sectionRecords.Remove(sectionRecord.ConfigKey);
}
}
}
// Remove all location section input defined here
if (_locationSections != null) {
_locationSections.Clear();
}
// Remove all factory records
if (_factoryRecords != null) {
_factoryRecords.Clear();
}
}
if (!implicitSectionsAdded) {
// Always add implicit sections no matter we have a file or not.
AddImplicitSections(null);
}
}
private bool IsInitDelayed {
get {
return _initDelayedRoot != null;
}
}
// RefreshFactoryRecord
//
// Refresh the Factory Record for a particular section.
//
private void RefreshFactoryRecord(string configKey) {
Hashtable factoryList = null;
FactoryRecord factoryRecord = null;
ConfigurationSchemaErrors errors;
errors = new ConfigurationSchemaErrors();
// Get Updated Factory List from File
int lineNumber = 0;
try {
using (Impersonate()) {
using (Stream stream = Host.OpenStreamForRead(ConfigStreamInfo.StreamName)) {
if (stream != null) {
ConfigStreamInfo.HasStream = true;
using (XmlUtil xmlUtil = new XmlUtil(stream, ConfigStreamInfo.StreamName, true, errors)) {
try {
factoryList = ScanFactories(xmlUtil);
ThrowIfParseErrors(xmlUtil.SchemaErrors);
}
catch {
lineNumber = xmlUtil.LineNumber;
throw;
}
}
}
}
}
// Add implicit sections to the factory list
if (factoryList == null) {
// But if factoryList isn't found in this config, we still try to
// add implicit sections to an empty factoryList.
factoryList = new Hashtable();
}
AddImplicitSections(factoryList);
if (factoryList != null) {
factoryRecord = (FactoryRecord) factoryList[configKey];
}
}
//
// Guarantee that exceptions contain the name of the stream and an approximate line number if available.
//
// And don't allow frames up the stack to run exception filters while impersonated.
catch (Exception e) {
errors.AddError(
ExceptionUtil.WrapAsConfigException(SR.GetString(SR.Config_error_loading_XML_file), e, ConfigStreamInfo.StreamName, lineNumber),
ExceptionAction.Global);
}
// Set/Add/Remove Record
// Note that the _factoryRecords hashtable is protected by the hierarchy lock.
if (factoryRecord != null || HasFactoryRecords) {
EnsureFactories()[configKey] = factoryRecord;
}
// Throw accumulated errors
ThrowIfParseErrors(errors);
}
internal IInternalConfigHost Host {
get {return _configRoot.Host;}
}
internal IInternalConfigurationBuilderHost ConfigBuilderHost {
get { return _configRoot.ConfigBuilderHost; }
}
internal BaseConfigurationRecord Parent {
get {return _parent;}
}
internal bool IsRootConfig {
get {return _parent == null;}
}
internal bool IsMachineConfig {
get {return _parent == _configRoot.RootConfigRecord;}
}
internal string LocationSubPath {
get {return _locationSubPath;}
}
internal bool IsLocationConfig {
get {return _locationSubPath != null;}
}
protected ConfigRecordStreamInfo ConfigStreamInfo {
get {
if (IsLocationConfig) {
return _parent._configStreamInfo;
}
else {
return _configStreamInfo;
}
}
}
private object GetSection(string configKey, bool getLkg, bool checkPermission) {
object result;
object resultRuntimeObject;
//
// Note that GetSectionRecursive may invalidate this record,
// so there should be no further references to 'this' after the call.
//
GetSectionRecursive(
configKey, getLkg, checkPermission, true /* getRuntimeObject */, true /* requestIsHere */,
out result, out resultRuntimeObject);
return resultRuntimeObject;
}
private void GetSectionRecursive(
string configKey, bool getLkg, bool checkPermission, bool getRuntimeObject, bool requestIsHere,
out object result, out object resultRuntimeObject) {
result = null;
resultRuntimeObject = null;
#if DBG
Debug.Assert(requestIsHere || !checkPermission, "requestIsHere || !checkPermission");
if (getLkg) {
Debug.Assert(getRuntimeObject == true, "getRuntimeObject == true");
Debug.Assert(requestIsHere == true, "requestIsHere == true");
}
#endif
//
// Store results in temporary variables, because we don't want to return
// results if an exception is thrown by CheckPermissionAllowed.
//
object tmpResult = null;
object tmpResultRuntimeObject = null;
bool requirePermission = true;
bool isResultTrustedWithoutAptca = true;
// Throw errors from initial parse, if any.
if (!getLkg) {
ThrowIfInitErrors();
}
//
// check for a cached result
//
bool hasResult = false;
SectionRecord sectionRecord = GetSectionRecord(configKey, getLkg);
if (sectionRecord != null && sectionRecord.HasResult) {
// Results should never be stored if the section has errors.
Debug.Assert(!sectionRecord.HasErrors, "!sectionRecord.HasErrors");
// Create the runtime object if requested and does not yet exist.
if (getRuntimeObject && !sectionRecord.HasResultRuntimeObject) {
try {
sectionRecord.ResultRuntimeObject = GetRuntimeObject(sectionRecord.Result);
}
catch {
//
// Ignore the error if we are attempting to retreive
// the last known good configuration.
//
if (!getLkg) {
throw;
}
}
}
// Get the cached result.
if (!getRuntimeObject || sectionRecord.HasResultRuntimeObject) {
requirePermission = sectionRecord.RequirePermission;
isResultTrustedWithoutAptca = sectionRecord.IsResultTrustedWithoutAptca;
tmpResult = sectionRecord.Result;
if (getRuntimeObject) {
tmpResultRuntimeObject = sectionRecord.ResultRuntimeObject;
}
hasResult = true;
}
}
//
// If there is no cached result, get the parent's section,
// then merge it with our own input if we have any.
//
if (!hasResult) {
FactoryRecord factoryRecord = null;
bool hasInput = (sectionRecord != null && sectionRecord.HasInput);
//
// We want to cache results in a section record if:
// - The request is made at this level, and so is likely to be
// made here again.
// OR
// - The section has input, in which case we want to
// avoid evaluating the same input multiple times.
//
bool cacheResults = (requestIsHere || hasInput);
bool isRootDeclaration;
try {
//
// We need to get a factory record to:
// - Check whether the caller has permission to access a section.
// - Determine if this is the root declaration of a config section,
// and thus the termination point for recursion.
// - Get a factory that can create a configuration section.
//
// Since most factories will be declared in machine.config and not in
// child config files, we do not optimize for checking whether a
// factory record is the root declaration, as the calculation at
// machine.config is trivial.
//
// It WILL be common in web scenarios for there to be
// deep hierarchies of config files, most of which have
// sparse input. Therefore we do not want to retreive a
// factory record if it is not necessary to do so, as
// it would always lead to an order N-squared operation,
// where N is the depth of the config hierarchy.
//
// We can skip the reteival of a factory record if:
// - This is the recursive call to GetSectionRecursive,
// AND
// - There is no section input at this level,
// AND
// - No factory is declared at this level.
//
// In this case, we'll simply continue the recursion to our parent.
//
if (requestIsHere) {
//
// Ensure that we have a valid factory record and a valid factory
// for creating sections when a request for a section is first
// made.
//
factoryRecord = FindAndEnsureFactoryRecord(configKey, out isRootDeclaration);
//
// If initialization is delayed, complete initialization if:
// - We can't find the requested factory, and it therefore
// may be in the file we haven't yet read,
// OR
// - The definition of that factory is allowed at
// levels of the config hierarchy that have not
// been initialized.
//
// This works for client config scenarios because the default
// for AllowExeDefinition is MachineToApplication. It would not
// be useful for Web scenarios, as most sections can be requested
// Everywhere.
//
// Note that configuration errors that may be present in the
// file where intialization is delayed will be ignored, and
// thus the order in which configuration sections are requested
// will affect results. This is considered OK as it is very
// expensive to determine configuration paths to
// client user configuration files, which aren't needed by
// most applications.
//
if ( IsInitDelayed
&& ( factoryRecord == null
|| _initDelayedRoot.IsDefinitionAllowed(factoryRecord.AllowDefinition, factoryRecord.AllowExeDefinition))) {
//
// We are going to remove this record, so get any data we need
// before the reference to 'this' becomes invalid.
//
string configPath = this._configPath;
InternalConfigRoot configRoot = this._configRoot;
// Tell the host to no longer permit delayed initialization.
Host.RequireCompleteInit(_initDelayedRoot);
// Removed config at the root of where initialization is delayed.
_initDelayedRoot.Remove();
// Get the config record for this config path
BaseConfigurationRecord newRecord = (BaseConfigurationRecord) configRoot.GetConfigRecord(configPath);
// Repeat the call to GetSectionRecursive
newRecord.GetSectionRecursive(
configKey, getLkg, checkPermission,
getRuntimeObject, requestIsHere,
out result, out resultRuntimeObject);
// Return and make no more references to this record.
return;
}
//
// For compatibility with previous versions,
// return null if the section is not found
// or is a group.
//
if (factoryRecord == null || factoryRecord.IsGroup) {
return;
}
//
// Use the factory record's copy of the configKey,
// so that we don't store more than one instance
// of the same configKey.
//
configKey = factoryRecord.ConfigKey;
}
else if (hasInput) {
//
// We'll need a factory to evaluate the input.
//
factoryRecord = FindAndEnsureFactoryRecord(configKey, out isRootDeclaration);
Debug.Assert(factoryRecord != null, "factoryRecord != null");
}
else {
//
// We don't need a factory record unless this is the root declaration.
// We know it is not the root declaration if there is no factory
// declared here. This is important to avoid a walk up the config
// hierachy when there is no input in this record.
//
factoryRecord = GetFactoryRecord(configKey, false);
if (factoryRecord == null) {
isRootDeclaration = false;
}
else {
factoryRecord = FindAndEnsureFactoryRecord(configKey, out isRootDeclaration);
Debug.Assert(factoryRecord != null, "factoryRecord != null");
}
}
// We need a factory record to check permission.
Debug.Assert(!checkPermission || factoryRecord != null, "!checkPermission || factoryRecord != null");
//
// If this is the root declaration, then we always want to cache
// the result, in order to prevent the section default from being
// created multiple times.
//
if (isRootDeclaration) {
cacheResults = true;
}
//
// We'll need a section record to cache results,
// and maybe to use in creating the section default.
//
if (sectionRecord == null && cacheResults) {
sectionRecord = EnsureSectionRecord(configKey, true);
}
//
// Retrieve the parent's runtime object if the runtimeObject
// is requested, and we are not going to merge that input
// with input in this section.
//
bool getParentRuntimeObject = (getRuntimeObject && !hasInput);
object parentResult = null;
object parentResultRuntimeObject = null;
if (isRootDeclaration) {
//
// Create the default section.
//
// Use the existing section record to create it if there is no input,
// so that the cached result is attached to the correct record.
//
SectionRecord sectionRecordForDefault = (hasInput) ? null : sectionRecord;
CreateSectionDefault(configKey, getParentRuntimeObject, factoryRecord, sectionRecordForDefault,
out parentResult, out parentResultRuntimeObject);
}
else {
//
// Get the parent section.
//
_parent.GetSectionRecursive(
configKey, false /* getLkg */, false /* checkPermission */,
getParentRuntimeObject, false /* requestIsHere */,
out parentResult, out parentResultRuntimeObject);
}
if (hasInput) {
//
// Evaluate the input.
//
// If Evaluate() encounters an error, it may not throw an exception
// when getLkg == true.
//
// The complete success of the evaluation is determined by the return value.
//
bool success = Evaluate(factoryRecord, sectionRecord, parentResult, getLkg, getRuntimeObject,
out tmpResult, out tmpResultRuntimeObject);
Debug.Assert(success || getLkg, "success || getLkg");
if (!success) {
Debug.Assert(getLkg == true, "getLkg == true");
// Do not cache partial results if getLkg was specified.
cacheResults = false;
}
}
else {
//
// If we are going to cache results here, we will need
// to create a copy in the case of MgmtConfigurationRecord -
// otherwise we could inadvertently return the parent to the user,
// which could then be modified.
//
if (sectionRecord != null) {
tmpResult = UseParentResult(configKey, parentResult, sectionRecord);
if (getRuntimeObject) {
//
// If the parent result is the same as the parent runtime object,
// then use the same copy of the parent result for our own runtime object.
//
if (object.ReferenceEquals(parentResult, parentResultRuntimeObject)) {
tmpResultRuntimeObject = tmpResult;
}
else {
tmpResultRuntimeObject = UseParentResult(configKey, parentResultRuntimeObject, sectionRecord);
}
}
}
else {
Debug.Assert(!requestIsHere, "!requestIsHere");
//
// We don't need to make a copy if we are not storing
// the result, and thus not returning the result to the
// caller of GetSection.
//
tmpResult = parentResult;
tmpResultRuntimeObject = parentResultRuntimeObject;
}
}
//
// Determine which permissions are required of the caller.
//
if (cacheResults || checkPermission) {
requirePermission = factoryRecord.RequirePermission;
isResultTrustedWithoutAptca = factoryRecord.IsFactoryTrustedWithoutAptca;
//
// Cache the results.
//
if (cacheResults) {
if (sectionRecord == null) {
sectionRecord = EnsureSectionRecord(configKey, true);
}
sectionRecord.Result = tmpResult;
if (getRuntimeObject) {
sectionRecord.ResultRuntimeObject = tmpResultRuntimeObject;
}
sectionRecord.RequirePermission = requirePermission;
sectionRecord.IsResultTrustedWithoutAptca = isResultTrustedWithoutAptca;
}
}
hasResult = true;
}
catch {
//
// Ignore the error if we are attempting to retreive
// the last known good configuration.
//
if (!getLkg) {
throw;
}
}
//
// If we don't have a result, ask our parent for its
// last known good result.
//
if (!hasResult) {
Debug.Assert(getLkg == true, "getLkg == true");
_parent.GetSectionRecursive(
configKey, true /* getLkg */, checkPermission,
true /* getRuntimeObject */, true /* requestIsHere */,
out result, out resultRuntimeObject);
return;
}
}
//
// Check if permission to access the section is allowed.
//
if (checkPermission) {
CheckPermissionAllowed(configKey, requirePermission, isResultTrustedWithoutAptca);
}
//
// Return the results.
//
result = tmpResult;
if (getRuntimeObject) {
resultRuntimeObject = tmpResultRuntimeObject;
}
}
protected void CreateSectionDefault(
string configKey, bool getRuntimeObject, FactoryRecord factoryRecord, SectionRecord sectionRecord,
out object result, out object resultRuntimeObject) {
result = null;
resultRuntimeObject = null;
SectionRecord sectionRecordForDefault;
if (sectionRecord != null) {
sectionRecordForDefault = sectionRecord;
}
else {
sectionRecordForDefault = new SectionRecord(configKey);
}
object tmpResult = CallCreateSection(true, factoryRecord, sectionRecordForDefault, null, null, null);
object tmpResultRuntimeObject;
if (getRuntimeObject) {
tmpResultRuntimeObject = GetRuntimeObject(tmpResult);
}
else {
tmpResultRuntimeObject = null;
}
result = tmpResult;
resultRuntimeObject = tmpResultRuntimeObject;
}
#if UNUSED_CODE
//
// Create a section that is used to manipulate a section that has errors.
//
private DefaultSection CreateErrorSection(
string configKey, FactoryRecord factoryRecord, SectionRecord sectionRecord, SectionInput input, Exception e) {
//
// We make assumptions in this implemntation that CreateErrorSection is called
// only for MgmtConfigurationRecord.
//
Debug.Assert(this is MgmtConfigurationRecord, "this is MgmtConfigurationRecord");
string group;
string name;
string factoryTypeName;
bool allowLocation;
ConfigurationAllowDefinition allowDefinition;
ConfigurationAllowExeDefinition allowExeDefinition;
bool restartOnExternalChanges;
bool requirePermission;
bool isFromTrustedConfigRecord;
string factoryFilename;
int factoryLineNumber;
// The original factory record will contain either valid values,
// or the default values in places where there was an error.
if (factoryRecord != null) {
configKey = factoryRecord.ConfigKey;
group = factoryRecord.Group;
name = factoryRecord.Name;
factoryTypeName = factoryRecord.FactoryTypeName;
allowLocation = factoryRecord.AllowLocation;
allowDefinition = factoryRecord.AllowDefinition;
allowExeDefinition = factoryRecord.AllowExeDefinition;
restartOnExternalChanges = factoryRecord.RestartOnExternalChanges;
requirePermission = factoryRecord.RequirePermission;
isFromTrustedConfigRecord = factoryRecord.IsFromTrustedConfigRecord;
factoryFilename = factoryRecord.Filename;
factoryLineNumber = factoryRecord.LineNumber;
}
else {
SplitConfigKey(configKey, out group, out name);
factoryTypeName = typeof(DefaultSection).AssemblyQualifiedName;
allowLocation = true;
allowDefinition = ConfigurationAllowDefinition.Everywhere;
allowExeDefinition = ConfigurationAllowExeDefinition.MachineToApplication;
restartOnExternalChanges = true;
requirePermission = true;
isFromTrustedConfigRecord = false;
factoryFilename = null;
factoryLineNumber = -1;
}
// create a new factory record
FactoryRecord factoryRecordForCreate = new FactoryRecord(
configKey,
group,
name,
factoryTypeName,
allowLocation,
allowDefinition,
allowExeDefinition,
restartOnExternalChanges,
requirePermission,
isFromTrustedConfigRecord,
factoryFilename,
factoryLineNumber);
//
// Create the factory needed to create the section.
//
Debug.Assert(this is MgmtConfigurationRecord, "this is MgmtConfigurationRecord");
ConstructorInfo ctor = TypeUtil.GetConstructorWithReflectionPermission(typeof(DefaultSection), typeof(ConfigurationSection), true);
factoryRecordForCreate.Factory = ctor;
factoryRecordForCreate.IsFactoryTrustedWithoutAptca = false;
//
// Try to get the section content as raw xml.
//
ConfigXmlReader configXmlReader = null;
string filename = null;
int lineNumber = -1;
if (input != null) {
filename = input.SectionXmlInfo.Filename;
lineNumber = input.SectionXmlInfo.LineNumber;
string [] keys = sectionRecord.ConfigKey.Split(ConfigPathSeparatorParams);
try {
configXmlReader = GetSectionXmlReader(keys, input);
}
catch {
}
}
DefaultSection section = (DefaultSection) CallCreateSection(
isFromTrustedConfigRecord, factoryRecordForCreate, sectionRecord,
null /* parentConfig */, configXmlReader, filename, lineNumber);
section.ElementInformation.SetError(configKey, e);
return section;
}
#endif
//
// Check if an input should be skipped based on inheritInChildApplications setting.
//
// If skipInChildApps == true (it means inheritInChildApplications=="false" in the location tag):
//
// - If _flags[IsAboveApplication]==true, that means the app pointed to by _configPath is above of the
// current running app. In another word, the running app is a child app of the app pointed to by _configPath.
// In this case, we should skip the input.
//
// - If _flags[IsAboveApplication]==false, that means the app pointed to by _configPath == current running app.
// In this case it's okay to use the input.
//
private bool ShouldSkipDueToInheritInChildApplications(bool skipInChildApps) {
return (skipInChildApps && _flags[IsAboveApplication]);
}
// configPath - The config path of the config record to which a location tag points to.
private bool ShouldSkipDueToInheritInChildApplications(bool skipInChildApps, string configPath) {
return (skipInChildApps && Host.IsAboveApplication(configPath));
}
//
//
// Evaluate the input.
//
// If Evaluate() encounters an error, it may not throw an exception
// when getLkg == true.
//
// The complete success of the evaluation is determined by the return value.
//
private bool Evaluate(
FactoryRecord factoryRecord, SectionRecord sectionRecord, object parentResult,
bool getLkg, bool getRuntimeObject, out object result, out object resultRuntimeObject) {
result = null;
resultRuntimeObject = null;
//
// Store results in temporary variables, because we don't want to return
// results if an exception is thrown.
//
object tmpResult = null;
object tmpResultRuntimeObject = null;
// Factory record should be error-free.
Debug.Assert(!factoryRecord.HasErrors, "!factoryRecord.HasErrors");
// We should have some input
Debug.Assert(sectionRecord.HasInput, "sectionRecord.HasInput");
//
// Grab inputs before checking result,
// as inputs may be cleared once the result is set.
//
List<SectionInput> locationInputs = sectionRecord.LocationInputs;
List<SectionInput> indirectLocationInputs = sectionRecord.IndirectLocationInputs;
SectionInput fileInput = sectionRecord.FileInput;
Debug.Assert(!(IsLocationConfig && getLkg),
"Don't expect getLkg to be true when we're dealing with a location config record");
//
// Now that we have our inputs, lets check if there
// is a result, because if there is, our inputs might
// have been invalidated.
//
bool success = false;
if (sectionRecord.HasResult) {
// Results should never be stored if the section has errors.
Debug.Assert(!sectionRecord.HasErrors, "!sectionRecord.HasErrors");
// Create the runtime object if requested and it does not yet exist.
if (getRuntimeObject && !sectionRecord.HasResultRuntimeObject) {
try {
sectionRecord.ResultRuntimeObject = GetRuntimeObject(sectionRecord.Result);
}
catch {
//
// Ignore the error if we are attempting to retreive
// the last known good configuration.
//
if (!getLkg) {
throw;
}
}
}
// Get the cached result.
if (!getRuntimeObject || sectionRecord.HasResultRuntimeObject) {
tmpResult = sectionRecord.Result;
if (getRuntimeObject) {
tmpResultRuntimeObject = sectionRecord.ResultRuntimeObject;
}
success = true;
}
}
if (!success) {
Exception savedException = null;
try {
string configKey = factoryRecord.ConfigKey;
string [] keys = configKey.Split(ConfigPathSeparatorParams);
object currentResult = parentResult;
//
// Evaluate indirectLocationInputs. Used only in location config record.
// See the comment for VSWhidbey 540184 in Init() for more details.
//
if (indirectLocationInputs != null) {
Debug.Assert(IsLocationConfig, "indirectLocationInputs is non-null only in location config record");
foreach (SectionInput input in indirectLocationInputs) {
if (!input.HasResult) {
input.ThrowOnErrors();
bool isTrusted = Host.IsTrustedConfigPath(input.SectionXmlInfo.DefinitionConfigPath);
input.Result = EvaluateOne(keys, input, isTrusted, factoryRecord, sectionRecord, currentResult);
}
currentResult = input.Result;
}
}
//
// Evaluate location inputs
//
if (locationInputs != null) {
foreach (SectionInput locationInput in locationInputs) {
if (!locationInput.HasResult) {
locationInput.ThrowOnErrors();
bool isTrusted = Host.IsTrustedConfigPath(locationInput.SectionXmlInfo.DefinitionConfigPath);
locationInput.Result = EvaluateOne(keys, locationInput, isTrusted, factoryRecord, sectionRecord, currentResult);
}
currentResult = locationInput.Result;
}
}
//
// Evaluate file input
//
if (fileInput != null) {
if (!fileInput.HasResult) {
fileInput.ThrowOnErrors();
bool isTrusted = _flags[IsTrusted];
fileInput.Result = EvaluateOne(keys, fileInput, isTrusted, factoryRecord, sectionRecord, currentResult);
}
currentResult = fileInput.Result;
}
else {
//
// The section needs its own copy of the result that is distinct
// from its location parent result.
//
// Please note that this is needed only in design-time because any
// change to the section shouldn't go to the locationInput.Result.
//
// In runtime, UseParentResult does nothing.
//
Debug.Assert(locationInputs != null || indirectLocationInputs != null,
"locationInputs != null || indirectLocationInputs != null");
currentResult = UseParentResult(configKey, currentResult, sectionRecord);
}
if (getRuntimeObject) {
tmpResultRuntimeObject = GetRuntimeObject(currentResult);
}
tmpResult = currentResult;
success = true;
}
catch (Exception e) {
//
// Catch the exception if LKG is requested and we have
// location input to fall back on.
//
if (getLkg && locationInputs != null) {
savedException = e;
}
else {
throw;
}
}
//
// If getLkg, then return a result from the last valid location input.
//
if (!success) {
Debug.Assert(getLkg == true, "getLkg == true");
int i = locationInputs.Count;
while (--i >= 0) {
SectionInput locationInput = locationInputs[i];
if (locationInput.HasResult) {
if (getRuntimeObject && !locationInput.HasResultRuntimeObject) {
try {
locationInput.ResultRuntimeObject = GetRuntimeObject(locationInput.Result);
}
catch {
}
}
if (!getRuntimeObject || locationInput.HasResultRuntimeObject) {
tmpResult = locationInput.Result;
if (getRuntimeObject) {
tmpResultRuntimeObject = locationInput.ResultRuntimeObject;
}
break;
}
}
}
if (i < 0) {
throw savedException;
}
}
}
//
// If evaluation was successful, we can remove any saved rawXml.
//
if (success && !_flags[SupportsKeepInputs]) {
sectionRecord.ClearRawXml();
}
result = tmpResult;
if (getRuntimeObject) {
resultRuntimeObject = tmpResultRuntimeObject;
}
return success;
}
private object EvaluateOne(
string[] keys, SectionInput input, bool isTrusted,
FactoryRecord factoryRecord, SectionRecord sectionRecord, object parentResult) {
object result;
try {
ConfigXmlReader reader = GetSectionXmlReader(keys, input);
if (reader == null) {
//
// If section is not found in a file, use the parent result
//
result = UseParentResult(factoryRecord.ConfigKey, parentResult, sectionRecord);
}
else {
result = CallCreateSection(isTrusted, factoryRecord, sectionRecord, input, parentResult, reader);
}
}
catch (Exception e) {
throw ExceptionUtil.WrapAsConfigException(
SR.GetString(SR.Config_exception_creating_section, factoryRecord.ConfigKey),
e, input.SectionXmlInfo);
}
return result;
}
//
// Create a single cached instance of UnrestrictedConfigPermission.
//
private static ConfigurationPermission UnrestrictedConfigPermission {
get {
if (s_unrestrictedConfigPermission == null) {
s_unrestrictedConfigPermission = new ConfigurationPermission(PermissionState.Unrestricted);
}
return s_unrestrictedConfigPermission;
}
}
//
// Check whether permission to the section is allowed to the caller.
//
private void CheckPermissionAllowed(string configKey, bool requirePermission, bool isTrustedWithoutAptca) {
//
// Demand unrestricted ConfigurationPermission if the section requires it
//
if (requirePermission) {
try {
UnrestrictedConfigPermission.Demand();
}
catch (SecurityException e) {
//
// Add a nice error message that includes the sectionName and explains
// how to use the requirePermission attribute.
//
throw new SecurityException(
SR.GetString(SR.ConfigurationPermission_Denied, configKey),
e);
}
}
//
// Ensure that the recepient isn't receiving an object they otherwise
// wouldn't be able to create due to Aptca.
//
if (isTrustedWithoutAptca && !Host.IsFullTrustSectionWithoutAptcaAllowed(this)) {
throw new ConfigurationErrorsException(SR.GetString(SR.Section_from_untrusted_assembly, configKey));
}
}
private ConfigXmlReader FindSection(string [] keys, SectionXmlInfo sectionXmlInfo, out int lineNumber) {
lineNumber = 0;
ConfigXmlReader section = null;
try {
using (Impersonate()) {
using (Stream stream = Host.OpenStreamForRead(sectionXmlInfo.Filename)) {
if ( !_flags[SupportsRefresh]
&& (stream == null || HasStreamChanged(sectionXmlInfo.Filename, sectionXmlInfo.StreamVersion))) {
throw new ConfigurationErrorsException(SR.GetString(SR.Config_file_has_changed), sectionXmlInfo.Filename, 0);
}
if (stream != null) {
//
using (XmlUtil xmlUtil = new XmlUtil(stream, sectionXmlInfo.Filename, true)) {
if (sectionXmlInfo.SubPath == null) {
section = FindSectionRecursive(keys, 0, xmlUtil, ref lineNumber);
}
else {
// search children of <configuration> for <location>
xmlUtil.ReadToNextElement();
while (xmlUtil.Reader.Depth > 0) {
if (xmlUtil.Reader.Name == KEYWORD_LOCATION) {
bool locationValid = false;
string locationSubPathAttribute = xmlUtil.Reader.GetAttribute(KEYWORD_LOCATION_PATH);
try {
locationSubPathAttribute = NormalizeLocationSubPath(locationSubPathAttribute, xmlUtil);
locationValid = true;
}
catch (ConfigurationException ce) {
xmlUtil.SchemaErrors.AddError(ce, ExceptionAction.NonSpecific);
}
if (locationValid &&
StringUtil.EqualsIgnoreCase(sectionXmlInfo.SubPath, locationSubPathAttribute)) {
section = FindSectionRecursive(keys, 0, xmlUtil, ref lineNumber);
if (section != null)
break;
}
}
xmlUtil.SkipToNextElement();
}
}
// Throw accumulated errors
ThrowIfParseErrors(xmlUtil.SchemaErrors);
}
}
}
}
}
// Don't allow frames up the stack to run exception filters while impersonated.
catch {
throw;
}
return section;
}
private ConfigXmlReader FindSectionRecursive(string [] keys, int iKey, XmlUtil xmlUtil, ref int lineNumber) {
string name = keys[iKey];
ConfigXmlReader section = null;
int depth = xmlUtil.Reader.Depth;
xmlUtil.ReadToNextElement();
while (xmlUtil.Reader.Depth > depth) {
if (xmlUtil.Reader.Name == name) {
if (iKey < keys.Length - 1) {
//
// We haven't reached the section yet, so keep evaluating
//
section = FindSectionRecursive(keys, iKey + 1, xmlUtil, ref lineNumber);
if (section != null) {
break;
}
continue; // don't call "Skip" -- FindSectionRecursive forwards the reader
}
else {
//
// We've reached the section. Load the section into a string.
//
string filename = ((IConfigErrorInfo)xmlUtil).Filename;
int lineOffset = xmlUtil.Reader.LineNumber;
string rawXml = xmlUtil.CopySection();
section = new ConfigXmlReader(rawXml, filename, lineOffset);
break;
}
}
else if (iKey == 0 && xmlUtil.Reader.Name == KEYWORD_LOCATION) {
string locationSubPath = xmlUtil.Reader.GetAttribute(KEYWORD_LOCATION_PATH);
bool isValid = false;
try {
locationSubPath = NormalizeLocationSubPath(locationSubPath, xmlUtil);
isValid = true;
}
catch (ConfigurationException ce) {
xmlUtil.SchemaErrors.AddError(ce, ExceptionAction.NonSpecific);
}
if (isValid && locationSubPath == null) {
//
// Location sections that don't have a subpath are treated
// as ordinary sections.
//
section = FindSectionRecursive(keys, iKey, xmlUtil, ref lineNumber);
if (section != null) {
break;
}
continue; // don't call "Skip" -- FindSectionRecursive forwards the reader
}
}
xmlUtil.SkipToNextElement();
}
return section;
}
private ConfigXmlReader LoadConfigSource(string name, SectionXmlInfo sectionXmlInfo) {
string configSourceStreamName = sectionXmlInfo.ConfigSourceStreamName;
try {
using (Impersonate()) {
using (Stream stream = Host.OpenStreamForRead(configSourceStreamName)) {
if (stream == null) {
throw new ConfigurationErrorsException(
SR.GetString(SR.Config_cannot_open_config_source, sectionXmlInfo.ConfigSource),
sectionXmlInfo);
}
using (XmlUtil xmlUtil = new XmlUtil(stream, configSourceStreamName, true)) {
if (xmlUtil.Reader.Name != name) {
throw new ConfigurationErrorsException(SR.GetString(SR.Config_source_file_format), xmlUtil);
}
// Check for protectionProvider
string protectionProviderAttribute = xmlUtil.Reader.GetAttribute(KEYWORD_PROTECTION_PROVIDER);
if (protectionProviderAttribute != null) {
if (xmlUtil.Reader.AttributeCount != 1) {
// Error: elements with protectionProvider should not have other attributes
throw new ConfigurationErrorsException(SR.GetString(SR.Protection_provider_syntax_error), xmlUtil);
}
sectionXmlInfo.ProtectionProviderName = ValidateProtectionProviderAttribute(protectionProviderAttribute, xmlUtil);
}
// Check for configBuilder
string configBuilderAttribute = xmlUtil.Reader.GetAttribute(KEYWORD_CONFIG_BUILDER);
if (configBuilderAttribute != null) {
sectionXmlInfo.ConfigBuilderName = ValidateConfigBuilderAttribute(configBuilderAttribute, xmlUtil);
}
int lineOffset = xmlUtil.Reader.LineNumber;
string rawXml = xmlUtil.CopySection();
// Detect if there is any XML left over after the section
while (!xmlUtil.Reader.EOF) {
XmlNodeType t = xmlUtil.Reader.NodeType;
if (t != XmlNodeType.Comment) {
throw new ConfigurationErrorsException(SR.GetString(SR.Config_source_file_format), xmlUtil);
}
xmlUtil.Reader.Read();
}
ConfigXmlReader section = new ConfigXmlReader(rawXml, configSourceStreamName, lineOffset);
return section;
}
}
}
}
catch {
// Don't allow frames up the stack to run exception filters while impersonated.
throw;
}
}
protected ConfigXmlReader GetSectionXmlReader(string[] keys, SectionInput input) {
ConfigXmlReader reader = null;
string filename = input.SectionXmlInfo.Filename;
int lineNumber = input.SectionXmlInfo.LineNumber;
try {
string name = keys[keys.Length-1];
string rawXml = input.SectionXmlInfo.RawXml;
if (rawXml != null) {
// Use the stored raw xml to provide the content of the section.
reader = new ConfigXmlReader(rawXml, input.SectionXmlInfo.Filename, input.SectionXmlInfo.LineNumber);
}
else if (!String.IsNullOrEmpty(input.SectionXmlInfo.ConfigSource)) {
// Load the config source to provide the content of the section.
filename = input.SectionXmlInfo.ConfigSourceStreamName;
lineNumber = 0;
reader = LoadConfigSource(name, input.SectionXmlInfo);
}
else {
// Find the content of the section in the config file.
lineNumber = 0;
reader = FindSection(keys, input.SectionXmlInfo, out lineNumber);
}
// Decrypt protected sections
if (reader != null) {
if (!input.IsProtectionProviderDetermined) {
input.ProtectionProvider = GetProtectionProviderFromName(input.SectionXmlInfo.ProtectionProviderName, false);
}
if (input.ProtectionProvider != null) {
reader = DecryptConfigSection(reader, input.ProtectionProvider);
}
}
// Allow configBuilder a chance to modify
if (reader != null) {
if (!input.IsConfigBuilderDetermined && !String.IsNullOrWhiteSpace(input.SectionXmlInfo.ConfigBuilderName)) {
input.ConfigBuilder = GetConfigBuilderFromName(input.SectionXmlInfo.ConfigBuilderName);
}
if (input.IsConfigBuilderDetermined) {
// Decrypt removes the invalid "configProtectionProvider" attribute simply by returning an xml reader for the
// decrypted inner xml... which persumably does not have the attribute. ConfigBuilders OTOH, will presumably
// return an xml reader based on this whole section as is. And the "configBuilders" attribute will be an
// "unrecognized attribute" further down the road. So let's remove it here.
XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
doc.LoadXml(reader.RawXml);
doc.DocumentElement.RemoveAttribute(KEYWORD_CONFIG_BUILDER);
reader = new ConfigXmlReader(doc.DocumentElement.OuterXml, filename, lineNumber);
}
if (input.ConfigBuilder != null) {
reader = ProcessRawXml(reader, input.ConfigBuilder);
}
}
}
//
// Guarantee that exceptions contain the name of the stream and an approximate line number.
//
catch (Exception e) {
throw ExceptionUtil.WrapAsConfigException(SR.GetString(SR.Config_error_loading_XML_file), e, filename, lineNumber);
}
return reader;
}
internal string DefaultProviderName {
get {
return ProtectedConfig.DefaultProvider;
}
}
internal ProtectedConfigurationProvider GetProtectionProviderFromName(string providerName, bool throwIfNotFound) {
ProtectedConfigurationProvider provider = null;
if (String.IsNullOrEmpty(providerName)) {
if (throwIfNotFound) {
throw new ConfigurationErrorsException(SR.GetString(SR.ProtectedConfigurationProvider_not_found, providerName));
}
else {
return null;
}
}
provider = ProtectedConfig.GetProviderFromName(providerName);
return provider;
}
private ProtectedConfigurationSection ProtectedConfig {
get {
if (!_flags[ProtectedDataInitialized]) {
InitProtectedConfigurationSection();
}
return _protectedConfig;
}
}
internal void InitProtectedConfigurationSection() {
if (!_flags[ProtectedDataInitialized]) {
_protectedConfig = GetSection(BaseConfigurationRecord.RESERVED_SECTION_PROTECTED_CONFIGURATION, false, false) as ProtectedConfigurationSection;
Debug.Assert(_protectedConfig != null, "<configProtectedData> section should always be available because it's a built-in section");
_flags[ProtectedDataInitialized] = true;
}
}
internal ConfigurationBuilder GetConfigBuilderFromName(string builderName) {
if (String.IsNullOrEmpty(builderName) || ConfigBuilders == null) {
throw new ConfigurationErrorsException(SR.GetString(SR.Config_builder_not_found, builderName));
}
return ConfigBuilders.GetBuilderFromName(builderName);
}
private ConfigurationBuildersSection ConfigBuilders {
get {
if (!_flags[ConfigBuildersInitialized]) {
InitConfigBuildersSection();
}
return _configBuilders;
}
}
internal void InitConfigBuildersSection() {
if (!_flags[ConfigBuildersInitialized]) {
_configBuilders = GetSection(BaseConfigurationRecord.RESERVED_SECTION_CONFIGURATION_BUILDERS, false, false) as ConfigurationBuildersSection;
_flags[ConfigBuildersInitialized] = true;
}
}
protected object CallCreateSection(bool inputIsTrusted, FactoryRecord factoryRecord, SectionRecord sectionRecord, SectionInput sectionInput, object parentConfig, ConfigXmlReader reader) {
object config;
string filename = null;
int line = -1;
if (sectionInput != null && sectionInput.SectionXmlInfo != null) {
filename = sectionInput.SectionXmlInfo.Filename;
line = sectionInput.SectionXmlInfo.LineNumber;
}
// Call into config section while impersonating process or UNC identity
// so that the section could read files from disk if needed
try {
using (Impersonate()) {
config = CreateSection(inputIsTrusted, factoryRecord, sectionRecord, sectionInput, parentConfig, reader);
if (config == null && parentConfig != null) {
throw new ConfigurationErrorsException(SR.GetString(SR.Config_object_is_null), filename, line);
}
}
}
catch (ThreadAbortException) {
throw;
}
catch (Exception e) {
throw ExceptionUtil.WrapAsConfigException(SR.GetString(SR.Config_exception_creating_section_handler, factoryRecord.ConfigKey), e, filename, line);
}
return config;
}
// IsRootDeclaration
//
// Is this the Root Record of where this configKey is Declared
//
// If parent is null, or there is not a factory record above
// this one, then it is the root of where it can be declared
//
// Optionally consider whether implicit sections are to be considered rooted.
//
internal bool IsRootDeclaration(string configKey, bool implicitIsRooted) {
if (!implicitIsRooted && IsImplicitSection(configKey)) {
return false;
}
return (_parent.IsRootConfig || _parent.FindFactoryRecord(configKey, true) == null);
}
// Search the config hierarchy for a FactoryRecord.
// Note that callers should check whether the returned factory has errors.
internal FactoryRecord FindFactoryRecord(string configKey, bool permitErrors, out BaseConfigurationRecord configRecord) {
configRecord = null;
BaseConfigurationRecord tConfigRecord = this;
while (!tConfigRecord.IsRootConfig) {
FactoryRecord factoryRecord = tConfigRecord.GetFactoryRecord(configKey, permitErrors);
if (factoryRecord != null) {
#if DBG
if (IsImplicitSection(configKey) && !factoryRecord.HasErrors) {
Debug.Assert(tConfigRecord._parent.IsRootConfig,
"Implicit section should be found only at the record beneath the root (e.g. machine.config)");
}
#endif
configRecord = tConfigRecord;
return factoryRecord;
}
tConfigRecord = tConfigRecord._parent;
}
return null;
}
internal FactoryRecord FindFactoryRecord(string configKey, bool permitErrors) {
BaseConfigurationRecord dummy;
return FindFactoryRecord(configKey, permitErrors, out dummy);
}
//
// FindAndEnsureFactoryRecord:
//
// - Find the nearest factory record
// - Determine if it is the root
// - Create the factory in the root if it doesn't exist.
// - Determine if the factory type is from a global assembly without APTCA
// - Copy the factory and IsFactoryTrustedWithoutAptca bit into the child record
//
private FactoryRecord FindAndEnsureFactoryRecord(string configKey, out bool isRootDeclaredHere) {
isRootDeclaredHere = false;
BaseConfigurationRecord configRecord;
FactoryRecord factoryRecord = FindFactoryRecord(configKey, false, out configRecord);
if (factoryRecord != null && !factoryRecord.IsGroup) {
//
// Find the root declaration
//
FactoryRecord rootFactoryRecord = factoryRecord;
BaseConfigurationRecord rootConfigRecord = configRecord;
BaseConfigurationRecord currentConfigRecord = configRecord._parent;
while (!currentConfigRecord.IsRootConfig) {
BaseConfigurationRecord tempConfigRecord;
FactoryRecord tempFactoryRecord = currentConfigRecord.FindFactoryRecord(configKey, false, out tempConfigRecord);
if (tempFactoryRecord == null)
break;
rootFactoryRecord = tempFactoryRecord;
rootConfigRecord = tempConfigRecord;
// continue the search from the parent of the configRecord we found
currentConfigRecord = tempConfigRecord.Parent;
}
//
// A child factory record must be equivalent to its parent,
// so if the child has no errors, the parent must also have no errors.
//
Debug.Assert(!rootFactoryRecord.HasErrors, "!rootFactoryRecord.HasErrors");
if (rootFactoryRecord.Factory == null) {
try {
//
// Create the factory from the type string, and cache it
//
object factory = rootConfigRecord.CreateSectionFactory(rootFactoryRecord);
bool isFactoryTrustedWithoutAptca = TypeUtil.IsTypeFromTrustedAssemblyWithoutAptca(factory.GetType());
rootFactoryRecord.Factory = factory;
rootFactoryRecord.IsFactoryTrustedWithoutAptca = isFactoryTrustedWithoutAptca;
}
catch (Exception e) {
throw ExceptionUtil.WrapAsConfigException(SR.GetString(SR.Config_exception_creating_section_handler, factoryRecord.ConfigKey), e, factoryRecord);
}
}
if (factoryRecord.Factory == null) {
factoryRecord.Factory = rootFactoryRecord.Factory;
factoryRecord.IsFactoryTrustedWithoutAptca = rootFactoryRecord.IsFactoryTrustedWithoutAptca;
}
isRootDeclaredHere = Object.ReferenceEquals(this, rootConfigRecord);
}
return factoryRecord;
}
private Hashtable ScanFactories(XmlUtil xmlUtil) {
Hashtable factoryList;
factoryList = new Hashtable();
if (xmlUtil.Reader.NodeType != XmlNodeType.Element || xmlUtil.Reader.Name != KEYWORD_CONFIGURATION) {
//
string safeFilename = ConfigurationErrorsException.AlwaysSafeFilename(((IConfigErrorInfo)xmlUtil).Filename);
throw new ConfigurationErrorsException(
SR.GetString(SR.Config_file_doesnt_have_root_configuration, safeFilename),
xmlUtil);
}
// Ignore xmlns attribute
while (xmlUtil.Reader.MoveToNextAttribute()) {
switch (xmlUtil.Reader.Name) {
case KEYWORD_XMLNS:
if (xmlUtil.Reader.Value == KEYWORD_CONFIGURATION_NAMESPACE) {
_flags[NamespacePresentInFile] = true;
_flags[NamespacePresentCurrent] = true;
} else {
ConfigurationErrorsException ce;
ce = new ConfigurationErrorsException(
SR.GetString(SR.Config_namespace_invalid, xmlUtil.Reader.Value, KEYWORD_CONFIGURATION_NAMESPACE),
xmlUtil);
xmlUtil.SchemaErrors.AddError(ce, ExceptionAction.Global);
}
break;
default:
xmlUtil.AddErrorUnrecognizedAttribute(ExceptionAction.NonSpecific);
break;
}
}
// move to first child of <configuration>
xmlUtil.StrictReadToNextElement(ExceptionAction.NonSpecific);
if (xmlUtil.Reader.Depth == 1 && xmlUtil.Reader.Name == KEYWORD_CONFIGSECTIONS) {
xmlUtil.VerifyNoUnrecognizedAttributes(ExceptionAction.NonSpecific);
ScanFactoriesRecursive(xmlUtil, string.Empty, factoryList);
}
return factoryList;
}
// Scans the <configSections> section of a configuration file. The function is recursive
// to traverse arbitrarily nested config groups.
//
// <sectionGroup name="foo">
// <sectionGroup name="bar">
// <section name="----Section" type="..." />
// ...
//
// Note: This function valiates that the factory record has not been
// declared before in a parent record. (it does not check
// current record, which allows you to update list)
//
private void ScanFactoriesRecursive(XmlUtil xmlUtil, string parentConfigKey, Hashtable factoryList) {
// discard any accumulated local errors
xmlUtil.SchemaErrors.ResetLocalErrors();
int depth = xmlUtil.Reader.Depth;
xmlUtil.StrictReadToNextElement(ExceptionAction.NonSpecific);
while (xmlUtil.Reader.Depth == depth + 1) {
bool positionedAtNextElement = false;
switch (xmlUtil.Reader.Name) {
//
// Handle <sectionGroup name="groupName" [type="typename"] />
//
case KEYWORD_SECTIONGROUP: {
string tagName = null;
string typeName = null;
int lineNumber = xmlUtil.Reader.LineNumber;
while (xmlUtil.Reader.MoveToNextAttribute()) {
switch (xmlUtil.Reader.Name) {
case KEYWORD_SECTIONGROUP_NAME:
tagName = xmlUtil.Reader.Value;
VerifySectionName(tagName, xmlUtil, ExceptionAction.Local, false, false);
break;
case KEYWORD_SECTIONGROUP_TYPE:
xmlUtil.VerifyAndGetNonEmptyStringAttribute(ExceptionAction.Local, out typeName);
break;
default:
xmlUtil.AddErrorUnrecognizedAttribute(ExceptionAction.Local);
break;
}
}
xmlUtil.Reader.MoveToElement(); // if on an attribute move back to the element
if (!xmlUtil.VerifyRequiredAttribute(
tagName,
KEYWORD_SECTIONGROUP_NAME,
ExceptionAction.NonSpecific)) {
//
// Without a name, we cannot continue parsing the sections and groups within.
// Skip the entire section.
//
xmlUtil.SchemaErrors.RetrieveAndResetLocalErrors(true);
xmlUtil.StrictSkipToNextElement(ExceptionAction.NonSpecific);
}
else {
string configKey = CombineConfigKey(parentConfigKey, tagName);
FactoryRecord factoryRecord = (FactoryRecord) factoryList[configKey];
if (factoryRecord != null) {
// Error: duplicate sectionGroup declaration
xmlUtil.SchemaErrors.AddError(
new ConfigurationErrorsException(SR.GetString(SR.Config_tag_name_already_defined_at_this_level, tagName), xmlUtil),
ExceptionAction.Local);
} else {
FactoryRecord parentFactoryRecord = _parent.FindFactoryRecord(configKey, true);
if (parentFactoryRecord != null) {
configKey = parentFactoryRecord.ConfigKey;
// make sure that an ancestor has not defined a section with the same name as the group
if ( parentFactoryRecord != null &&
(!parentFactoryRecord.IsGroup ||
!parentFactoryRecord.IsEquivalentSectionGroupFactory(Host, typeName))) {
xmlUtil.SchemaErrors.AddError(
new ConfigurationErrorsException(SR.GetString(SR.Config_tag_name_already_defined, tagName), xmlUtil),
ExceptionAction.Local);
parentFactoryRecord = null;
}
}
if (parentFactoryRecord != null) {
factoryRecord = parentFactoryRecord.CloneSectionGroup(typeName, xmlUtil.Filename, lineNumber);
}
else {
factoryRecord = new FactoryRecord(configKey, parentConfigKey, tagName, typeName, xmlUtil.Filename, lineNumber);
}
factoryList[configKey] = factoryRecord;
}
// Add any errors we may have encountered
factoryRecord.AddErrors(xmlUtil.SchemaErrors.RetrieveAndResetLocalErrors(true));
// continue recursive scan
ScanFactoriesRecursive(xmlUtil, configKey, factoryList);
}
continue;
}
case KEYWORD_SECTION: {
string tagName = null;
string typeName = null;
ConfigurationAllowDefinition allowDefinition = ConfigurationAllowDefinition.Everywhere;
ConfigurationAllowExeDefinition allowExeDefinition = ConfigurationAllowExeDefinition.MachineToApplication;
OverrideModeSetting overrideModeDefault = OverrideModeSetting.SectionDefault;
bool allowLocation = true;
bool restartOnExternalChanges = true;
bool requirePermission = true;
bool gotType = false;
// parse section attributes
int lineNumber = xmlUtil.Reader.LineNumber;
while (xmlUtil.Reader.MoveToNextAttribute()) {
switch (xmlUtil.Reader.Name) {
case KEYWORD_SECTION_NAME:
tagName = xmlUtil.Reader.Value;
VerifySectionName(tagName, xmlUtil, ExceptionAction.Local, false, true);
break;
case KEYWORD_SECTION_TYPE:
xmlUtil.VerifyAndGetNonEmptyStringAttribute(ExceptionAction.Local, out typeName);
gotType = true;
break;
case KEYWORD_SECTION_ALLOWLOCATION:
xmlUtil.VerifyAndGetBooleanAttribute(
ExceptionAction.Local, true, out allowLocation);
break;
case KEYWORD_SECTION_ALLOWEXEDEFINITION:
try {
allowExeDefinition = AllowExeDefinitionToEnum(xmlUtil.Reader.Value, xmlUtil);
}
catch (ConfigurationException ce) {
xmlUtil.SchemaErrors.AddError(ce, ExceptionAction.Local);
}
break;
case KEYWORD_SECTION_ALLOWDEFINITION:
try {
allowDefinition = AllowDefinitionToEnum(xmlUtil.Reader.Value, xmlUtil);
}
catch (ConfigurationException ce) {
xmlUtil.SchemaErrors.AddError(ce, ExceptionAction.Local);
}
break;
case KEYWORD_SECTION_RESTARTONEXTERNALCHANGES:
xmlUtil.VerifyAndGetBooleanAttribute(
ExceptionAction.Local, true, out restartOnExternalChanges);
break;
case KEYWORD_SECTION_REQUIREPERMISSION:
xmlUtil.VerifyAndGetBooleanAttribute(
ExceptionAction.Local, true, out requirePermission);
break;
case KEYWORD_SECTION_OVERRIDEMODEDEFAULT:
try {
overrideModeDefault = OverrideModeSetting.CreateFromXmlReadValue(
OverrideModeSetting.ParseOverrideModeXmlValue(xmlUtil.Reader.Value, xmlUtil));
// Inherit means Allow when comming from the default value
if (overrideModeDefault.OverrideMode == OverrideMode.Inherit) {
overrideModeDefault.ChangeModeInternal(OverrideMode.Allow);
}
}
catch (ConfigurationException ce) {
xmlUtil.SchemaErrors.AddError(ce, ExceptionAction.Local);
}
break;
default:
xmlUtil.AddErrorUnrecognizedAttribute(ExceptionAction.Local);
break;
}
}
xmlUtil.Reader.MoveToElement(); // if on an attribute move back to the element
if (!xmlUtil.VerifyRequiredAttribute(
tagName, KEYWORD_SECTION_NAME, ExceptionAction.NonSpecific)) {
//
// Without a name, we cannot continue to create a factoryRecord.
//
xmlUtil.SchemaErrors.RetrieveAndResetLocalErrors(true);
}
else {
// Verify that the Type attribute was present.
// Note that 'typeName' will be null if the attribute was present
// but specified as an empty string.
if (!gotType) {
xmlUtil.AddErrorRequiredAttribute(KEYWORD_SECTION_TYPE, ExceptionAction.Local);
}
// Disallow names starting with "config" unless it is the special configBuilders section.
if (StringUtil.StartsWith(tagName, "config")) {
Type sectionType = Type.GetType(typeName);
if (!StringUtil.Equals(tagName, RESERVED_SECTION_CONFIGURATION_BUILDERS) || sectionType != ConfigurationBuildersSectionType) {
throw new ConfigurationErrorsException(SR.GetString(SR.Config_tag_name_cannot_begin_with_config), xmlUtil);
}
}
string configKey = CombineConfigKey(parentConfigKey, tagName);
FactoryRecord factoryRecord = (FactoryRecord) factoryList[configKey];
if (factoryRecord != null) {
// Error: duplicate section declaration
xmlUtil.SchemaErrors.AddError(
new ConfigurationErrorsException(SR.GetString(SR.Config_tag_name_already_defined_at_this_level, tagName), xmlUtil),
ExceptionAction.Local);
} else {
FactoryRecord parentFactoryRecord = _parent.FindFactoryRecord(configKey, true);
if (parentFactoryRecord != null) {
configKey = parentFactoryRecord.ConfigKey;
// make sure that an ancestor has not defined a section with the same name as the group
if (parentFactoryRecord.IsGroup) {
xmlUtil.SchemaErrors.AddError(
new ConfigurationErrorsException(SR.GetString(SR.Config_tag_name_already_defined, tagName), xmlUtil),
ExceptionAction.Local);
parentFactoryRecord = null;
}
else if (!parentFactoryRecord.IsEquivalentSectionFactory(Host, typeName, allowLocation, allowDefinition, allowExeDefinition, restartOnExternalChanges, requirePermission)) {
xmlUtil.SchemaErrors.AddError(
new ConfigurationErrorsException(SR.GetString(SR.Config_tag_name_already_defined, tagName), xmlUtil),
ExceptionAction.Local);
parentFactoryRecord = null;
}
}
if (parentFactoryRecord != null) {
// Note - Clone will propagate the IsFromTrustedConfigRecord bit,
// which is what we want - if this record is a duplicate of an ancestor,
// the ancestor may be from a trusted config record.
factoryRecord = parentFactoryRecord.CloneSection(xmlUtil.Filename, lineNumber);
}
else {
factoryRecord = new FactoryRecord(
configKey,
parentConfigKey,
tagName,
typeName,
allowLocation,
allowDefinition,
allowExeDefinition,
overrideModeDefault,
restartOnExternalChanges,
requirePermission,
_flags[IsTrusted],
false, // isUndeclared
xmlUtil.Filename,
lineNumber);
}
factoryList[configKey] = factoryRecord;
}
// Add any errors we may have encountered
factoryRecord.AddErrors(xmlUtil.SchemaErrors.RetrieveAndResetLocalErrors(true));
}
}
break;
case KEYWORD_REMOVE: {
string name = null;
int lineNumber = -1;
// parse attributes
while (xmlUtil.Reader.MoveToNextAttribute()) {
if (xmlUtil.Reader.Name != KEYWORD_SECTION_NAME) {
xmlUtil.AddErrorUnrecognizedAttribute(ExceptionAction.NonSpecific);
}
name = xmlUtil.Reader.Value;
lineNumber = xmlUtil.Reader.LineNumber;
}
xmlUtil.Reader.MoveToElement();
if (xmlUtil.VerifyRequiredAttribute(
name, KEYWORD_SECTION_NAME, ExceptionAction.NonSpecific)) {
VerifySectionName(name, xmlUtil, ExceptionAction.NonSpecific, false, true);
}
}
break;
case KEYWORD_CLEAR: {
xmlUtil.VerifyNoUnrecognizedAttributes(ExceptionAction.NonSpecific);
}
break;
default:
xmlUtil.AddErrorUnrecognizedElement(ExceptionAction.NonSpecific);
xmlUtil.StrictSkipToNextElement(ExceptionAction.NonSpecific);
positionedAtNextElement = true;
break;
}
if (!positionedAtNextElement) {
// Need to read to next element, and check if an unrecognized child
// element is found.
xmlUtil.StrictReadToNextElement(ExceptionAction.NonSpecific);
// unrecognized children are not allowed in <configSections>
if (xmlUtil.Reader.Depth > depth + 1) {
xmlUtil.AddErrorUnrecognizedElement(ExceptionAction.NonSpecific);
// Lets try to backup to where we are suppose to be
while (xmlUtil.Reader.Depth > (depth + 1)) {
xmlUtil.ReadToNextElement();
}
}
}
}
}
// ExeDefinitionToEnum
//
// Translate an ExeDefinition string from the Declaration in a file
// to the appropriate enumeration
//
// Parameters:
// allowExeDefinition - string representation of value
// xmlUtil [optional] - can provide better error
//
static internal ConfigurationAllowExeDefinition
AllowExeDefinitionToEnum(string allowExeDefinition, XmlUtil xmlUtil)
{
switch (allowExeDefinition)
{
case KEYWORD_SECTION_ALLOWDEFINITION_MACHINEONLY:
return ConfigurationAllowExeDefinition.MachineOnly;
case KEYWORD_SECTION_ALLOWDEFINITION_MACHINETOAPPLICATION:
return ConfigurationAllowExeDefinition.MachineToApplication;
case KEYWORD_SECTION_ALLOWEXEDEFINITION_MACHTOROAMING:
return ConfigurationAllowExeDefinition.MachineToRoamingUser;
case KEYWORD_SECTION_ALLOWEXEDEFINITION_MACHTOLOCAL:
return ConfigurationAllowExeDefinition.MachineToLocalUser;
default:
throw new ConfigurationErrorsException(
SR.GetString(SR.Config_section_allow_exe_definition_attribute_invalid),
xmlUtil);
}
}
static internal ConfigurationAllowDefinition
AllowDefinitionToEnum(string allowDefinition, XmlUtil xmlUtil) {
switch (xmlUtil.Reader.Value) {
case KEYWORD_SECTION_ALLOWDEFINITION_EVERYWHERE:
return ConfigurationAllowDefinition.Everywhere;
case KEYWORD_SECTION_ALLOWDEFINITION_MACHINEONLY:
return ConfigurationAllowDefinition.MachineOnly;
case KEYWORD_SECTION_ALLOWDEFINITION_MACHINETOAPPLICATION:
return ConfigurationAllowDefinition.MachineToApplication;
case KEYWORD_SECTION_ALLOWDEFINITION_MACHINETOWEBROOT:
return ConfigurationAllowDefinition.MachineToWebRoot;
default:
throw new ConfigurationErrorsException(
SR.GetString(SR.Config_section_allow_definition_attribute_invalid),
xmlUtil);
}
}
static internal string CombineConfigKey(string parentConfigKey, string tagName) {
if (String.IsNullOrEmpty(parentConfigKey)) {
return tagName;
}
if (String.IsNullOrEmpty(tagName)) {
return parentConfigKey;
}
return parentConfigKey + "/" + tagName;
}
static internal void SplitConfigKey(string configKey, out string group, out string name) {
int lastSlash = configKey.LastIndexOf('/');
if (lastSlash == -1) {
group = string.Empty;
name = configKey;
}
else {
group = configKey.Substring(0, lastSlash);
name = configKey.Substring(lastSlash + 1);
}
}
[System.Diagnostics.Conditional("DBG")]
private void DebugValidateIndirectInputs(SectionRecord sectionRecord) {
if (_parent.IsRootConfig) {
return;
}
// Verify that for each indirect input, its target config path is a child path of _parent.
// That's the definition of indirect input.
for(int i = sectionRecord.IndirectLocationInputs.Count-1; i >= 0; i--) {
SectionInput input = sectionRecord.IndirectLocationInputs[i];
// Get the override mode starting from the closest input.
Debug.Assert(UrlPath.IsSubpath(_parent.ConfigPath, input.SectionXmlInfo.TargetConfigPath));
}
}
// Return the lock mode for a section as comming from parent config levels
private OverrideMode ResolveOverrideModeFromParent(string configKey, out OverrideMode childLockMode) {
// When the current record is a location config level we are a direct child of the config level of the actual
// config file inside which the location tag is. For example we have a file d:\inetpub\wwwroot\web.config which
// containts <location path="Sub"> then "this" will be the config level inside the location tag and this.Parent
// is the config level of d:\inetpub\wwwroot\web.config.
// What we will do to come up with the result is:
// 1) Try to find an existing section record somewhere above us.
// If we find an existing section record then it will have the effective value of the lock mode
// that applies to us in it's LockChidlren. We dont need to go further up once we find a section record
// as it has the lock mode of all it's parents accumulated
//
// There is one huge trick though - Location config records are different ( see begining of the func for what a location config record is )
// A location config record is not locked if the config level of the web.config file in which it lives is not locked.
// I.e. when we are looking for the effective value for a location config we have two cases
// a) There is a section record in our immediate parent ( remember our immediate parent is the config file in which we /as a location tag/ are defined )
// In this case our lock mode is not the LockChildren of this section record because this lock mode applies to child config levels in child config files
// The real lock mode for us is the Locked mode of the section record in self.
// b) There is no section record in our immediate parent - in this case the locking is the same as for normal config - LockChildren value of any section
// record we may find above us.
//
// 2) If we can't find an existing section record we have two cases again:
// a) We are at the section declaration level - at this level a section is always unlocked by definition
// If this wasnt so there would be no way to unlock a section that is locked by default
// A Location config is a bit wierd again in a sence that a location config is unlocked if its in the config file where the section is declared
// I.e. if "this" is a location record then a section is unconditionally unlocked if "this.Parent" is the section declaration level
// b) We are not at section declaration level - in this case the result is whatever the default lock mode for the section is ( remember
// that we fall back to the default since we couldnt find a section record with explicit lock mode nowhere above us)
//
// I sure hope that made some sense!
OverrideMode mode = OverrideMode.Inherit;
BaseConfigurationRecord parent = Parent;
BaseConfigurationRecord immediateParent = Parent;
childLockMode = OverrideMode.Inherit;
// Walk the hierarchy until we find an explicit setting for lock state at a config level or we reach to root
while (!parent.IsRootConfig && (mode == OverrideMode.Inherit)) {
SectionRecord sectionRecord = parent.GetSectionRecord(configKey, true);
if (sectionRecord != null) {
// Check for 1a
if (IsLocationConfig && object.ReferenceEquals(immediateParent, parent)) {
// Apply case 1a
mode = sectionRecord.Locked ? OverrideMode.Deny : OverrideMode.Allow;
// In this specific case the lock mode for our children is whatever the children of our parent should inherit
// For example imagine a web.config which has a <location path="." overrideMode="Deny"> and we open "locationSubPath" from this web.config
// The lock for the section is not Deny and will be allow ( see the code line above ). However the chidlren of this location tag
// inherit the lock that applies to the children of the web.config file itself
childLockMode = sectionRecord.LockChildren ? OverrideMode.Deny : OverrideMode.Allow;
}
else {
mode = sectionRecord.LockChildren ? OverrideMode.Deny : OverrideMode.Allow;
// When the lock mode is comming from a parent level the
// lock mode that applies to children of "this" is the same as what applies to "this"
childLockMode = mode;
}
}
parent = parent._parent;
}
// Case 2
if (mode == OverrideMode.Inherit) {
Debug.Assert(FindFactoryRecord(configKey, true) != null);
bool atDeclarationLevel = false;
OverrideMode defaultMode = FindFactoryRecord(configKey, true).OverrideModeDefault.OverrideMode;
if (IsLocationConfig) {
atDeclarationLevel = this.Parent.GetFactoryRecord(configKey, true) != null;
}
else {
atDeclarationLevel = this.GetFactoryRecord(configKey, true) != null;
}
if (!atDeclarationLevel) {
// 2b
/////////
// Lock mode for children and self is the same since the default value is comming
// from a parent level and hence - applies to both
childLockMode = mode = defaultMode;
Debug.Assert(mode != OverrideMode.Inherit); // Remember that the default is never Inherit
}
else {
// 2a
////////
// Self is always allow at section declaration level
// Child lock mode is the default value ( remember we are here because no explici mode was set anywhere above us )
mode = OverrideMode.Allow;
childLockMode = defaultMode;
}
}
// This function must return Allow or Deny
Debug.Assert(mode != OverrideMode.Inherit);
return mode;
}
protected OverrideMode GetSectionLockedMode(string configKey) {
OverrideMode dummy = OverrideMode.Inherit;
return GetSectionLockedMode(configKey, out dummy);
}
// Return the current lock mode for a section
protected OverrideMode GetSectionLockedMode(string configKey, out OverrideMode childLockMode) {
OverrideMode result = OverrideMode.Inherit;
SectionRecord sectionRecord = GetSectionRecord(configKey, true);
// If there is a section record it has the effective locking settings resolved
// There is no need to do ResolveOverrideModeFromParent because it was done in:
// 1) In EnsureSectionRecord when the section record was creteted
// 2) Right after the SectionRecord was created without initialization of the lock settings
// in this:ScanSectionsRecursive().
// As long as nobody uses EnsureSectionRecordUnsafe this method will be returning the correct
// lock value only by looking at the section record
if (sectionRecord != null) {
result = sectionRecord.Locked ? OverrideMode.Deny : OverrideMode.Allow;
childLockMode = sectionRecord.LockChildren ? OverrideMode.Deny : OverrideMode.Allow;
}
else {
result = ResolveOverrideModeFromParent(configKey, out childLockMode);
}
return result;
}
private void ScanSections(XmlUtil xmlUtil) {
ScanSectionsRecursive(xmlUtil, string.Empty, false, null, OverrideModeSetting.LocationDefault, false);
}
private void ScanSectionsRecursive(
XmlUtil xmlUtil,
string parentConfigKey,
bool inLocation,
string locationSubPath,
OverrideModeSetting overrideMode,
bool skipInChildApps) {
// discard any accumulated local errors
xmlUtil.SchemaErrors.ResetLocalErrors();
int depth;
// only move to child nodes when not on first level (we've already passed the first <configsections>)
if (parentConfigKey.Length == 0 && !inLocation) {
depth = 0;
}
else {
depth = xmlUtil.Reader.Depth;
xmlUtil.StrictReadToNextElement(ExceptionAction.NonSpecific);
}
while (xmlUtil.Reader.Depth == depth + 1) {
string tagName = xmlUtil.Reader.Name;
//
// Check for reserved elements before looking up the factory,
// which may have the same name if it is in error.
//
if (tagName == KEYWORD_CONFIGSECTIONS) {
// Error: duplicate <configSections> tag, or <configSections> not the first tag under <configuration>
xmlUtil.SchemaErrors.AddError(
new ConfigurationErrorsException(SR.GetString(SR.Config_client_config_too_many_configsections_elements, tagName), xmlUtil),
ExceptionAction.NonSpecific);
xmlUtil.StrictSkipToNextElement(ExceptionAction.NonSpecific);
continue;
}
if (tagName == KEYWORD_LOCATION) {
if (parentConfigKey.Length > 0 || inLocation) {
// Error: <location> section not at top level
xmlUtil.SchemaErrors.AddError(
new ConfigurationErrorsException(SR.GetString(SR.Config_location_location_not_allowed), xmlUtil),
ExceptionAction.Global);
xmlUtil.StrictSkipToNextElement(ExceptionAction.NonSpecific);
}
else {
// Recurse into the location section
ScanLocationSection(xmlUtil);
}
continue;
}
string configKey = CombineConfigKey(parentConfigKey, tagName);
FactoryRecord factoryRecord = FindFactoryRecord(configKey, true);
if (factoryRecord == null) {
//
// Unregistered configuration section
//
// At runtime, it is a local error to have an unrecognized section.
// By treating it as local we avoid throwing an error if the
// section is encountered within a location section, just as we treat
// other section errors in a location tag.
//
// At designtime, we do not consider it an error, so that programs
// that worked on version N config files can continue to work with
// version N+1 config files that may introduce new sections.
//
if (!ClassFlags[ClassIgnoreLocalErrors]) {
xmlUtil.SchemaErrors.AddError(
new ConfigurationErrorsException(SR.GetString(SR.Config_unrecognized_configuration_section, configKey), xmlUtil),
ExceptionAction.Local);
}
VerifySectionName(tagName, xmlUtil, ExceptionAction.Local, false);
factoryRecord = new FactoryRecord(
configKey,
parentConfigKey,
tagName,
typeof(DefaultSection).AssemblyQualifiedName,
true, // allowLocation
ConfigurationAllowDefinition.Everywhere,
ConfigurationAllowExeDefinition.MachineToRoamingUser,
OverrideModeSetting.SectionDefault,
true, // restartOnExternalChanges
true, // requirePermission
_flags[IsTrusted],
true, // isUndeclared
null,
-1);
// Add any errors we may have encountered to the factory record,
// so that child config that also refer to this unrecognized section
// get the error.
factoryRecord.AddErrors(xmlUtil.SchemaErrors.RetrieveAndResetLocalErrors(true));
// Add the factory to the list of factories
EnsureFactories()[configKey] = factoryRecord;
}
if (factoryRecord.IsGroup) {
//
// Section Group
//
if (factoryRecord.HasErrors) {
xmlUtil.StrictSkipToNextElement(ExceptionAction.NonSpecific);
}
else {
if (xmlUtil.Reader.AttributeCount > 0) {
// We allow unrecognized attributes for backward compatibility (VSWhidbey 516534)
// However, we will still throw if the unrecognized attribute is reserved.
while (xmlUtil.Reader.MoveToNextAttribute()) {
if (IsReservedAttributeName(xmlUtil.Reader.Name)) {
xmlUtil.AddErrorReservedAttribute(ExceptionAction.NonSpecific);
}
}
xmlUtil.Reader.MoveToElement(); // if on an attribute move back to the element
}
// Recurse into group definition
ScanSectionsRecursive(xmlUtil, configKey, inLocation, locationSubPath, overrideMode, skipInChildApps);
}
}
else {
//
// Section
//
configKey = factoryRecord.ConfigKey;
string fileName = xmlUtil.Filename;
int lineNumber = xmlUtil.LineNumber;
string rawXml = null;
string configSource = null;
string configSourceStreamName = null;
object configSourceStreamVersion = null;
string configBuilderName = null;
string protectionProviderName = null;
OverrideMode sectionLockMode = OverrideMode.Inherit;
OverrideMode sectionChildLockMode = OverrideMode.Inherit;
bool positionedAtNextElement = false;
bool isFileInput = (locationSubPath == null);
if (!factoryRecord.HasErrors) {
// We have a valid factoryRecord for a section
if (inLocation && factoryRecord.AllowLocation == false) {
xmlUtil.SchemaErrors.AddError(
new ConfigurationErrorsException(SR.GetString(SR.Config_section_cannot_be_used_in_location), xmlUtil),
ExceptionAction.Local);
}
// Verify correctness for file inputs.
if (isFileInput) {
// Verify that the section is unique
SectionRecord sectionRecord = GetSectionRecord(configKey, true);
if (sectionRecord != null && sectionRecord.HasFileInput) {
if (!(factoryRecord.IsIgnorable())) {
xmlUtil.SchemaErrors.AddError(
new ConfigurationErrorsException(SR.GetString(SR.Config_sections_must_be_unique), xmlUtil),
ExceptionAction.Local);
}
}
// Verify that the definition is allowed.
try {
VerifyDefinitionAllowed(factoryRecord, _configPath, xmlUtil);
}
catch (ConfigurationException ce) {
xmlUtil.SchemaErrors.AddError(ce, ExceptionAction.Local);
}
}
// Verify that section is unlocked, both for file and location inputs.
sectionLockMode = GetSectionLockedMode(configKey, out sectionChildLockMode);
if (sectionLockMode == OverrideMode.Deny) {
xmlUtil.SchemaErrors.AddError( new ConfigurationErrorsException(SR.GetString(SR.Config_section_locked), xmlUtil),
ExceptionAction.Local);
}
// check for configSource or protectionProvider
if (xmlUtil.Reader.AttributeCount >= 1) {
// First do all the attributes reading without advancing the reader.
string configSourceAttribute = xmlUtil.Reader.GetAttribute(KEYWORD_CONFIGSOURCE);
if (configSourceAttribute != null) {
try {
configSource = NormalizeConfigSource(configSourceAttribute, xmlUtil);
}
catch (ConfigurationException ce) {
xmlUtil.SchemaErrors.AddError(ce, ExceptionAction.Local);
}
if (xmlUtil.Reader.AttributeCount != 1) {
// Error: elements with configSource should not have other attributes
xmlUtil.SchemaErrors.AddError(
new ConfigurationErrorsException(SR.GetString(SR.Config_source_syntax_error), xmlUtil),
ExceptionAction.Local);
}
}
string protectionProviderAttribute = xmlUtil.Reader.GetAttribute(KEYWORD_PROTECTION_PROVIDER);
if (protectionProviderAttribute != null) {
try {
protectionProviderName = ValidateProtectionProviderAttribute(protectionProviderAttribute, xmlUtil);
}
catch (ConfigurationException ce) {
xmlUtil.SchemaErrors.AddError(ce, ExceptionAction.Local);
}
if (xmlUtil.Reader.AttributeCount != 1) {
// Error: elements with protectionProvider should not have other attributes
xmlUtil.SchemaErrors.AddError(
new ConfigurationErrorsException(SR.GetString(SR.Protection_provider_syntax_error), xmlUtil),
ExceptionAction.Local);
}
}
string configBuilderAttribute = xmlUtil.Reader.GetAttribute(KEYWORD_CONFIG_BUILDER);
if (configBuilderAttribute != null) {
try {
configBuilderName = ValidateConfigBuilderAttribute(configBuilderAttribute, xmlUtil);
}
catch (ConfigurationException ce) {
xmlUtil.SchemaErrors.AddError(ce, ExceptionAction.Local);
}
}
// The 2nd part of the configSource check requires advancing the reader.
// Please note that this part should be done only AFTER all other attributes
// checking are done.
if (configSourceAttribute != null) {
if (!xmlUtil.Reader.IsEmptyElement) {
while (xmlUtil.Reader.Read()) {
XmlNodeType t = xmlUtil.Reader.NodeType;
if (t == XmlNodeType.EndElement)
break;
if (t != XmlNodeType.Comment) {
// Error: elements with configSource should not subelements other than comments
xmlUtil.SchemaErrors.AddError(
new ConfigurationErrorsException(SR.GetString(SR.Config_source_syntax_error), xmlUtil),
ExceptionAction.Local);
if (t == XmlNodeType.Element) {
xmlUtil.StrictSkipToOurParentsEndElement(ExceptionAction.NonSpecific);
}
else {
xmlUtil.StrictSkipToNextElement(ExceptionAction.NonSpecific);
}
positionedAtNextElement = true;
break;
}
}
}
}
}
if (configSource != null) {
try {
try {
configSourceStreamName = Host.GetStreamNameForConfigSource(ConfigStreamInfo.StreamName, configSource);
}
catch (Exception e) {
throw ExceptionUtil.WrapAsConfigException(SR.GetString(SR.Config_source_invalid), e, xmlUtil);
}
ValidateUniqueConfigSource(configKey, configSourceStreamName, configSource, xmlUtil);
configSourceStreamVersion = MonitorStream(configKey, configSource, configSourceStreamName);
}
catch (ConfigurationException ex) {
xmlUtil.SchemaErrors.AddError(ex, ExceptionAction.Local);
}
}
//
// prefetch the raw xml
//
if (!xmlUtil.SchemaErrors.HasLocalErrors) {
if (configSource == null && ShouldPrefetchRawXml(factoryRecord)) {
Debug.Assert(!positionedAtNextElement, "!positionedAtNextElement");
rawXml = xmlUtil.CopySection();
if (xmlUtil.Reader.NodeType != XmlNodeType.Element) {
xmlUtil.VerifyIgnorableNodeType(ExceptionAction.NonSpecific);
xmlUtil.StrictReadToNextElement(ExceptionAction.NonSpecific);
}
positionedAtNextElement = true;
}
}
}
// Get the list of errors before advancing the reader
List<ConfigurationException> localErrors = xmlUtil.SchemaErrors.RetrieveAndResetLocalErrors(isFileInput);
// advance the reader to the next element
if (!positionedAtNextElement) {
xmlUtil.StrictSkipToNextElement(ExceptionAction.NonSpecific);
}
// Add the input either to:
// 1. The file input at the current config level, or
// 2. LocationSections, where it will be used in sub paths
bool addInput = true;
if (isFileInput) {
// If isFileInput==true, Input added will be used against this config level.
// Need to check if we need to skip it due to inheritInChildApplications.
if (ShouldSkipDueToInheritInChildApplications(skipInChildApps)) {
addInput = false;
}
}
else {
if (!_flags[SupportsLocation]) {
// Skip if we have a location input but we don't support location tag.
addInput = false;
}
}
if (addInput) {
string targetConfigPath = (locationSubPath == null) ? _configPath : null;
SectionXmlInfo sectionXmlInfo = new SectionXmlInfo(
configKey, _configPath, targetConfigPath, locationSubPath,
fileName, lineNumber, ConfigStreamInfo.StreamVersion, rawXml,
configSource, configSourceStreamName, configSourceStreamVersion,
configBuilderName, protectionProviderName, overrideMode, skipInChildApps);
if (locationSubPath == null) {
//
// Add this file input to the section record
//
// We've already checked for locked above, so use skip the second check
// and set the locked bit.
SectionRecord sectionRecord = EnsureSectionRecordUnsafe(configKey, true);
// Since we called EnsureSectionRecordUnsafe the section record does not have its lock mode resolved
// but we have it in sectionLockMode and childLockMode. Apply it now
sectionRecord.ChangeLockSettings(sectionLockMode, sectionChildLockMode);
// Note that we first apply the lock mode comming from parent levels ( the line above ) and then
// add the file input since the file input takes precedence over whats comming from parent
SectionInput fileInput = new SectionInput(sectionXmlInfo, localErrors);
sectionRecord.AddFileInput(fileInput);
}
else {
//
// Add this location input to this list of location sections
//
LocationSectionRecord locationSectionRecord = new LocationSectionRecord(sectionXmlInfo, localErrors);
EnsureLocationSections().Add(locationSectionRecord);
}
}
}
}
}
private void ScanLocationSection(XmlUtil xmlUtil) {
string locationSubPath = null;
bool inheritInChildApp = true;
int errorCountBeforeScan = xmlUtil.SchemaErrors.GlobalErrorCount;
OverrideModeSetting overrideMode = OverrideModeSetting.LocationDefault;
bool overrideModeInit = false;
// Get the location section attributes
while (xmlUtil.Reader.MoveToNextAttribute()) {
switch (xmlUtil.Reader.Name) {
case KEYWORD_LOCATION_PATH:
locationSubPath = xmlUtil.Reader.Value;
break;
case KEYWORD_LOCATION_ALLOWOVERRIDE:
// Check that allowOverride and OverrideMode werent specified at the same time
if (overrideModeInit == true){
xmlUtil.SchemaErrors.AddError(new ConfigurationErrorsException(SR.GetString(SR.Invalid_override_mode_declaration), xmlUtil), ExceptionAction.Global);
}
else {
bool value = true;
// Read the value
xmlUtil.VerifyAndGetBooleanAttribute(
ExceptionAction.Global, true, out value);
overrideMode = OverrideModeSetting.CreateFromXmlReadValue(value);
overrideModeInit = true;
}
break;
case KEYWORD_LOCATION_OVERRIDEMODE:
if (overrideModeInit == true){
xmlUtil.SchemaErrors.AddError(new ConfigurationErrorsException(SR.GetString(SR.Invalid_override_mode_declaration), xmlUtil), ExceptionAction.Global);
}
else {
overrideMode = OverrideModeSetting.CreateFromXmlReadValue(
OverrideModeSetting.ParseOverrideModeXmlValue(xmlUtil.Reader.Value, xmlUtil));
overrideModeInit = true;
}
break;
case KEYWORD_LOCATION_INHERITINCHILDAPPLICATIONS:
xmlUtil.VerifyAndGetBooleanAttribute(
ExceptionAction.Global, true, out inheritInChildApp);
break;
default:
xmlUtil.AddErrorUnrecognizedAttribute(ExceptionAction.Global);
break;
}
}
xmlUtil.Reader.MoveToElement(); // if on an attribute move back to the element
try {
locationSubPath = NormalizeLocationSubPath(locationSubPath, xmlUtil);
// VSWhidbey 535595
// See attached email in the bug. Basically, we decided to throw if we see one of these
// in machine.config or root web.config:
// <location path="." inheritInChildApplications="false" >
// <location inheritInChildApplications="false" >
//
// To detect whetherewe're machine.config or root web.config, the current fix is to use
// Host.IsDefinitionAllowed. Instead of this we should invent a new method in
// IInternalConfigHost to return whether a configPath can be part of an app or not.
// But since it's Whidbey RC "Ask Mode" I chose not to do it due to bigger code churn.
//
//
if (locationSubPath == null &&
!inheritInChildApp &&
Host.IsDefinitionAllowed(_configPath, ConfigurationAllowDefinition.MachineToWebRoot, ConfigurationAllowExeDefinition.MachineOnly)) {
throw new ConfigurationErrorsException(SR.GetString(SR.Location_invalid_inheritInChildApplications_in_machine_or_root_web_config), xmlUtil);
}
}
catch (ConfigurationErrorsException ce) {
xmlUtil.SchemaErrors.AddError(ce, ExceptionAction.Global);
}
// Skip over this location section if there are errors
if (xmlUtil.SchemaErrors.GlobalErrorCount > errorCountBeforeScan) {
xmlUtil.StrictSkipToNextElement(ExceptionAction.NonSpecific);
return;
}
// Scan elements of the location section if the path is the current path.
// We do not add <location path="." /> to the _locationSections list.
if (locationSubPath == null) {
ScanSectionsRecursive(xmlUtil, string.Empty, true, null, overrideMode, !inheritInChildApp);
return;
}
// Skip over location sections for client config
if (!_flags[SupportsLocation]) {
xmlUtil.StrictSkipToNextElement(ExceptionAction.NonSpecific);
return;
}
// WOS 1955773: (Perf) 4,000 location sections in web.config file degrades working set
// Skip over location sections that don't apply to this (application) host
// WOS 1983387: do this for the runtime record only. It's a valid scenario for
// mgt config record
IInternalConfigHost host = Host;
if ((this is RuntimeConfigurationRecord) && host != null && locationSubPath.Length != 0 && locationSubPath[0] != '.') {
// The application's config path is global to the AppDomain
if (s_appConfigPath == null) {
object ctx = ConfigContext;
if (ctx != null) {
string appConfigPath = ctx.ToString();
Interlocked.CompareExchange(ref s_appConfigPath, appConfigPath, null);
}
}
// If targetConfigPath is not upstream or downstream of the application's config path,
// skip this location section.
//
// Example #1: <location path="Site1"> has a targetConfigPath of "machine/webroot/1". This applies
// to Site1, whose application config path is "machine/webroot/1", but it does not apply
// to Site2, whose application config path is "machine/webroot/2"
//
// Example #2: <location path="subdir"> has a targetConfigPath of "machine/webroot/1/root/subdir".
// This applies to an application with an application config path of "machine/webroot/1/root/subdir/app".
//
string targetConfigPath = host.GetConfigPathFromLocationSubPath(_configPath, locationSubPath);
if (!StringUtil.StartsWithIgnoreCase(s_appConfigPath, targetConfigPath)
&& !StringUtil.StartsWithIgnoreCase(targetConfigPath, s_appConfigPath)) {
xmlUtil.StrictSkipToNextElement(ExceptionAction.NonSpecific);
return;
}
}
AddLocation(locationSubPath);
ScanSectionsRecursive(xmlUtil, string.Empty, true, locationSubPath, overrideMode, !inheritInChildApp);
}
// AddLocation
//
// If you wish to keep track of the Location Fields, then use this
//
protected virtual void AddLocation(string LocationSubPath) {}
//
// Resolve information about a location section at the time that the location section
// is being used by child configuration records. This allows us to:
// * Delay determining the configuration path for the location record until the sites section is available.
// * Delay reporting bad location paths until the location record has to be used.
//
private void ResolveLocationSections() {
if (!_flags[IsLocationListResolved]) {
// Resolve outside of any lock
if (!_parent.IsRootConfig) {
_parent.ResolveLocationSections();
}
lock (this) {
if (!_flags[IsLocationListResolved]) {
if (_locationSections != null) {
//
// Create dictionary that maps configPaths to (dictionary that maps sectionNames to locationSectionRecords)
//
HybridDictionary locationConfigPaths = new HybridDictionary(true);
foreach (LocationSectionRecord locationSectionRecord in _locationSections) {
//
// Resolve the target config path
//
string targetConfigPath = Host.GetConfigPathFromLocationSubPath(_configPath, locationSectionRecord.SectionXmlInfo.SubPath);
locationSectionRecord.SectionXmlInfo.TargetConfigPath = targetConfigPath;
//
// Check uniqueness
//
HybridDictionary locationSectionRecordDictionary = (HybridDictionary) locationConfigPaths[targetConfigPath];
if (locationSectionRecordDictionary == null) {
locationSectionRecordDictionary = new HybridDictionary(false);
locationConfigPaths.Add(targetConfigPath, locationSectionRecordDictionary);
}
LocationSectionRecord duplicateRecord = (LocationSectionRecord) locationSectionRecordDictionary[locationSectionRecord.ConfigKey];
FactoryRecord factoryRecord = null;
if (duplicateRecord == null) {
locationSectionRecordDictionary.Add(locationSectionRecord.ConfigKey, locationSectionRecord);
}
else {
factoryRecord = FindFactoryRecord(locationSectionRecord.ConfigKey, true);
if (factoryRecord == null || !(factoryRecord.IsIgnorable())) {
if (!duplicateRecord.HasErrors) {
duplicateRecord.AddError(
new ConfigurationErrorsException(
SR.GetString(SR.Config_sections_must_be_unique),
duplicateRecord.SectionXmlInfo));
}
locationSectionRecord.AddError(
new ConfigurationErrorsException(
SR.GetString(SR.Config_sections_must_be_unique),
locationSectionRecord.SectionXmlInfo));
}
}
//
// Check if the definition is allowed
//
if (factoryRecord == null)
factoryRecord = FindFactoryRecord(locationSectionRecord.ConfigKey, true);
if (!factoryRecord.HasErrors) {
try {
VerifyDefinitionAllowed(factoryRecord, targetConfigPath, locationSectionRecord.SectionXmlInfo);
}
catch (ConfigurationException e) {
locationSectionRecord.AddError(e);
}
}
}
//
// Check location section for being locked.
//
BaseConfigurationRecord parent = _parent;
while (!parent.IsRootConfig) {
foreach (LocationSectionRecord locationSectionRecord in this._locationSections) {
bool locked = false;
//
// It is an error if a parent section with the same configKey is locked.
//
SectionRecord sectionRecord = parent.GetSectionRecord(locationSectionRecord.ConfigKey, true);
if ( sectionRecord != null &&
(sectionRecord.LockChildren || sectionRecord.Locked)) {
locked = true;
}
else {
//
// It is an error if a parent configuration file locks a section for the
// locationConfigPath or any sub-path of the locationConfigPath.
//
if (parent._locationSections != null) {
string targetConfigPath = locationSectionRecord.SectionXmlInfo.TargetConfigPath;
foreach (LocationSectionRecord parentLocationSectionRecord in parent._locationSections) {
string parentTargetConfigPath = parentLocationSectionRecord.SectionXmlInfo.TargetConfigPath;
if ( parentLocationSectionRecord.SectionXmlInfo.OverrideModeSetting.IsLocked &&
locationSectionRecord.ConfigKey == parentLocationSectionRecord.ConfigKey &&
UrlPath.IsEqualOrSubpath(targetConfigPath, parentTargetConfigPath)) {
locked = true;
break;
}
}
}
}
if (locked) {
locationSectionRecord.AddError(new ConfigurationErrorsException(
SR.GetString(SR.Config_section_locked),
locationSectionRecord.SectionXmlInfo));
}
}
parent = parent._parent;
}
}
}
_flags[IsLocationListResolved] = true;
}
}
}
// VerifyDefinitionAllowed
//
// Verify that the Definition is allowed at this
// place.
//
// For example, if this config record is an application then
// make sure the section say's it can be defined in an
// application
//
private void VerifyDefinitionAllowed(FactoryRecord factoryRecord, string configPath, IConfigErrorInfo errorInfo) {
Host.VerifyDefinitionAllowed(configPath, factoryRecord.AllowDefinition, factoryRecord.AllowExeDefinition, errorInfo);
}
internal bool IsDefinitionAllowed(ConfigurationAllowDefinition allowDefinition, ConfigurationAllowExeDefinition allowExeDefinition) {
return Host.IsDefinitionAllowed(_configPath, allowDefinition, allowExeDefinition);
}
static protected void VerifySectionName(string name, XmlUtil xmlUtil, ExceptionAction action, bool allowImplicit, bool allowConfigNames = false) {
try {
VerifySectionName(name, (IConfigErrorInfo) xmlUtil, allowImplicit, allowConfigNames);
}
catch (ConfigurationErrorsException ce) {
xmlUtil.SchemaErrors.AddError(ce, action);
}
}
// Check if the section name contains reserved words from the config system,
// and is a valid name for an XML Element.
static protected void VerifySectionName(string name, IConfigErrorInfo errorInfo, bool allowImplicit, bool allowConfigNames = false) {
if (String.IsNullOrEmpty(name)) {
throw new ConfigurationErrorsException(SR.GetString(SR.Config_tag_name_invalid), errorInfo);
}
// must be a valid name in xml, so that it can be used as an element
// n.b. - it also excludes forward slash '/'
try {
XmlConvert.VerifyName(name);
}
// Do not let the exception propagate as an XML exception,
// for we want errors in the section name to be treated as local errors,
// not global ones.
catch (Exception e) {
throw ExceptionUtil.WrapAsConfigException(SR.GetString(SR.Config_tag_name_invalid), e, errorInfo);
}
if (IsImplicitSection(name)) {
if (allowImplicit) {
// avoid test below for strings starting with "config"
return;
}
else {
throw new ConfigurationErrorsException(SR.GetString(SR.Cannot_declare_or_remove_implicit_section, name), errorInfo);
}
}
if (!allowConfigNames && StringUtil.StartsWith(name, "config")) {
throw new ConfigurationErrorsException(SR.GetString(SR.Config_tag_name_cannot_begin_with_config), errorInfo);
}
if (name == KEYWORD_LOCATION) {
throw new ConfigurationErrorsException(SR.GetString(SR.Config_tag_name_cannot_be_location), errorInfo);
}
}
/*
From http://www.w3.org/Addressing/
reserved = ';' | '/' | '?' | ':' | '@' | '&' | '=' | '+' | '$' | ','
From Platform SDK
reserved = '\' | '/' | '|' | ':' | '"' | '<' | '>'
*/
// NOTE: If you change these strings, you must change the associated error message
const string invalidFirstSubPathCharacters = @"\./";
const string invalidLastSubPathCharacters = @"\./";
const string invalidSubPathCharactersString = @"\?:*""<>|";
static char[] s_invalidSubPathCharactersArray = invalidSubPathCharactersString.ToCharArray();
// Return null if the subPath represents the current directory, for example:
// path=""
// path=" "
// path="."
// path="./"
internal static string NormalizeLocationSubPath(string subPath, IConfigErrorInfo errorInfo) {
// if subPath is null or empty, it is the current dir
if (String.IsNullOrEmpty(subPath))
return null;
// if subPath=".", it is the current dir
if (subPath == ".")
return null;
// do not allow whitespace in front of subPath, as the OS
// handles beginning and trailing whitespace inconsistently
string trimmedSubPath = subPath.TrimStart();
if (trimmedSubPath.Length != subPath.Length) {
throw new ConfigurationErrorsException(SR.GetString(SR.Config_location_path_invalid_first_character), errorInfo);
}
// do not allow problematic starting characters
if (invalidFirstSubPathCharacters.IndexOf(subPath[0]) != -1) {
throw new ConfigurationErrorsException(SR.GetString(SR.Config_location_path_invalid_first_character), errorInfo);
}
// do not allow whitespace at end of subPath, as the OS
// handles beginning and trailing whitespace inconsistently
trimmedSubPath = subPath.TrimEnd();
if (trimmedSubPath.Length != subPath.Length) {
throw new ConfigurationErrorsException(SR.GetString(SR.Config_location_path_invalid_last_character), errorInfo);
}
// the file system ignores trailing '.', '\', or '/', so do not allow it in a location subpath specification
if (invalidLastSubPathCharacters.IndexOf(subPath[subPath.Length-1]) != -1) {
throw new ConfigurationErrorsException(SR.GetString(SR.Config_location_path_invalid_last_character), errorInfo);
}
// combination of URI reserved characters and OS invalid filename characters, minus / (allowed reserved character)
if (subPath.IndexOfAny(s_invalidSubPathCharactersArray) != -1) {
throw new ConfigurationErrorsException(SR.GetString(SR.Config_location_path_invalid_character), errorInfo);
}
return subPath;
}
//
// Return the SectionRecord for a section.
// If the record does not exist, return null.
// Throw cached errors if the section is in error and permitErrors == false.
//
protected SectionRecord GetSectionRecord(string configKey, bool permitErrors) {
SectionRecord sectionRecord;
if (_sectionRecords != null) {
sectionRecord = (SectionRecord) _sectionRecords[configKey];
}
else {
sectionRecord = null;
}
if (sectionRecord != null && !permitErrors) {
sectionRecord.ThrowOnErrors();
}
return sectionRecord;
}
// Return an existing SectionRecord, or create one if one does not exist.
// Propagate the Locked bit from parent
protected SectionRecord EnsureSectionRecord(string configKey, bool permitErrors) {
return EnsureSectionRecordImpl(configKey, permitErrors, true);
}
// Return an existing SectionRecord, or create one if one does not exist.
// Do not propagate the Locked bit from parent, because caller will check
// himself later.
protected SectionRecord EnsureSectionRecordUnsafe(string configKey, bool permitErrors) {
return EnsureSectionRecordImpl(configKey, permitErrors, false);
}
// Return an existing SectionRecord, or create one if one does not exist.
// If desired, set the lock settings based on parent configs.
private SectionRecord EnsureSectionRecordImpl(string configKey, bool permitErrors, bool setLockSettings) {
SectionRecord sectionRecord = GetSectionRecord(configKey, permitErrors);
if (sectionRecord == null) {
lock (this) {
if (_sectionRecords == null) {
_sectionRecords = new Hashtable();
}
else {
sectionRecord = GetSectionRecord(configKey, permitErrors);
}
if (sectionRecord == null) {
sectionRecord = new SectionRecord(configKey);
_sectionRecords.Add(configKey, sectionRecord);
}
}
if (setLockSettings) {
// Get the lock mode from parent configs
OverrideMode parentMode = OverrideMode.Inherit;
OverrideMode childLockMode = OverrideMode.Inherit;
parentMode = ResolveOverrideModeFromParent(configKey, out childLockMode);
sectionRecord.ChangeLockSettings(parentMode, childLockMode);
}
}
return sectionRecord;
}
private bool HasFactoryRecords {
get {
return _factoryRecords != null;
}
}
internal FactoryRecord GetFactoryRecord(string configKey, bool permitErrors) {
FactoryRecord factoryRecord;
if (_factoryRecords == null) {
return null;
}
factoryRecord = (FactoryRecord) _factoryRecords[configKey];
if (factoryRecord != null && !permitErrors) {
factoryRecord.ThrowOnErrors();
}
return factoryRecord;
}
// Only create a _factories hashtable when necessary.
// Most config records won't have factories, so we can save 120 bytes
// per record by creating the table on demand.
protected Hashtable EnsureFactories() {
if (_factoryRecords == null) {
_factoryRecords = new Hashtable();
}
return _factoryRecords;
}
private ArrayList EnsureLocationSections() {
if (_locationSections == null) {
_locationSections = new ArrayList();
}
return _locationSections;
}
// Return true if there is no unique configuration information in this record.
internal bool IsEmpty {
get {
return
_parent != null
&& !_initErrors.HasErrors(false)
&& (_sectionRecords == null || _sectionRecords.Count == 0)
&& (_factoryRecords == null || _factoryRecords.Count == 0)
&& (_locationSections == null || _locationSections.Count == 0);
}
}
static internal string NormalizeConfigSource(string configSource, IConfigErrorInfo errorInfo) {
if (String.IsNullOrEmpty(configSource)) {
throw new ConfigurationErrorsException(SR.GetString(SR.Config_source_invalid_format), errorInfo);
}
string trimmedConfigSource = configSource.Trim();
if (trimmedConfigSource.Length != configSource.Length) {
throw new ConfigurationErrorsException(SR.GetString(SR.Config_source_invalid_format), errorInfo);
}
if (configSource.IndexOf('/') != -1) {
throw new ConfigurationErrorsException(SR.GetString(SR.Config_source_invalid_chars), errorInfo);
}
if (String.IsNullOrEmpty(configSource) || System.IO.Path.IsPathRooted(configSource)) {
throw new ConfigurationErrorsException(SR.GetString(SR.Config_source_invalid_format), errorInfo);
}
return configSource;
}
protected object MonitorStream(string configKey, string configSource, string streamname) {
lock (this) {
if (_flags[Closed]) {
return null;
}
StreamInfo streamInfo = (StreamInfo) ConfigStreamInfo.StreamInfos[streamname];
if (streamInfo != null) {
if (streamInfo.SectionName != configKey) {
throw new ConfigurationErrorsException(SR.GetString(SR.Config_source_cannot_be_shared, streamname));
}
if (streamInfo.IsMonitored) {
return streamInfo.Version;
}
}
else {
streamInfo = new StreamInfo(configKey, configSource, streamname);
ConfigStreamInfo.StreamInfos.Add(streamname, streamInfo);
}
}
//
// Call the host outside the lock to avoid deadlock.
//
object version = Host.GetStreamVersion(streamname);
StreamChangeCallback callbackDelegate = null;
lock (this) {
if (_flags[Closed]) {
return null;
}
StreamInfo streamInfo = (StreamInfo) ConfigStreamInfo.StreamInfos[streamname];
if (streamInfo.IsMonitored) {
return streamInfo.Version;
}
streamInfo.IsMonitored = true;
streamInfo.Version = version;
if (_flags[SupportsChangeNotifications]) {
if (ConfigStreamInfo.CallbackDelegate == null) {
ConfigStreamInfo.CallbackDelegate = new StreamChangeCallback(this.OnStreamChanged);
}
callbackDelegate = ConfigStreamInfo.CallbackDelegate;
}
}
if (_flags[SupportsChangeNotifications]) {
Host.StartMonitoringStreamForChanges(streamname, callbackDelegate);
}
return version;
}
private void OnStreamChanged(string streamname) {
bool notifyChanged;
StreamInfo streamInfo;
string sectionName;
lock (this) {
if (_flags[Closed])
return;
streamInfo = (StreamInfo) ConfigStreamInfo.StreamInfos[streamname];
if (streamInfo == null || !streamInfo.IsMonitored)
return;
sectionName = streamInfo.SectionName;
}
if (sectionName == null) {
notifyChanged = true;
}
else {
FactoryRecord factoryRecord = FindFactoryRecord(sectionName, false);
notifyChanged = factoryRecord.RestartOnExternalChanges;
}
if (notifyChanged) {
_configRoot.FireConfigChanged(_configPath);
}
else {
_configRoot.ClearResult(this, sectionName, false);
}
}
// ValidateUniqueConfigSource
//
// Validate that the configSource is unique for this particular
// configKey. This looks up at the parents and makes sure it is
// unique. It if is in a child, then it's check will find this
// one. If it is in a peer, then we don't care as much, since it
// will not affect Merge and UnMerge
//
// See VSWhidbey 460219 for details.
//
private void ValidateUniqueConfigSource(
string configKey, string configSourceStreamName, string configSourceArg, IConfigErrorInfo errorInfo) {
//
// Detect if another section in this file is using the same configSource
// with has a different section name.
//
lock (this) {
if (ConfigStreamInfo.HasStreamInfos) {
StreamInfo streamInfo = (StreamInfo) ConfigStreamInfo.StreamInfos[configSourceStreamName];
if (streamInfo != null && streamInfo.SectionName != configKey) {
throw new ConfigurationErrorsException(
SR.GetString(SR.Config_source_cannot_be_shared, configSourceArg),
errorInfo);
}
}
}
ValidateUniqueChildConfigSource(configKey, configSourceStreamName, configSourceArg, errorInfo);
}
protected void ValidateUniqueChildConfigSource(
string configKey, string configSourceStreamName, string configSourceArg, IConfigErrorInfo errorInfo) {
//
// Detect if a parent config file is using the same config source stream.
//
BaseConfigurationRecord current;
if (IsLocationConfig) {
current = _parent._parent;
}
else {
current = _parent;
}
while (!current.IsRootConfig) {
lock (current) {
if (current.ConfigStreamInfo.HasStreamInfos) {
StreamInfo streamInfo = (StreamInfo) current.ConfigStreamInfo.StreamInfos[configSourceStreamName];
if (streamInfo != null) {
throw new ConfigurationErrorsException(
SR.GetString(SR.Config_source_parent_conflict, configSourceArg),
errorInfo);
}
}
}
current = current.Parent;
}
}
// Recursively clear the result.
// If forceEvaluation == true, force a rescan of the config file to find
// the section.
// Requires the hierarchy lock to be acquired (hl)
internal void hlClearResultRecursive(string configKey, bool forceEvaluatation) {
SectionRecord sectionRecord;
// Refresh it's factory Record
RefreshFactoryRecord(configKey);
// Clear any stored result in the section
sectionRecord = GetSectionRecord(configKey, false);
if (sectionRecord != null) {
sectionRecord.ClearResult();
// VSWhidbey 535724: Need to clear all RawXml so that when GetSectionXmlReader
// is called later it will reload the file.
sectionRecord.ClearRawXml();
}
//
// If we need to reevaluate, add a dummy file input so
// that we open the file on the next evaluation
//
if (forceEvaluatation && !IsInitDelayed && !String.IsNullOrEmpty(ConfigStreamInfo.StreamName)) {
if (_flags[SupportsPath]) {
throw ExceptionUtil.UnexpectedError("BaseConfigurationRecord::hlClearResultRecursive");
}
FactoryRecord factoryRecord = FindFactoryRecord(configKey, false);
if (factoryRecord != null && !factoryRecord.IsGroup) {
configKey = factoryRecord.ConfigKey;
sectionRecord = EnsureSectionRecord(configKey, false);
if (!sectionRecord.HasFileInput) {
SectionXmlInfo sectionXmlInfo = new SectionXmlInfo(
configKey, _configPath, _configPath, null,
ConfigStreamInfo.StreamName, 0, null, null,
null, null, null, null,
null, OverrideModeSetting.LocationDefault, false);
SectionInput fileInput = new SectionInput(sectionXmlInfo, null);
sectionRecord.AddFileInput(fileInput);
}
}
}
// Recurse
if (_children != null) {
IEnumerable children = _children.Values;
foreach (BaseConfigurationRecord child in children) {
child.hlClearResultRecursive(configKey, forceEvaluatation);
}
}
}
// Returns a child record.
// Requires the hierarchy lock to be acquired (hl)
internal BaseConfigurationRecord hlGetChild(string configName) {
if (_children == null)
return null;
return (BaseConfigurationRecord) _children[configName];
}
// Adds a child record.
// Requires the hierarchy lock to be acquired (hl)
internal void hlAddChild(string configName, BaseConfigurationRecord child) {
if (_children == null) {
_children = new Hashtable(StringComparer.OrdinalIgnoreCase);
}
_children.Add(configName, child);
}
// Removes a child record.
// Requires the hierarchy lock to be acquired (hl)
internal void hlRemoveChild(string configName) {
if (_children != null) {
_children.Remove(configName);
}
}
// Removes true if a child record is needed for a
// child config path.
// Requires the hierarchy lock to be acquired (hl)
internal bool hlNeedsChildFor(string configName) {
// Always return true for root config record
if (IsRootConfig)
return true;
// Never create a child record when the parent has an exception.
if (HasInitErrors) {
return false;
}
string childConfigPath = ConfigPathUtility.Combine(_configPath, configName);
try {
using (Impersonate()) {
// check host if required
if (Host.IsConfigRecordRequired(childConfigPath)) {
return true;
}
}
}
catch {
// Don't allow frames up the stack to run exception filters while impersonated.
throw;
}
// see if there's a location
if (_flags[SupportsLocation]) {
BaseConfigurationRecord configRecord = this;
while (!configRecord.IsRootConfig) {
if (configRecord._locationSections != null) {
configRecord.ResolveLocationSections();
foreach (LocationSectionRecord locationSectionRecord in configRecord._locationSections) {
if (UrlPath.IsEqualOrSubpath(childConfigPath, locationSectionRecord.SectionXmlInfo.TargetConfigPath)) {
return true;
}
}
}
configRecord = configRecord._parent;
}
}
return false;
}
// Close the record. An explicit close is needed
// in order to stop monitoring streams used by
// this record. Stream monitors cause this record
// to be rooted in the GC heap.
//
// Note that we purposely do not cleanup the child/parent
// hierarchy. This is so that a config system which has
// a pointer to this record can still call GetSection on
// it while another thread closes it.
internal void CloseRecursive() {
if (!_flags[Closed]) {
bool doClose = false;
HybridDictionary streamInfos = null;
StreamChangeCallback callbackDelegate = null;
lock (this) {
if (!_flags[Closed]) {
_flags[Closed] = true;
doClose = true;
if (!IsLocationConfig && ConfigStreamInfo.HasStreamInfos) {
callbackDelegate = ConfigStreamInfo.CallbackDelegate;
streamInfos = ConfigStreamInfo.StreamInfos;
ConfigStreamInfo.CallbackDelegate = null;
ConfigStreamInfo.ClearStreamInfos();
}
}
}
if (doClose) {
// no hierarchy lock is needed to access _children here,
// as it has already been detached from the hierarchy tree
if (_children != null) {
foreach (BaseConfigurationRecord child in _children.Values) {
child.CloseRecursive();
}
}
if (streamInfos != null) {
foreach (StreamInfo streamInfo in streamInfos.Values) {
if (streamInfo.IsMonitored) {
Host.StopMonitoringStreamForChanges(streamInfo.StreamName, callbackDelegate);
streamInfo.IsMonitored = false;
}
}
}
}
}
}
internal string FindChangedConfigurationStream() {
BaseConfigurationRecord configRecord = this;
while (!configRecord.IsRootConfig) {
lock (configRecord) {
if (configRecord.ConfigStreamInfo.HasStreamInfos) {
foreach (StreamInfo streamInfo in configRecord.ConfigStreamInfo.StreamInfos.Values) {
if (streamInfo.IsMonitored && HasStreamChanged(streamInfo.StreamName, streamInfo.Version)) {
return streamInfo.StreamName;
}
}
}
}
configRecord = configRecord._parent;
}
return null;
}
private bool HasStreamChanged(string streamname, object lastVersion) {
object currentVersion = Host.GetStreamVersion(streamname);
if (lastVersion != null) {
return (currentVersion == null || !lastVersion.Equals(currentVersion));
}
else {
return currentVersion != null;
}
}
// RuntimeConfigurationRecord will override it in order to Assert Fulltrust before calling the provider.
// See VSWhidbey 429996.
protected virtual string CallHostDecryptSection(string encryptedXml, ProtectedConfigurationProvider protectionProvider, ProtectedConfigurationSection protectedConfig) {
return Host.DecryptSection(encryptedXml, protectionProvider, protectedConfig);
}
protected virtual XmlNode CallHostProcessRawXml(XmlNode rawXml, ConfigurationBuilder configBuilder) {
if (ConfigBuilderHost != null) {
return ConfigBuilderHost.ProcessRawXml(rawXml, configBuilder);
}
return rawXml;
}
protected virtual ConfigurationSection CallHostProcessConfigurationSection(ConfigurationSection configSection, ConfigurationBuilder configBuilder) {
if (ConfigBuilderHost != null) {
return ConfigBuilderHost.ProcessConfigurationSection(configSection, configBuilder);
}
return configSection;
}
static internal string ValidateConfigBuilderAttribute(string configBuilder, IConfigErrorInfo errorInfo) {
if (String.IsNullOrEmpty(configBuilder)) {
throw new ConfigurationErrorsException(SR.GetString(SR.Config_builder_invalid_format), errorInfo);
}
return configBuilder;
}
static internal string ValidateProtectionProviderAttribute(string protectionProvider, IConfigErrorInfo errorInfo) {
if (String.IsNullOrEmpty(protectionProvider)) {
throw new ConfigurationErrorsException(SR.GetString(SR.Protection_provider_invalid_format), errorInfo);
}
return protectionProvider;
}
private ConfigXmlReader DecryptConfigSection(ConfigXmlReader reader, ProtectedConfigurationProvider protectionProvider) {
ConfigXmlReader clone = reader.Clone();
IConfigErrorInfo err = (IConfigErrorInfo)clone;
string encryptedXml = null;
string clearTextXml = null;
XmlNodeType nodeType;
clone.Read();
// Save the file and line at the top of the section
string filename = err.Filename;
int lineNumber = err.LineNumber;
int sectionLineNumber = lineNumber;
if (clone.IsEmptyElement) {
throw new ConfigurationErrorsException(SR.GetString(SR.EncryptedNode_not_found), filename, lineNumber);
}
//////////////////////////////////////////////////////////
// Find the <EncryptedData> node
for (;;) {
clone.Read(); // Keep reading till we find a relavant node
nodeType = clone.NodeType;
if (nodeType == XmlNodeType.Element && clone.Name == "EncryptedData") { // Found it!
break;
}
if (nodeType == XmlNodeType.EndElement) {
throw new ConfigurationErrorsException(SR.GetString(SR.EncryptedNode_not_found), filename, lineNumber);
}
else if (nodeType != XmlNodeType.Comment && nodeType != XmlNodeType.Whitespace) {
// some other unexpected content
throw new ConfigurationErrorsException(SR.GetString(SR.EncryptedNode_is_in_invalid_format), filename, lineNumber);
}
}
//////////////////////////////////////////////////////////
// Do the decryption
// Save the line at the top of the <EncryptedData> node
lineNumber = err.LineNumber;
encryptedXml = clone.ReadOuterXml();
try {
clearTextXml = CallHostDecryptSection(encryptedXml, protectionProvider, ProtectedConfig);
} catch (Exception e) {
throw new ConfigurationErrorsException(SR.GetString(SR.Decryption_failed, protectionProvider.Name, e.Message), e, filename, lineNumber);
}
// Detect if there is any XML left over after <EncryptedData>
do {
nodeType = clone.NodeType;
if (nodeType == XmlNodeType.EndElement) {
break;
}
else if (nodeType != XmlNodeType.Comment && nodeType != XmlNodeType.Whitespace) {
// Got other unexpected content
throw new ConfigurationErrorsException(SR.GetString(SR.EncryptedNode_is_in_invalid_format), filename, lineNumber);
}
} while (clone.Read());
// Create a new reader, using the position of the original reader
return new ConfigXmlReader(clearTextXml, filename, sectionLineNumber, true);
}
private ConfigXmlReader ProcessRawXml(ConfigXmlReader reader, ConfigurationBuilder configBuilder) {
IConfigErrorInfo err = (IConfigErrorInfo)reader;
XmlNode processedXml = null;
string filename = err.Filename;
int lineNumber = err.LineNumber;
try {
XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
doc.LoadXml(reader.RawXml);
processedXml = CallHostProcessRawXml(doc.DocumentElement, configBuilder);
}
catch (Exception e) {
throw new ConfigurationErrorsException(SR.GetString(SR.ConfigBuilder_processXml_error, configBuilder.Name, e.Message), e, filename, lineNumber);
}
return new ConfigXmlReader(processedXml.OuterXml, filename, lineNumber, true);
}
// ConfigContext
//
// Retrieve the context for the config
//
internal object ConfigContext
{
get
{
if (!_flags[ContextEvaluated]) {
// Retrieve context for Path
_configContext = Host.CreateConfigurationContext(ConfigPath, LocationSubPath);
_flags[ContextEvaluated] = true;
}
return _configContext;
}
}
// ThrowIfParseErrors
//
// Throw if there were parse errors detected
//
private void ThrowIfParseErrors(ConfigurationSchemaErrors schemaErrors) {
schemaErrors.ThrowIfErrors(ClassFlags[ClassIgnoreLocalErrors]);
}
// RecordSupportsLocation
//
// Does it make sense to put use location tags in this file?
// In the web case this is true at any level. In the exe case
// this is only true for machine.config (since machine.config
// can really be used for any scenario)
//
internal bool RecordSupportsLocation {
get {
return (_flags[SupportsLocation] || IsMachineConfig);
}
}
//
// Note: Some of the per-attribute encryption stuff is moved to the end of the file to minimize
// FI merging conflicts
//
const string ConfigurationBuildersSectionTypeName = "System.Configuration.ConfigurationBuildersSection, " + AssemblyRef.SystemConfiguration;
internal const string RESERVED_SECTION_CONFIGURATION_BUILDERS = "configBuilders";
Type ConfigurationBuildersSectionType = Type.GetType(ConfigurationBuildersSectionTypeName);
const string ProtectedConfigurationSectionTypeName = "System.Configuration.ProtectedConfigurationSection, " + AssemblyRef.SystemConfiguration;
internal const string RESERVED_SECTION_PROTECTED_CONFIGURATION = "configProtectedData";
internal const string Microsoft_CONFIGURATION_SECTION = ConfigurationStringConstants.WinformsApplicationConfigurationSectionName;
const string SystemConfigurationSectionTypeName = "System.Configuration.AppSettingsSection, " + AssemblyRef.SystemConfiguration;
internal static bool IsImplicitSection(string configKey) {
if (string.Equals(configKey, RESERVED_SECTION_PROTECTED_CONFIGURATION, StringComparison.Ordinal) ||
//string.Equals(configKey, RESERVED_SECTION_CONFIGURATION_BUILDERS, StringComparison.Ordinal) ||
string.Equals(configKey, Microsoft_CONFIGURATION_SECTION, StringComparison.Ordinal)) {
return true;
}
else {
return false;
}
}
//
// Add implicit sections to the factory list.
// If factoryList == null, then add to the config record's factory list.
//
private void AddImplicitSections(Hashtable factoryList) {
// Add implicit sections to the factoryList if we're under the root
// (e.g. if we're in machine.config)
if (_parent.IsRootConfig) {
if (factoryList == null) {
factoryList = EnsureFactories();
}
FactoryRecord factoryRecord = (FactoryRecord)factoryList[RESERVED_SECTION_PROTECTED_CONFIGURATION];
// If the user has mistakenly declared an implicit section, we should leave the factoryRecord
// alone because it contains the error and the error will be thrown later.
if (factoryRecord != null) {
Debug.Assert(factoryRecord.HasErrors, "If the user has mistakenly declared an implicit section, we should have recorded an error.");
}
else {
factoryList[RESERVED_SECTION_PROTECTED_CONFIGURATION] =
new FactoryRecord(
RESERVED_SECTION_PROTECTED_CONFIGURATION, // configKey
string.Empty, // group
RESERVED_SECTION_PROTECTED_CONFIGURATION, // name
ProtectedConfigurationSectionTypeName, // factoryTypeName
true, // allowLocation
ConfigurationAllowDefinition.Everywhere, // allowDefinition
ConfigurationAllowExeDefinition.MachineToApplication, // allowExeDefinition
OverrideModeSetting.SectionDefault, // overrideModeDefault
true, // restartOnExternalChanges
true, // requirePermission
true, // isFromTrustedConfig
true, // isUndeclared
null, // filename
-1); // lineNumber
}
factoryRecord = (FactoryRecord)factoryList[Microsoft_CONFIGURATION_SECTION];
// If the user has mistakenly declared an implicit section, we should leave the factoryRecord
// alone because it contains the error and the error will be thrown later.
if (factoryRecord != null)
{
Debug.Assert(factoryRecord.HasErrors, "If the user has mistakenly declared an implicit section, we should have recorded an error.");
}
else
{
factoryList[Microsoft_CONFIGURATION_SECTION] =
new FactoryRecord(
Microsoft_CONFIGURATION_SECTION, // configKey
string.Empty, // group
Microsoft_CONFIGURATION_SECTION, // name
SystemConfigurationSectionTypeName, // factoryTypeName
true, // allowLocation
ConfigurationAllowDefinition.Everywhere, // allowDefinition
ConfigurationAllowExeDefinition.MachineToApplication, // allowExeDefinition
OverrideModeSetting.SectionDefault, // overrideModeDefault
true, // restartOnExternalChanges
true, // requirePermission
true, // isFromTrustedConfig
true, // isUndeclared
null, // filename
-1); // lineNumber
}
}
}
// We reserve all attribute names starting with config or lock
internal static bool IsReservedAttributeName(string name) {
if (StringUtil.StartsWith(name, "config") ||
StringUtil.StartsWith(name, "lock")) {
return true;
}
else {
return false;
}
}
protected class ConfigRecordStreamInfo {
private bool _hasStream; // does the stream exist?
private string _streamname; // name of the stream of this record
private object _streamVersion; // version of the stream
private Encoding _encoding; // encoding of the stream
private StreamChangeCallback _callbackDelegate; // host delegate to callback to when stream has changed
private HybridDictionary _streamInfos; // streamname -> StreamInfo. It'll also contain the main stream pointed to by _streamname
internal ConfigRecordStreamInfo() {
// default encoding
_encoding = Encoding.UTF8;
}
internal bool HasStream {
get { return _hasStream; }
set { _hasStream = value; }
}
internal string StreamName {
get { return _streamname; }
set { _streamname = value; }
}
internal object StreamVersion {
get { return _streamVersion; }
set { _streamVersion = value; }
}
internal Encoding StreamEncoding {
get { return _encoding; }
set { _encoding = value; }
}
internal StreamChangeCallback CallbackDelegate {
get { return _callbackDelegate; }
set { _callbackDelegate = value; }
}
internal HybridDictionary StreamInfos {
get {
if (_streamInfos == null) {
_streamInfos = new HybridDictionary(true);
}
return _streamInfos;
}
}
internal bool HasStreamInfos {
get { return _streamInfos != null; }
}
internal void ClearStreamInfos() {
_streamInfos = null;
}
#if DBG
// For Debugging only
internal string[] Keys {
get {
string[] keys = new string[StreamInfos.Count];
StreamInfos.Keys.CopyTo(keys, 0);
return keys;
}
}
#endif
}
private class IndirectLocationInputComparer : IComparer<SectionInput> {
public int Compare(SectionInput x, SectionInput y) {
// We have to sort the indirect inputs
// 1. First by the location tag's target config path, and if they're the same,
// 2. Then by the location tag's definition config path.
//
// In the final sorted list, a child will be smaller than a parent.
Debug.Assert(x.SectionXmlInfo.ConfigKey == y.SectionXmlInfo.ConfigKey);
if (Object.ReferenceEquals(x, y)) {
// Check if they're the same object.
return 0;
}
string xTargetConfigPath = x.SectionXmlInfo.TargetConfigPath;
string yTargetConfigPath = y.SectionXmlInfo.TargetConfigPath;
// First compare using location tag's target config path:
if (UrlPath.IsSubpath(xTargetConfigPath, yTargetConfigPath)) {
// yTargetConfigPath is a child path of xTargetConfigPath, so y < x
return 1;
}
else if (UrlPath.IsSubpath(yTargetConfigPath, xTargetConfigPath)) {
// xTargetConfigPath is a child path of yTargetConfigPath, so x < y
return -1;
}
else {
// Because all indirect inputs must be pointing to nodes along a
// single branch of config hierarchy, so if the above two cases
// aren't true, then the two target config path must be equal;
// in another word, they should not be siblings.
Debug.Assert(StringUtil.EqualsIgnoreCase(yTargetConfigPath, xTargetConfigPath));
string xDefinitionConfigPath = x.SectionXmlInfo.DefinitionConfigPath;
string yDefinitionConfigPath = y.SectionXmlInfo.DefinitionConfigPath;
// Then compare using where the location tag is defined.
if (UrlPath.IsSubpath(xDefinitionConfigPath, yDefinitionConfigPath)) {
// yDefinitionConfigPath is a child path of xDefinitionConfigPath, so y < x
return 1;
}
else if (UrlPath.IsSubpath(yDefinitionConfigPath, xDefinitionConfigPath)) {
// xDefinitionConfigPath is a child path of yDefinitionConfigPath, so x < y
return -1;
}
else {
Debug.Assert(false,
"It's not possible for two location input to come from the same config file and point to the same target");
return 0;
}
}
}
}
internal Configuration CurrentConfiguration {
get {
return _configRoot.CurrentConfiguration;
}
}
internal bool TypeStringTransformerIsSet {
get {
return (CurrentConfiguration == null) ? false : CurrentConfiguration.TypeStringTransformerIsSet;
}
}
internal bool AssemblyStringTransformerIsSet {
get {
return (CurrentConfiguration == null) ? false : CurrentConfiguration.AssemblyStringTransformerIsSet;
}
}
internal System.Func<string, string> TypeStringTransformer {
get {
return (CurrentConfiguration == null) ? null : CurrentConfiguration.TypeStringTransformer;
}
}
internal System.Func<string, string> AssemblyStringTransformer {
get {
return (CurrentConfiguration == null) ? null : CurrentConfiguration.AssemblyStringTransformer;
}
}
internal FrameworkName TargetFramework {
get {
return (CurrentConfiguration == null) ? null : CurrentConfiguration.TargetFramework;
}
}
internal Stack SectionsStack {
get {
return (CurrentConfiguration == null) ? (new Stack()) : CurrentConfiguration.SectionsStack;
}
}
}
}
|