summaryrefslogtreecommitdiffstats
path: root/source4/scripting/python/misc.i
diff options
context:
space:
mode:
authorJelmer Vernooij <jelmer@samba.org>2008-04-16 12:34:53 +0200
committerJelmer Vernooij <jelmer@samba.org>2008-04-16 12:34:53 +0200
commitf540669c48f96a65cd25edeb0c1e63bcc801dfed (patch)
tree52a06ab812e6e5cd695e1ffbe2f238c20fcde8db /source4/scripting/python/misc.i
parent7c4a45de26010996192912694e5a0a5a3d990fdc (diff)
downloadsamba-f540669c48f96a65cd25edeb0c1e63bcc801dfed.tar.gz
samba-f540669c48f96a65cd25edeb0c1e63bcc801dfed.tar.xz
samba-f540669c48f96a65cd25edeb0c1e63bcc801dfed.zip
Use library for subunit test functions.
(This used to be commit 690924dc7f43b69b9c4cfc1dd0c9c6e83d333518)
Diffstat (limited to 'source4/scripting/python/misc.i')
0 files changed, 0 insertions, 0 deletions
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546
/*
 * Copyright (C) 2004-2008  Internet Systems Consortium, Inc. ("ISC")
 * Copyright (C) 1999-2003  Internet Software Consortium.
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
 * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
 * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
 * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
 * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 * PERFORMANCE OF THIS SOFTWARE.
 */

/* $Id: server.c,v 1.520 2008/11/14 23:47:32 tbox Exp $ */

/*! \file */

#include <config.h>

#include <stdlib.h>
#include <unistd.h>

#include <isc/app.h>
#include <isc/base64.h>
#include <isc/dir.h>
#include <isc/entropy.h>
#include <isc/file.h>
#include <isc/hash.h>
#include <isc/httpd.h>
#include <isc/lex.h>
#include <isc/parseint.h>
#include <isc/portset.h>
#include <isc/print.h>
#include <isc/resource.h>
#include <isc/socket.h>
#include <isc/stdio.h>
#include <isc/string.h>
#include <isc/task.h>
#include <isc/timer.h>
#include <isc/util.h>
#include <isc/xml.h>

#include <isccfg/namedconf.h>

#include <bind9/check.h>

#include <dns/acache.h>
#include <dns/adb.h>
#include <dns/cache.h>
#include <dns/db.h>
#include <dns/dispatch.h>
#ifdef DLZ
#include <dns/dlz.h>
#endif
#include <dns/dynamic_db.h>
#include <dns/forward.h>
#include <dns/journal.h>
#include <dns/keytable.h>
#include <dns/lib.h>
#include <dns/master.h>
#include <dns/masterdump.h>
#include <dns/order.h>
#include <dns/peer.h>
#include <dns/portlist.h>
#include <dns/rbt.h>
#include <dns/rdataclass.h>
#include <dns/rdataset.h>
#include <dns/rdatastruct.h>
#include <dns/resolver.h>
#include <dns/rootns.h>
#include <dns/secalg.h>
#include <dns/stats.h>
#include <dns/tkey.h>
#include <dns/tsig.h>
#include <dns/view.h>
#include <dns/zone.h>
#include <dns/zt.h>

#include <dst/dst.h>
#include <dst/result.h>

#include <named/client.h>
#include <named/config.h>
#include <named/control.h>
#include <named/interfacemgr.h>
#include <named/log.h>
#include <named/logconf.h>
#include <named/lwresd.h>
#include <named/main.h>
#include <named/os.h>
#include <named/server.h>
#include <named/statschannel.h>
#include <named/tkeyconf.h>
#include <named/tsigconf.h>
#include <named/zoneconf.h>
#ifdef HAVE_LIBSCF
#include <named/ns_smf_globals.h>
#include <stdlib.h>
#endif

/*%
 * Check an operation for failure.  Assumes that the function
 * using it has a 'result' variable and a 'cleanup' label.
 */
#define CHECK(op) \
	do { result = (op);					 \
	       if (result != ISC_R_SUCCESS) goto cleanup;	 \
	} while (0)

#define CHECKM(op, msg) \
	do { result = (op);					  \
	       if (result != ISC_R_SUCCESS) {			  \
			isc_log_write(ns_g_lctx,		  \
				      NS_LOGCATEGORY_GENERAL,	  \
				      NS_LOGMODULE_SERVER,	  \
				      ISC_LOG_ERROR,		  \
				      "%s: %s", msg,		  \
				      isc_result_totext(result)); \
			goto cleanup;				  \
		}						  \
	} while (0)						  \

#define CHECKMF(op, msg, file) \
	do { result = (op);					  \
	       if (result != ISC_R_SUCCESS) {			  \
			isc_log_write(ns_g_lctx,		  \
				      NS_LOGCATEGORY_GENERAL,	  \
				      NS_LOGMODULE_SERVER,	  \
				      ISC_LOG_ERROR,		  \
				      "%s '%s': %s", msg, file,	  \
				      isc_result_totext(result)); \
			goto cleanup;				  \
		}						  \
	} while (0)						  \

#define CHECKFATAL(op, msg) \
	do { result = (op);					  \
	       if (result != ISC_R_SUCCESS)			  \
			fatal(msg, result);			  \
	} while (0)						  \

struct ns_dispatch {
	isc_sockaddr_t			addr;
	unsigned int			dispatchgen;
	dns_dispatch_t			*dispatch;
	ISC_LINK(struct ns_dispatch)	link;
};

struct dumpcontext {
	isc_mem_t			*mctx;
	isc_boolean_t			dumpcache;
	isc_boolean_t			dumpzones;
	FILE				*fp;
	ISC_LIST(struct viewlistentry)	viewlist;
	struct viewlistentry		*view;
	struct zonelistentry		*zone;
	dns_dumpctx_t			*mdctx;
	dns_db_t			*db;
	dns_db_t			*cache;
	isc_task_t			*task;
	dns_dbversion_t			*version;
};

struct viewlistentry {
	dns_view_t			*view;
	ISC_LINK(struct viewlistentry)	link;
	ISC_LIST(struct zonelistentry)	zonelist;
};

struct zonelistentry {
	dns_zone_t			*zone;
	ISC_LINK(struct zonelistentry)	link;
};

/*
 * These zones should not leak onto the Internet.
 */
static const struct {
	const char	*zone;
	isc_boolean_t	rfc1918;
} empty_zones[] = {
#ifdef notyet
	/* RFC 1918 */
	{ "10.IN-ADDR.ARPA", ISC_TRUE },
	{ "16.172.IN-ADDR.ARPA", ISC_TRUE },
	{ "17.172.IN-ADDR.ARPA", ISC_TRUE },
	{ "18.172.IN-ADDR.ARPA", ISC_TRUE },
	{ "19.172.IN-ADDR.ARPA", ISC_TRUE },
	{ "20.172.IN-ADDR.ARPA", ISC_TRUE },
	{ "21.172.IN-ADDR.ARPA", ISC_TRUE },
	{ "22.172.IN-ADDR.ARPA", ISC_TRUE },
	{ "23.172.IN-ADDR.ARPA", ISC_TRUE },
	{ "24.172.IN-ADDR.ARPA", ISC_TRUE },
	{ "25.172.IN-ADDR.ARPA", ISC_TRUE },
	{ "26.172.IN-ADDR.ARPA", ISC_TRUE },
	{ "27.172.IN-ADDR.ARPA", ISC_TRUE },
	{ "28.172.IN-ADDR.ARPA", ISC_TRUE },
	{ "29.172.IN-ADDR.ARPA", ISC_TRUE },
	{ "30.172.IN-ADDR.ARPA", ISC_TRUE },
	{ "31.172.IN-ADDR.ARPA", ISC_TRUE },
	{ "168.192.IN-ADDR.ARPA", ISC_TRUE },
#endif

	/* RFC 3330 */
	{ "0.IN-ADDR.ARPA", ISC_FALSE },	/* THIS NETWORK */
	{ "127.IN-ADDR.ARPA", ISC_FALSE },	/* LOOPBACK */
	{ "254.169.IN-ADDR.ARPA", ISC_FALSE },	/* LINK LOCAL */
	{ "2.0.192.IN-ADDR.ARPA", ISC_FALSE },	/* TEST NET */
	{ "255.255.255.255.IN-ADDR.ARPA", ISC_FALSE },	/* BROADCAST */

	/* Local IPv6 Unicast Addresses */
	{ "0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.IP6.ARPA", ISC_FALSE },
	{ "1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.IP6.ARPA", ISC_FALSE },
	/* LOCALLY ASSIGNED LOCAL ADDRES S SCOPE */
	{ "D.F.IP6.ARPA", ISC_FALSE },
	{ "8.E.F.IP6.ARPA", ISC_FALSE },	/* LINK LOCAL */
	{ "9.E.F.IP6.ARPA", ISC_FALSE },	/* LINK LOCAL */
	{ "A.E.F.IP6.ARPA", ISC_FALSE },	/* LINK LOCAL */
	{ "B.E.F.IP6.ARPA", ISC_FALSE },	/* LINK LOCAL */

	{ NULL, ISC_FALSE }
};

static void
fatal(const char *msg, isc_result_t result);

static void
ns_server_reload(isc_task_t *task, isc_event_t *event);

static isc_result_t
ns_listenelt_fromconfig(const cfg_obj_t *listener, const cfg_obj_t *config,
			cfg_aclconfctx_t *actx,
			isc_mem_t *mctx, ns_listenelt_t **target);
static isc_result_t
ns_listenlist_fromconfig(const cfg_obj_t *listenlist, const cfg_obj_t *config,
			 cfg_aclconfctx_t *actx,
			 isc_mem_t *mctx, ns_listenlist_t **target);

static isc_result_t
configure_forward(const cfg_obj_t *config, dns_view_t *view, dns_name_t *origin,
		  const cfg_obj_t *forwarders, const cfg_obj_t *forwardtype);

static isc_result_t
configure_alternates(const cfg_obj_t *config, dns_view_t *view,
		     const cfg_obj_t *alternates);

static isc_result_t
configure_zone(const cfg_obj_t *config, const cfg_obj_t *zconfig,
	       const cfg_obj_t *vconfig, isc_mem_t *mctx, dns_view_t *view,
	       cfg_aclconfctx_t *aclconf);

static void
end_reserved_dispatches(ns_server_t *server, isc_boolean_t all);

/*%
 * Configure a single view ACL at '*aclp'.  Get its configuration by
 * calling 'getvcacl' (for per-view configuration) and maybe 'getscacl'
 * (for a global default).
 */
static isc_result_t
configure_view_acl(const cfg_obj_t *vconfig, const cfg_obj_t *config,
		   const char *aclname, cfg_aclconfctx_t *actx,
		   isc_mem_t *mctx, dns_acl_t **aclp)
{
	isc_result_t result;
	const cfg_obj_t *maps[3];
	const cfg_obj_t *aclobj = NULL;
	int i = 0;

	if (*aclp != NULL)
		dns_acl_detach(aclp);
	if (vconfig != NULL)
		maps[i++] = cfg_tuple_get(vconfig, "options");
	if (config != NULL) {
		const cfg_obj_t *options = NULL;
		(void)cfg_map_get(config, "options", &options);
		if (options != NULL)
			maps[i++] = options;
	}
	maps[i] = NULL;

	(void)ns_config_get(maps, aclname, &aclobj);
	if (aclobj == NULL)
		/*
		 * No value available.	*aclp == NULL.
		 */
		return (ISC_R_SUCCESS);

	result = cfg_acl_fromconfig(aclobj, config, ns_g_lctx,
				    actx, mctx, 0, aclp);

	return (result);
}


/*%
 * Configure a sortlist at '*aclp'.  Essentially the same as
 * configure_view_acl() except it calls cfg_acl_fromconfig with a
 * nest_level value of 2.
 */
static isc_result_t
configure_view_sortlist(const cfg_obj_t *vconfig, const cfg_obj_t *config,
			cfg_aclconfctx_t *actx, isc_mem_t *mctx,
			dns_acl_t **aclp)
{
	isc_result_t result;
	const cfg_obj_t *maps[3];
	const cfg_obj_t *aclobj = NULL;
	int i = 0;

	if (*aclp != NULL)
		dns_acl_detach(aclp);
	if (vconfig != NULL)
		maps[i++] = cfg_tuple_get(vconfig, "options");
	if (config != NULL) {
		const cfg_obj_t *options = NULL;
		(void)cfg_map_get(config, "options", &options);
		if (options != NULL)
			maps[i++] = options;
	}
	maps[i] = NULL;

	(void)ns_config_get(maps, "sortlist", &aclobj);
	if (aclobj == NULL)
		return (ISC_R_SUCCESS);

	/*
	 * Use a nest level of 3 for the "top level" of the sortlist;
	 * this means each entry in the top three levels will be stored
	 * as lists of separate, nested ACLs, rather than merged together
	 * into IP tables as is usually done with ACLs.
	 */
	result = cfg_acl_fromconfig(aclobj, config, ns_g_lctx,
				    actx, mctx, 3, aclp);

	return (result);
}

static isc_result_t
configure_view_dnsseckey(const cfg_obj_t *vconfig, const cfg_obj_t *key,
			 dns_keytable_t *keytable, isc_mem_t *mctx)
{
	dns_rdataclass_t viewclass;
	dns_rdata_dnskey_t keystruct;
	isc_uint32_t flags, proto, alg;
	const char *keystr, *keynamestr;
	unsigned char keydata[4096];
	isc_buffer_t keydatabuf;
	unsigned char rrdata[4096];
	isc_buffer_t rrdatabuf;
	isc_region_t r;
	dns_fixedname_t fkeyname;
	dns_name_t *keyname;
	isc_buffer_t namebuf;
	isc_result_t result;
	dst_key_t *dstkey = NULL;

	flags = cfg_obj_asuint32(cfg_tuple_get(key, "flags"));
	proto = cfg_obj_asuint32(cfg_tuple_get(key, "protocol"));
	alg = cfg_obj_asuint32(cfg_tuple_get(key, "algorithm"));
	keyname = dns_fixedname_name(&fkeyname);
	keynamestr = cfg_obj_asstring(cfg_tuple_get(key, "name"));

	if (vconfig == NULL)
		viewclass = dns_rdataclass_in;
	else {
		const cfg_obj_t *classobj = cfg_tuple_get(vconfig, "class");
		CHECK(ns_config_getclass(classobj, dns_rdataclass_in,
					 &viewclass));
	}
	keystruct.common.rdclass = viewclass;
	keystruct.common.rdtype = dns_rdatatype_dnskey;
	/*
	 * The key data in keystruct is not dynamically allocated.
	 */
	keystruct.mctx = NULL;

	ISC_LINK_INIT(&keystruct.common, link);

	if (flags > 0xffff)
		CHECKM(ISC_R_RANGE, "key flags");
	if (proto > 0xff)
		CHECKM(ISC_R_RANGE, "key protocol");
	if (alg > 0xff)
		CHECKM(ISC_R_RANGE, "key algorithm");
	keystruct.flags = (isc_uint16_t)flags;
	keystruct.protocol = (isc_uint8_t)proto;
	keystruct.algorithm = (isc_uint8_t)alg;

	isc_buffer_init(&keydatabuf, keydata, sizeof(keydata));
	isc_buffer_init(&rrdatabuf, rrdata, sizeof(rrdata));

	keystr = cfg_obj_asstring(cfg_tuple_get(key, "key"));
	CHECK(isc_base64_decodestring(keystr, &keydatabuf));
	isc_buffer_usedregion(&keydatabuf, &r);
	keystruct.datalen = r.length;
	keystruct.data = r.base;

	if ((keystruct.algorithm == DST_ALG_RSASHA1 ||
	     keystruct.algorithm == DST_ALG_RSAMD5) &&
	    r.length > 1 && r.base[0] == 1 && r.base[1] == 3)
		cfg_obj_log(key, ns_g_lctx, ISC_LOG_WARNING,
			    "trusted key '%s' has a weak exponent",
			    keynamestr);

	CHECK(dns_rdata_fromstruct(NULL,
				   keystruct.common.rdclass,
				   keystruct.common.rdtype,
				   &keystruct, &rrdatabuf));
	dns_fixedname_init(&fkeyname);
	isc_buffer_init(&namebuf, keynamestr, strlen(keynamestr));
	isc_buffer_add(&namebuf, strlen(keynamestr));
	CHECK(dns_name_fromtext(keyname, &namebuf,
				dns_rootname, ISC_FALSE,
				NULL));
	CHECK(dst_key_fromdns(keyname, viewclass, &rrdatabuf,
			      mctx, &dstkey));

	CHECK(dns_keytable_add(keytable, &dstkey));
	INSIST(dstkey == NULL);
	return (ISC_R_SUCCESS);

 cleanup:
	if (result == DST_R_NOCRYPTO) {
		cfg_obj_log(key, ns_g_lctx, ISC_LOG_ERROR,
			    "ignoring trusted key for '%s': no crypto support",
			    keynamestr);
		result = ISC_R_SUCCESS;
	} else {
		cfg_obj_log(key, ns_g_lctx, ISC_LOG_ERROR,
			    "configuring trusted key for '%s': %s",
			    keynamestr, isc_result_totext(result));
		result = ISC_R_FAILURE;
	}

	if (dstkey != NULL)
		dst_key_free(&dstkey);

	return (result);
}

/*%
 * Configure DNSSEC keys for a view.  Currently used only for
 * the security roots.
 *
 * The per-view configuration values and the server-global defaults are read
 * from 'vconfig' and 'config'.	 The variable to be configured is '*target'.
 */
static isc_result_t
configure_view_dnsseckeys(const cfg_obj_t *vconfig, const cfg_obj_t *config,
			  isc_mem_t *mctx, dns_keytable_t **target)
{
	isc_result_t result;
	const cfg_obj_t *keys = NULL;
	const cfg_obj_t *voptions = NULL;
	const cfg_listelt_t *element, *element2;
	const cfg_obj_t *keylist;
	const cfg_obj_t *key;
	dns_keytable_t *keytable = NULL;

	CHECK(dns_keytable_create(mctx, &keytable));

	if (vconfig != NULL)
		voptions = cfg_tuple_get(vconfig, "options");

	keys = NULL;
	if (voptions != NULL)
		(void)cfg_map_get(voptions, "trusted-keys", &keys);
	if (keys == NULL)
		(void)cfg_map_get(config, "trusted-keys", &keys);

	for (element = cfg_list_first(keys);
	     element != NULL;
	     element = cfg_list_next(element))
	{
		keylist = cfg_listelt_value(element);
		for (element2 = cfg_list_first(keylist);
		     element2 != NULL;
		     element2 = cfg_list_next(element2))
		{
			key = cfg_listelt_value(element2);
			CHECK(configure_view_dnsseckey(vconfig, key,
						       keytable, mctx));
		}
	}

	dns_keytable_detach(target);
	*target = keytable; /* Transfer ownership. */
	keytable = NULL;
	result = ISC_R_SUCCESS;

 cleanup:
	return (result);
}

static isc_result_t
mustbesecure(const cfg_obj_t *mbs, dns_resolver_t *resolver)
{
	const cfg_listelt_t *element;
	const cfg_obj_t *obj;
	const char *str;
	dns_fixedname_t fixed;
	dns_name_t *name;
	isc_boolean_t value;
	isc_result_t result;
	isc_buffer_t b;

	dns_fixedname_init(&fixed);
	name = dns_fixedname_name(&fixed);
	for (element = cfg_list_first(mbs);
	     element != NULL;
	     element = cfg_list_next(element))
	{
		obj = cfg_listelt_value(element);
		str = cfg_obj_asstring(cfg_tuple_get(obj, "name"));
		isc_buffer_init(&b, str, strlen(str));
		isc_buffer_add(&b, strlen(str));
		CHECK(dns_name_fromtext(name, &b, dns_rootname,
					ISC_FALSE, NULL));
		value = cfg_obj_asboolean(cfg_tuple_get(obj, "value"));
		CHECK(dns_resolver_setmustbesecure(resolver, name, value));
	}

	result = ISC_R_SUCCESS;

 cleanup:
	return (result);
}

/*%
 * Get a dispatch appropriate for the resolver of a given view.
 */
static isc_result_t
get_view_querysource_dispatch(const cfg_obj_t **maps,
			      int af, dns_dispatch_t **dispatchp,
			      isc_boolean_t is_firstview)
{
	isc_result_t result;
	dns_dispatch_t *disp;
	isc_sockaddr_t sa;
	unsigned int attrs, attrmask;
	const cfg_obj_t *obj = NULL;
	unsigned int maxdispatchbuffers;

	/*
	 * Make compiler happy.
	 */
	result = ISC_R_FAILURE;

	switch (af) {
	case AF_INET:
		result = ns_config_get(maps, "query-source", &obj);
		INSIST(result == ISC_R_SUCCESS);
		break;
	case AF_INET6:
		result = ns_config_get(maps, "query-source-v6", &obj);
		INSIST(result == ISC_R_SUCCESS);
		break;
	default:
		INSIST(0);
	}

	sa = *(cfg_obj_assockaddr(obj));
	INSIST(isc_sockaddr_pf(&sa) == af);

	/*
	 * If we don't support this address family, we're done!
	 */
	switch (af) {
	case AF_INET:
		result = isc_net_probeipv4();
		break;
	case AF_INET6:
		result = isc_net_probeipv6();
		break;
	default:
		INSIST(0);
	}
	if (result != ISC_R_SUCCESS)
		return (ISC_R_SUCCESS);

	/*
	 * Try to find a dispatcher that we can share.
	 */
	attrs = 0;
	attrs |= DNS_DISPATCHATTR_UDP;
	switch (af) {
	case AF_INET:
		attrs |= DNS_DISPATCHATTR_IPV4;
		break;
	case AF_INET6:
		attrs |= DNS_DISPATCHATTR_IPV6;
		break;
	}
	if (isc_sockaddr_getport(&sa) == 0) {
		attrs |= DNS_DISPATCHATTR_EXCLUSIVE;
		maxdispatchbuffers = 4096;
	} else {
		INSIST(obj != NULL);
		if (is_firstview) {
			cfg_obj_log(obj, ns_g_lctx, ISC_LOG_INFO,
				    "using specific query-source port "
				    "suppresses port randomization and can be "
				    "insecure.");
		}
		maxdispatchbuffers = 1000;
	}

	attrmask = 0;
	attrmask |= DNS_DISPATCHATTR_UDP;
	attrmask |= DNS_DISPATCHATTR_TCP;
	attrmask |= DNS_DISPATCHATTR_IPV4;
	attrmask |= DNS_DISPATCHATTR_IPV6;

	disp = NULL;
	result = dns_dispatch_getudp(ns_g_dispatchmgr, ns_g_socketmgr,
				     ns_g_taskmgr, &sa, 4096,
				     maxdispatchbuffers, 32768, 16411, 16433,
				     attrs, attrmask, &disp);
	if (result != ISC_R_SUCCESS) {
		isc_sockaddr_t any;
		char buf[ISC_SOCKADDR_FORMATSIZE];

		switch (af) {
		case AF_INET:
			isc_sockaddr_any(&any);
			break;
		case AF_INET6:
			isc_sockaddr_any6(&any);
			break;
		}
		if (isc_sockaddr_equal(&sa, &any))
			return (ISC_R_SUCCESS);
		isc_sockaddr_format(&sa, buf, sizeof(buf));
		isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
			      NS_LOGMODULE_SERVER, ISC_LOG_ERROR,
			      "could not get query source dispatcher (%s)",
			      buf);
		return (result);
	}

	*dispatchp = disp;

	return (ISC_R_SUCCESS);
}

static isc_result_t
configure_order(dns_order_t *order, const cfg_obj_t *ent) {
	dns_rdataclass_t rdclass;
	dns_rdatatype_t rdtype;
	const cfg_obj_t *obj;
	dns_fixedname_t fixed;
	unsigned int mode = 0;
	const char *str;
	isc_buffer_t b;
	isc_result_t result;
	isc_boolean_t addroot;

	result = ns_config_getclass(cfg_tuple_get(ent, "class"),
				    dns_rdataclass_any, &rdclass);
	if (result != ISC_R_SUCCESS)
		return (result);

	result = ns_config_gettype(cfg_tuple_get(ent, "type"),
				   dns_rdatatype_any, &rdtype);
	if (result != ISC_R_SUCCESS)
		return (result);

	obj = cfg_tuple_get(ent, "name");
	if (cfg_obj_isstring(obj))
		str = cfg_obj_asstring(obj);
	else
		str = "*";
	addroot = ISC_TF(strcmp(str, "*") == 0);
	isc_buffer_init(&b, str, strlen(str));
	isc_buffer_add(&b, strlen(str));
	dns_fixedname_init(&fixed);
	result = dns_name_fromtext(dns_fixedname_name(&fixed), &b,
				   dns_rootname, ISC_FALSE, NULL);
	if (result != ISC_R_SUCCESS)
		return (result);

	obj = cfg_tuple_get(ent, "ordering");
	INSIST(cfg_obj_isstring(obj));
	str = cfg_obj_asstring(obj);
	if (!strcasecmp(str, "fixed"))
		mode = DNS_RDATASETATTR_FIXEDORDER;
	else if (!strcasecmp(str, "random"))
		mode = DNS_RDATASETATTR_RANDOMIZE;
	else if (!strcasecmp(str, "cyclic"))
		mode = 0;
	else
		INSIST(0);

	/*
	 * "*" should match everything including the root (BIND 8 compat).
	 * As dns_name_matcheswildcard(".", "*.") returns FALSE add a
	 * explicit entry for "." when the name is "*".
	 */
	if (addroot) {
		result = dns_order_add(order, dns_rootname,
				       rdtype, rdclass, mode);
		if (result != ISC_R_SUCCESS)
			return (result);
	}

	return (dns_order_add(order, dns_fixedname_name(&fixed),
			      rdtype, rdclass, mode));
}

static isc_result_t
configure_peer(const cfg_obj_t *cpeer, isc_mem_t *mctx, dns_peer_t **peerp) {
	isc_netaddr_t na;
	dns_peer_t *peer;
	const cfg_obj_t *obj;
	const char *str;
	isc_result_t result;
	unsigned int prefixlen;

	cfg_obj_asnetprefix(cfg_map_getname(cpeer), &na, &prefixlen);

	peer = NULL;
	result = dns_peer_newprefix(mctx, &na, prefixlen, &peer);
	if (result != ISC_R_SUCCESS)
		return (result);

	obj = NULL;
	(void)cfg_map_get(cpeer, "bogus", &obj);
	if (obj != NULL)
		CHECK(dns_peer_setbogus(peer, cfg_obj_asboolean(obj)));

	obj = NULL;
	(void)cfg_map_get(cpeer, "provide-ixfr", &obj);
	if (obj != NULL)
		CHECK(dns_peer_setprovideixfr(peer, cfg_obj_asboolean(obj)));

	obj = NULL;
	(void)cfg_map_get(cpeer, "request-ixfr", &obj);
	if (obj != NULL)
		CHECK(dns_peer_setrequestixfr(peer, cfg_obj_asboolean(obj)));

	obj = NULL;
	(void)cfg_map_get(cpeer, "request-nsid", &obj);
	if (obj != NULL)
		CHECK(dns_peer_setrequestnsid(peer, cfg_obj_asboolean(obj)));

	obj = NULL;
	(void)cfg_map_get(cpeer, "edns", &obj);
	if (obj != NULL)
		CHECK(dns_peer_setsupportedns(peer, cfg_obj_asboolean(obj)));

	obj = NULL;
	(void)cfg_map_get(cpeer, "edns-udp-size", &obj);
	if (obj != NULL) {
		isc_uint32_t udpsize = cfg_obj_asuint32(obj);
		if (udpsize < 512)
			udpsize = 512;
		if (udpsize > 4096)
			udpsize = 4096;
		CHECK(dns_peer_setudpsize(peer, (isc_uint16_t)udpsize));
	}

	obj = NULL;
	(void)cfg_map_get(cpeer, "max-udp-size", &obj);
	if (obj != NULL) {
		isc_uint32_t udpsize = cfg_obj_asuint32(obj);
		if (udpsize < 512)
			udpsize = 512;
		if (udpsize > 4096)
			udpsize = 4096;
		CHECK(dns_peer_setmaxudp(peer, (isc_uint16_t)udpsize));
	}

	obj = NULL;
	(void)cfg_map_get(cpeer, "transfers", &obj);
	if (obj != NULL)
		CHECK(dns_peer_settransfers(peer, cfg_obj_asuint32(obj)));

	obj = NULL;
	(void)cfg_map_get(cpeer, "transfer-format", &obj);
	if (obj != NULL) {
		str = cfg_obj_asstring(obj);
		if (strcasecmp(str, "many-answers") == 0)
			CHECK(dns_peer_settransferformat(peer,
							 dns_many_answers));
		else if (strcasecmp(str, "one-answer") == 0)
			CHECK(dns_peer_settransferformat(peer,
							 dns_one_answer));
		else
			INSIST(0);
	}

	obj = NULL;
	(void)cfg_map_get(cpeer, "keys", &obj);
	if (obj != NULL) {
		result = dns_peer_setkeybycharp(peer, cfg_obj_asstring(obj));
		if (result != ISC_R_SUCCESS)
			goto cleanup;
	}

	obj = NULL;
	if (na.family == AF_INET)
		(void)cfg_map_get(cpeer, "transfer-source", &obj);
	else
		(void)cfg_map_get(cpeer, "transfer-source-v6", &obj);
	if (obj != NULL) {
		result = dns_peer_settransfersource(peer,
						    cfg_obj_assockaddr(obj));
		if (result != ISC_R_SUCCESS)
			goto cleanup;
		ns_add_reserved_dispatch(ns_g_server, cfg_obj_assockaddr(obj));
	}

	obj = NULL;
	if (na.family == AF_INET)
		(void)cfg_map_get(cpeer, "notify-source", &obj);
	else
		(void)cfg_map_get(cpeer, "notify-source-v6", &obj);
	if (obj != NULL) {
		result = dns_peer_setnotifysource(peer,
						  cfg_obj_assockaddr(obj));
		if (result != ISC_R_SUCCESS)
			goto cleanup;
		ns_add_reserved_dispatch(ns_g_server, cfg_obj_assockaddr(obj));
	}

	obj = NULL;
	if (na.family == AF_INET)
		(void)cfg_map_get(cpeer, "query-source", &obj);
	else
		(void)cfg_map_get(cpeer, "query-source-v6", &obj);
	if (obj != NULL) {
		result = dns_peer_setquerysource(peer,
						 cfg_obj_assockaddr(obj));
		if (result != ISC_R_SUCCESS)
			goto cleanup;
		ns_add_reserved_dispatch(ns_g_server, cfg_obj_assockaddr(obj));
	}

	*peerp = peer;
	return (ISC_R_SUCCESS);

 cleanup:
	dns_peer_detach(&peer);
	return (result);
}

static isc_result_t
configure_dynamic_db(const cfg_obj_t *dynamic_db, isc_mem_t *mctx,
		     dns_view_t *view)
{
	isc_result_t result;
	const cfg_obj_t *obj;
	const cfg_obj_t *options;
	const cfg_listelt_t *element;
	const char *name;
	const char *libname;
	const char **argv = NULL;
	unsigned int i;
	unsigned int len;

	/* Get the name of the database. */
	obj = cfg_tuple_get(dynamic_db, "name");
	name = cfg_obj_asstring(obj);

	/* Get options. */
	options = cfg_tuple_get(dynamic_db, "options");

	/* Get library name. */
	obj = NULL;
	CHECK(cfg_map_get(options, "library", &obj));
	libname = cfg_obj_asstring(obj);

	/* Create a list of arguments. */
	obj = NULL;
	result = cfg_map_get(options, "arg", &obj);
	if (result == ISC_R_NOTFOUND)
		len = 0;
	else if (result == ISC_R_SUCCESS)
		len = cfg_list_length(obj, isc_boolean_false);
	else
		goto cleanup;

	/* Account for the last terminating NULL. */
	len++;

	argv = isc_mem_allocate(mctx, len * sizeof(const char *));
	if (argv == NULL) {
		result = ISC_R_NOMEMORY;
		goto cleanup;
	}
	for (element = cfg_list_first(obj), i = 0;
	     element != NULL;
	     element = cfg_list_next(element), i++)
	{
		REQUIRE(i < len);

		obj = cfg_listelt_value(element);
		argv[i] = cfg_obj_asstring(obj);
	}
	REQUIRE(i < len);
	argv[i] = NULL;

	CHECK(dns_dynamic_db_load(libname, name, mctx, argv, view));

cleanup:
	if (argv != NULL)
		isc_mem_free(mctx, argv);

	return result;
}


static isc_result_t
disable_algorithms(const cfg_obj_t *disabled, dns_resolver_t *resolver) {
	isc_result_t result;
	const cfg_obj_t *algorithms;
	const cfg_listelt_t *element;
	const char *str;
	dns_fixedname_t fixed;
	dns_name_t *name;
	isc_buffer_t b;

	dns_fixedname_init(&fixed);
	name = dns_fixedname_name(&fixed);
	str = cfg_obj_asstring(cfg_tuple_get(disabled, "name"));
	isc_buffer_init(&b, str, strlen(str));
	isc_buffer_add(&b, strlen(str));
	CHECK(dns_name_fromtext(name, &b, dns_rootname, ISC_FALSE, NULL));

	algorithms = cfg_tuple_get(disabled, "algorithms");
	for (element = cfg_list_first(algorithms);
	     element != NULL;
	     element = cfg_list_next(element))
	{
		isc_textregion_t r;
		dns_secalg_t alg;

		DE_CONST(cfg_obj_asstring(cfg_listelt_value(element)), r.base);
		r.length = strlen(r.base);

		result = dns_secalg_fromtext(&alg, &r);
		if (result != ISC_R_SUCCESS) {
			isc_uint8_t ui;
			result = isc_parse_uint8(&ui, r.base, 10);
			alg = ui;
		}
		if (result != ISC_R_SUCCESS) {
			cfg_obj_log(cfg_listelt_value(element),
				    ns_g_lctx, ISC_LOG_ERROR,
				    "invalid algorithm");
			CHECK(result);
		}
		CHECK(dns_resolver_disable_algorithm(resolver, name, alg));
	}
 cleanup:
	return (result);
}

static isc_boolean_t
on_disable_list(const cfg_obj_t *disablelist, dns_name_t *zonename) {
	const cfg_listelt_t *element;
	dns_fixedname_t fixed;
	dns_name_t *name;
	isc_result_t result;
	const cfg_obj_t *value;
	const char *str;
	isc_buffer_t b;

	dns_fixedname_init(&fixed);
	name = dns_fixedname_name(&fixed);

	for (element = cfg_list_first(disablelist);
	     element != NULL;
	     element = cfg_list_next(element))
	{
		value = cfg_listelt_value(element);
		str = cfg_obj_asstring(value);
		isc_buffer_init(&b, str, strlen(str));
		isc_buffer_add(&b, strlen(str));
		result = dns_name_fromtext(name, &b, dns_rootname,
					   ISC_TRUE, NULL);
		RUNTIME_CHECK(result == ISC_R_SUCCESS);
		if (dns_name_equal(name, zonename))
			return (ISC_TRUE);
	}
	return (ISC_FALSE);
}

static void
check_dbtype(dns_zone_t **zonep, unsigned int dbtypec, const char **dbargv,
	     isc_mem_t *mctx)
{
	char **argv = NULL;
	unsigned int i;
	isc_result_t result;

	result = dns_zone_getdbtype(*zonep, &argv, mctx);
	if (result != ISC_R_SUCCESS) {
		dns_zone_detach(zonep);
		return;
	}

	/*
	 * Check that all the arguments match.
	 */
	for (i = 0; i < dbtypec; i++)
		if (argv[i] == NULL || strcmp(argv[i], dbargv[i]) != 0) {
			dns_zone_detach(zonep);
			break;
		}

	/*
	 * Check that there are not extra arguments.
	 */
	if (i == dbtypec && argv[i] != NULL)
		dns_zone_detach(zonep);
	isc_mem_free(mctx, argv);
}

static isc_result_t
setquerystats(dns_zone_t *zone, isc_mem_t *mctx, isc_boolean_t on) {
	isc_result_t result;
	dns_stats_t *zoneqrystats;

	zoneqrystats = NULL;
	if (on) {
		result = dns_generalstats_create(mctx, &zoneqrystats,
						 dns_nsstatscounter_max);
		if (result != ISC_R_SUCCESS)
			return (result);
	}
	dns_zone_setrequeststats(zone, zoneqrystats);
	if (zoneqrystats != NULL)
		dns_stats_detach(&zoneqrystats);

	return (ISC_R_SUCCESS);
}

/*
 * Configure 'view' according to 'vconfig', taking defaults from 'config'
 * where values are missing in 'vconfig'.
 *
 * When configuring the default view, 'vconfig' will be NULL and the
 * global defaults in 'config' used exclusively.
 */
static isc_result_t
configure_view(dns_view_t *view, const cfg_obj_t *config,
	       const cfg_obj_t *vconfig, isc_mem_t *mctx,
	       cfg_aclconfctx_t *actx, isc_boolean_t need_hints)
{
	const cfg_obj_t *maps[4];
	const cfg_obj_t *cfgmaps[3];
	const cfg_obj_t *options = NULL;
	const cfg_obj_t *voptions = NULL;
	const cfg_obj_t *forwardtype;
	const cfg_obj_t *forwarders;
	const cfg_obj_t *alternates;
	const cfg_obj_t *zonelist;
#ifdef DLZ
	const cfg_obj_t *dlz;
	unsigned int dlzargc;
	char **dlzargv;
#endif
	const cfg_obj_t *dynamic_db_list;
	const cfg_obj_t *disabled;
	const cfg_obj_t *obj;
	const cfg_listelt_t *element;
	in_port_t port;
	dns_cache_t *cache = NULL;
	isc_result_t result;
	isc_uint32_t max_adb_size;
	isc_uint32_t max_cache_size;
	isc_uint32_t max_acache_size;
	isc_uint32_t lame_ttl;
	dns_tsig_keyring_t *ring;
	dns_view_t *pview = NULL;	/* Production view */
	isc_mem_t *cmctx;
	dns_dispatch_t *dispatch4 = NULL;
	dns_dispatch_t *dispatch6 = NULL;
	isc_boolean_t reused_cache = ISC_FALSE;
	int i;
	const char *str;
	dns_order_t *order = NULL;
	isc_uint32_t udpsize;
	unsigned int resopts = 0;
	dns_zone_t *zone = NULL;
	isc_uint32_t max_clients_per_query;
	const char *sep = ": view ";
	const char *viewname = view->name;
	const char *forview = " for view ";
	isc_boolean_t rfc1918;
	isc_boolean_t empty_zones_enable;
	const cfg_obj_t *disablelist = NULL;
	dns_stats_t *resstats = NULL;
	dns_stats_t *resquerystats = NULL;

	REQUIRE(DNS_VIEW_VALID(view));

	cmctx = NULL;

	if (config != NULL)
		(void)cfg_map_get(config, "options", &options);

	i = 0;
	if (vconfig != NULL) {
		voptions = cfg_tuple_get(vconfig, "options");
		maps[i++] = voptions;
	}
	if (options != NULL)
		maps[i++] = options;
	maps[i++] = ns_g_defaults;
	maps[i] = NULL;

	i = 0;
	if (voptions != NULL)
		cfgmaps[i++] = voptions;
	if (config != NULL)
		cfgmaps[i++] = config;
	cfgmaps[i] = NULL;

	if (!strcmp(viewname, "_default")) {
		sep = "";
		viewname = "";
		forview = "";
	}

	/*
	 * Set the view's port number for outgoing queries.
	 */
	CHECKM(ns_config_getport(config, &port), "port");
	dns_view_setdstport(view, port);

	/*
	 * Create additional cache for this view and zones under the view
	 * if explicitly enabled.
	 * XXX950 default to on.
	 */
	obj = NULL;
	(void)ns_config_get(maps, "acache-enable", &obj);
	if (obj != NULL && cfg_obj_asboolean(obj)) {
		cmctx = NULL;
		CHECK(isc_mem_create(0, 0, &cmctx));
		CHECK(dns_acache_create(&view->acache, cmctx, ns_g_taskmgr,
					ns_g_timermgr));
		isc_mem_setname(cmctx, "acache", NULL);
		isc_mem_detach(&cmctx);
	}
	if (view->acache != NULL) {
		obj = NULL;
		result = ns_config_get(maps, "acache-cleaning-interval", &obj);
		INSIST(result == ISC_R_SUCCESS);
		dns_acache_setcleaninginterval(view->acache,
					       cfg_obj_asuint32(obj) * 60);

		obj = NULL;
		result = ns_config_get(maps, "max-acache-size", &obj);
		INSIST(result == ISC_R_SUCCESS);
		if (cfg_obj_isstring(obj)) {
			str = cfg_obj_asstring(obj);
			INSIST(strcasecmp(str, "unlimited") == 0);
			max_acache_size = ISC_UINT32_MAX;
		} else {
			isc_resourcevalue_t value;

			value = cfg_obj_asuint64(obj);
			if (value > ISC_UINT32_MAX) {
				cfg_obj_log(obj, ns_g_lctx, ISC_LOG_ERROR,
					    "'max-acache-size "
					    "%" ISC_PRINT_QUADFORMAT
					    "d' is too large",
					    value);
				result = ISC_R_RANGE;
				goto cleanup;
			}
			max_acache_size = (isc_uint32_t)value;
		}
		dns_acache_setcachesize(view->acache, max_acache_size);
	}

	/*
	 * Configure the zones.
	 */
	zonelist = NULL;
	if (voptions != NULL)
		(void)cfg_map_get(voptions, "zone", &zonelist);
	else
		(void)cfg_map_get(config, "zone", &zonelist);
	for (element = cfg_list_first(zonelist);
	     element != NULL;
	     element = cfg_list_next(element))
	{
		const cfg_obj_t *zconfig = cfg_listelt_value(element);
		CHECK(configure_zone(config, zconfig, vconfig, mctx, view,
				     actx));
	}

#ifdef DLZ
	/*
	 * Create Dynamically Loadable Zone driver.
	 */
	dlz = NULL;
	if (voptions != NULL)
		(void)cfg_map_get(voptions, "dlz", &dlz);
	else
		(void)cfg_map_get(config, "dlz", &dlz);

	obj = NULL;
	if (dlz != NULL) {
		(void)cfg_map_get(cfg_tuple_get(dlz, "options"),
				  "database", &obj);
		if (obj != NULL) {
			char *s = isc_mem_strdup(mctx, cfg_obj_asstring(obj));
			if (s == NULL) {
				result = ISC_R_NOMEMORY;
				goto cleanup;
			}

			result = dns_dlzstrtoargv(mctx, s, &dlzargc, &dlzargv);
			if (result != ISC_R_SUCCESS) {
				isc_mem_free(mctx, s);
				goto cleanup;
			}

			obj = cfg_tuple_get(dlz, "name");
			result = dns_dlzcreate(mctx, cfg_obj_asstring(obj),
					       dlzargv[0], dlzargc, dlzargv,
					       &view->dlzdatabase);
			isc_mem_free(mctx, s);
			isc_mem_put(mctx, dlzargv, dlzargc * sizeof(*dlzargv));
			if (result != ISC_R_SUCCESS)
				goto cleanup;
		}
	}
#endif

	/*
	 * Configure dynamic databases.
	 */
	dynamic_db_list = NULL;
	if (voptions != NULL)
		(void)cfg_map_get(voptions, "dynamic-db", &dynamic_db_list);
	else
		(void)cfg_map_get(config, "dynamic-db", &dynamic_db_list);
	for (element = cfg_list_first(dynamic_db_list);
	     element != NULL;
	     element = cfg_list_next(element))
	{
		obj = cfg_listelt_value(element);
		CHECK(configure_dynamic_db(obj, mctx, view));
	}

	/*
	 * Configure the view's cache.  Try to reuse an existing
	 * cache if possible, otherwise create a new cache.
	 * Note that the ADB is not preserved in either case.
	 * When a matching view is found, the associated statistics are
	 * also retrieved and reused.
	 *
	 * XXX Determining when it is safe to reuse a cache is
	 * tricky.  When the view's configuration changes, the cached
	 * data may become invalid because it reflects our old
	 * view of the world.  As more view attributes become
	 * configurable, we will have to add code here to check
	 * whether they have changed in ways that could
	 * invalidate the cache.
	 */
	result = dns_viewlist_find(&ns_g_server->viewlist,
				   view->name, view->rdclass,
				   &pview);
	if (result != ISC_R_NOTFOUND && result != ISC_R_SUCCESS)
		goto cleanup;
	if (pview != NULL) {
		INSIST(pview->cache != NULL);
		isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
			      NS_LOGMODULE_SERVER, ISC_LOG_DEBUG(3),
			      "reusing existing cache");
		reused_cache = ISC_TRUE;
		dns_cache_attach(pview->cache, &cache);
		dns_view_getresstats(pview, &resstats);
		dns_view_getresquerystats(pview, &resquerystats);
		dns_view_detach(&pview);
	} else {
		CHECK(isc_mem_create(0, 0, &cmctx));
		CHECK(dns_cache_create(cmctx, ns_g_taskmgr, ns_g_timermgr,
				       view->rdclass, "rbt", 0, NULL, &cache));
		isc_mem_setname(cmctx, "cache", NULL);
	}
	dns_view_setcache(view, cache);

	/*
	 * cache-file cannot be inherited if views are present, but this
	 * should be caught by the configuration checking stage.
	 */
	obj = NULL;
	result = ns_config_get(maps, "cache-file", &obj);
	if (result == ISC_R_SUCCESS && strcmp(view->name, "_bind") != 0) {
		CHECK(dns_cache_setfilename(cache, cfg_obj_asstring(obj)));
		if (!reused_cache)
			CHECK(dns_cache_load(cache));
	}

	obj = NULL;
	result = ns_config_get(maps, "cleaning-interval", &obj);
	INSIST(result == ISC_R_SUCCESS);
	dns_cache_setcleaninginterval(cache, cfg_obj_asuint32(obj) * 60);

	obj = NULL;
	result = ns_config_get(maps, "max-cache-size", &obj);
	INSIST(result == ISC_R_SUCCESS);
	if (cfg_obj_isstring(obj)) {
		str = cfg_obj_asstring(obj);
		INSIST(strcasecmp(str, "unlimited") == 0);
		max_cache_size = ISC_UINT32_MAX;
	} else {
		isc_resourcevalue_t value;
		value = cfg_obj_asuint64(obj);
		if (value > ISC_UINT32_MAX) {
			cfg_obj_log(obj, ns_g_lctx, ISC_LOG_ERROR,
				    "'max-cache-size "
				    "%" ISC_PRINT_QUADFORMAT "d' is too large",
				    value);
			result = ISC_R_RANGE;
			goto cleanup;
		}
		max_cache_size = (isc_uint32_t)value;
	}
	dns_cache_setcachesize(cache, max_cache_size);

	dns_cache_detach(&cache);

	/*
	 * Check-names.
	 */
	obj = NULL;
	result = ns_checknames_get(maps, "response", &obj);
	INSIST(result == ISC_R_SUCCESS);

	str = cfg_obj_asstring(obj);
	if (strcasecmp(str, "fail") == 0) {
		resopts |= DNS_RESOLVER_CHECKNAMES |
			DNS_RESOLVER_CHECKNAMESFAIL;
		view->checknames = ISC_TRUE;
	} else if (strcasecmp(str, "warn") == 0) {
		resopts |= DNS_RESOLVER_CHECKNAMES;
		view->checknames = ISC_FALSE;
	} else if (strcasecmp(str, "ignore") == 0) {
		view->checknames = ISC_FALSE;
	} else
		INSIST(0);

	/*
	 * Resolver.
	 *
	 * XXXRTH  Hardwired number of tasks.
	 */
	CHECK(get_view_querysource_dispatch(maps, AF_INET, &dispatch4,
					    ISC_TF(ISC_LIST_PREV(view, link)
						   == NULL)));
	CHECK(get_view_querysource_dispatch(maps, AF_INET6, &dispatch6,
					    ISC_TF(ISC_LIST_PREV(view, link)
						   == NULL)));
	if (dispatch4 == NULL && dispatch6 == NULL) {
		UNEXPECTED_ERROR(__FILE__, __LINE__,
				 "unable to obtain neither an IPv4 nor"
				 " an IPv6 dispatch");
		result = ISC_R_UNEXPECTED;
		goto cleanup;
	}
	CHECK(dns_view_createresolver(view, ns_g_taskmgr, 31,
				      ns_g_socketmgr, ns_g_timermgr,
				      resopts, ns_g_dispatchmgr,
				      dispatch4, dispatch6));

	if (resstats == NULL) {
		CHECK(dns_generalstats_create(mctx, &resstats,
					      dns_resstatscounter_max));
	}
	dns_view_setresstats(view, resstats);
	if (resquerystats == NULL)
		CHECK(dns_rdatatypestats_create(mctx, &resquerystats));
	dns_view_setresquerystats(view, resquerystats);

	/*
	 * Set the ADB cache size to 1/8th of the max-cache-size.
	 */
	max_adb_size = 0;
	if (max_cache_size != 0) {
		max_adb_size = max_cache_size / 8;
		if (max_adb_size == 0)
			max_adb_size = 1;	/* Force minimum. */
	}
	dns_adb_setadbsize(view->adb, max_adb_size);

	/*
	 * Set resolver's lame-ttl.
	 */
	obj = NULL;
	result = ns_config_get(maps, "lame-ttl", &obj);
	INSIST(result == ISC_R_SUCCESS);
	lame_ttl = cfg_obj_asuint32(obj);
	if (lame_ttl > 1800)
		lame_ttl = 1800;
	dns_resolver_setlamettl(view->resolver, lame_ttl);

	obj = NULL;
	result = ns_config_get(maps, "zero-no-soa-ttl-cache", &obj);
	INSIST(result == ISC_R_SUCCESS);
	dns_resolver_setzeronosoattl(view->resolver, cfg_obj_asboolean(obj));

	/*
	 * Set the resolver's EDNS UDP size.
	 */
	obj = NULL;
	result = ns_config_get(maps, "edns-udp-size", &obj);
	INSIST(result == ISC_R_SUCCESS);
	udpsize = cfg_obj_asuint32(obj);
	if (udpsize < 512)
		udpsize = 512;
	if (udpsize > 4096)
		udpsize = 4096;
	dns_resolver_setudpsize(view->resolver, (isc_uint16_t)udpsize);

	/*
	 * Set the maximum UDP response size.
	 */
	obj = NULL;
	result = ns_config_get(maps, "max-udp-size", &obj);
	INSIST(result == ISC_R_SUCCESS);
	udpsize = cfg_obj_asuint32(obj);
	if (udpsize < 512)
		udpsize = 512;
	if (udpsize > 4096)
		udpsize = 4096;
	view->maxudp = udpsize;

	/*
	 * Set supported DNSSEC algorithms.
	 */
	dns_resolver_reset_algorithms(view->resolver);
	disabled = NULL;
	(void)ns_config_get(maps, "disable-algorithms", &disabled);
	if (disabled != NULL) {
		for (element = cfg_list_first(disabled);
		     element != NULL;
		     element = cfg_list_next(element))
			CHECK(disable_algorithms(cfg_listelt_value(element),
						 view->resolver));
	}

	/*
	 * A global or view "forwarders" option, if present,
	 * creates an entry for "." in the forwarding table.
	 */
	forwardtype = NULL;
	forwarders = NULL;
	(void)ns_config_get(maps, "forward", &forwardtype);
	(void)ns_config_get(maps, "forwarders", &forwarders);
	if (forwarders != NULL)
		CHECK(configure_forward(config, view, dns_rootname,
					forwarders, forwardtype));

	/*
	 * Dual Stack Servers.
	 */
	alternates = NULL;
	(void)ns_config_get(maps, "dual-stack-servers", &alternates);
	if (alternates != NULL)
		CHECK(configure_alternates(config, view, alternates));

	/*
	 * We have default hints for class IN if we need them.
	 */
	if (view->rdclass == dns_rdataclass_in && view->hints == NULL)
		dns_view_sethints(view, ns_g_server->in_roothints);

	/*
	 * If we still have no hints, this is a non-IN view with no
	 * "hints zone" configured.  Issue a warning, except if this
	 * is a root server.  Root servers never need to consult
	 * their hints, so it's no point requiring users to configure
	 * them.
	 */
	if (view->hints == NULL) {
		dns_zone_t *rootzone = NULL;
		(void)dns_view_findzone(view, dns_rootname, &rootzone);
		if (rootzone != NULL) {
			dns_zone_detach(&rootzone);
			need_hints = ISC_FALSE;
		}
		if (need_hints)
			isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
				      NS_LOGMODULE_SERVER, ISC_LOG_WARNING,
				      "no root hints for view '%s'",
				      view->name);
	}

	/*
	 * Configure the view's TSIG keys.
	 */
	ring = NULL;
	CHECK(ns_tsigkeyring_fromconfig(config, vconfig, view->mctx, &ring));
	dns_view_setkeyring(view, ring);

	/*
	 * Configure the view's peer list.
	 */
	{
		const cfg_obj_t *peers = NULL;
		const cfg_listelt_t *element;
		dns_peerlist_t *newpeers = NULL;

		(void)ns_config_get(cfgmaps, "server", &peers);
		CHECK(dns_peerlist_new(mctx, &newpeers));
		for (element = cfg_list_first(peers);
		     element != NULL;
		     element = cfg_list_next(element))
		{
			const cfg_obj_t *cpeer = cfg_listelt_value(element);
			dns_peer_t *peer;

			CHECK(configure_peer(cpeer, mctx, &peer));
			dns_peerlist_addpeer(newpeers, peer);
			dns_peer_detach(&peer);
		}
		dns_peerlist_detach(&view->peers);
		view->peers = newpeers; /* Transfer ownership. */
	}

	/*
	 *	Configure the views rrset-order.
	 */
	{
		const cfg_obj_t *rrsetorder = NULL;
		const cfg_listelt_t *element;

		(void)ns_config_get(maps, "rrset-order", &rrsetorder);
		CHECK(dns_order_create(mctx, &order));
		for (element = cfg_list_first(rrsetorder);
		     element != NULL;
		     element = cfg_list_next(element))
		{
			const cfg_obj_t *ent = cfg_listelt_value(element);

			CHECK(configure_order(order, ent));
		}
		if (view->order != NULL)
			dns_order_detach(&view->order);
		dns_order_attach(order, &view->order);
		dns_order_detach(&order);
	}
	/*
	 * Copy the aclenv object.
	 */
	dns_aclenv_copy(&view->aclenv, &ns_g_server->aclenv);

	/*
	 * Configure the "match-clients" and "match-destinations" ACL.
	 */
	CHECK(configure_view_acl(vconfig, config, "match-clients", actx,
				 ns_g_mctx, &view->matchclients));
	CHECK(configure_view_acl(vconfig, config, "match-destinations", actx,
				 ns_g_mctx, &view->matchdestinations));

	/*
	 * Configure the "match-recursive-only" option.
	 */
	obj = NULL;
	(void)ns_config_get(maps, "match-recursive-only", &obj);
	if (obj != NULL && cfg_obj_asboolean(obj))
		view->matchrecursiveonly = ISC_TRUE;
	else
		view->matchrecursiveonly = ISC_FALSE;

	/*
	 * Configure other configurable data.
	 */
	obj = NULL;
	result = ns_config_get(maps, "recursion", &obj);
	INSIST(result == ISC_R_SUCCESS);
	view->recursion = cfg_obj_asboolean(obj);

	obj = NULL;
	result = ns_config_get(maps, "auth-nxdomain", &obj);
	INSIST(result == ISC_R_SUCCESS);
	view->auth_nxdomain = cfg_obj_asboolean(obj);

	obj = NULL;
	result = ns_config_get(maps, "minimal-responses", &obj);
	INSIST(result == ISC_R_SUCCESS);
	view->minimalresponses = cfg_obj_asboolean(obj);

	obj = NULL;
	result = ns_config_get(maps, "transfer-format", &obj);
	INSIST(result == ISC_R_SUCCESS);
	str = cfg_obj_asstring(obj);
	if (strcasecmp(str, "many-answers") == 0)
		view->transfer_format = dns_many_answers;
	else if (strcasecmp(str, "one-answer") == 0)
		view->transfer_format = dns_one_answer;
	else
		INSIST(0);

	/*
	 * Set sources where additional data and CNAME/DNAME
	 * targets for authoritative answers may be found.
	 */
	obj = NULL;
	result = ns_config_get(maps, "additional-from-auth", &obj);
	INSIST(result == ISC_R_SUCCESS);
	view->additionalfromauth = cfg_obj_asboolean(obj);
	if (view->recursion && ! view->additionalfromauth) {
		cfg_obj_log(obj, ns_g_lctx, ISC_LOG_WARNING,
			    "'additional-from-auth no' is only supported "
			    "with 'recursion no'");
		view->additionalfromauth = ISC_TRUE;
	}

	obj = NULL;
	result = ns_config_get(maps, "additional-from-cache", &obj);
	INSIST(result == ISC_R_SUCCESS);
	view->additionalfromcache = cfg_obj_asboolean(obj);
	if (view->recursion && ! view->additionalfromcache) {
		cfg_obj_log(obj, ns_g_lctx, ISC_LOG_WARNING,
			    "'additional-from-cache no' is only supported "
			    "with 'recursion no'");
		view->additionalfromcache = ISC_TRUE;
	}

	/*
	 * Set "allow-query-cache", "allow-query-cache-on",
	 * "allow-recursion", and "allow-recursion-on" acls if
	 * configured in named.conf.
	 */
	CHECK(configure_view_acl(vconfig, config, "allow-query-cache",
				 actx, ns_g_mctx, &view->queryacl));
	CHECK(configure_view_acl(vconfig, config, "allow-query-cache-on",
				 actx, ns_g_mctx, &view->queryonacl));
	if (view->queryonacl == NULL)
		CHECK(configure_view_acl(NULL, ns_g_config,
					 "allow-query-cache-on", actx,
					 ns_g_mctx, &view->queryonacl));
	if (strcmp(view->name, "_bind") != 0) {
		CHECK(configure_view_acl(vconfig, config, "allow-recursion",
					 actx, ns_g_mctx,
					 &view->recursionacl));
		CHECK(configure_view_acl(vconfig, config, "allow-recursion-on",
					 actx, ns_g_mctx,
					 &view->recursiononacl));
	}

	/*
	 * "allow-query-cache" inherits from "allow-recursion" if set,
	 * otherwise from "allow-query" if set.
	 * "allow-recursion" inherits from "allow-query-cache" if set,
	 * otherwise from "allow-query" if set.
	 */
	if (view->queryacl == NULL && view->recursionacl != NULL)
		dns_acl_attach(view->recursionacl, &view->queryacl);
	if (view->queryacl == NULL)
		CHECK(configure_view_acl(vconfig, config, "allow-query",
					 actx, ns_g_mctx, &view->queryacl));
	if (view->recursionacl == NULL && view->queryacl != NULL)
		dns_acl_attach(view->queryacl, &view->recursionacl);

	/*
	 * Set default "allow-recursion", "allow-recursion-on" and
	 * "allow-query-cache" acls.
	 */
	if (view->recursionacl == NULL && view->recursion)
		CHECK(configure_view_acl(NULL, ns_g_config,
					 "allow-recursion",
					 actx, ns_g_mctx,
					 &view->recursionacl));
	if (view->recursiononacl == NULL && view->recursion)
		CHECK(configure_view_acl(NULL, ns_g_config,
					 "allow-recursion-on",
					 actx, ns_g_mctx,
					 &view->recursiononacl));
	if (view->queryacl == NULL)
		CHECK(configure_view_acl(NULL, ns_g_config,
					 "allow-query-cache", actx,
					 ns_g_mctx, &view->queryacl));

	/*
	 * Configure sortlist, if set
	 */
	CHECK(configure_view_sortlist(vconfig, config, actx, ns_g_mctx,
				      &view->sortlist));

	/*
	 * Configure default allow-transfer, allow-notify, allow-update
	 * and allow-update-forwarding ACLs, if set, so they can be
	 * inherited by zones.
	 */
	if (view->notifyacl == NULL)
		CHECK(configure_view_acl(NULL, ns_g_config,
					 "allow-notify", actx,
					 ns_g_mctx, &view->notifyacl));
	if (view->transferacl == NULL)
		CHECK(configure_view_acl(NULL, ns_g_config,
					 "allow-transfer", actx,
					 ns_g_mctx, &view->transferacl));
	if (view->updateacl == NULL)
		CHECK(configure_view_acl(NULL, ns_g_config,
					 "allow-update", actx,
					 ns_g_mctx, &view->updateacl));
	if (view->upfwdacl == NULL)
		CHECK(configure_view_acl(NULL, ns_g_config,
					 "allow-update-forwarding", actx,
					 ns_g_mctx, &view->upfwdacl));

	obj = NULL;
	result = ns_config_get(maps, "request-ixfr", &obj);
	INSIST(result == ISC_R_SUCCESS);
	view->requestixfr = cfg_obj_asboolean(obj);

	obj = NULL;
	result = ns_config_get(maps, "provide-ixfr", &obj);
	INSIST(result == ISC_R_SUCCESS);
	view->provideixfr = cfg_obj_asboolean(obj);

	obj = NULL;
	result = ns_config_get(maps, "request-nsid", &obj);
	INSIST(result == ISC_R_SUCCESS);
	view->requestnsid = cfg_obj_asboolean(obj);

	obj = NULL;
	result = ns_config_get(maps, "max-clients-per-query", &obj);
	INSIST(result == ISC_R_SUCCESS);
	max_clients_per_query = cfg_obj_asuint32(obj);

	obj = NULL;
	result = ns_config_get(maps, "clients-per-query", &obj);
	INSIST(result == ISC_R_SUCCESS);
	dns_resolver_setclientsperquery(view->resolver,
					cfg_obj_asuint32(obj),
					max_clients_per_query);

	obj = NULL;
	result = ns_config_get(maps, "dnssec-enable", &obj);
	INSIST(result == ISC_R_SUCCESS);
	view->enablednssec = cfg_obj_asboolean(obj);

	obj = NULL;
	result = ns_config_get(maps, "dnssec-accept-expired", &obj);
	INSIST(result == ISC_R_SUCCESS);
	view->acceptexpired = cfg_obj_asboolean(obj);

	obj = NULL;
	result = ns_config_get(maps, "dnssec-validation", &obj);
	INSIST(result == ISC_R_SUCCESS);
	view->enablevalidation = cfg_obj_asboolean(obj);

	obj = NULL;
	result = ns_config_get(maps, "dnssec-lookaside", &obj);
	if (result == ISC_R_SUCCESS) {
		for (element = cfg_list_first(obj);
		     element != NULL;
		     element = cfg_list_next(element))
		{
			const char *str;
			isc_buffer_t b;
			dns_name_t *dlv;

			obj = cfg_listelt_value(element);
#if 0
			dns_fixedname_t fixed;
			dns_name_t *name;

			/*
			 * When we support multiple dnssec-lookaside
			 * entries this is how to find the domain to be
			 * checked. XXXMPA
			 */
			dns_fixedname_init(&fixed);
			name = dns_fixedname_name(&fixed);
			str = cfg_obj_asstring(cfg_tuple_get(obj,
							     "domain"));
			isc_buffer_init(&b, str, strlen(str));
			isc_buffer_add(&b, strlen(str));
			CHECK(dns_name_fromtext(name, &b, dns_rootname,
						ISC_TRUE, NULL));
#endif
			str = cfg_obj_asstring(cfg_tuple_get(obj,
							     "trust-anchor"));
			isc_buffer_init(&b, str, strlen(str));
			isc_buffer_add(&b, strlen(str));
			dlv = dns_fixedname_name(&view->dlv_fixed);
			CHECK(dns_name_fromtext(dlv, &b, dns_rootname,
						ISC_TRUE, NULL));
			view->dlv = dns_fixedname_name(&view->dlv_fixed);
		}
	} else
		view->dlv = NULL;

	/*
	 * For now, there is only one kind of trusted keys, the
	 * "security roots".
	 */
	CHECK(configure_view_dnsseckeys(vconfig, config, mctx,
					&view->secroots));
	dns_resolver_resetmustbesecure(view->resolver);
	obj = NULL;
	result = ns_config_get(maps, "dnssec-must-be-secure", &obj);
	if (result == ISC_R_SUCCESS)
		CHECK(mustbesecure(obj, view->resolver));

	obj = NULL;
	result = ns_config_get(maps, "max-cache-ttl", &obj);
	INSIST(result == ISC_R_SUCCESS);
	view->maxcachettl = cfg_obj_asuint32(obj);

	obj = NULL;
	result = ns_config_get(maps, "max-ncache-ttl", &obj);
	INSIST(result == ISC_R_SUCCESS);
	view->maxncachettl = cfg_obj_asuint32(obj);
	if (view->maxncachettl > 7 * 24 * 3600)
		view->maxncachettl = 7 * 24 * 3600;

	obj = NULL;
	result = ns_config_get(maps, "preferred-glue", &obj);
	if (result == ISC_R_SUCCESS) {
		str = cfg_obj_asstring(obj);
		if (strcasecmp(str, "a") == 0)
			view->preferred_glue = dns_rdatatype_a;
		else if (strcasecmp(str, "aaaa") == 0)
			view->preferred_glue = dns_rdatatype_aaaa;
		else
			view->preferred_glue = 0;
	} else
		view->preferred_glue = 0;

	obj = NULL;
	result = ns_config_get(maps, "root-delegation-only", &obj);
	if (result == ISC_R_SUCCESS) {
		dns_view_setrootdelonly(view, ISC_TRUE);
		if (!cfg_obj_isvoid(obj)) {
			dns_fixedname_t fixed;
			dns_name_t *name;
			isc_buffer_t b;
			const char *str;
			const cfg_obj_t *exclude;

			dns_fixedname_init(&fixed);
			name = dns_fixedname_name(&fixed);
			for (element = cfg_list_first(obj);
			     element != NULL;
			     element = cfg_list_next(element)) {
				exclude = cfg_listelt_value(element);
				str = cfg_obj_asstring(exclude);
				isc_buffer_init(&b, str, strlen(str));
				isc_buffer_add(&b, strlen(str));
				CHECK(dns_name_fromtext(name, &b, dns_rootname,
							ISC_FALSE, NULL));
				CHECK(dns_view_excludedelegationonly(view,
								     name));
			}
		}
	} else
		dns_view_setrootdelonly(view, ISC_FALSE);

	/*
	 * Setup automatic empty zones.  If recursion is off then
	 * they are disabled by default.
	 */
	obj = NULL;
	(void)ns_config_get(maps, "empty-zones-enable", &obj);
	(void)ns_config_get(maps, "disable-empty-zone", &disablelist);
	if (obj == NULL && disablelist == NULL &&
	    view->rdclass == dns_rdataclass_in) {
		rfc1918 = ISC_FALSE;
		empty_zones_enable = view->recursion;
	} else if (view->rdclass == dns_rdataclass_in) {
		rfc1918 = ISC_TRUE;
		if (obj != NULL)
			empty_zones_enable = cfg_obj_asboolean(obj);
		else
			empty_zones_enable = view->recursion;
	} else {
		rfc1918 = ISC_FALSE;
		empty_zones_enable = ISC_FALSE;
	}
	if (empty_zones_enable) {
		const char *empty;
		int empty_zone = 0;
		dns_fixedname_t fixed;
		dns_name_t *name;
		isc_buffer_t buffer;
		const char *str;
		char server[DNS_NAME_FORMATSIZE + 1];
		char contact[DNS_NAME_FORMATSIZE + 1];
		isc_boolean_t logit;
		const char *empty_dbtype[4] =
				    { "_builtin", "empty", NULL, NULL };
		int empty_dbtypec = 4;
		isc_boolean_t zonestats_on;

		dns_fixedname_init(&fixed);
		name = dns_fixedname_name(&fixed);

		obj = NULL;
		result = ns_config_get(maps, "empty-server", &obj);
		if (result == ISC_R_SUCCESS) {
			str = cfg_obj_asstring(obj);
			isc_buffer_init(&buffer, str, strlen(str));
			isc_buffer_add(&buffer, strlen(str));
			CHECK(dns_name_fromtext(name, &buffer, dns_rootname,
						ISC_FALSE, NULL));
			isc_buffer_init(&buffer, server, sizeof(server) - 1);
			CHECK(dns_name_totext(name, ISC_FALSE, &buffer));
			server[isc_buffer_usedlength(&buffer)] = 0;
			empty_dbtype[2] = server;
		} else
			empty_dbtype[2] = "@";

		obj = NULL;
		result = ns_config_get(maps, "empty-contact", &obj);
		if (result == ISC_R_SUCCESS) {
			str = cfg_obj_asstring(obj);
			isc_buffer_init(&buffer, str, strlen(str));
			isc_buffer_add(&buffer, strlen(str));
			CHECK(dns_name_fromtext(name, &buffer, dns_rootname,
						ISC_FALSE, NULL));
			isc_buffer_init(&buffer, contact, sizeof(contact) - 1);
			CHECK(dns_name_totext(name, ISC_FALSE, &buffer));
			contact[isc_buffer_usedlength(&buffer)] = 0;
			empty_dbtype[3] = contact;
		} else
			empty_dbtype[3] = ".";

		obj = NULL;
		result = ns_config_get(maps, "zone-statistics", &obj);
		INSIST(result == ISC_R_SUCCESS);
		zonestats_on = cfg_obj_asboolean(obj);

		logit = ISC_TRUE;
		for (empty = empty_zones[empty_zone].zone;
		     empty != NULL;
		     empty = empty_zones[++empty_zone].zone)
		{
			dns_forwarders_t *forwarders = NULL;
			dns_view_t *pview = NULL;

			isc_buffer_init(&buffer, empty, strlen(empty));
			isc_buffer_add(&buffer, strlen(empty));
			/*
			 * Look for zone on drop list.
			 */
			CHECK(dns_name_fromtext(name, &buffer, dns_rootname,
						ISC_FALSE, NULL));
			if (disablelist != NULL &&
			    on_disable_list(disablelist, name))
				continue;

			/*
			 * This zone already exists.
			 */
			(void)dns_view_findzone(view, name, &zone);
			if (zone != NULL) {
				CHECK(setquerystats(zone, mctx, zonestats_on));
				dns_zone_detach(&zone);
				continue;
			}

			/*
			 * If we would forward this name don't add a
			 * empty zone for it.
			 */
			result = dns_fwdtable_find(view->fwdtable, name,
						   &forwarders);
			if (result == ISC_R_SUCCESS &&
			    forwarders->fwdpolicy == dns_fwdpolicy_only)
				continue;

			if (!rfc1918 && empty_zones[empty_zone].rfc1918) {
				if (logit) {
					isc_log_write(ns_g_lctx,
						      NS_LOGCATEGORY_GENERAL,
						      NS_LOGMODULE_SERVER,
						      ISC_LOG_WARNING,
						      "Warning%s%s: "
						      "'empty-zones-enable/"
						      "disable-empty-zone' "
						      "not set: disabling "
						      "RFC 1918 empty zones",
						      sep, viewname);
					logit = ISC_FALSE;
				}
				continue;
			}

			/*
			 * See if we can re-use a existing zone.
			 */
			result = dns_viewlist_find(&ns_g_server->viewlist,
						   view->name, view->rdclass,
						   &pview);
			if (result != ISC_R_NOTFOUND &&
			    result != ISC_R_SUCCESS)
				goto cleanup;

			if (pview != NULL) {
				(void)dns_view_findzone(pview, name, &zone);
				dns_view_detach(&pview);
				if (zone != NULL)
					check_dbtype(&zone, empty_dbtypec,
						     empty_dbtype, mctx);
				if (zone != NULL) {
					dns_zone_setview(zone, view);
					CHECK(dns_view_addzone(view, zone));
					CHECK(setquerystats(zone, mctx,
							    zonestats_on));
					dns_zone_detach(&zone);
					continue;
				}
			}

			CHECK(dns_zone_create(&zone, mctx));
			CHECK(dns_zone_setorigin(zone, name));
			dns_zone_setview(zone, view);
			CHECK(dns_zonemgr_managezone(ns_g_server->zonemgr, zone));
			dns_zone_setclass(zone, view->rdclass);
			dns_zone_settype(zone, dns_zone_master);
			dns_zone_setstats(zone, ns_g_server->zonestats);
			CHECK(dns_zone_setdbtype(zone, empty_dbtypec,
						 empty_dbtype));
			if (view->queryacl != NULL)
				dns_zone_setqueryacl(zone, view->queryacl);
			if (view->queryonacl != NULL)
				dns_zone_setqueryonacl(zone, view->queryonacl);
			dns_zone_setdialup(zone, dns_dialuptype_no);
			dns_zone_setnotifytype(zone, dns_notifytype_no);
			dns_zone_setoption(zone, DNS_ZONEOPT_NOCHECKNS,
					   ISC_TRUE);
			CHECK(setquerystats(zone, mctx, zonestats_on));
			CHECK(dns_view_addzone(view, zone));
			isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
				      NS_LOGMODULE_SERVER, ISC_LOG_INFO,
				      "automatic empty zone%s%s: %s",
				      sep, viewname,  empty);
			dns_zone_detach(&zone);
		}
	}

	result = ISC_R_SUCCESS;

 cleanup:
	if (zone != NULL)
		dns_zone_detach(&zone);
	if (dispatch4 != NULL)
		dns_dispatch_detach(&dispatch4);
	if (dispatch6 != NULL)
		dns_dispatch_detach(&dispatch6);
	if (resstats != NULL)
		dns_stats_detach(&resstats);
	if (resquerystats != NULL)
		dns_stats_detach(&resquerystats);
	if (order != NULL)
		dns_order_detach(&order);
	if (cmctx != NULL)
		isc_mem_detach(&cmctx);

	if (cache != NULL)
		dns_cache_detach(&cache);

	return (result);
}

static isc_result_t
configure_hints(dns_view_t *view, const char *filename) {
	isc_result_t result;
	dns_db_t *db;

	db = NULL;
	result = dns_rootns_create(view->mctx, view->rdclass, filename, &db);
	if (result == ISC_R_SUCCESS) {
		dns_view_sethints(view, db);
		dns_db_detach(&db);
	}

	return (result);
}

static isc_result_t
configure_alternates(const cfg_obj_t *config, dns_view_t *view,
		     const cfg_obj_t *alternates)
{
	const cfg_obj_t *portobj;
	const cfg_obj_t *addresses;
	const cfg_listelt_t *element;
	isc_result_t result = ISC_R_SUCCESS;
	in_port_t port;

	/*
	 * Determine which port to send requests to.
	 */
	if (ns_g_lwresdonly && ns_g_port != 0)
		port = ns_g_port;
	else
		CHECKM(ns_config_getport(config, &port), "port");

	if (alternates != NULL) {
		portobj = cfg_tuple_get(alternates, "port");
		if (cfg_obj_isuint32(portobj)) {
			isc_uint32_t val = cfg_obj_asuint32(portobj);
			if (val > ISC_UINT16_MAX) {
				cfg_obj_log(portobj, ns_g_lctx, ISC_LOG_ERROR,
					    "port '%u' out of range", val);
				return (ISC_R_RANGE);
			}
			port = (in_port_t) val;
		}
	}

	addresses = NULL;
	if (alternates != NULL)
		addresses = cfg_tuple_get(alternates, "addresses");

	for (element = cfg_list_first(addresses);
	     element != NULL;
	     element = cfg_list_next(element))
	{
		const cfg_obj_t *alternate = cfg_listelt_value(element);
		isc_sockaddr_t sa;

		if (!cfg_obj_issockaddr(alternate)) {
			dns_fixedname_t fixed;
			dns_name_t *name;
			const char *str = cfg_obj_asstring(cfg_tuple_get(
							   alternate, "name"));
			isc_buffer_t buffer;
			in_port_t myport = port;

			isc_buffer_init(&buffer, str, strlen(str));
			isc_buffer_add(&buffer, strlen(str));
			dns_fixedname_init(&fixed);
			name = dns_fixedname_name(&fixed);
			CHECK(dns_name_fromtext(name, &buffer, dns_rootname,
						ISC_FALSE, NULL));

			portobj = cfg_tuple_get(alternate, "port");
			if (cfg_obj_isuint32(portobj)) {
				isc_uint32_t val = cfg_obj_asuint32(portobj);
				if (val > ISC_UINT16_MAX) {
					cfg_obj_log(portobj, ns_g_lctx,
						    ISC_LOG_ERROR,
						    "port '%u' out of range",
						     val);
					return (ISC_R_RANGE);
				}
				myport = (in_port_t) val;
			}
			CHECK(dns_resolver_addalternate(view->resolver, NULL,
							name, myport));
			continue;
		}

		sa = *cfg_obj_assockaddr(alternate);
		if (isc_sockaddr_getport(&sa) == 0)
			isc_sockaddr_setport(&sa, port);
		CHECK(dns_resolver_addalternate(view->resolver, &sa,
						NULL, 0));
	}

 cleanup:
	return (result);
}

static isc_result_t
configure_forward(const cfg_obj_t *config, dns_view_t *view, dns_name_t *origin,
		  const cfg_obj_t *forwarders, const cfg_obj_t *forwardtype)
{
	const cfg_obj_t *portobj;
	const cfg_obj_t *faddresses;
	const cfg_listelt_t *element;
	dns_fwdpolicy_t fwdpolicy = dns_fwdpolicy_none;
	isc_sockaddrlist_t addresses;
	isc_sockaddr_t *sa;
	isc_result_t result;
	in_port_t port;

	ISC_LIST_INIT(addresses);

	/*
	 * Determine which port to send forwarded requests to.
	 */
	if (ns_g_lwresdonly && ns_g_port != 0)
		port = ns_g_port;
	else
		CHECKM(ns_config_getport(config, &port), "port");

	if (forwarders != NULL) {
		portobj = cfg_tuple_get(forwarders, "port");
		if (cfg_obj_isuint32(portobj)) {
			isc_uint32_t val = cfg_obj_asuint32(portobj);
			if (val > ISC_UINT16_MAX) {
				cfg_obj_log(portobj, ns_g_lctx, ISC_LOG_ERROR,
					    "port '%u' out of range", val);
				return (ISC_R_RANGE);
			}
			port = (in_port_t) val;
		}
	}

	faddresses = NULL;
	if (forwarders != NULL)
		faddresses = cfg_tuple_get(forwarders, "addresses");

	for (element = cfg_list_first(faddresses);
	     element != NULL;
	     element = cfg_list_next(element))
	{
		const cfg_obj_t *forwarder = cfg_listelt_value(element);
		sa = isc_mem_get(view->mctx, sizeof(isc_sockaddr_t));
		if (sa == NULL) {
			result = ISC_R_NOMEMORY;
			goto cleanup;
		}
		*sa = *cfg_obj_assockaddr(forwarder);
		if (isc_sockaddr_getport(sa) == 0)
			isc_sockaddr_setport(sa, port);
		ISC_LINK_INIT(sa, link);
		ISC_LIST_APPEND(addresses, sa, link);
	}

	if (ISC_LIST_EMPTY(addresses)) {
		if (forwardtype != NULL)
			cfg_obj_log(forwarders, ns_g_lctx, ISC_LOG_WARNING,
				    "no forwarders seen; disabling "
				    "forwarding");
		fwdpolicy = dns_fwdpolicy_none;
	} else {
		if (forwardtype == NULL)
			fwdpolicy = dns_fwdpolicy_first;
		else {
			const char *forwardstr = cfg_obj_asstring(forwardtype);
			if (strcasecmp(forwardstr, "first") == 0)
				fwdpolicy = dns_fwdpolicy_first;
			else if (strcasecmp(forwardstr, "only") == 0)
				fwdpolicy = dns_fwdpolicy_only;
			else
				INSIST(0);
		}
	}

	result = dns_fwdtable_add(view->fwdtable, origin, &addresses,
				  fwdpolicy);
	if (result != ISC_R_SUCCESS) {
		char namebuf[DNS_NAME_FORMATSIZE];
		dns_name_format(origin, namebuf, sizeof(namebuf));
		cfg_obj_log(forwarders, ns_g_lctx, ISC_LOG_WARNING,
			    "could not set up forwarding for domain '%s': %s",
			    namebuf, isc_result_totext(result));
		goto cleanup;
	}

	result = ISC_R_SUCCESS;

 cleanup:

	while (!ISC_LIST_EMPTY(addresses)) {
		sa = ISC_LIST_HEAD(addresses);
		ISC_LIST_UNLINK(addresses, sa, link);
		isc_mem_put(view->mctx, sa, sizeof(isc_sockaddr_t));
	}

	return (result);
}

/*
 * Create a new view and add it to the list.
 *
 * If 'vconfig' is NULL, create the default view.
 *
 * The view created is attached to '*viewp'.
 */
static isc_result_t
create_view(const cfg_obj_t *vconfig, dns_viewlist_t *viewlist,
	    dns_view_t **viewp)
{
	isc_result_t result;
	const char *viewname;
	dns_rdataclass_t viewclass;
	dns_view_t *view = NULL;

	if (vconfig != NULL) {
		const cfg_obj_t *classobj = NULL;

		viewname = cfg_obj_asstring(cfg_tuple_get(vconfig, "name"));
		classobj = cfg_tuple_get(vconfig, "class");
		result = ns_config_getclass(classobj, dns_rdataclass_in,
					    &viewclass);
	} else {
		viewname = "_default";
		viewclass = dns_rdataclass_in;
	}
	result = dns_viewlist_find(viewlist, viewname, viewclass, &view);
	if (result == ISC_R_SUCCESS)
		return (ISC_R_EXISTS);
	if (result != ISC_R_NOTFOUND)
		return (result);
	INSIST(view == NULL);

	result = dns_view_create(ns_g_mctx, viewclass, viewname, &view);
	if (result != ISC_R_SUCCESS)
		return (result);

	ISC_LIST_APPEND(*viewlist, view, link);
	dns_view_attach(view, viewp);
	return (ISC_R_SUCCESS);
}

/*
 * Configure or reconfigure a zone.
 */
static isc_result_t
configure_zone(const cfg_obj_t *config, const cfg_obj_t *zconfig,
	       const cfg_obj_t *vconfig, isc_mem_t *mctx, dns_view_t *view,
	       cfg_aclconfctx_t *aclconf)
{
	dns_view_t *pview = NULL;	/* Production view */
	dns_zone_t *zone = NULL;	/* New or reused zone */
	dns_zone_t *dupzone = NULL;
	const cfg_obj_t *options = NULL;
	const cfg_obj_t *zoptions = NULL;
	const cfg_obj_t *typeobj = NULL;
	const cfg_obj_t *forwarders = NULL;
	const cfg_obj_t *forwardtype = NULL;
	const cfg_obj_t *only = NULL;
	isc_result_t result;
	isc_result_t tresult;
	isc_buffer_t buffer;
	dns_fixedname_t fixorigin;
	dns_name_t *origin;
	const char *zname;
	dns_rdataclass_t zclass;
	const char *ztypestr;

	options = NULL;
	(void)cfg_map_get(config, "options", &options);

	zoptions = cfg_tuple_get(zconfig, "options");

	/*
	 * Get the zone origin as a dns_name_t.
	 */
	zname = cfg_obj_asstring(cfg_tuple_get(zconfig, "name"));
	isc_buffer_init(&buffer, zname, strlen(zname));
	isc_buffer_add(&buffer, strlen(zname));
	dns_fixedname_init(&fixorigin);
	CHECK(dns_name_fromtext(dns_fixedname_name(&fixorigin),
				&buffer, dns_rootname, ISC_FALSE, NULL));
	origin = dns_fixedname_name(&fixorigin);

	CHECK(ns_config_getclass(cfg_tuple_get(zconfig, "class"),
				 view->rdclass, &zclass));
	if (zclass != view->rdclass) {
		const char *vname = NULL;
		if (vconfig != NULL)
			vname = cfg_obj_asstring(cfg_tuple_get(vconfig,
							       "name"));
		else
			vname = "<default view>";

		isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
			      NS_LOGMODULE_SERVER, ISC_LOG_ERROR,
			      "zone '%s': wrong class for view '%s'",
			      zname, vname);
		result = ISC_R_FAILURE;
		goto cleanup;
	}

	(void)cfg_map_get(zoptions, "type", &typeobj);
	if (typeobj == NULL) {
		cfg_obj_log(zconfig, ns_g_lctx, ISC_LOG_ERROR,
			    "zone '%s' 'type' not specified", zname);
		return (ISC_R_FAILURE);
	}
	ztypestr = cfg_obj_asstring(typeobj);

	/*
	 * "hints zones" aren't zones.  If we've got one,
	 * configure it and return.
	 */
	if (strcasecmp(ztypestr, "hint") == 0) {
		const cfg_obj_t *fileobj = NULL;
		if (cfg_map_get(zoptions, "file", &fileobj) != ISC_R_SUCCESS) {
			isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
				      NS_LOGMODULE_SERVER, ISC_LOG_ERROR,
				      "zone '%s': 'file' not specified",
				      zname);
			result = ISC_R_FAILURE;
			goto cleanup;
		}
		if (dns_name_equal(origin, dns_rootname)) {
			const char *hintsfile = cfg_obj_asstring(fileobj);

			result = configure_hints(view, hintsfile);
			if (result != ISC_R_SUCCESS) {
				isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
					      NS_LOGMODULE_SERVER,
					      ISC_LOG_ERROR,
					      "could not configure root hints "
					      "from '%s': %s", hintsfile,
					      isc_result_totext(result));
				goto cleanup;
			}
			/*
			 * Hint zones may also refer to delegation only points.
			 */
			only = NULL;
			tresult = cfg_map_get(zoptions, "delegation-only",
					      &only);
			if (tresult == ISC_R_SUCCESS && cfg_obj_asboolean(only))
				CHECK(dns_view_adddelegationonly(view, origin));
		} else {
			isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
				      NS_LOGMODULE_SERVER, ISC_LOG_WARNING,
				      "ignoring non-root hint zone '%s'",
				      zname);
			result = ISC_R_SUCCESS;
		}
		/* Skip ordinary zone processing. */
		goto cleanup;
	}

	/*
	 * "forward zones" aren't zones either.  Translate this syntax into
	 * the appropriate selective forwarding configuration and return.
	 */
	if (strcasecmp(ztypestr, "forward") == 0) {
		forwardtype = NULL;
		forwarders = NULL;

		(void)cfg_map_get(zoptions, "forward", &forwardtype);
		(void)cfg_map_get(zoptions, "forwarders", &forwarders);
		result = configure_forward(config, view, origin, forwarders,
					   forwardtype);
		goto cleanup;
	}

	/*
	 * "delegation-only zones" aren't zones either.
	 */
	if (strcasecmp(ztypestr, "delegation-only") == 0) {
		result = dns_view_adddelegationonly(view, origin);
		goto cleanup;
	}

	/*
	 * Check for duplicates in the new zone table.
	 */
	result = dns_view_findzone(view, origin, &dupzone);
	if (result == ISC_R_SUCCESS) {
		/*
		 * We already have this zone!
		 */
		cfg_obj_log(zconfig, ns_g_lctx, ISC_LOG_ERROR,
			    "zone '%s' already exists", zname);
		dns_zone_detach(&dupzone);
		result = ISC_R_EXISTS;
		goto cleanup;
	}
	INSIST(dupzone == NULL);

	/*
	 * See if we can reuse an existing zone.  This is
	 * only possible if all of these are true:
	 *   - The zone's view exists
	 *   - A zone with the right name exists in the view
	 *   - The zone is compatible with the config
	 *     options (e.g., an existing master zone cannot
	 *     be reused if the options specify a slave zone)
	 */
	result = dns_viewlist_find(&ns_g_server->viewlist,
				   view->name, view->rdclass,
				   &pview);
	if (result != ISC_R_NOTFOUND && result != ISC_R_SUCCESS)
		goto cleanup;
	if (pview != NULL)
		result = dns_view_findzone(pview, origin, &zone);
	if (result != ISC_R_NOTFOUND && result != ISC_R_SUCCESS)
		goto cleanup;
	if (zone != NULL && !ns_zone_reusable(zone, zconfig))
		dns_zone_detach(&zone);

	if (zone != NULL) {
		/*
		 * We found a reusable zone.  Make it use the
		 * new view.
		 */
		dns_zone_setview(zone, view);
		if (view->acache != NULL)
			dns_zone_setacache(zone, view->acache);
	} else {
		/*
		 * We cannot reuse an existing zone, we have
		 * to create a new one.
		 */
		CHECK(dns_zone_create(&zone, mctx));
		CHECK(dns_zone_setorigin(zone, origin));
		dns_zone_setview(zone, view);
		if (view->acache != NULL)
			dns_zone_setacache(zone, view->acache);
		CHECK(dns_zonemgr_managezone(ns_g_server->zonemgr, zone));
		dns_zone_setstats(zone, ns_g_server->zonestats);
	}

	/*
	 * If the zone contains a 'forwarders' statement, configure
	 * selective forwarding.
	 */
	forwarders = NULL;
	if (cfg_map_get(zoptions, "forwarders", &forwarders) == ISC_R_SUCCESS)
	{
		forwardtype = NULL;
		(void)cfg_map_get(zoptions, "forward", &forwardtype);
		CHECK(configure_forward(config, view, origin, forwarders,
					forwardtype));
	}

	/*
	 * Stub and forward zones may also refer to delegation only points.
	 */
	only = NULL;
	if (cfg_map_get(zoptions, "delegation-only", &only) == ISC_R_SUCCESS)
	{
		if (cfg_obj_asboolean(only))
			CHECK(dns_view_adddelegationonly(view, origin));
	}

	/*
	 * Configure the zone.
	 */
	CHECK(ns_zone_configure(config, vconfig, zconfig, aclconf, zone));

	/*
	 * Add the zone to its view in the new view list.
	 */
	CHECK(dns_view_addzone(view, zone));

 cleanup:
	if (zone != NULL)
		dns_zone_detach(&zone);
	if (pview != NULL)
		dns_view_detach(&pview);

	return (result);
}

/*
 * Configure a single server quota.
 */
static void
configure_server_quota(const cfg_obj_t **maps, const char *name,
		       isc_quota_t *quota)
{
	const cfg_obj_t *obj = NULL;
	isc_result_t result;

	result = ns_config_get(maps, name, &obj);
	INSIST(result == ISC_R_SUCCESS);
	isc_quota_max(quota, cfg_obj_asuint32(obj));
}

/*
 * This function is called as soon as the 'directory' statement has been
 * parsed.  This can be extended to support other options if necessary.
 */
static isc_result_t
directory_callback(const char *clausename, const cfg_obj_t *obj, void *arg) {
	isc_result_t result;
	const char *directory;

	REQUIRE(strcasecmp("directory", clausename) == 0);

	UNUSED(arg);
	UNUSED(clausename);

	/*
	 * Change directory.
	 */
	directory = cfg_obj_asstring(obj);

	if (! isc_file_ischdiridempotent(directory))
		cfg_obj_log(obj, ns_g_lctx, ISC_LOG_WARNING,
			    "option 'directory' contains relative path '%s'",
			    directory);

	result = isc_dir_chdir(directory);
	if (result != ISC_R_SUCCESS) {
		cfg_obj_log(obj, ns_g_lctx, ISC_LOG_ERROR,
			    "change directory to '%s' failed: %s",
			    directory, isc_result_totext(result));
		return (result);
	}

	return (ISC_R_SUCCESS);
}

static void
scan_interfaces(ns_server_t *server, isc_boolean_t verbose) {
	isc_boolean_t match_mapped = server->aclenv.match_mapped;

	ns_interfacemgr_scan(server->interfacemgr, verbose);
	/*
	 * Update the "localhost" and "localnets" ACLs to match the
	 * current set of network interfaces.
	 */
	dns_aclenv_copy(&server->aclenv,
			ns_interfacemgr_getaclenv(server->interfacemgr));

	server->aclenv.match_mapped = match_mapped;
}

static isc_result_t
add_listenelt(isc_mem_t *mctx, ns_listenlist_t *list, isc_sockaddr_t *addr,
	      isc_boolean_t wcardport_ok)
{
	ns_listenelt_t *lelt = NULL;
	dns_acl_t *src_acl = NULL;
	isc_result_t result;
	isc_sockaddr_t any_sa6;
	isc_netaddr_t netaddr;

	REQUIRE(isc_sockaddr_pf(addr) == AF_INET6);

	isc_sockaddr_any6(&any_sa6);
	if (!isc_sockaddr_equal(&any_sa6, addr) &&
	    (wcardport_ok || isc_sockaddr_getport(addr) != 0)) {
		isc_netaddr_fromin6(&netaddr, &addr->type.sin6.sin6_addr);

		result = dns_acl_create(mctx, 0, &src_acl);
		if (result != ISC_R_SUCCESS)
			return (result);

		result = dns_iptable_addprefix(src_acl->iptable,
					       &netaddr, 128, ISC_TRUE);
		if (result != ISC_R_SUCCESS)
			goto clean;

		result = ns_listenelt_create(mctx, isc_sockaddr_getport(addr),
					     src_acl, &lelt);
		if (result != ISC_R_SUCCESS)
			goto clean;
		ISC_LIST_APPEND(list->elts, lelt, link);
	}

	return (ISC_R_SUCCESS);

 clean:
	INSIST(lelt == NULL);
	dns_acl_detach(&src_acl);

	return (result);
}

/*
 * Make a list of xxx-source addresses and call ns_interfacemgr_adjust()
 * to update the listening interfaces accordingly.
 * We currently only consider IPv6, because this only affects IPv6 wildcard
 * sockets.
 */
static void
adjust_interfaces(ns_server_t *server, isc_mem_t *mctx) {
	isc_result_t result;
	ns_listenlist_t *list = NULL;
	dns_view_t *view;
	dns_zone_t *zone, *next;
	isc_sockaddr_t addr, *addrp;

	result = ns_listenlist_create(mctx, &list);
	if (result != ISC_R_SUCCESS)
		return;

	for (view = ISC_LIST_HEAD(server->viewlist);
	     view != NULL;
	     view = ISC_LIST_NEXT(view, link)) {
		dns_dispatch_t *dispatch6;

		dispatch6 = dns_resolver_dispatchv6(view->resolver);
		if (dispatch6 == NULL)
			continue;
		result = dns_dispatch_getlocaladdress(dispatch6, &addr);
		if (result != ISC_R_SUCCESS)
			goto fail;

		/*
		 * We always add non-wildcard address regardless of whether
		 * the port is 'any' (the fourth arg is TRUE): if the port is
		 * specific, we need to add it since it may conflict with a
		 * listening interface; if it's zero, we'll dynamically open
		 * query ports, and some of them may override an existing
		 * wildcard IPv6 port.
		 */
		result = add_listenelt(mctx, list, &addr, ISC_TRUE);
		if (result != ISC_R_SUCCESS)
			goto fail;
	}

	zone = NULL;
	for (result = dns_zone_first(server->zonemgr, &zone);
	     result == ISC_R_SUCCESS;
	     next = NULL, result = dns_zone_next(zone, &next), zone = next) {
		dns_view_t *zoneview;

		/*
		 * At this point the zone list may contain a stale zone
		 * just removed from the configuration.  To see the validity,
		 * check if the corresponding view is in our current view list.
		 * There may also be old zones that are still in the process
		 * of shutting down and have detached from their old view
		 * (zoneview == NULL).
		 */
		zoneview = dns_zone_getview(zone);
		if (zoneview == NULL)
			continue;
		for (view = ISC_LIST_HEAD(server->viewlist);
		     view != NULL && view != zoneview;
		     view = ISC_LIST_NEXT(view, link))
			;
		if (view == NULL)
			continue;

		addrp = dns_zone_getnotifysrc6(zone);
		result = add_listenelt(mctx, list, addrp, ISC_FALSE);
		if (result != ISC_R_SUCCESS)
			goto fail;

		addrp = dns_zone_getxfrsource6(zone);
		result = add_listenelt(mctx, list, addrp, ISC_FALSE);
		if (result != ISC_R_SUCCESS)
			goto fail;
	}

	ns_interfacemgr_adjust(server->interfacemgr, list, ISC_TRUE);

 clean:
	ns_listenlist_detach(&list);
	return;

 fail:
	/*
	 * Even when we failed the procedure, most of other interfaces
	 * should work correctly.  We therefore just warn it.
	 */
	isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
		      NS_LOGMODULE_SERVER, ISC_LOG_WARNING,
		      "could not adjust the listen-on list; "
		      "some interfaces may not work");
	goto clean;
}

/*
 * This event callback is invoked to do periodic network
 * interface scanning.
 */
static void
interface_timer_tick(isc_task_t *task, isc_event_t *event) {
	isc_result_t result;
	ns_server_t *server = (ns_server_t *) event->ev_arg;
	INSIST(task == server->task);
	UNUSED(task);
	isc_event_free(&event);
	/*
	 * XXX should scan interfaces unlocked and get exclusive access
	 * only to replace ACLs.
	 */
	result = isc_task_beginexclusive(server->task);
	RUNTIME_CHECK(result == ISC_R_SUCCESS);
	scan_interfaces(server, ISC_FALSE);
	isc_task_endexclusive(server->task);
}

static void
heartbeat_timer_tick(isc_task_t *task, isc_event_t *event) {
	ns_server_t *server = (ns_server_t *) event->ev_arg;
	dns_view_t *view;

	UNUSED(task);
	isc_event_free(&event);
	view = ISC_LIST_HEAD(server->viewlist);
	while (view != NULL) {
		dns_view_dialup(view);
		view = ISC_LIST_NEXT(view, link);
	}
}

static void
pps_timer_tick(isc_task_t *task, isc_event_t *event) {
	static unsigned int oldrequests = 0;
	unsigned int requests = ns_client_requests;

	UNUSED(task);
	isc_event_free(&event);

	/*
	 * Don't worry about wrapping as the overflow result will be right.
	 */
	dns_pps = (requests - oldrequests) / 1200;
	oldrequests = requests;
}

/*
 * Replace the current value of '*field', a dynamically allocated
 * string or NULL, with a dynamically allocated copy of the
 * null-terminated string pointed to by 'value', or NULL.
 */
static isc_result_t
setstring(ns_server_t *server, char **field, const char *value) {
	char *copy;

	if (value != NULL) {
		copy = isc_mem_strdup(server->mctx, value);
		if (copy == NULL)
			return (ISC_R_NOMEMORY);
	} else {
		copy = NULL;
	}

	if (*field != NULL)
		isc_mem_free(server->mctx, *field);

	*field = copy;
	return (ISC_R_SUCCESS);
}

/*
 * Replace the current value of '*field', a dynamically allocated
 * string or NULL, with another dynamically allocated string
 * or NULL if whether 'obj' is a string or void value, respectively.
 */
static isc_result_t
setoptstring(ns_server_t *server, char **field, const cfg_obj_t *obj) {
	if (cfg_obj_isvoid(obj))
		return (setstring(server, field, NULL));
	else
		return (setstring(server, field, cfg_obj_asstring(obj)));
}

static void
set_limit(const cfg_obj_t **maps, const char *configname,
	  const char *description, isc_resource_t resourceid,
	  isc_resourcevalue_t defaultvalue)
{
	const cfg_obj_t *obj = NULL;
	const char *resource;
	isc_resourcevalue_t value;
	isc_result_t result;

	if (ns_config_get(maps, configname, &obj) != ISC_R_SUCCESS)
		return;

	if (cfg_obj_isstring(obj)) {
		resource = cfg_obj_asstring(obj);
		if (strcasecmp(resource, "unlimited") == 0)
			value = ISC_RESOURCE_UNLIMITED;
		else {
			INSIST(strcasecmp(resource, "default") == 0);
			value = defaultvalue;
		}
	} else
		value = cfg_obj_asuint64(obj);

	result = isc_resource_setlimit(resourceid, value);
	isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER,
		      result == ISC_R_SUCCESS ?
			ISC_LOG_DEBUG(3) : ISC_LOG_WARNING,
		      "set maximum %s to %" ISC_PRINT_QUADFORMAT "d: %s",
		      description, value, isc_result_totext(result));
}

#define SETLIMIT(cfgvar, resource, description) \
	set_limit(maps, cfgvar, description, isc_resource_ ## resource, \
		  ns_g_init ## resource)

static void
set_limits(const cfg_obj_t **maps) {
	SETLIMIT("stacksize", stacksize, "stack size");
	SETLIMIT("datasize", datasize, "data size");
	SETLIMIT("coresize", coresize, "core size");
	SETLIMIT("files", openfiles, "open files");
}

static void
portset_fromconf(isc_portset_t *portset, const cfg_obj_t *ports,
		 isc_boolean_t positive)
{
	const cfg_listelt_t *element;

	for (element = cfg_list_first(ports);
	     element != NULL;
	     element = cfg_list_next(element)) {
		const cfg_obj_t *obj = cfg_listelt_value(element);

		if (cfg_obj_isuint32(obj)) {
			in_port_t port = (in_port_t)cfg_obj_asuint32(obj);

			if (positive)
				isc_portset_add(portset, port);
			else
				isc_portset_remove(portset, port);
		} else {
			const cfg_obj_t *obj_loport, *obj_hiport;
			in_port_t loport, hiport;

			obj_loport = cfg_tuple_get(obj, "loport");
			loport = (in_port_t)cfg_obj_asuint32(obj_loport);
			obj_hiport = cfg_tuple_get(obj, "hiport");
			hiport = (in_port_t)cfg_obj_asuint32(obj_hiport);

			if (positive)
				isc_portset_addrange(portset, loport, hiport);
			else {
				isc_portset_removerange(portset, loport,
							hiport);
			}
		}
	}
}

static isc_result_t
removed(dns_zone_t *zone, void *uap) {
	const char *type;

	if (dns_zone_getview(zone) != uap)
		return (ISC_R_SUCCESS);

	switch (dns_zone_gettype(zone)) {
	case dns_zone_master:
		type = "master";
		break;
	case dns_zone_slave:
		type = "slave";
		break;
	case dns_zone_stub:
		type = "stub";
		break;
	default:
		type = "other";
		break;
	}
	dns_zone_log(zone, ISC_LOG_INFO, "(%s) removed", type);
	return (ISC_R_SUCCESS);
}

static isc_result_t
load_configuration(const char *filename, ns_server_t *server,
		   isc_boolean_t first_time)
{
	cfg_aclconfctx_t aclconfctx;
	cfg_obj_t *config;
	cfg_parser_t *parser = NULL;
	const cfg_listelt_t *element;
	const cfg_obj_t *builtin_views;
	const cfg_obj_t *maps[3];
	const cfg_obj_t *obj;
	const cfg_obj_t *options;
	const cfg_obj_t *usev4ports, *avoidv4ports, *usev6ports, *avoidv6ports;
	const cfg_obj_t *views;
	dns_view_t *view = NULL;
	dns_view_t *view_next;
	dns_viewlist_t tmpviewlist;
	dns_viewlist_t viewlist;
	in_port_t listen_port, udpport_low, udpport_high;
	int i;
	isc_interval_t interval;
	isc_portset_t *v4portset = NULL;
	isc_portset_t *v6portset = NULL;
	isc_resourcevalue_t nfiles;
	isc_result_t result;
	isc_uint32_t heartbeat_interval;
	isc_uint32_t interface_interval;
	isc_uint32_t reserved;
	isc_uint32_t udpsize;
	unsigned int maxsocks;

	cfg_aclconfctx_init(&aclconfctx);
	ISC_LIST_INIT(viewlist);

	/* Ensure exclusive access to configuration data. */
	result = isc_task_beginexclusive(server->task);
	RUNTIME_CHECK(result == ISC_R_SUCCESS);

	/*
	 * Parse the global default pseudo-config file.
	 */
	if (first_time) {
		CHECK(ns_config_parsedefaults(ns_g_parser, &ns_g_config));
		RUNTIME_CHECK(cfg_map_get(ns_g_config, "options",
					  &ns_g_defaults) ==
			      ISC_R_SUCCESS);
	}

	/*
	 * Parse the configuration file using the new config code.
	 */
	result = ISC_R_FAILURE;
	config = NULL;

	/*
	 * Unless this is lwresd with the -C option, parse the config file.
	 */
	if (!(ns_g_lwresdonly && lwresd_g_useresolvconf)) {
		isc_log_write(ns_g_lctx,
			      NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER,
			      ISC_LOG_INFO, "loading configuration from '%s'",
			      filename);
		CHECK(cfg_parser_create(ns_g_mctx, ns_g_lctx, &parser));
		cfg_parser_setcallback(parser, directory_callback, NULL);
		result = cfg_parse_file(parser, filename, &cfg_type_namedconf,
					&config);
	}

	/*
	 * If this is lwresd with the -C option, or lwresd with no -C or -c
	 * option where the above parsing failed, parse resolv.conf.
	 */
	if (ns_g_lwresdonly &&
	    (lwresd_g_useresolvconf ||
	     (!ns_g_conffileset && result == ISC_R_FILENOTFOUND)))
	{
		isc_log_write(ns_g_lctx,
			      NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER,
			      ISC_LOG_INFO, "loading configuration from '%s'",
			      lwresd_g_resolvconffile);
		if (parser != NULL)
			cfg_parser_destroy(&parser);
		CHECK(cfg_parser_create(ns_g_mctx, ns_g_lctx, &parser));
		result = ns_lwresd_parseeresolvconf(ns_g_mctx, parser,
						    &config);
	}
	CHECK(result);

	/*
	 * Check the validity of the configuration.
	 */
	CHECK(bind9_check_namedconf(config, ns_g_lctx, ns_g_mctx));

	/*
	 * Fill in the maps array, used for resolving defaults.
	 */
	i = 0;
	options = NULL;
	result = cfg_map_get(config, "options", &options);
	if (result == ISC_R_SUCCESS)
		maps[i++] = options;
	maps[i++] = ns_g_defaults;
	maps[i++] = NULL;

	/*
	 * Set process limits, which (usually) needs to be done as root.
	 */
	set_limits(maps);

	/*
	 * Check if max number of open sockets that the system allows is
	 * sufficiently large.  Failing this condition is not necessarily fatal,
	 * but may cause subsequent runtime failures for a busy recursive
	 * server.
	 */
	result = isc_socketmgr_getmaxsockets(ns_g_socketmgr, &maxsocks);
	if (result != ISC_R_SUCCESS)
		maxsocks = 0;
	result = isc_resource_getcurlimit(isc_resource_openfiles, &nfiles);
	if (result == ISC_R_SUCCESS && (isc_resourcevalue_t)maxsocks > nfiles) {
		isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
			      NS_LOGMODULE_SERVER, ISC_LOG_WARNING,
			      "max open files (%" ISC_PRINT_QUADFORMAT "u)"
			      " is smaller than max sockets (%u)",
			      nfiles, maxsocks);
	}

	/*
	 * Set the number of socket reserved for TCP, stdio etc.
	 */
	obj = NULL;
	result = ns_config_get(maps, "reserved-sockets", &obj);
	INSIST(result == ISC_R_SUCCESS);
	reserved = cfg_obj_asuint32(obj);
	if (maxsocks != 0) {
		if (maxsocks < 128U)			/* Prevent underflow. */
			reserved = 0;
		else if (reserved > maxsocks - 128U)	/* Minimum UDP space. */
			reserved = maxsocks - 128;
	}
	/* Minimum TCP/stdio space. */
	if (reserved < 128U)
		reserved = 128;
	if (reserved + 128U > maxsocks && maxsocks != 0) {
		isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
			      NS_LOGMODULE_SERVER, ISC_LOG_WARNING,
			      "less than 128 UDP sockets available after "
			      "applying 'reserved-sockets' and 'maxsockets'");
	}
	isc__socketmgr_setreserved(ns_g_socketmgr, reserved);

	/*
	 * Configure various server options.
	 */
	configure_server_quota(maps, "transfers-out", &server->xfroutquota);
	configure_server_quota(maps, "tcp-clients", &server->tcpquota);
	configure_server_quota(maps, "recursive-clients",
			       &server->recursionquota);
	if (server->recursionquota.max > 1000)
		isc_quota_soft(&server->recursionquota,
			       server->recursionquota.max - 100);
	else
		isc_quota_soft(&server->recursionquota, 0);

	CHECK(configure_view_acl(NULL, config, "blackhole", &aclconfctx,
				 ns_g_mctx, &server->blackholeacl));
	if (server->blackholeacl != NULL)
		dns_dispatchmgr_setblackhole(ns_g_dispatchmgr,
					     server->blackholeacl);

	obj = NULL;
	result = ns_config_get(maps, "match-mapped-addresses", &obj);
	INSIST(result == ISC_R_SUCCESS);
	server->aclenv.match_mapped = cfg_obj_asboolean(obj);

	CHECKM(ns_statschannels_configure(ns_g_server, config, &aclconfctx),
	       "configuring statistics server(s)");

	/*
	 * Configure sets of UDP query source ports.
	 */
	CHECKM(isc_portset_create(ns_g_mctx, &v4portset),
	       "creating UDP port set");
	CHECKM(isc_portset_create(ns_g_mctx, &v6portset),
	       "creating UDP port set");

	usev4ports = NULL;
	usev6ports = NULL;
	avoidv4ports = NULL;
	avoidv6ports = NULL;

	(void)ns_config_get(maps, "use-v4-udp-ports", &usev4ports);
	if (usev4ports != NULL)
		portset_fromconf(v4portset, usev4ports, ISC_TRUE);
	else {
		CHECKM(isc_net_getudpportrange(AF_INET, &udpport_low,
					       &udpport_high),
		       "get the default UDP/IPv4 port range");
		if (udpport_low == udpport_high)
			isc_portset_add(v4portset, udpport_low);
		else {
			isc_portset_addrange(v4portset, udpport_low,
					     udpport_high);
		}
		isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
			      NS_LOGMODULE_SERVER, ISC_LOG_INFO,
			      "using default UDP/IPv4 port range: [%d, %d]",
			      udpport_low, udpport_high);
	}
	(void)ns_config_get(maps, "avoid-v4-udp-ports", &avoidv4ports);
	if (avoidv4ports != NULL)
		portset_fromconf(v4portset, avoidv4ports, ISC_FALSE);

	(void)ns_config_get(maps, "use-v6-udp-ports", &usev6ports);
	if (usev6ports != NULL)
		portset_fromconf(v6portset, usev6ports, ISC_TRUE);
	else {
		CHECKM(isc_net_getudpportrange(AF_INET6, &udpport_low,
					       &udpport_high),
		       "get the default UDP/IPv6 port range");
		if (udpport_low == udpport_high)
			isc_portset_add(v6portset, udpport_low);
		else {
			isc_portset_addrange(v6portset, udpport_low,
					     udpport_high);
		}
		isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
			      NS_LOGMODULE_SERVER, ISC_LOG_INFO,
			      "using default UDP/IPv6 port range: [%d, %d]",
			      udpport_low, udpport_high);
	}
	(void)ns_config_get(maps, "avoid-v6-udp-ports", &avoidv6ports);
	if (avoidv6ports != NULL)
		portset_fromconf(v6portset, avoidv6ports, ISC_FALSE);

	dns_dispatchmgr_setavailports(ns_g_dispatchmgr, v4portset, v6portset);

	/*
	 * Set the EDNS UDP size when we don't match a view.
	 */
	obj = NULL;
	result = ns_config_get(maps, "edns-udp-size", &obj);
	INSIST(result == ISC_R_SUCCESS);
	udpsize = cfg_obj_asuint32(obj);
	if (udpsize < 512)
		udpsize = 512;
	if (udpsize > 4096)
		udpsize = 4096;
	ns_g_udpsize = (isc_uint16_t)udpsize;

	/*
	 * Configure the zone manager.
	 */
	obj = NULL;
	result = ns_config_get(maps, "transfers-in", &obj);
	INSIST(result == ISC_R_SUCCESS);
	dns_zonemgr_settransfersin(server->zonemgr, cfg_obj_asuint32(obj));

	obj = NULL;
	result = ns_config_get(maps, "transfers-per-ns", &obj);
	INSIST(result == ISC_R_SUCCESS);
	dns_zonemgr_settransfersperns(server->zonemgr, cfg_obj_asuint32(obj));

	obj = NULL;
	result = ns_config_get(maps, "serial-query-rate", &obj);
	INSIST(result == ISC_R_SUCCESS);
	dns_zonemgr_setserialqueryrate(server->zonemgr, cfg_obj_asuint32(obj));

	/*
	 * Determine which port to use for listening for incoming connections.
	 */
	if (ns_g_port != 0)
		listen_port = ns_g_port;
	else
		CHECKM(ns_config_getport(config, &listen_port), "port");

	/*
	 * Find the listen queue depth.
	 */
	obj = NULL;
	result = ns_config_get(maps, "tcp-listen-queue", &obj);
	INSIST(result == ISC_R_SUCCESS);
	ns_g_listen = cfg_obj_asuint32(obj);
	if (ns_g_listen < 3)
		ns_g_listen = 3;

	/*
	 * Configure the interface manager according to the "listen-on"
	 * statement.
	 */
	{
		const cfg_obj_t *clistenon = NULL;
		ns_listenlist_t *listenon = NULL;

		clistenon = NULL;
		/*
		 * Even though listen-on is present in the default
		 * configuration, we can't use it here, since it isn't
		 * used if we're in lwresd mode.  This way is easier.
		 */
		if (options != NULL)
			(void)cfg_map_get(options, "listen-on", &clistenon);
		if (clistenon != NULL) {
			result = ns_listenlist_fromconfig(clistenon,
							  config,
							  &aclconfctx,
							  ns_g_mctx,
							  &listenon);
		} else if (!ns_g_lwresdonly) {
			/*
			 * Not specified, use default.
			 */
			CHECK(ns_listenlist_default(ns_g_mctx, listen_port,
						    ISC_TRUE, &listenon));
		}
		if (listenon != NULL) {
			ns_interfacemgr_setlistenon4(server->interfacemgr,
						     listenon);
			ns_listenlist_detach(&listenon);
		}
	}
	/*
	 * Ditto for IPv6.
	 */
	{
		const cfg_obj_t *clistenon = NULL;
		ns_listenlist_t *listenon = NULL;

		if (options != NULL)
			(void)cfg_map_get(options, "listen-on-v6", &clistenon);
		if (clistenon != NULL) {
			result = ns_listenlist_fromconfig(clistenon,
							  config,
							  &aclconfctx,
							  ns_g_mctx,
							  &listenon);
		} else if (!ns_g_lwresdonly) {
			isc_boolean_t enable;
			/*
			 * Not specified, use default.
			 */
			enable = ISC_TF(isc_net_probeipv4() != ISC_R_SUCCESS);
			CHECK(ns_listenlist_default(ns_g_mctx, listen_port,
						    enable, &listenon));
		}
		if (listenon != NULL) {
			ns_interfacemgr_setlistenon6(server->interfacemgr,
						     listenon);
			ns_listenlist_detach(&listenon);
		}
	}

	/*
	 * Rescan the interface list to pick up changes in the
	 * listen-on option.  It's important that we do this before we try
	 * to configure the query source, since the dispatcher we use might
	 * be shared with an interface.
	 */
	scan_interfaces(server, ISC_TRUE);

	/*
	 * Arrange for further interface scanning to occur periodically
	 * as specified by the "interface-interval" option.
	 */
	obj = NULL;
	result = ns_config_get(maps, "interface-interval", &obj);
	INSIST(result == ISC_R_SUCCESS);
	interface_interval = cfg_obj_asuint32(obj) * 60;
	if (interface_interval == 0) {
		CHECK(isc_timer_reset(server->interface_timer,
				      isc_timertype_inactive,
				      NULL, NULL, ISC_TRUE));
	} else if (server->interface_interval != interface_interval) {
		isc_interval_set(&interval, interface_interval, 0);
		CHECK(isc_timer_reset(server->interface_timer,
				      isc_timertype_ticker,
				      NULL, &interval, ISC_FALSE));
	}
	server->interface_interval = interface_interval;

	/*
	 * Configure the dialup heartbeat timer.
	 */
	obj = NULL;
	result = ns_config_get(maps, "heartbeat-interval", &obj);
	INSIST(result == ISC_R_SUCCESS);
	heartbeat_interval = cfg_obj_asuint32(obj) * 60;
	if (heartbeat_interval == 0) {
		CHECK(isc_timer_reset(server->heartbeat_timer,
				      isc_timertype_inactive,
				      NULL, NULL, ISC_TRUE));
	} else if (server->heartbeat_interval != heartbeat_interval) {
		isc_interval_set(&interval, heartbeat_interval, 0);
		CHECK(isc_timer_reset(server->heartbeat_timer,
				      isc_timertype_ticker,
				      NULL, &interval, ISC_FALSE));
	}
	server->heartbeat_interval = heartbeat_interval;

	isc_interval_set(&interval, 1200, 0);
	CHECK(isc_timer_reset(server->pps_timer, isc_timertype_ticker, NULL,
			      &interval, ISC_FALSE));

	/*
	 * Configure and freeze all explicit views.  Explicit
	 * views that have zones were already created at parsing
	 * time, but views with no zones must be created here.
	 */
	views = NULL;
	(void)cfg_map_get(config, "view", &views);
	for (element = cfg_list_first(views);
	     element != NULL;
	     element = cfg_list_next(element))
	{
		const cfg_obj_t *vconfig = cfg_listelt_value(element);
		view = NULL;

		CHECK(create_view(vconfig, &viewlist, &view));
		INSIST(view != NULL);
		CHECK(configure_view(view, config, vconfig,
				     ns_g_mctx, &aclconfctx, ISC_TRUE));
		dns_view_freeze(view);
		dns_view_detach(&view);
	}

	/*
	 * Make sure we have a default view if and only if there
	 * were no explicit views.
	 */
	if (views == NULL) {
		/*
		 * No explicit views; there ought to be a default view.
		 * There may already be one created as a side effect
		 * of zone statements, or we may have to create one.
		 * In either case, we need to configure and freeze it.
		 */
		CHECK(create_view(NULL, &viewlist, &view));
		CHECK(configure_view(view, config, NULL, ns_g_mctx,
				     &aclconfctx, ISC_TRUE));
		dns_view_freeze(view);
		dns_view_detach(&view);
	}

	/*
	 * Create (or recreate) the built-in views.  Currently
	 * there is only one, the _bind view.
	 */
	builtin_views = NULL;
	RUNTIME_CHECK(cfg_map_get(ns_g_config, "view",
				  &builtin_views) == ISC_R_SUCCESS);
	for (element = cfg_list_first(builtin_views);
	     element != NULL;
	     element = cfg_list_next(element))
	{
		const cfg_obj_t *vconfig = cfg_listelt_value(element);
		CHECK(create_view(vconfig, &viewlist, &view));
		CHECK(configure_view(view, config, vconfig, ns_g_mctx,
				     &aclconfctx, ISC_FALSE));
		dns_view_freeze(view);
		dns_view_detach(&view);
		view = NULL;
	}

	/*
	 * Swap our new view list with the production one.
	 */
	tmpviewlist = server->viewlist;
	server->viewlist = viewlist;
	viewlist = tmpviewlist;

	/*
	 * Load the TKEY information from the configuration.
	 */
	if (options != NULL) {
		dns_tkeyctx_t *t = NULL;
		CHECKM(ns_tkeyctx_fromconfig(options, ns_g_mctx, ns_g_entropy,
					     &t),
		       "configuring TKEY");
		if (server->tkeyctx != NULL)
			dns_tkeyctx_destroy(&server->tkeyctx);
		server->tkeyctx = t;
	}

	/*
	 * Bind the control port(s).
	 */
	CHECKM(ns_controls_configure(ns_g_server->controls, config,
				     &aclconfctx),
	       "binding control channel(s)");

	/*
	 * Bind the lwresd port(s).
	 */
	CHECKM(ns_lwresd_configure(ns_g_mctx, config),
	       "binding lightweight resolver ports");

	/*
	 * Open the source of entropy.
	 */
	if (first_time) {
		obj = NULL;
		result = ns_config_get(maps, "random-device", &obj);
		if (result != ISC_R_SUCCESS) {
			isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
				      NS_LOGMODULE_SERVER, ISC_LOG_INFO,
				      "no source of entropy found");
		} else {
			const char *randomdev = cfg_obj_asstring(obj);
			result = isc_entropy_createfilesource(ns_g_entropy,
							      randomdev);
			if (result != ISC_R_SUCCESS)
				isc_log_write(ns_g_lctx,
					      NS_LOGCATEGORY_GENERAL,
					      NS_LOGMODULE_SERVER,
					      ISC_LOG_INFO,
					      "could not open entropy source "
					      "%s: %s",
					      randomdev,
					      isc_result_totext(result));
#ifdef PATH_RANDOMDEV
			if (ns_g_fallbackentropy != NULL) {
				if (result != ISC_R_SUCCESS) {
					isc_log_write(ns_g_lctx,
						      NS_LOGCATEGORY_GENERAL,
						      NS_LOGMODULE_SERVER,
						      ISC_LOG_INFO,
						      "using pre-chroot entropy source "
						      "%s",
						      PATH_RANDOMDEV);
					isc_entropy_detach(&ns_g_entropy);
					isc_entropy_attach(ns_g_fallbackentropy,
							   &ns_g_entropy);
				}
				isc_entropy_detach(&ns_g_fallbackentropy);
			}
#endif
		}
	}

	/*
	 * Relinquish root privileges.
	 */
	if (first_time)
		ns_os_changeuser();

	/*
	 * Check that the working directory is writable.
	 */
	if (access(".", W_OK) != 0) {
		isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
			      NS_LOGMODULE_SERVER, ISC_LOG_ERROR,
			      "the working directory is not writable");
	}

	/*
	 * Configure the logging system.
	 *
	 * Do this after changing UID to make sure that any log
	 * files specified in named.conf get created by the
	 * unprivileged user, not root.
	 */
	if (ns_g_logstderr) {
		isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
			      NS_LOGMODULE_SERVER, ISC_LOG_INFO,
			      "ignoring config file logging "
			      "statement due to -g option");
	} else {
		const cfg_obj_t *logobj = NULL;
		isc_logconfig_t *logc = NULL;

		CHECKM(isc_logconfig_create(ns_g_lctx, &logc),
		       "creating new logging configuration");

		logobj = NULL;
		(void)cfg_map_get(config, "logging", &logobj);
		if (logobj != NULL) {
			CHECKM(ns_log_configure(logc, logobj),
			       "configuring logging");
		} else {
			CHECKM(ns_log_setdefaultchannels(logc),
			       "setting up default logging channels");
			CHECKM(ns_log_setunmatchedcategory(logc),
			       "setting up default 'category unmatched'");
			CHECKM(ns_log_setdefaultcategory(logc),
			       "setting up default 'category default'");
		}

		result = isc_logconfig_use(ns_g_lctx, logc);
		if (result != ISC_R_SUCCESS) {
			isc_logconfig_destroy(&logc);
			CHECKM(result, "installing logging configuration");
		}

		isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
			      NS_LOGMODULE_SERVER, ISC_LOG_DEBUG(1),
			      "now using logging configuration from "
			      "config file");
	}

	/*
	 * Set the default value of the query logging flag depending
	 * whether a "queries" category has been defined.  This is
	 * a disgusting hack, but we need to do this for BIND 8
	 * compatibility.
	 */
	if (first_time) {
		const cfg_obj_t *logobj = NULL;
		const cfg_obj_t *categories = NULL;

		obj = NULL;
		if (ns_config_get(maps, "querylog", &obj) == ISC_R_SUCCESS) {
			server->log_queries = cfg_obj_asboolean(obj);
		} else {

			(void)cfg_map_get(config, "logging", &logobj);
			if (logobj != NULL)
				(void)cfg_map_get(logobj, "category",
						  &categories);
			if (categories != NULL) {
				const cfg_listelt_t *element;
				for (element = cfg_list_first(categories);
				     element != NULL;
				     element = cfg_list_next(element))
				{
					const cfg_obj_t *catobj;
					const char *str;

					obj = cfg_listelt_value(element);
					catobj = cfg_tuple_get(obj, "name");
					str = cfg_obj_asstring(catobj);
					if (strcasecmp(str, "queries") == 0)
						server->log_queries = ISC_TRUE;
				}
			}
		}
	}

	obj = NULL;
	if (ns_config_get(maps, "pid-file", &obj) == ISC_R_SUCCESS)
		if (cfg_obj_isvoid(obj))
			ns_os_writepidfile(NULL, first_time);
		else
			ns_os_writepidfile(cfg_obj_asstring(obj), first_time);
	else if (ns_g_lwresdonly)
		ns_os_writepidfile(lwresd_g_defaultpidfile, first_time);
	else
		ns_os_writepidfile(ns_g_defaultpidfile, first_time);

	obj = NULL;
	if (options != NULL &&
	    cfg_map_get(options, "memstatistics", &obj) == ISC_R_SUCCESS)
		ns_g_memstatistics = cfg_obj_asboolean(obj);
	else
		ns_g_memstatistics =
			ISC_TF((isc_mem_debugging & ISC_MEM_DEBUGRECORD) != 0);

	obj = NULL;
	if (ns_config_get(maps, "memstatistics-file", &obj) == ISC_R_SUCCESS)
		ns_main_setmemstats(cfg_obj_asstring(obj));
	else if (ns_g_memstatistics)
		ns_main_setmemstats("named.memstats");
	else
		ns_main_setmemstats(NULL);

	obj = NULL;
	result = ns_config_get(maps, "statistics-file", &obj);
	INSIST(result == ISC_R_SUCCESS);
	CHECKM(setstring(server, &server->statsfile, cfg_obj_asstring(obj)),
	       "strdup");

	obj = NULL;
	result = ns_config_get(maps, "dump-file", &obj);
	INSIST(result == ISC_R_SUCCESS);
	CHECKM(setstring(server, &server->dumpfile, cfg_obj_asstring(obj)),
	       "strdup");

	obj = NULL;
	result = ns_config_get(maps, "recursing-file", &obj);
	INSIST(result == ISC_R_SUCCESS);
	CHECKM(setstring(server, &server->recfile, cfg_obj_asstring(obj)),
	       "strdup");

	obj = NULL;
	result = ns_config_get(maps, "version", &obj);
	if (result == ISC_R_SUCCESS) {
		CHECKM(setoptstring(server, &server->version, obj), "strdup");
		server->version_set = ISC_TRUE;
	} else {
		server->version_set = ISC_FALSE;
	}

	obj = NULL;
	result = ns_config_get(maps, "hostname", &obj);
	if (result == ISC_R_SUCCESS) {
		CHECKM(setoptstring(server, &server->hostname, obj), "strdup");
		server->hostname_set = ISC_TRUE;
	} else {
		server->hostname_set = ISC_FALSE;
	}

	obj = NULL;
	result = ns_config_get(maps, "server-id", &obj);
	server->server_usehostname = ISC_FALSE;
	if (result == ISC_R_SUCCESS && cfg_obj_isboolean(obj)) {
		/* The parser translates "hostname" to ISC_TRUE */
		server->server_usehostname = cfg_obj_asboolean(obj);
		result = setstring(server, &server->server_id, NULL);
		RUNTIME_CHECK(result == ISC_R_SUCCESS);
	} else if (result == ISC_R_SUCCESS) {
		/* Found a quoted string */
		CHECKM(setoptstring(server, &server->server_id, obj), "strdup");
	} else {
		result = setstring(server, &server->server_id, NULL);
		RUNTIME_CHECK(result == ISC_R_SUCCESS);
	}

	obj = NULL;
	result = ns_config_get(maps, "flush-zones-on-shutdown", &obj);
	if (result == ISC_R_SUCCESS) {
		server->flushonshutdown = cfg_obj_asboolean(obj);
	} else {
		server->flushonshutdown = ISC_FALSE;
	}

	result = ISC_R_SUCCESS;

 cleanup:
	if (v4portset != NULL)
		isc_portset_destroy(ns_g_mctx, &v4portset);

	if (v6portset != NULL)
		isc_portset_destroy(ns_g_mctx, &v6portset);

	cfg_aclconfctx_destroy(&aclconfctx);

	if (parser != NULL) {
		if (config != NULL)
			cfg_obj_destroy(parser, &config);
		cfg_parser_destroy(&parser);
	}

	if (view != NULL)
		dns_view_detach(&view);

	/*
	 * This cleans up either the old production view list
	 * or our temporary list depending on whether they
	 * were swapped above or not.
	 */
	for (view = ISC_LIST_HEAD(viewlist);
	     view != NULL;
	     view = view_next) {
		view_next = ISC_LIST_NEXT(view, link);
		ISC_LIST_UNLINK(viewlist, view, link);
		if (result == ISC_R_SUCCESS &&
		    strcmp(view->name, "_bind") != 0)
			(void)dns_zt_apply(view->zonetable, ISC_FALSE,
					   removed, view);
		dns_view_detach(&view);
	}

	/*
	 * Adjust the listening interfaces in accordance with the source
	 * addresses specified in views and zones.
	 */
	if (isc_net_probeipv6() == ISC_R_SUCCESS)
		adjust_interfaces(server, ns_g_mctx);

	/* Relinquish exclusive access to configuration data. */
	isc_task_endexclusive(server->task);

	isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER,
		      ISC_LOG_DEBUG(1), "load_configuration: %s",
		      isc_result_totext(result));

	return (result);
}

static isc_result_t
load_zones(ns_server_t *server, isc_boolean_t stop) {
	isc_result_t result;
	dns_view_t *view;

	result = isc_task_beginexclusive(server->task);
	RUNTIME_CHECK(result == ISC_R_SUCCESS);

	/*
	 * Load zone data from disk.
	 */
	for (view = ISC_LIST_HEAD(server->viewlist);
	     view != NULL;
	     view = ISC_LIST_NEXT(view, link))
	{
		CHECK(dns_view_load(view, stop));
	}

	/*
	 * Force zone maintenance.  Do this after loading
	 * so that we know when we need to force AXFR of
	 * slave zones whose master files are missing.
	 */
	CHECK(dns_zonemgr_forcemaint(server->zonemgr));
 cleanup:
	isc_task_endexclusive(server->task);
	return (result);
}

static isc_result_t
load_new_zones(ns_server_t *server, isc_boolean_t stop) {
	isc_result_t result;
	dns_view_t *view;

	result = isc_task_beginexclusive(server->task);
	RUNTIME_CHECK(result == ISC_R_SUCCESS);

	/*
	 * Load zone data from disk.
	 */
	for (view = ISC_LIST_HEAD(server->viewlist);
	     view != NULL;
	     view = ISC_LIST_NEXT(view, link))
	{
		CHECK(dns_view_loadnew(view, stop));
	}
	/*
	 * Force zone maintenance.  Do this after loading
	 * so that we know when we need to force AXFR of
	 * slave zones whose master files are missing.
	 */
	dns_zonemgr_resumexfrs(server->zonemgr);
 cleanup:
	isc_task_endexclusive(server->task);
	return (result);
}

static void
run_server(isc_task_t *task, isc_event_t *event) {
	isc_result_t result;
	ns_server_t *server = (ns_server_t *)event->ev_arg;

	INSIST(task == server->task);

	isc_event_free(&event);

	CHECKFATAL(dns_dispatchmgr_create(ns_g_mctx, ns_g_entropy,
					  &ns_g_dispatchmgr),
		   "creating dispatch manager");

	dns_dispatchmgr_setstats(ns_g_dispatchmgr, server->resolverstats);

	CHECKFATAL(ns_interfacemgr_create(ns_g_mctx, ns_g_taskmgr,
					  ns_g_socketmgr, ns_g_dispatchmgr,
					  &server->interfacemgr),
		   "creating interface manager");

	CHECKFATAL(isc_timer_create(ns_g_timermgr, isc_timertype_inactive,
				    NULL, NULL, server->task,
				    interface_timer_tick,
				    server, &server->interface_timer),
		   "creating interface timer");

	CHECKFATAL(isc_timer_create(ns_g_timermgr, isc_timertype_inactive,
				    NULL, NULL, server->task,
				    heartbeat_timer_tick,
				    server, &server->heartbeat_timer),
		   "creating heartbeat timer");

	CHECKFATAL(isc_timer_create(ns_g_timermgr, isc_timertype_inactive,
				    NULL, NULL, server->task, pps_timer_tick,
				    server, &server->pps_timer),
		   "creating pps timer");

	CHECKFATAL(cfg_parser_create(ns_g_mctx, NULL, &ns_g_parser),
		   "creating default configuration parser");

	if (ns_g_lwresdonly)
		CHECKFATAL(load_configuration(lwresd_g_conffile, server,
					      ISC_TRUE),
			   "loading configuration");
	else
		CHECKFATAL(load_configuration(ns_g_conffile, server, ISC_TRUE),
			   "loading configuration");

	isc_hash_init();

	CHECKFATAL(load_zones(server, ISC_FALSE), "loading zones");

	ns_os_started();
	isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER,
		      ISC_LOG_NOTICE, "running");
}

void
ns_server_flushonshutdown(ns_server_t *server, isc_boolean_t flush) {

	REQUIRE(NS_SERVER_VALID(server));

	server->flushonshutdown = flush;
}

static void
shutdown_server(isc_task_t *task, isc_event_t *event) {
	isc_result_t result;
	dns_view_t *view, *view_next;
	ns_server_t *server = (ns_server_t *)event->ev_arg;
	isc_boolean_t flush = server->flushonshutdown;

	UNUSED(task);
	INSIST(task == server->task);

	result = isc_task_beginexclusive(server->task);
	RUNTIME_CHECK(result == ISC_R_SUCCESS);

	isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER,
		      ISC_LOG_INFO, "shutting down%s",
		      flush ? ": flushing changes" : "");

	ns_statschannels_shutdown(server);
	ns_controls_shutdown(server->controls);
	end_reserved_dispatches(server, ISC_TRUE);

	cfg_obj_destroy(ns_g_parser, &ns_g_config);
	cfg_parser_destroy(&ns_g_parser);

	for (view = ISC_LIST_HEAD(server->viewlist);
	     view != NULL;
	     view = view_next) {
		view_next = ISC_LIST_NEXT(view, link);
		ISC_LIST_UNLINK(server->viewlist, view, link);
		if (flush)
			dns_view_flushanddetach(&view);
		else
			dns_view_detach(&view);
	}

	isc_timer_detach(&server->interface_timer);
	isc_timer_detach(&server->heartbeat_timer);
	isc_timer_detach(&server->pps_timer);

	ns_interfacemgr_shutdown(server->interfacemgr);
	ns_interfacemgr_detach(&server->interfacemgr);

	dns_dispatchmgr_destroy(&ns_g_dispatchmgr);

	dns_zonemgr_shutdown(server->zonemgr);

	if (server->blackholeacl != NULL)
		dns_acl_detach(&server->blackholeacl);

	dns_db_detach(&server->in_roothints);

	isc_task_endexclusive(server->task);

	isc_task_detach(&server->task);

	isc_event_free(&event);
}

void
ns_server_create(isc_mem_t *mctx, ns_server_t **serverp) {
	isc_result_t result;

	ns_server_t *server = isc_mem_get(mctx, sizeof(*server));
	if (server == NULL)
		fatal("allocating server object", ISC_R_NOMEMORY);

	server->mctx = mctx;
	server->task = NULL;

	/* Initialize configuration data with default values. */

	result = isc_quota_init(&server->xfroutquota, 10);
	RUNTIME_CHECK(result == ISC_R_SUCCESS);
	result = isc_quota_init(&server->tcpquota, 10);
	RUNTIME_CHECK(result == ISC_R_SUCCESS);
	result = isc_quota_init(&server->recursionquota, 100);
	RUNTIME_CHECK(result == ISC_R_SUCCESS);

	result = dns_aclenv_init(mctx, &server->aclenv);
	RUNTIME_CHECK(result == ISC_R_SUCCESS);

	/* Initialize server data structures. */
	server->zonemgr = NULL;
	server->interfacemgr = NULL;
	ISC_LIST_INIT(server->viewlist);
	server->in_roothints = NULL;
	server->blackholeacl = NULL;

	CHECKFATAL(dns_rootns_create(mctx, dns_rdataclass_in, NULL,
				     &server->in_roothints),
		   "setting up root hints");

	CHECKFATAL(isc_mutex_init(&server->reload_event_lock),
		   "initializing reload event lock");
	server->reload_event =
		isc_event_allocate(ns_g_mctx, server,
				   NS_EVENT_RELOAD,
				   ns_server_reload,
				   server,
				   sizeof(isc_event_t));
	CHECKFATAL(server->reload_event == NULL ?
		   ISC_R_NOMEMORY : ISC_R_SUCCESS,
		   "allocating reload event");

	CHECKFATAL(dst_lib_init(ns_g_mctx, ns_g_entropy, ISC_ENTROPY_GOODONLY),
		   "initializing DST");

	server->tkeyctx = NULL;
	CHECKFATAL(dns_tkeyctx_create(ns_g_mctx, ns_g_entropy,
				      &server->tkeyctx),
		   "creating TKEY context");

	/*
	 * Setup the server task, which is responsible for coordinating
	 * startup and shutdown of the server.
	 */
	CHECKFATAL(isc_task_create(ns_g_taskmgr, 0, &server->task),
		   "creating server task");
	isc_task_setname(server->task, "server", server);
	CHECKFATAL(isc_task_onshutdown(server->task, shutdown_server, server),
		   "isc_task_onshutdown");
	CHECKFATAL(isc_app_onrun(ns_g_mctx, server->task, run_server, server),
		   "isc_app_onrun");

	server->interface_timer = NULL;
	server->heartbeat_timer = NULL;
	server->pps_timer = NULL;

	server->interface_interval = 0;
	server->heartbeat_interval = 0;

	CHECKFATAL(dns_zonemgr_create(ns_g_mctx, ns_g_taskmgr, ns_g_timermgr,
				      ns_g_socketmgr, &server->zonemgr),
		   "dns_zonemgr_create");

	server->statsfile = isc_mem_strdup(server->mctx, "named.stats");
	CHECKFATAL(server->statsfile == NULL ? ISC_R_NOMEMORY : ISC_R_SUCCESS,
		   "isc_mem_strdup");
	server->nsstats = NULL;
	server->rcvquerystats = NULL;
	server->opcodestats = NULL;
	server->zonestats = NULL;
	server->resolverstats = NULL;

	server->dumpfile = isc_mem_strdup(server->mctx, "named_dump.db");
	CHECKFATAL(server->dumpfile == NULL ? ISC_R_NOMEMORY : ISC_R_SUCCESS,
		   "isc_mem_strdup");

	server->recfile = isc_mem_strdup(server->mctx, "named.recursing");
	CHECKFATAL(server->recfile == NULL ? ISC_R_NOMEMORY : ISC_R_SUCCESS,
		   "isc_mem_strdup");

	server->hostname_set = ISC_FALSE;
	server->hostname = NULL;
	server->version_set = ISC_FALSE;
	server->version = NULL;
	server->server_usehostname = ISC_FALSE;
	server->server_id = NULL;

	CHECKFATAL(dns_generalstats_create(ns_g_mctx, &server->nsstats,
					   dns_nsstatscounter_max),
		   "dns_stats_create (server)");

	CHECKFATAL(dns_rdatatypestats_create(ns_g_mctx,
					     &server->rcvquerystats),
		   "dns_stats_create (rcvquery)");

	CHECKFATAL(dns_opcodestats_create(ns_g_mctx, &server->opcodestats),
		   "dns_stats_create (opcode)");

	CHECKFATAL(dns_generalstats_create(ns_g_mctx, &server->zonestats,
					   dns_zonestatscounter_max),
		   "dns_stats_create (zone)");

	CHECKFATAL(dns_generalstats_create(ns_g_mctx, &server->resolverstats,
					   dns_resstatscounter_max),
		   "dns_stats_create (resolver)");

	server->flushonshutdown = ISC_FALSE;
	server->log_queries = ISC_FALSE;

	server->controls = NULL;
	CHECKFATAL(ns_controls_create(server, &server->controls),
		   "ns_controls_create");
	server->dispatchgen = 0;
	ISC_LIST_INIT(server->dispatches);

	ISC_LIST_INIT(server->statschannels);

	server->magic = NS_SERVER_MAGIC;
	*serverp = server;
}

void
ns_server_destroy(ns_server_t **serverp) {
	ns_server_t *server = *serverp;
	REQUIRE(NS_SERVER_VALID(server));

	ns_controls_destroy(&server->controls);

	dns_stats_detach(&server->nsstats);
	dns_stats_detach(&server->rcvquerystats);
	dns_stats_detach(&server->opcodestats);
	dns_stats_detach(&server->zonestats);
	dns_stats_detach(&server->resolverstats);

	isc_mem_free(server->mctx, server->statsfile);
	isc_mem_free(server->mctx, server->dumpfile);
	isc_mem_free(server->mctx, server->recfile);

	if (server->version != NULL)
		isc_mem_free(server->mctx, server->version);
	if (server->hostname != NULL)
		isc_mem_free(server->mctx, server->hostname);
	if (server->server_id != NULL)
		isc_mem_free(server->mctx, server->server_id);

	dns_zonemgr_detach(&server->zonemgr);

	if (server->tkeyctx != NULL)
		dns_tkeyctx_destroy(&server->tkeyctx);

	dst_lib_destroy();

	isc_event_free(&server->reload_event);

	INSIST(ISC_LIST_EMPTY(server->viewlist));

	dns_aclenv_destroy(&server->aclenv);

	isc_quota_destroy(&server->recursionquota);
	isc_quota_destroy(&server->tcpquota);
	isc_quota_destroy(&server->xfroutquota);

	server->magic = 0;
	isc_mem_put(server->mctx, server, sizeof(*server));
	*serverp = NULL;
}

static void
fatal(const char *msg, isc_result_t result) {
	isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER,
		      ISC_LOG_CRITICAL, "%s: %s", msg,
		      isc_result_totext(result));
	isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER,
		      ISC_LOG_CRITICAL, "exiting (due to fatal error)");
	exit(1);
}

static void
start_reserved_dispatches(ns_server_t *server) {

	REQUIRE(NS_SERVER_VALID(server));

	server->dispatchgen++;
}

static void
end_reserved_dispatches(ns_server_t *server, isc_boolean_t all) {
	ns_dispatch_t *dispatch, *nextdispatch;

	REQUIRE(NS_SERVER_VALID(server));

	for (dispatch = ISC_LIST_HEAD(server->dispatches);
	     dispatch != NULL;
	     dispatch = nextdispatch) {
		nextdispatch = ISC_LIST_NEXT(dispatch, link);
		if (!all && server->dispatchgen == dispatch-> dispatchgen)
			continue;
		ISC_LIST_UNLINK(server->dispatches, dispatch, link);
		dns_dispatch_detach(&dispatch->dispatch);
		isc_mem_put(server->mctx, dispatch, sizeof(*dispatch));
	}
}

void
ns_add_reserved_dispatch(ns_server_t *server, const isc_sockaddr_t *addr) {
	ns_dispatch_t *dispatch;
	in_port_t port;
	char addrbuf[ISC_SOCKADDR_FORMATSIZE];
	isc_result_t result;
	unsigned int attrs, attrmask;

	REQUIRE(NS_SERVER_VALID(server));

	port = isc_sockaddr_getport(addr);
	if (port == 0 || port >= 1024)
		return;

	for (dispatch = ISC_LIST_HEAD(server->dispatches);
	     dispatch != NULL;
	     dispatch = ISC_LIST_NEXT(dispatch, link)) {
		if (isc_sockaddr_equal(&dispatch->addr, addr))
			break;
	}
	if (dispatch != NULL) {
		dispatch->dispatchgen = server->dispatchgen;
		return;
	}

	dispatch = isc_mem_get(server->mctx, sizeof(*dispatch));
	if (dispatch == NULL) {
		result = ISC_R_NOMEMORY;
		goto cleanup;
	}

	dispatch->addr = *addr;
	dispatch->dispatchgen = server->dispatchgen;
	dispatch->dispatch = NULL;

	attrs = 0;
	attrs |= DNS_DISPATCHATTR_UDP;
	switch (isc_sockaddr_pf(addr)) {
	case AF_INET:
		attrs |= DNS_DISPATCHATTR_IPV4;
		break;
	case AF_INET6:
		attrs |= DNS_DISPATCHATTR_IPV6;
		break;
	default:
		result = ISC_R_NOTIMPLEMENTED;
		goto cleanup;
	}
	attrmask = 0;
	attrmask |= DNS_DISPATCHATTR_UDP;
	attrmask |= DNS_DISPATCHATTR_TCP;
	attrmask |= DNS_DISPATCHATTR_IPV4;
	attrmask |= DNS_DISPATCHATTR_IPV6;

	result = dns_dispatch_getudp(ns_g_dispatchmgr, ns_g_socketmgr,
				     ns_g_taskmgr, &dispatch->addr, 4096,
				     1000, 32768, 16411, 16433,
				     attrs, attrmask, &dispatch->dispatch);
	if (result != ISC_R_SUCCESS)
		goto cleanup;

	ISC_LIST_INITANDPREPEND(server->dispatches, dispatch, link);

	return;

 cleanup:
	if (dispatch != NULL)
		isc_mem_put(server->mctx, dispatch, sizeof(*dispatch));
	isc_sockaddr_format(addr, addrbuf, sizeof(addrbuf));
	isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
		      NS_LOGMODULE_SERVER, ISC_LOG_WARNING,
		      "unable to create dispatch for reserved port %s: %s",
		      addrbuf, isc_result_totext(result));
}


static isc_result_t
loadconfig(ns_server_t *server) {
	isc_result_t result;
	start_reserved_dispatches(server);
	result = load_configuration(ns_g_lwresdonly ?
				    lwresd_g_conffile : ns_g_conffile,
				    server, ISC_FALSE);
	if (result == ISC_R_SUCCESS) {
		end_reserved_dispatches(server, ISC_FALSE);
		isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
			      NS_LOGMODULE_SERVER, ISC_LOG_INFO,
			      "reloading configuration succeeded");
	} else {
		isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
			      NS_LOGMODULE_SERVER, ISC_LOG_ERROR,
			      "reloading configuration failed: %s",
			      isc_result_totext(result));
	}
	return (result);
}

static isc_result_t
reload(ns_server_t *server) {
	isc_result_t result;
	CHECK(loadconfig(server));

	result = load_zones(server, ISC_FALSE);
	if (result == ISC_R_SUCCESS)
		isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
			      NS_LOGMODULE_SERVER, ISC_LOG_INFO,
			      "reloading zones succeeded");
	else
		isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
			      NS_LOGMODULE_SERVER, ISC_LOG_ERROR,
			      "reloading zones failed: %s",
			      isc_result_totext(result));

 cleanup:
	return (result);
}

static void
reconfig(ns_server_t *server) {
	isc_result_t result;
	CHECK(loadconfig(server));

	result = load_new_zones(server, ISC_FALSE);
	if (result == ISC_R_SUCCESS)
		isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
			      NS_LOGMODULE_SERVER, ISC_LOG_INFO,
			      "any newly configured zones are now loaded");
	else
		isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
			      NS_LOGMODULE_SERVER, ISC_LOG_ERROR,
			      "loading new zones failed: %s",
			      isc_result_totext(result));

 cleanup: ;
}

/*
 * Handle a reload event (from SIGHUP).
 */
static void
ns_server_reload(isc_task_t *task, isc_event_t *event) {
	ns_server_t *server = (ns_server_t *)event->ev_arg;

	INSIST(task = server->task);
	UNUSED(task);

	isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
		      NS_LOGMODULE_SERVER, ISC_LOG_INFO,
		      "received SIGHUP signal to reload zones");
	(void)reload(server);

	LOCK(&server->reload_event_lock);
	INSIST(server->reload_event == NULL);
	server->reload_event = event;
	UNLOCK(&server->reload_event_lock);
}

void
ns_server_reloadwanted(ns_server_t *server) {
	LOCK(&server->reload_event_lock);
	if (server->reload_event != NULL)
		isc_task_send(server->task, &server->reload_event);
	UNLOCK(&server->reload_event_lock);
}

static char *
next_token(char **stringp, const char *delim) {
	char *res;

	do {
		res = strsep(stringp, delim);
		if (res == NULL)
			break;
	} while (*res == '\0');
	return (res);
}

/*
 * Find the zone specified in the control channel command 'args',
 * if any.  If a zone is specified, point '*zonep' at it, otherwise
 * set '*zonep' to NULL.
 */
static isc_result_t
zone_from_args(ns_server_t *server, char *args, dns_zone_t **zonep) {
	char *input, *ptr;
	const char *zonetxt;
	char *classtxt;
	const char *viewtxt = NULL;
	dns_fixedname_t name;
	isc_result_t result;
	isc_buffer_t buf;
	dns_view_t *view = NULL;
	dns_rdataclass_t rdclass;

	REQUIRE(zonep != NULL && *zonep == NULL);

	input = args;

	/* Skip the command name. */
	ptr = next_token(&input, " \t");
	if (ptr == NULL)
		return (ISC_R_UNEXPECTEDEND);

	/* Look for the zone name. */
	zonetxt = next_token(&input, " \t");
	if (zonetxt == NULL)
		return (ISC_R_SUCCESS);

	/* Look for the optional class name. */
	classtxt = next_token(&input, " \t");
	if (classtxt != NULL) {
		/* Look for the optional view name. */
		viewtxt = next_token(&input, " \t");
	}

	isc_buffer_init(&buf, zonetxt, strlen(zonetxt));
	isc_buffer_add(&buf, strlen(zonetxt));
	dns_fixedname_init(&name);
	result = dns_name_fromtext(dns_fixedname_name(&name),
				   &buf, dns_rootname, ISC_FALSE, NULL);
	if (result != ISC_R_SUCCESS)
		goto fail1;

	if (classtxt != NULL) {
		isc_textregion_t r;
		r.base = classtxt;
		r.length = strlen(classtxt);
		result = dns_rdataclass_fromtext(&rdclass, &r);
		if (result != ISC_R_SUCCESS)
			goto fail1;
	} else
		rdclass = dns_rdataclass_in;

	if (viewtxt == NULL) {
		result = dns_viewlist_findzone(&server->viewlist,
					       dns_fixedname_name(&name),
					       ISC_TF(classtxt == NULL),
					       rdclass, zonep);
	} else {
		result = dns_viewlist_find(&server->viewlist, viewtxt,
					   rdclass, &view);
		if (result != ISC_R_SUCCESS)
			goto fail1;

		result = dns_zt_find(view->zonetable, dns_fixedname_name(&name),
				     0, NULL, zonep);
		dns_view_detach(&view);
	}

	/* Partial match? */
	if (result != ISC_R_SUCCESS && *zonep != NULL)
		dns_zone_detach(zonep);
 fail1:
	return (result);
}

/*
 * Act on a "retransfer" command from the command channel.
 */
isc_result_t
ns_server_retransfercommand(ns_server_t *server, char *args) {
	isc_result_t result;
	dns_zone_t *zone = NULL;
	dns_zonetype_t type;

	result = zone_from_args(server, args, &zone);
	if (result != ISC_R_SUCCESS)
		return (result);
	if (zone == NULL)
		return (ISC_R_UNEXPECTEDEND);
	type = dns_zone_gettype(zone);
	if (type == dns_zone_slave || type == dns_zone_stub)
		dns_zone_forcereload(zone);
	else
		result = ISC_R_NOTFOUND;
	dns_zone_detach(&zone);
	return (result);
}

/*
 * Act on a "reload" command from the command channel.
 */
isc_result_t
ns_server_reloadcommand(ns_server_t *server, char *args, isc_buffer_t *text) {
	isc_result_t result;
	dns_zone_t *zone = NULL;
	dns_zonetype_t type;
	const char *msg = NULL;

	result = zone_from_args(server, args, &zone);
	if (result != ISC_R_SUCCESS)
		return (result);
	if (zone == NULL) {
		result = reload(server);
		if (result == ISC_R_SUCCESS)
			msg = "server reload successful";
	} else {
		type = dns_zone_gettype(zone);
		if (type == dns_zone_slave || type == dns_zone_stub) {
			dns_zone_refresh(zone);
			dns_zone_detach(&zone);
			msg = "zone refresh queued";
		} else {
			result = dns_zone_load(zone);
			dns_zone_detach(&zone);
			switch (result) {
			case ISC_R_SUCCESS:
				 msg = "zone reload successful";
				 break;
			case DNS_R_CONTINUE:
				msg = "zone reload queued";
				result = ISC_R_SUCCESS;
				break;
			case DNS_R_UPTODATE:
				msg = "zone reload up-to-date";
				result = ISC_R_SUCCESS;
				break;
			default:
				/* failure message will be generated by rndc */
				break;
			}
		}
	}
	if (msg != NULL && strlen(msg) < isc_buffer_availablelength(text))
		isc_buffer_putmem(text, (const unsigned char *)msg,
				  strlen(msg) + 1);
	return (result);
}

/*
 * Act on a "reconfig" command from the command channel.
 */
isc_result_t
ns_server_reconfigcommand(ns_server_t *server, char *args) {
	UNUSED(args);

	reconfig(server);
	return (ISC_R_SUCCESS);
}

/*
 * Act on a "notify" command from the command channel.
 */
isc_result_t
ns_server_notifycommand(ns_server_t *server, char *args, isc_buffer_t *text) {
	isc_result_t result;
	dns_zone_t *zone = NULL;
	const unsigned char msg[] = "zone notify queued";

	result = zone_from_args(server, args, &zone);
	if (result != ISC_R_SUCCESS)
		return (result);
	if (zone == NULL)
		return (ISC_R_UNEXPECTEDEND);

	dns_zone_notify(zone);
	dns_zone_detach(&zone);
	if (sizeof(msg) <= isc_buffer_availablelength(text))
		isc_buffer_putmem(text, msg, sizeof(msg));

	return (ISC_R_SUCCESS);
}

/*
 * Act on a "refresh" command from the command channel.
 */
isc_result_t
ns_server_refreshcommand(ns_server_t *server, char *args, isc_buffer_t *text) {
	isc_result_t result;
	dns_zone_t *zone = NULL;
	const unsigned char msg1[] = "zone refresh queued";
	const unsigned char msg2[] = "not a slave or stub zone";
	dns_zonetype_t type;

	result = zone_from_args(server, args, &zone);
	if (result != ISC_R_SUCCESS)
		return (result);
	if (zone == NULL)
		return (ISC_R_UNEXPECTEDEND);

	type = dns_zone_gettype(zone);
	if (type == dns_zone_slave || type == dns_zone_stub) {
		dns_zone_refresh(zone);
		dns_zone_detach(&zone);
		if (sizeof(msg1) <= isc_buffer_availablelength(text))
			isc_buffer_putmem(text, msg1, sizeof(msg1));
		return (ISC_R_SUCCESS);
	}

	dns_zone_detach(&zone);
	if (sizeof(msg2) <= isc_buffer_availablelength(text))
		isc_buffer_putmem(text, msg2, sizeof(msg2));
	return (ISC_R_FAILURE);
}

isc_result_t
ns_server_togglequerylog(ns_server_t *server) {
	server->log_queries = server->log_queries ? ISC_FALSE : ISC_TRUE;

	isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
		      NS_LOGMODULE_SERVER, ISC_LOG_INFO,
		      "query logging is now %s",
		      server->log_queries ? "on" : "off");
	return (ISC_R_SUCCESS);
}

static isc_result_t
ns_listenlist_fromconfig(const cfg_obj_t *listenlist, const cfg_obj_t *config,
			 cfg_aclconfctx_t *actx,
			 isc_mem_t *mctx, ns_listenlist_t **target)
{
	isc_result_t result;
	const cfg_listelt_t *element;
	ns_listenlist_t *dlist = NULL;

	REQUIRE(target != NULL && *target == NULL);

	result = ns_listenlist_create(mctx, &dlist);
	if (result != ISC_R_SUCCESS)
		return (result);

	for (element = cfg_list_first(listenlist);
	     element != NULL;
	     element = cfg_list_next(element))
	{
		ns_listenelt_t *delt = NULL;
		const cfg_obj_t *listener = cfg_listelt_value(element);
		result = ns_listenelt_fromconfig(listener, config, actx,
						 mctx, &delt);
		if (result != ISC_R_SUCCESS)
			goto cleanup;
		ISC_LIST_APPEND(dlist->elts, delt, link);
	}
	*target = dlist;
	return (ISC_R_SUCCESS);

 cleanup:
	ns_listenlist_detach(&dlist);
	return (result);
}

/*
 * Create a listen list from the corresponding configuration
 * data structure.
 */
static isc_result_t
ns_listenelt_fromconfig(const cfg_obj_t *listener, const cfg_obj_t *config,
			cfg_aclconfctx_t *actx,
			isc_mem_t *mctx, ns_listenelt_t **target)
{
	isc_result_t result;
	const cfg_obj_t *portobj;
	in_port_t port;
	ns_listenelt_t *delt = NULL;
	REQUIRE(target != NULL && *target == NULL);

	portobj = cfg_tuple_get(listener, "port");
	if (!cfg_obj_isuint32(portobj)) {
		if (ns_g_port != 0) {
			port = ns_g_port;
		} else {
			result = ns_config_getport(config, &port);
			if (result != ISC_R_SUCCESS)
				return (result);
		}
	} else {
		if (cfg_obj_asuint32(portobj) >= ISC_UINT16_MAX) {
			cfg_obj_log(portobj, ns_g_lctx, ISC_LOG_ERROR,
				    "port value '%u' is out of range",
				    cfg_obj_asuint32(portobj));
			return (ISC_R_RANGE);
		}
		port = (in_port_t)cfg_obj_asuint32(portobj);
	}

	result = ns_listenelt_create(mctx, port, NULL, &delt);
	if (result != ISC_R_SUCCESS)
		return (result);

	result = cfg_acl_fromconfig(cfg_tuple_get(listener, "acl"),
				   config, ns_g_lctx, actx, mctx, 0,
				   &delt->acl);
	if (result != ISC_R_SUCCESS) {
		ns_listenelt_destroy(delt);
		return (result);
	}
	*target = delt;
	return (ISC_R_SUCCESS);
}

isc_result_t
ns_server_dumpstats(ns_server_t *server) {
	isc_result_t result;
	FILE *fp = NULL;

	CHECKMF(isc_stdio_open(server->statsfile, "a", &fp),
		"could not open statistics dump file", server->statsfile);

	result = ns_stats_dump(server, fp);
	CHECK(result);

 cleanup:
	if (fp != NULL)
		(void)isc_stdio_close(fp);
	if (result == ISC_R_SUCCESS)
		isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
			      NS_LOGMODULE_SERVER, ISC_LOG_INFO,
			      "dumpstats complete");
	else
		isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
			      NS_LOGMODULE_SERVER, ISC_LOG_ERROR,
			      "dumpstats failed: %s",
			      dns_result_totext(result));
	return (result);
}

static isc_result_t
add_zone_tolist(dns_zone_t *zone, void *uap) {
	struct dumpcontext *dctx = uap;
	struct zonelistentry *zle;

	zle = isc_mem_get(dctx->mctx, sizeof *zle);
	if (zle ==  NULL)
		return (ISC_R_NOMEMORY);
	zle->zone = NULL;
	dns_zone_attach(zone, &zle->zone);
	ISC_LINK_INIT(zle, link);
	ISC_LIST_APPEND(ISC_LIST_TAIL(dctx->viewlist)->zonelist, zle, link);
	return (ISC_R_SUCCESS);
}

static isc_result_t
add_view_tolist(struct dumpcontext *dctx, dns_view_t *view) {
	struct viewlistentry *vle;
	isc_result_t result = ISC_R_SUCCESS;

	/*
	 * Prevent duplicate views.
	 */
	for (vle = ISC_LIST_HEAD(dctx->viewlist);
	     vle != NULL;
	     vle = ISC_LIST_NEXT(vle, link))
		if (vle->view == view)
			return (ISC_R_SUCCESS);

	vle = isc_mem_get(dctx->mctx, sizeof *vle);
	if (vle == NULL)
		return (ISC_R_NOMEMORY);
	vle->view = NULL;
	dns_view_attach(view, &vle->view);
	ISC_LINK_INIT(vle, link);
	ISC_LIST_INIT(vle->zonelist);
	ISC_LIST_APPEND(dctx->viewlist, vle, link);
	if (dctx->dumpzones)
		result = dns_zt_apply(view->zonetable, ISC_TRUE,
				      add_zone_tolist, dctx);
	return (result);
}

static void
dumpcontext_destroy(struct dumpcontext *dctx) {
	struct viewlistentry *vle;
	struct zonelistentry *zle;

	vle = ISC_LIST_HEAD(dctx->viewlist);
	while (vle != NULL) {
		ISC_LIST_UNLINK(dctx->viewlist, vle, link);
		zle = ISC_LIST_HEAD(vle->zonelist);
		while (zle != NULL) {
			ISC_LIST_UNLINK(vle->zonelist, zle, link);
			dns_zone_detach(&zle->zone);
			isc_mem_put(dctx->mctx, zle, sizeof *zle);
			zle = ISC_LIST_HEAD(vle->zonelist);
		}
		dns_view_detach(&vle->view);
		isc_mem_put(dctx->mctx, vle, sizeof *vle);
		vle = ISC_LIST_HEAD(dctx->viewlist);
	}
	if (dctx->version != NULL)
		dns_db_closeversion(dctx->db, &dctx->version, ISC_FALSE);
	if (dctx->db != NULL)
		dns_db_detach(&dctx->db);
	if (dctx->cache != NULL)
		dns_db_detach(&dctx->cache);
	if (dctx->task != NULL)
		isc_task_detach(&dctx->task);
	if (dctx->fp != NULL)
		(void)isc_stdio_close(dctx->fp);
	if (dctx->mdctx != NULL)
		dns_dumpctx_detach(&dctx->mdctx);
	isc_mem_put(dctx->mctx, dctx, sizeof *dctx);
}

static void
dumpdone(void *arg, isc_result_t result) {
	struct dumpcontext *dctx = arg;
	char buf[1024+32];
	const dns_master_style_t *style;

	if (result != ISC_R_SUCCESS)
		goto cleanup;
	if (dctx->mdctx != NULL)
		dns_dumpctx_detach(&dctx->mdctx);
	if (dctx->view == NULL) {
		dctx->view = ISC_LIST_HEAD(dctx->viewlist);
		if (dctx->view == NULL)
			goto done;
		INSIST(dctx->zone == NULL);
	} else
		goto resume;
 nextview:
	fprintf(dctx->fp, ";\n; Start view %s\n;\n", dctx->view->view->name);
 resume:
	if (dctx->zone == NULL && dctx->cache == NULL && dctx->dumpcache) {
		style = &dns_master_style_cache;
		/* start cache dump */
		if (dctx->view->view->cachedb != NULL)
			dns_db_attach(dctx->view->view->cachedb, &dctx->cache);
		if (dctx->cache != NULL) {

			fprintf(dctx->fp, ";\n; Cache dump of view '%s'\n;\n",
				dctx->view->view->name);
			result = dns_master_dumptostreaminc(dctx->mctx,
							    dctx->cache, NULL,
							    style, dctx->fp,
							    dctx->task,
							    dumpdone, dctx,
							    &dctx->mdctx);
			if (result == DNS_R_CONTINUE)
				return;
			if (result == ISC_R_NOTIMPLEMENTED)
				fprintf(dctx->fp, "; %s\n",
					dns_result_totext(result));
			else if (result != ISC_R_SUCCESS)
				goto cleanup;
		}
	}
	if (dctx->cache != NULL) {
		dns_adb_dump(dctx->view->view->adb, dctx->fp);
		dns_db_detach(&dctx->cache);
	}
	if (dctx->dumpzones) {
		style = &dns_master_style_full;
 nextzone:
		if (dctx->version != NULL)
			dns_db_closeversion(dctx->db, &dctx->version,
					    ISC_FALSE);
		if (dctx->db != NULL)
			dns_db_detach(&dctx->db);
		if (dctx->zone == NULL)
			dctx->zone = ISC_LIST_HEAD(dctx->view->zonelist);
		else
			dctx->zone = ISC_LIST_NEXT(dctx->zone, link);
		if (dctx->zone != NULL) {
			/* start zone dump */
			dns_zone_name(dctx->zone->zone, buf, sizeof(buf));
			fprintf(dctx->fp, ";\n; Zone dump of '%s'\n;\n", buf);
			result = dns_zone_getdb(dctx->zone->zone, &dctx->db);
			if (result != ISC_R_SUCCESS) {
				fprintf(dctx->fp, "; %s\n",
					dns_result_totext(result));
				goto nextzone;
			}
			dns_db_currentversion(dctx->db, &dctx->version);
			result = dns_master_dumptostreaminc(dctx->mctx,
							    dctx->db,
							    dctx->version,
							    style, dctx->fp,
							    dctx->task,
							    dumpdone, dctx,
							    &dctx->mdctx);
			if (result == DNS_R_CONTINUE)
				return;
			if (result == ISC_R_NOTIMPLEMENTED) {
				fprintf(dctx->fp, "; %s\n",
					dns_result_totext(result));
				result = ISC_R_SUCCESS;
				goto nextzone;
			}
			if (result != ISC_R_SUCCESS)
				goto cleanup;
		}
	}
	if (dctx->view != NULL)
		dctx->view = ISC_LIST_NEXT(dctx->view, link);
	if (dctx->view != NULL)
		goto nextview;
 done:
	fprintf(dctx->fp, "; Dump complete\n");
	result = isc_stdio_flush(dctx->fp);
	if (result == ISC_R_SUCCESS)
		isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
			      NS_LOGMODULE_SERVER, ISC_LOG_INFO,
			      "dumpdb complete");
 cleanup:
	if (result != ISC_R_SUCCESS)
		isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
			      NS_LOGMODULE_SERVER, ISC_LOG_ERROR,
			      "dumpdb failed: %s", dns_result_totext(result));
	dumpcontext_destroy(dctx);
}

isc_result_t
ns_server_dumpdb(ns_server_t *server, char *args) {
	struct dumpcontext *dctx = NULL;
	dns_view_t *view;
	isc_result_t result;
	char *ptr;
	const char *sep;

	/* Skip the command name. */
	ptr = next_token(&args, " \t");
	if (ptr == NULL)
		return (ISC_R_UNEXPECTEDEND);

	dctx = isc_mem_get(server->mctx, sizeof(*dctx));
	if (dctx == NULL)
		return (ISC_R_NOMEMORY);

	dctx->mctx = server->mctx;
	dctx->dumpcache = ISC_TRUE;
	dctx->dumpzones = ISC_FALSE;
	dctx->fp = NULL;
	ISC_LIST_INIT(dctx->viewlist);
	dctx->view = NULL;
	dctx->zone = NULL;
	dctx->cache = NULL;
	dctx->mdctx = NULL;
	dctx->db = NULL;
	dctx->cache = NULL;
	dctx->task = NULL;
	dctx->version = NULL;
	isc_task_attach(server->task, &dctx->task);

	CHECKMF(isc_stdio_open(server->dumpfile, "w", &dctx->fp),
		"could not open dump file", server->dumpfile);

	sep = (args == NULL) ? "" : ": ";
	isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
		      NS_LOGMODULE_SERVER, ISC_LOG_INFO,
		      "dumpdb started%s%s", sep, (args != NULL) ? args : "");

	ptr = next_token(&args, " \t");
	if (ptr != NULL && strcmp(ptr, "-all") == 0) {
		dctx->dumpzones = ISC_TRUE;
		dctx->dumpcache = ISC_TRUE;
		ptr = next_token(&args, " \t");
	} else if (ptr != NULL && strcmp(ptr, "-cache") == 0) {
		dctx->dumpzones = ISC_FALSE;
		dctx->dumpcache = ISC_TRUE;
		ptr = next_token(&args, " \t");
	} else if (ptr != NULL && strcmp(ptr, "-zones") == 0) {
		dctx->dumpzones = ISC_TRUE;
		dctx->dumpcache = ISC_FALSE;
		ptr = next_token(&args, " \t");
	}

 nextview:
	for (view = ISC_LIST_HEAD(server->viewlist);
	     view != NULL;
	     view = ISC_LIST_NEXT(view, link))
	{
		if (ptr != NULL && strcmp(view->name, ptr) != 0)
			continue;
		CHECK(add_view_tolist(dctx, view));
	}
	if (ptr != NULL) {
		ptr = next_token(&args, " \t");
		if (ptr != NULL)
			goto nextview;
	}
	dumpdone(dctx, ISC_R_SUCCESS);
	return (ISC_R_SUCCESS);

 cleanup:
	if (dctx != NULL)
		dumpcontext_destroy(dctx);
	return (result);
}

isc_result_t
ns_server_dumprecursing(ns_server_t *server) {
	FILE *fp = NULL;
	isc_result_t result;

	CHECKMF(isc_stdio_open(server->recfile, "w", &fp),
		"could not open dump file", server->recfile);
	fprintf(fp,";\n; Recursing Queries\n;\n");
	ns_interfacemgr_dumprecursing(fp, server->interfacemgr);
	fprintf(fp, "; Dump complete\n");

 cleanup:
	if (fp != NULL)
		result = isc_stdio_close(fp);
	if (result == ISC_R_SUCCESS)
		isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
			      NS_LOGMODULE_SERVER, ISC_LOG_INFO,
			      "dumprecursing complete");
	else
		isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
			      NS_LOGMODULE_SERVER, ISC_LOG_ERROR,
			      "dumprecursing failed: %s",
			      dns_result_totext(result));
	return (result);
}

isc_result_t
ns_server_setdebuglevel(ns_server_t *server, char *args) {
	char *ptr;
	char *levelstr;
	char *endp;
	long newlevel;

	UNUSED(server);

	/* Skip the command name. */
	ptr = next_token(&args, " \t");
	if (ptr == NULL)
		return (ISC_R_UNEXPECTEDEND);

	/* Look for the new level name. */
	levelstr = next_token(&args, " \t");
	if (levelstr == NULL) {
		if (ns_g_debuglevel < 99)
			ns_g_debuglevel++;
	} else {
		newlevel = strtol(levelstr, &endp, 10);
		if (*endp != '\0' || newlevel < 0 || newlevel > 99)
			return (ISC_R_RANGE);
		ns_g_debuglevel = (unsigned int)newlevel;
	}
	isc_log_setdebuglevel(ns_g_lctx, ns_g_debuglevel);
	isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
		      NS_LOGMODULE_SERVER, ISC_LOG_INFO,
		      "debug level is now %d", ns_g_debuglevel);
	return (ISC_R_SUCCESS);
}

isc_result_t
ns_server_validation(ns_server_t *server, char *args) {
	char *ptr, *viewname;
	dns_view_t *view;
	isc_boolean_t changed = ISC_FALSE;
	isc_result_t result;
	isc_boolean_t enable;

	/* Skip the command name. */
	ptr = next_token(&args, " \t");
	if (ptr == NULL)
		return (ISC_R_UNEXPECTEDEND);

	/* Find out what we are to do. */
	ptr = next_token(&args, " \t");
	if (ptr == NULL)
		return (ISC_R_UNEXPECTEDEND);

	if (!strcasecmp(ptr, "on") || !strcasecmp(ptr, "yes") ||
	    !strcasecmp(ptr, "enable") || !strcasecmp(ptr, "true"))
		enable = ISC_TRUE;
	else if (!strcasecmp(ptr, "off") || !strcasecmp(ptr, "no") ||
		 !strcasecmp(ptr, "disable") || !strcasecmp(ptr, "false"))
		enable = ISC_FALSE;
	else
		return (DNS_R_SYNTAX);

	/* Look for the view name. */
	viewname = next_token(&args, " \t");

	result = isc_task_beginexclusive(server->task);
	RUNTIME_CHECK(result == ISC_R_SUCCESS);
	for (view = ISC_LIST_HEAD(server->viewlist);
	     view != NULL;
	     view = ISC_LIST_NEXT(view, link))
	{
		if (viewname != NULL && strcasecmp(viewname, view->name) != 0)
			continue;
		result = dns_view_flushcache(view);
		if (result != ISC_R_SUCCESS)
			goto out;
		view->enablevalidation = enable;
		changed = ISC_TRUE;
	}
	if (changed)
		result = ISC_R_SUCCESS;
	else
		result = ISC_R_FAILURE;
 out:
	isc_task_endexclusive(server->task);
	return (result);
}

isc_result_t
ns_server_flushcache(ns_server_t *server, char *args) {
	char *ptr, *viewname;
	dns_view_t *view;
	isc_boolean_t flushed;
	isc_boolean_t found;
	isc_result_t result;

	/* Skip the command name. */
	ptr = next_token(&args, " \t");
	if (ptr == NULL)
		return (ISC_R_UNEXPECTEDEND);

	/* Look for the view name. */
	viewname = next_token(&args, " \t");

	result = isc_task_beginexclusive(server->task);
	RUNTIME_CHECK(result == ISC_R_SUCCESS);
	flushed = ISC_TRUE;
	found = ISC_FALSE;
	for (view = ISC_LIST_HEAD(server->viewlist);
	     view != NULL;
	     view = ISC_LIST_NEXT(view, link))
	{
		if (viewname != NULL && strcasecmp(viewname, view->name) != 0)
			continue;
		found = ISC_TRUE;
		result = dns_view_flushcache(view);
		if (result != ISC_R_SUCCESS) {
			flushed = ISC_FALSE;
			isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
				      NS_LOGMODULE_SERVER, ISC_LOG_ERROR,
				      "flushing cache in view '%s' failed: %s",
				      view->name, isc_result_totext(result));
		}
	}
	if (flushed && found) {
		if (viewname != NULL)
			isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
				      NS_LOGMODULE_SERVER, ISC_LOG_INFO,
				      "flushing cache in view '%s' succeeded",
				      viewname);
		else
			isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
				      NS_LOGMODULE_SERVER, ISC_LOG_INFO,
				      "flushing caches in all views succeeded");
		result = ISC_R_SUCCESS;
	} else {
		if (!found) {
			isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
				      NS_LOGMODULE_SERVER, ISC_LOG_ERROR,
				      "flushing cache in view '%s' failed: "
				      "view not found", viewname);
			result = ISC_R_NOTFOUND;
		} else
			result = ISC_R_FAILURE;
	}
	isc_task_endexclusive(server->task);
	return (result);
}

isc_result_t
ns_server_flushname(ns_server_t *server, char *args) {
	char *ptr, *target, *viewname;
	dns_view_t *view;
	isc_boolean_t flushed;
	isc_boolean_t found;
	isc_result_t result;
	isc_buffer_t b;
	dns_fixedname_t fixed;
	dns_name_t *name;

	/* Skip the command name. */
	ptr = next_token(&args, " \t");
	if (ptr == NULL)
		return (ISC_R_UNEXPECTEDEND);

	/* Find the domain name to flush. */
	target = next_token(&args, " \t");
	if (target == NULL)
		return (ISC_R_UNEXPECTEDEND);

	isc_buffer_init(&b, target, strlen(target));
	isc_buffer_add(&b, strlen(target));
	dns_fixedname_init(&fixed);
	name = dns_fixedname_name(&fixed);
	result = dns_name_fromtext(name, &b, dns_rootname, ISC_FALSE, NULL);
	if (result != ISC_R_SUCCESS)
		return (result);

	/* Look for the view name. */
	viewname = next_token(&args, " \t");

	result = isc_task_beginexclusive(server->task);
	RUNTIME_CHECK(result == ISC_R_SUCCESS);
	flushed = ISC_TRUE;
	found = ISC_FALSE;
	for (view = ISC_LIST_HEAD(server->viewlist);
	     view != NULL;
	     view = ISC_LIST_NEXT(view, link))
	{
		if (viewname != NULL && strcasecmp(viewname, view->name) != 0)
			continue;
		found = ISC_TRUE;
		result = dns_view_flushname(view, name);
		if (result != ISC_R_SUCCESS) {
			flushed = ISC_FALSE;
			isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
				      NS_LOGMODULE_SERVER, ISC_LOG_ERROR,
				      "flushing name '%s' in cache view '%s' "
				      "failed: %s", target, view->name,
				      isc_result_totext(result));
		}
	}
	if (flushed && found) {
		if (viewname != NULL)
			isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
				      NS_LOGMODULE_SERVER, ISC_LOG_INFO,
				      "flushing name '%s' in cache view '%s' "
				      "succeeded", target, viewname);
		else
			isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
				      NS_LOGMODULE_SERVER, ISC_LOG_INFO,
				      "flushing name '%s' in all cache views "
				      "succeeded", target);
		result = ISC_R_SUCCESS;
	} else {
		if (!found)
			isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
				      NS_LOGMODULE_SERVER, ISC_LOG_ERROR,
				      "flushing name '%s' in cache view '%s' "
				      "failed: view not found", target,
				      viewname);
		result = ISC_R_FAILURE;
	}
	isc_task_endexclusive(server->task);
	return (result);
}

isc_result_t
ns_server_status(ns_server_t *server, isc_buffer_t *text) {
	int zonecount, xferrunning, xferdeferred, soaqueries;
	unsigned int n;
	const char *ob = "", *cb = "", *alt = "";

	if (ns_g_server->version_set) {
		ob = " (";
		cb = ")";
		if (ns_g_server->version == NULL)
			alt = "version.bind/txt/ch disabled";
		else
			alt = ns_g_server->version;
	}
	zonecount = dns_zonemgr_getcount(server->zonemgr, DNS_ZONESTATE_ANY);
	xferrunning = dns_zonemgr_getcount(server->zonemgr,
					   DNS_ZONESTATE_XFERRUNNING);
	xferdeferred = dns_zonemgr_getcount(server->zonemgr,
					    DNS_ZONESTATE_XFERDEFERRED);
	soaqueries = dns_zonemgr_getcount(server->zonemgr,
					  DNS_ZONESTATE_SOAQUERY);

	n = snprintf((char *)isc_buffer_used(text),
		     isc_buffer_availablelength(text),
		     "version: %s%s%s%s\n"
#ifdef ISC_PLATFORM_USETHREADS
		     "CPUs found: %u\n"
		     "worker threads: %u\n"
#endif
		     "number of zones: %u\n"
		     "debug level: %d\n"
		     "xfers running: %u\n"
		     "xfers deferred: %u\n"
		     "soa queries in progress: %u\n"
		     "query logging is %s\n"
		     "recursive clients: %d/%d/%d\n"
		     "tcp clients: %d/%d\n"
		     "server is up and running",
		     ns_g_version, ob, alt, cb,
#ifdef ISC_PLATFORM_USETHREADS
		     ns_g_cpus_detected, ns_g_cpus,
#endif
		     zonecount, ns_g_debuglevel, xferrunning, xferdeferred,
		     soaqueries, server->log_queries ? "ON" : "OFF",
		     server->recursionquota.used, server->recursionquota.soft,
		     server->recursionquota.max,
		     server->tcpquota.used, server->tcpquota.max);
	if (n >= isc_buffer_availablelength(text))
		return (ISC_R_NOSPACE);
	isc_buffer_add(text, n);
	return (ISC_R_SUCCESS);
}

static isc_result_t
delete_keynames(dns_tsig_keyring_t *ring, char *target,
		unsigned int *foundkeys)
{
	char namestr[DNS_NAME_FORMATSIZE];
	isc_result_t result;
	dns_rbtnodechain_t chain;
	dns_name_t foundname;
	dns_fixedname_t fixedorigin;
	dns_name_t *origin;
	dns_rbtnode_t *node;
	dns_tsigkey_t *tkey;

	dns_name_init(&foundname, NULL);
	dns_fixedname_init(&fixedorigin);
	origin = dns_fixedname_name(&fixedorigin);

 again:
	dns_rbtnodechain_init(&chain, ring->mctx);
	result = dns_rbtnodechain_first(&chain, ring->keys, &foundname,
					origin);
	if (result == ISC_R_NOTFOUND) {
		dns_rbtnodechain_invalidate(&chain);
		return (ISC_R_SUCCESS);
	}
	if (result != ISC_R_SUCCESS && result != DNS_R_NEWORIGIN) {
		dns_rbtnodechain_invalidate(&chain);
		return (result);
	}

	for (;;) {
		node = NULL;
		dns_rbtnodechain_current(&chain, &foundname, origin, &node);
		tkey = node->data;

		if (tkey != NULL) {
			if (!tkey->generated)
				goto nextkey;

			dns_name_format(&tkey->name, namestr, sizeof(namestr));
			if (strcmp(namestr, target) == 0) {
				(*foundkeys)++;
				dns_rbtnodechain_invalidate(&chain);
				(void)dns_rbt_deletename(ring->keys,
							 &tkey->name,
							 ISC_FALSE);
				goto again;
			}
		}

	nextkey:
		result = dns_rbtnodechain_next(&chain, &foundname, origin);
		if (result == ISC_R_NOMORE)
			break;
		if (result != ISC_R_SUCCESS && result != DNS_R_NEWORIGIN) {
			dns_rbtnodechain_invalidate(&chain);
			return (result);
		}
	}

	return (ISC_R_SUCCESS);
}

isc_result_t
ns_server_tsigdelete(ns_server_t *server, char *command, isc_buffer_t *text) {
	isc_result_t result;
	unsigned int n;
	dns_view_t *view;
	unsigned int foundkeys = 0;
	char *target;
	char *viewname;

	(void)next_token(&command, " \t");  /* skip command name */
	target = next_token(&command, " \t");
	if (target == NULL)
		return (ISC_R_UNEXPECTEDEND);
	viewname = next_token(&command, " \t");

	result = isc_task_beginexclusive(server->task);
	RUNTIME_CHECK(result == ISC_R_SUCCESS);
	for (view = ISC_LIST_HEAD(server->viewlist);
	     view != NULL;
	     view = ISC_LIST_NEXT(view, link)) {
		if (viewname == NULL || strcmp(view->name, viewname) == 0) {
			RWLOCK(&view->dynamickeys->lock, isc_rwlocktype_write);
			result = delete_keynames(view->dynamickeys, target,
						 &foundkeys);
			RWUNLOCK(&view->dynamickeys->lock,
				 isc_rwlocktype_write);
			if (result != ISC_R_SUCCESS) {
				isc_task_endexclusive(server->task);
				return (result);
			}
		}
	}
	isc_task_endexclusive(server->task);

	n = snprintf((char *)isc_buffer_used(text),
		     isc_buffer_availablelength(text),
		     "%d tsig keys deleted.\n", foundkeys);
	if (n >= isc_buffer_availablelength(text)) {
		isc_task_endexclusive(server->task);
		return (ISC_R_NOSPACE);
	}
	isc_buffer_add(text, n);

	return (ISC_R_SUCCESS);
}

static isc_result_t
list_keynames(dns_view_t *view, dns_tsig_keyring_t *ring, isc_buffer_t *text,
	     unsigned int *foundkeys)
{
	char namestr[DNS_NAME_FORMATSIZE];
	char creatorstr[DNS_NAME_FORMATSIZE];
	isc_result_t result;
	dns_rbtnodechain_t chain;