aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/bind/bin/named/ns_resp.c
blob: 0174f9f02034bfd10a594585b1e6aebf21dcf20e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
#if !defined(lint) && !defined(SABER)
static const char sccsid[] = "@(#)ns_resp.c	4.65 (Berkeley) 3/3/91";
static const char rcsid[] = "$Id: ns_resp.c,v 8.186.6.4 2003/06/02 09:56:35 marka Exp $";
#endif /* not lint */

/*
 * Copyright (c) 1986, 1988, 1990
 *    The Regents of the University of California.  All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 * 	This product includes software developed by the University of
 * 	California, Berkeley and its contributors.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

/*
 * Portions Copyright (c) 1993 by Digital Equipment Corporation.
 * 
 * Permission to use, copy, modify, and 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, and that
 * the name of Digital Equipment Corporation not be used in advertising or
 * publicity pertaining to distribution of the document or software without
 * specific, written prior permission.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
 * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS.   IN NO EVENT SHALL DIGITAL EQUIPMENT
 * CORPORATION 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.
 */

/*
 * Portions Copyright (c) 1995 by International Business Machines, Inc.
 *
 * International Business Machines, Inc. (hereinafter called IBM) grants
 * permission under its copyrights to use, copy, modify, and distribute this
 * Software with or without fee, provided that the above copyright notice and
 * all paragraphs of this notice appear in all copies, and that the name of IBM
 * not be used in connection with the marketing of any product incorporating
 * the Software or modifications thereof, without specific, written prior
 * permission.
 *
 * To the extent it has a right to do so, IBM grants an immunity from suit
 * under its patents, if any, for the use, sale or manufacture of products to
 * the extent that such products are used for performing Domain Name System
 * dynamic updates in TCP/IP networks by means of the Software.  No immunity is
 * granted for any product per se or for any other function of any product.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", AND IBM DISCLAIMS ALL WARRANTIES,
 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE.  IN NO EVENT SHALL IBM BE LIABLE FOR ANY SPECIAL,
 * DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER ARISING
 * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE, EVEN
 * IF IBM IS APPRISED OF THE POSSIBILITY OF SUCH DAMAGES.
 */

/*
 * Portions Copyright (c) 1996-2000 by Internet Software Consortium.
 *
 * Permission to use, copy, modify, and 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 INTERNET SOFTWARE CONSORTIUM DISCLAIMS
 * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE
 * CONSORTIUM 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.
 */

#include "port_before.h"

#include <sys/types.h>
#include <sys/param.h>
#include <sys/socket.h>
#include <sys/file.h>
#include <sys/un.h>

#include <netinet/in.h>
#include <arpa/nameser.h>
#include <arpa/inet.h>

#include <errno.h>
#include <limits.h>
#include <resolv.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <syslog.h>
#include <time.h>

#include <isc/eventlib.h>
#include <isc/logging.h>
#include <isc/memcluster.h>

#include <isc/dst.h>

#include "port_after.h"

#include "named.h"

static u_int8_t		norootlogged[MAXCLASS];	/* XXX- should be a bitmap */

static const char	skipnameFailedAnswer[] = "skipname failed in answer",
			skipnameFailedAuth[] =	"skipname failed in authority",
			skipnameFailedQuery[] =	"skipname failed in query",
			outofDataQuery[] =	"ran out of data in query",
			outofDataAnswer[] =	"ran out of data in answer",
			notSingleQuery[] =	"not exactly one query",
			expandFailedQuery[] =	"dn_expand failed in query",
			expandFailedAnswer[] =	"dn_expand failed in answer",
			expandFailedAuth[] =	"dn_expand failed in authority",
			outofDataAuth[] =	"ran out of data in authority",
			dlenOverrunAnswer[] =	"dlen overrun in answer",
			dlenOverrunAuth[] =	"dlen overrun in authority",
			dlenUnderrunAnswer[] =	"dlen underrun in answer",
			outofDataFinal[] =	"out of data in final pass",
			outofDataAFinal[] =	"out of data after final pass",
			badNameFound[] =	"found an invalid domain name",
			wrongQuestion[] =	"answer to wrong question",
			danglingCname[] =	"dangling CNAME pointer",
			nonRecursiveForwarder[]= "non-recursive forwarder";

struct db_list {
	struct db_list *db_next;
	struct databuf *db_dp;
};

struct flush_set {
	char *		fs_name;
	int		fs_type;
	int		fs_class;
	u_int		fs_cred;
	struct db_list *fs_list;
	struct db_list *fs_last;
};

static void		rrsetadd(struct flush_set *, const char *, 
				 struct databuf *),
			rrsetupdate(struct flush_set *, int flags,
				    struct sockaddr_in, int),
			flushrrset(struct flush_set *, struct sockaddr_in),
			free_flushset(struct flush_set *, int),
			check_hints(struct flush_set *);
static int		rrsetcmp(char *, struct db_list *, struct hashbuf *),
			check_root(void),
			check_ns(void),
			wanted(const struct databuf *, int, int),
			wantedsig(const struct databuf *, int, int),
			rrextract(u_char *, int, u_char *,
				  struct databuf **, char *, int,
				  struct sockaddr_in, char **);
static void		mark_bad(struct qinfo *qp, struct sockaddr_in from);
static void		mark_lame(struct qinfo *qp, struct sockaddr_in from);
static int		mark_noedns(struct qinfo *qp, struct sockaddr_in from,
				    int cache);
static void		fast_retry(struct qinfo *qp, struct sockaddr_in from,
				   int samehost);
static void		add_related_additional(char *);
static void		free_related_additional(void);
static int		related_additional(char *);
static void		freestr_maybe(char **);
static enum ordering	match_order(const struct namebuf *, int, int);
static int 		match_name(const struct namebuf *, const char *, size_t);

#define MAX_RELATED 100

static int num_related = 0;
static char *related[MAX_RELATED];

static char *
learntFrom(struct qinfo *qp, struct sockaddr_in *server) {
	static char *buf = NULL;
	const char *a, *ns, *na;
	struct databuf *db;
	int i;
	char nsbuf[20];
	char abuf[20];
	static const char fmt[] = " '%s': learnt (A=%s,NS=%s)";
	
	a = ns = na = "<Not Available>";

	for (i = 0; (u_int)i < qp->q_naddr; i++) {
		if (ina_equal(qp->q_addr[i].ns_addr.sin_addr,
			      server->sin_addr)) {
			db = qp->q_addr[i].ns;
			if (db != NULL) {
				if (db->d_addr.s_addr != htonl(0)) {
					strcpy(nsbuf, inet_ntoa(db->d_addr));
					ns = nsbuf;
				} else {
					ns = zones[db->d_zone].z_origin;
				}
				if (db->d_rcode == 0)
					na = (char*)qp->q_addr[i].ns->d_data;
			}
			db = qp->q_addr[i].nsdata;
			if (db != NULL) {
				if (db->d_addr.s_addr != htonl(0)) {
					strcpy(abuf, inet_ntoa(db->d_addr));
					a = abuf;
				} else {
					a = zones[db->d_zone].z_origin;
				}
			}
			break;
		}
	}

	if (a == ns && ns == na)	/* all "UNKNOWN" */
		return (NULL);
	
	if (*a == '\0')
		a = "\".\"";
	if (*ns == '\0')
		ns = "\".\"";
	if (*na == '\0')
		na = "\".\"";


	buf = newstr(sizeof fmt + strlen(na) + strlen(a) + strlen(ns), 0);
	if (buf == NULL)
		return (NULL);
	sprintf(buf, fmt, na, a, ns);
	return (buf);
}

void
ns_resp(u_char *msg, int msglen, struct sockaddr_in from, struct qstream *qsp)
{
	struct qinfo *qp;
	HEADER *hp;
	struct qserv *qs = NULL;
	struct databuf *ns, *ns2;
	u_char *cp, *answers, *eom = msg + msglen;
	struct flush_set *flushset = NULL;
	int flushset_size = 0;
	struct sockaddr_in *nsa;
	struct databuf *nsp[NSMAX];
	int i, c, n, qdcount, ancount, aucount, nscount, arcount, arfirst;
	int soacount;
	u_int qtype, qclass;
	int validanswer, dbflags;
	int cname, lastwascname, externalcname;
	int count, founddata, foundname;
	int buflen;
	int newmsglen;
	char name[MAXDNAME], qname[MAXDNAME], aname[MAXDNAME];
	char msgbuf[MAXDNAME+100];
	char *dname, tmpdomain[MAXDNAME];
	const char *fname;
	const char *formerrmsg = "brain damage";
	u_char newmsg[NS_MAXMSG];
	u_char **dpp, *tp;
	time_t rtrip;
	struct hashbuf *htp;
	struct namebuf *np;
	struct fwdinfo *fwd;
	struct databuf *dp;
	char *tname = NULL;
	int sendto_errno = 0;
	int has_tsig, oldqlen = 0;
	u_char *oldqbuf = NULL;
	u_char *smsg = NULL;
	int smsglen, smsgsize = 0, siglen;
	u_char sig[TSIG_SIG_SIZE];
	time_t tsig_time;
	DST_KEY *key;
	int expect_cname;
	int pass = 0;

	nameserIncr(from.sin_addr, nssRcvdR);
	nsp[0] = NULL;
	hp = (HEADER *) msg;
	if ((qp = qfindid(hp->id)) == NULL ) {
		ns_debug(ns_log_default, 1, "DUP? dropped (id %d)",
			 ntohs(hp->id));
		nameserIncr(from.sin_addr, nssRcvdDupR);
		return;
	}

	if (ns_wouldlog(ns_log_default, 2)) {
		ns_debug(ns_log_default, 2, "Response (%s %s %s) nsid=%d id=%d",
			 (qp->q_flags & Q_SYSTEM) ?"SYSTEM" :"USER",
			 (qp->q_flags & Q_PRIMING) ?"PRIMING" :"NORMAL",
			 (qp->q_flags & Q_ZSERIAL) ?"ZSERIAL" :"-",
			 ntohs(qp->q_nsid), ntohs(qp->q_id));
	}

	if (qp->q_nstsig == NULL)
		has_tsig = 0;
	else {
		int ret;

		ret = ns_verify(msg, &msglen, qp->q_nstsig->key,
				qp->q_nstsig->sig, qp->q_nstsig->siglen,
				NULL, NULL, &tsig_time, 0);
		if (ret == 0)
			has_tsig = 1;
		else {
			if (hp->rcode == NOERROR)
				hp->rcode = NOTAUTH;
			ns_debug(ns_log_default, 1,
				 "resp: error bad tsig, record dropped");
			return;
		}
	}

	/*
	 * Here we handle high level formatting problems by parsing the header.
	 */
	qdcount = ntohs(hp->qdcount);
	ancount = ntohs(hp->ancount);
	aucount = ntohs(hp->nscount);
	arcount = ntohs(hp->arcount);
	free_addinfo();		/* sets addcount to zero */
	cp = msg + HFIXEDSZ;
	dpp = dnptrs;
	*dpp++ = msg;
	if ((*cp & INDIR_MASK) == 0)
		*dpp++ = cp;
	*dpp = NULL;
	if (qdcount == 1) {
		n = dn_expand(msg, eom, cp, qname, sizeof(qname));
		if (n <= 0) {
			formerrmsg = expandFailedQuery;
			goto formerr;
		}
		cp += n;
		if (cp + 2 * INT16SZ > eom) {
			formerrmsg = outofDataQuery;
			goto formerr;
		}
		GETSHORT(qtype, cp);
		GETSHORT(qclass, cp);
		if (!ns_nameok(qp, qname, qclass, NULL, response_trans,
			       ns_ownercontext(qtype, response_trans),
			       qname, from.sin_addr)) {
			formerrmsg = badNameFound;
			goto refused;
		}
		if (cp > eom) {
			formerrmsg = outofDataQuery;
			goto formerr;
		}
		if (qp->q_msg && qp->q_msglen &&
		    !res_nameinquery(qname, qtype, qclass,
				     qp->q_msg, qp->q_msg + qp->q_msglen)) {
			sprintf(msgbuf,
				"query section mismatch (%s %s %s)",
				qname, p_class(qclass), p_type(qtype));
			formerrmsg = msgbuf;
			goto formerr;
		}
		if (ns_samename(qp->q_name, qname) != 1 ||
		    qp->q_class != qclass ||
		    qp->q_type != qtype) {
			formerrmsg = wrongQuestion;
			goto formerr;
		}
	} else {
		strcpy(qname, qp->q_name);
		qclass = qp->q_class;
		qtype = qp->q_type;
	}

	/* cp now points after the query section. */

	/*
	 *  Here we handle bad responses from servers.
	 *  Several possibilities come to mind:
	 *	The server is sick and returns SERVFAIL
	 *	The server returns some garbage opcode (it's sick)
	 *	The server can't understand our query and return FORMERR
	 *  In all these cases, we drop the packet, disable retries on
	 *  this server and immediately force a retry.
	 */
	if ((hp->rcode != NOERROR && hp->rcode != NXDOMAIN)
	    || (hp->opcode != QUERY
#ifdef BIND_NOTIFY
		&& hp->opcode != NS_NOTIFY_OP
#endif
		)) {
		int noedns = 1;
		ns_debug(ns_log_default, 2,
			 "resp: error (ret %d, op %d), dropped",
			 hp->rcode, hp->opcode);
		switch (hp->rcode) {
		case SERVFAIL:
			nameserIncr(from.sin_addr, nssRcvdFail);
			noedns = mark_noedns(qp, from, 0);
			break;
		case FORMERR:
			nameserIncr(from.sin_addr, nssRcvdFErr);
			noedns = mark_noedns(qp, from, 1);
			break;
		case NOTIMP:
			nameserIncr(from.sin_addr, nssRcvdErr);
			noedns = mark_noedns(qp, from, 1);
			break;
		default:
			nameserIncr(from.sin_addr, nssRcvdErr);
			break;
		}
		if (ns_samename(qp->q_name, qp->q_domain) == 1 &&
		    hp->rcode == SERVFAIL && hp->opcode == QUERY &&
		    noedns)
			mark_lame(qp, from);
		if (noedns)
			mark_bad(qp, from);
		fast_retry(qp, from, noedns ? 0 : 1);
		return;
	}

	if (qdcount != 1) {
		/* We don't generate or forward these (yet). */
		formerrmsg = notSingleQuery;
		goto formerr;
	}

	/*
	 * Determine if the response came from a forwarder.  Packets from
	 * anyplace not listed as a forwarder or as a server to whom we
	 * might have forwarded the query will be dropped.
	 * XXX - should put this in STATS somewhere.
	 */
	for (fwd = NS_ZFWDTAB(qp->q_fzone); fwd; fwd = fwd->next)
		if (ina_equal(fwd->fwddata->fwdaddr.sin_addr, from.sin_addr))
			break;
	/*
	 * find the qinfo pointer and update
	 * the rtt and fact that we have called on this server before.
	 */
	{
		struct timeval *stp;

		for (n = 0, qs = qp->q_addr; (u_int)n < qp->q_naddr; n++, qs++)
			if (ina_equal(qs->ns_addr.sin_addr, from.sin_addr))
				break;
		if ((u_int)n >= qp->q_naddr) {
			if (!haveComplained(ina_ulong(from.sin_addr),
					    (u_long)"unexpected source")) {
				ns_info(ns_log_default,
					"Response from unexpected source (%s) for query \"%s %s %s\"",
					sin_ntoa(from),
                        		*(qp->q_name) ? qp->q_name : ".",
					p_class(qp->q_class), p_type(qp->q_type));
			}
			/* 
			 * We don't know who this response came from so it
			 * gets dropped on the floor.
			 */
			return;
		}
		stp = &qs->stime;

		/* Handle response from different (untried) interface. */
		if (qs->ns != NULL && stp->tv_sec == 0) {
			ns = qs->ns;
			while (qs > qp->q_addr
			       && (qs->stime.tv_sec == 0 || qs->ns != ns))
				qs--;
			*stp = qs->stime;
			/* XXX - sometimes stp still ends up pointing to
			 * a zero timeval, in spite of the above attempt.
			 * Why?  What should we do about it?
			 */
			/* XXX - catch aliases here */
		}

		/* compute query round trip time */
		/* XXX - avoid integer overflow, which is quite likely if stp
		 * points to a zero timeval (see above).
		 * rtrip is of type time_t, which we assume is at least
		 * as big as an int.
		 */
		if ((tt.tv_sec - stp->tv_sec) > (INT_MAX-999)/1000) {
			rtrip = INT_MAX;
		} else {
			rtrip = ((tt.tv_sec - stp->tv_sec) * 1000 +
				 (tt.tv_usec - stp->tv_usec) / 1000);
		}
		
		if (ns_wouldlog(ns_log_default, 3)) {
			ns_debug(ns_log_default, 3,
				 "stime %lu/%lu  now %lu/%lu rtt %ld",
				 (u_long)stp->tv_sec, (u_long)stp->tv_usec,
				 (u_long)tt.tv_sec, (u_long)tt.tv_usec,
				 (long)rtrip);
		}

		/* prevent floating point overflow, limit to 1000 sec */
		if (rtrip > 1000000) {
			rtrip = 1000000;
		}
		ns = qs->nsdata;
		/*
		 * Don't update nstime if this doesn't look
		 * like an address databuf now.			XXX
		 */
		if (ns &&
		    ns->d_type == T_A &&
		    ns->d_class == qs->ns->d_class) {
			u_long t;

			if (ns->d_nstime == 0)
				t = rtrip;
			else
				t = ns->d_nstime * ALPHA
					+
				    (1 - ALPHA) * rtrip;
			if (t > 65535)
				t = 65535;
			else if (t == 0)
				t = 1;
			ns->d_nstime = (u_int16_t)t;
		}

		/*
		 * Record the source so that we do not use this NS again.
		 */
		if (ns && qs->ns && (qp->q_nusedns < NSMAX)) {
			qp->q_usedns[qp->q_nusedns++] = qs->ns;
			if (ns_wouldlog(ns_log_default, 2)) {
				ns_debug(ns_log_default, 2,
					 "NS #%d addr %s used, rtt %d",
					 n, sin_ntoa(qs->ns_addr),
					 ns->d_nstime);
			}
		}

		/*
		 * Penalize those who had earlier chances but failed
		 * by multiplying round-trip times by BETA (>1).
		 * Improve nstime for unused addresses by applying GAMMA.
		 * The GAMMA factor makes unused entries slowly
		 * improve, so they eventually get tried again.
		 * GAMMA should be slightly less than 1.
		 * Watch out for records that may have timed out
		 * and are no longer the correct type.			XXX
		 */
		
		for (n = 0, qs = qp->q_addr;
		     (u_int)n < qp->q_naddr;
		     n++, qs++) {
			u_long t;

			ns2 = qs->nsdata;
			if (!ns2 || ns2 == ns)
				continue;
			if (ns2->d_type != T_A ||
			    ns2->d_class != qs->ns->d_class)	/* XXX */
				continue;
			if (qs->stime.tv_sec) {
				if (ns2->d_nstime == 0)
					t = (rtrip * BETA) + 1;
				else
					t = ns2->d_nstime * BETA
					        +
					    (1 - ALPHA) * rtrip + 1;
			} else
				t = ns2->d_nstime * GAMMA;
			if (t > 65535)
				t = 65535;
			else if (t == 0)
				t = 1;
			ns2->d_nstime = (u_int16_t)t;
			if (ns_wouldlog(ns_log_default, 2)) {
				ns_debug(ns_log_default, 2,
					 "NS #%d %s rtt now %d", n,
					 sin_ntoa(qs->ns_addr),
					 ns2->d_nstime);
			}
		}
	}

#ifdef BIND_NOTIFY
	/*
	 * For now, NOTIFY isn't defined for ANCOUNT!=0, AUCOUNT!=0,
	 * or ADCOUNT!=0.  Therefore the only real work to be done for
	 * a NOTIFY-QR is to remove it from the query queue.
	 */
	if (hp->opcode == NS_NOTIFY_OP) {
		ns_info(ns_log_notify,
		      "Received NOTIFY answer (%sAA) from %s for \"%s %s %s\"",
			hp->aa ? "" : "!",
			inet_ntoa(from.sin_addr), 
			*(qp->q_name) ? qp->q_name : ".",
			p_class(qp->q_class), p_type(qp->q_type));
		qremove(qp);
		return;
	}
#endif

	if ((qp->q_flags & Q_ZSERIAL) != 0) {
		if (hp->aa && ancount > 0 && hp->rcode == NOERROR &&
		    qtype == T_SOA && (qclass == C_IN || qclass == C_HS))
		{
			int n;
			u_int type, class, dlen;
			u_int32_t serial;
			u_char *tp = cp;
			u_char *rdatap;

			n = dn_expand(msg, eom, tp, name, sizeof name);
			if (n < 0) {
				formerrmsg = expandFailedAnswer;
				goto formerr;
			}
			tp += n;  		/* name */
			if (tp + 3 * INT16SZ + INT32SZ > eom) {
				formerrmsg = outofDataAnswer;
				goto formerr;
			}
			GETSHORT(type, tp);	/* type */
			GETSHORT(class, tp);	/* class */
			tp += INT32SZ;		/* ttl */
			GETSHORT(dlen, tp); 	/* dlen */
			rdatap = tp;		/* start of rdata */
			if (!ns_nameok(qp, name, class, NULL, response_trans,
				       ns_ownercontext(type, response_trans),
				       name, from.sin_addr)) {
				formerrmsg = badNameFound;
				goto refused;
			}
			if (ns_samename(qname, name) != 1 ||
			    qtype != type || qclass != class) {
				sprintf(msgbuf,
					"qserial answer mismatch (%s %s %s)",
					name, p_class(class), p_type(type));
				formerrmsg = msgbuf;
				goto formerr;
			}
			if (0 >= (n = dn_skipname(tp, eom))) {
				formerrmsg = skipnameFailedAnswer;
				goto formerr;
			}
			tp += n;  		/* mname */
			if (0 >= (n = dn_skipname(tp, eom))) {
				formerrmsg = skipnameFailedAnswer;
				goto formerr;
			}
			tp += n;  		/* rname */
			if (tp + 5 * INT32SZ > eom) {
				formerrmsg = dlenUnderrunAnswer;
				goto formerr;
			}
			GETLONG(serial, tp);
			tp += 4 * INT32SZ;	/* Skip rest of SOA. */
			if ((u_int)(tp - rdatap) != dlen) {
				formerrmsg = dlenOverrunAnswer;
				goto formerr;
			}
			for (n = 0, qs = qp->q_addr; (u_int)n < qp->q_naddr;
					n++, qs++)
				if (ina_equal(qs->ns_addr.sin_addr,
					      from.sin_addr))
					break;
			if (n == qp->q_naddr) {
				qserial_answer(qp);
				qremove(qp);
				return;
			}
			qs->serial = serial;
		}
		retry(qp, 0);
		return;
	}

	/*
	 *  Non-authoritative, no answer, no error, with referral.
	 */
	if (hp->rcode == NOERROR && !hp->tc && !hp->aa &&
	    ancount == 0 && aucount > 0
#ifdef BIND_NOTIFY
	    && hp->opcode != NS_NOTIFY_OP
#endif
	    ) {
		u_char *tp;
		int type, class = 0, dlen;
		int foundns, foundsoa;
#ifdef DEBUG
		if (debug > 0)
			res_pquery(&res, msg, msglen,
				    log_get_stream(packet_channel));
#endif
		/*
		 * Since there is no answer section (ancount == 0),
		 * we must be pointing at the authority section (aucount > 0).
		 */
		tp = cp;
		foundns = foundsoa = 0;
		for (i = 0 ; i < aucount ; i++) {
			n = dn_expand(msg, eom, tp, name, sizeof name);
			if (n < 0) {
				formerrmsg = expandFailedAuth;
				goto formerr;
			}
			tp += n;
			if (tp + 3 * INT16SZ + INT32SZ > eom) {
				formerrmsg = outofDataAuth;
				goto formerr;
			}
			GETSHORT(type, tp);
			GETSHORT(class, tp);
			tp += INT32SZ;	/* ttl */
			GETSHORT(dlen, tp);
			if (!ns_nameok(qp, name, class, NULL, response_trans,
				       ns_ownercontext(type, response_trans),
				       name, from.sin_addr)) {
				formerrmsg = badNameFound;
				goto refused;
			}
			/* skip rest of record */
			if (tp + dlen > eom) {
				formerrmsg = outofDataAuth;
				goto formerr;
			}
			tp += dlen;
			if (type == T_NS) {
				strcpy(aname, name);
				foundns = 1;
			}
			if (type == T_SOA)
				foundsoa = 1;
		}

		/*
		 * If the answer delegates us either to the same level in
		 * the hierarchy or closer to the root, we consider this
		 * server lame.  Note that for now we only log the message
		 * if the T_NS was C_IN, which is technically wrong (NS is
		 * visible in all classes) but necessary anyway (non-IN
		 * classes tend to not have good strong delegation graphs).
		 */

		if (foundns && !foundsoa &&
		    ns_samedomain(qp->q_domain, aname)) {
			if (fwd == NULL) {
				nameserIncr(from.sin_addr, nssRcvdLDel);
				mark_lame(qp, from);
			}
			mark_bad(qp, from);
			if (class == C_IN && fwd == NULL &&
			    !haveComplained(ina_ulong(from.sin_addr),
					    nhash(qp->q_domain))) {
				char *learnt_from = learntFrom(qp, &from);

				ns_info(ns_log_lame_servers,
					"Lame server on '%s' (in '%s'?): %s%s",
					qname, qp->q_domain, 
					sin_ntoa(from),
					(learnt_from == NULL) ? "" :
					learnt_from);
				if (learnt_from != NULL)
					learnt_from = freestr(learnt_from);
			} else if (fwd != NULL) {
				if (!haveComplained(ina_ulong(from.sin_addr),
					  (u_long)nonRecursiveForwarder))
					ns_warning(ns_log_default, "%s: %s",
						   nonRecursiveForwarder,
						   sin_ntoa(from));
			}

			fast_retry(qp, from, 0);
			return;
		}
	}

	/*
	 * Add the info received in the response to the data base.
	 */
	arfirst = ancount + aucount;
	c = arfirst + arcount;

	/* Don't return if it's a TSIG signed truncated message */
	if (has_tsig > 0 && hp->tc)
		goto tcp_retry;

	/* -ve $ing non-existence of record, must handle non-authoritative
	 * NOERRORs with c == 0.
	 */
	if (!hp->aa && !hp->tc && hp->rcode == NOERROR && c == 0)
		goto return_msg;

	if (qp->q_flags & Q_SYSTEM)
		dbflags = DB_NOTAUTH | DB_NODATA;
	else
		dbflags = DB_NOTAUTH | DB_NODATA | DB_NOHINTS;
	count = c;
	if (qp->q_flags & Q_PRIMING)
		dbflags |= DB_PRIMING;
	if (hp->tc) {
		count -= arcount;	/* truncation had to affect this */
		if (!arcount) {
			count -= aucount;	/* guess it got this too */
		}
		if (!(arcount || aucount)) {
			count -= ancount;	/* things are pretty grim */
		}

tcp_retry:
		/* retry using tcp provided this was not a tcp query */
		if (!(qp->q_flags & Q_USEVC)) {
			qp->q_flags |= Q_USEVC;
			unsched(qp);
			schedretry(qp, 60);

			nsa = Q_NEXTADDR(qp, 0);

			key = qp->q_keys[0];
			if (key != NULL)
				key = qp->q_keys[0] =
					 tsig_key_from_addr(nsa->sin_addr);
			if (key != NULL) {
				smsgsize = qp->q_msglen + TSIG_BUF_SIZE;
				smsg = memget(smsgsize);
				smsglen = qp->q_msglen;
				siglen = sizeof(sig);
				memcpy(smsg, qp->q_msg, qp->q_msglen);
				n = ns_sign(smsg, &smsglen, smsgsize,
					    NOERROR, key, NULL, 0,
					    sig, &siglen, 0);
				if (n == 0) {
					oldqbuf = qp->q_msg;
					oldqlen = qp->q_msglen;
					qp->q_msglen = smsglen;
					qp->q_msg = smsg;
					has_tsig = 1;
					free_tsig(qp->q_nstsig);
					qp->q_nstsig = new_tsig(key, sig,
								siglen);
				} else {
					has_tsig = 0;
					free_tsig(qp->q_nstsig);
					qp->q_nstsig = NULL;
					INSIST(0);
				}
			} else {
				has_tsig = 0;
				free_tsig(qp->q_nstsig);
				qp->q_nstsig = NULL;
			}

			if (tcp_send(qp) != NOERROR)
				/*
				 * We're probably in trouble if tcp_send
				 * failed, but we'll try to press on because
				 * there isn't anything else to do.
				 */
				retry(qp, 0);

			if (has_tsig == 1) {
				memput(qp->q_msg, smsgsize);
				qp->q_msg = oldqbuf;
				qp->q_msglen = oldqlen;
			}
			return;
		} else if (!qsp) {
			/* outstanding udp response */
			return;
		}

		/* XXX truncated tcp response */
		ns_error(ns_log_default,
			 "ns_resp: TCP truncated: \"%s\" %s %s from %s",
			 qname, p_class(qclass), p_type(qtype),
			 sin_ntoa(from));
		/* mark this server as bad */
		mark_bad(qp, from);
		/* try another server, it may have a bigger write buffer */
		retry(qp, 0);
		return;
	}

	tp = cp;

	validanswer = -1;
	nscount = 0;
	soacount = 0;
	cname = 0;
	lastwascname = 0;
	externalcname = 0;
	strcpy(aname, qname);

	if (count) {
		/* allocate 1 extra record for end of set detection */
		flushset_size = (count + 1) * sizeof *flushset;
		flushset = memget(flushset_size);
		if (flushset == NULL)
			panic("flushset: out of memory", NULL);
		memset(flushset, 0, flushset_size);
	} else
		flushset = NULL;

	expect_cname = 1;
	for (i = 0; i < count; i++) {
		struct databuf *dp;
		int type;

		freestr_maybe(&tname);
		if (cp >= eom) {
			free_related_additional();
			if (flushset != NULL)
				free_flushset(flushset, flushset_size);
			formerrmsg = outofDataFinal;
			goto formerr;
		}
		n = rrextract(msg, msglen, cp, &dp, name, sizeof name, from,
			      &tname);
		if (n < 0) {
			free_related_additional();
			freestr_maybe(&tname);
			if (flushset != NULL)
				free_flushset(flushset, flushset_size);
			formerrmsg = outofDataFinal;
			if (hp->rcode == REFUSED)
				goto refused;
			else
				goto formerr;
		}
		cp += n;
		if (!dp)
			continue;
		type = dp->d_type;
		if (i < ancount) {
			/* Answer section. */
			/*
			 * Check for attempts to overflow the buffer in
			 * getnameanswer.
			 */
			if (type == ns_t_cname && !expect_cname) {
				ns_warning(ns_log_security,
			     "late CNAME in answer section for %s %s from %s",
					   *qname ? qname : ".", p_type(qtype),
					   sin_ntoa(from));
					   
			} else if (type != ns_t_cname && type != ns_t_dname &&
				   type != ns_t_sig)
				expect_cname = 0;
			if (externalcname || ns_samename(name, aname) != 1) {
				if (!externalcname)
					ns_info(ns_log_resp_checks,
						"wrong ans. name (%s != %s)",
						name[0] ? name : ".", 
						aname[0] ? aname : ".");
				else
					ns_debug(ns_log_resp_checks, 3,
				 "ignoring answer '%s' after external cname",
						 name);
				db_detach(&dp);
				validanswer = 0;
				continue;
			}
			if (type == T_CNAME &&
			    qtype != T_CNAME && qtype != T_ANY) {
				strcpy(aname, (char *)dp->d_data);
				if (!ns_samedomain(aname, qp->q_domain))
					externalcname = 1;
				cname++;
				lastwascname = 1;
			} else {
				if (validanswer)
					validanswer = 1;
				lastwascname = 0;
			}

			if (tname != NULL) {
				add_related_additional(tname);
				tname = NULL;
			}

			/* Cache for current tick. */
			if (type == T_SOA)
				dp->d_ttl = tt.tv_sec;

			dp->d_cred = (hp->aa && ns_samename(name, qname) == 1)
				? DB_C_AUTH
				: DB_C_ANSWER;
		} else {
			/* After answer section. */
			if (lastwascname) {
				ns_debug(ns_log_resp_checks, 3,
				 "last was cname, ignoring auth. and add.");
				db_detach(&dp);
				validanswer = 0;
				break;
			}
			if (i < arfirst) {
				/* Authority section. */
				switch (type) {
				case T_NS:
				case T_SOA:
					if (!ns_samedomain(aname, name)) {
						ns_info(ns_log_resp_checks,
					    "bad referral (%s !< %s) from %s",
							aname[0] ? aname : ".",
							name[0] ? name : ".",
							sin_ntoa(from));
						db_detach(&dp);
						validanswer = 0;
						continue;
					} else if (!ns_samedomain(name,
							       qp->q_domain)) {
						if (fwd == NULL &&
						    !externalcname)
						    ns_info(ns_log_resp_checks,
					    "bad referral (%s !< %s) from %s",
							 name[0] ? name : ".",
							 qp->q_domain[0] ?
							 qp->q_domain : ".",
							 sin_ntoa(from));
						db_detach(&dp);
						validanswer = 0;
						continue;
					}
					if (type == T_NS) {
						nscount++;
						add_related_additional(tname);
						tname = NULL;
					}
					if (type == T_SOA) {
						soacount++;
						/* -ve caching only. */
						db_detach(&dp);
						continue;
					}
					break;
				case T_NXT:
					/* XXX check */
					break;
				case T_SIG:
					/* XXX check that it relates to an
					   NS or SOA or NXT */
					break;
				default:
					ns_info(ns_log_resp_checks,
	"invalid RR type '%s' in authority section (name = '%s') from %s",
						p_type(type), name,
						sin_ntoa(from));
					db_detach(&dp);
					validanswer = 0;
					continue;
				}
				dp->d_cred = (hp->aa && (cname == 0)) ?
					DB_C_AUTH : (qp->q_flags & Q_PRIMING)
						? DB_C_ANSWER
						: DB_C_ADDITIONAL;
			} else {
				/* Additional section. */
				switch (type) {
				case T_A:
				case ns_t_a6:
				case T_AAAA:
				case T_SRV:
					if (externalcname ||
					    !ns_samedomain(name, qp->q_domain)) {
						ns_debug(ns_log_resp_checks, 3,
				       "ignoring additional info '%s' type %s",
							 name, p_type(type));
						db_detach(&dp);
						validanswer = 0;
						continue;
					}
					if (!related_additional(name)) {
						ns_info(ns_log_resp_checks,
			     "unrelated additional info '%s' type %s from %s",
							 name, p_type(type),
							 sin_ntoa(from));
						db_detach(&dp);
						validanswer = 0;
						continue;
					}
					if (type == T_SRV && tname != NULL) {
						add_related_additional(tname);
						tname = NULL;
					}
					break;
				case T_KEY:
					/* XXX  check? */
					break;
				case T_SIG:
					/*
					 * XXX  a SIG RR should relate
					 * to some other RR in this section,
					 * although if it's the last RR
					 * it might be a transaction signature.
					 */
					break;
				case ns_t_opt:
					/*
					 * OPT does not get cached.
					 */
					db_detach(&dp);
					validanswer = 0;
					continue;
				default:
					ns_info(ns_log_resp_checks,
	"invalid RR type '%s' in additional section (name = '%s') from %s",
						p_type(type), name,
						sin_ntoa(from));
					db_detach(&dp);
					validanswer = 0;
					continue;
				}
				dp->d_cred = (qp->q_flags & Q_PRIMING)
					? DB_C_ANSWER
					: DB_C_ADDITIONAL;
			}
		}
#ifdef HITCOUNTS
		++dp->d_hitcnt;
		++db_total_hits;
#endif /* HITCOUNTS */
		rrsetadd(flushset, name, dp);
		db_detach(&dp);
	}
	free_related_additional();
	freestr_maybe(&tname);
	if (flushset != NULL) {
		if ((qp->q_flags & Q_SYSTEM) && (qp->q_flags & Q_PRIMING)) {
			check_hints(flushset); /* before rrsetupdate */
			rrsetupdate(flushset, dbflags, from, 1);
		} else
			rrsetupdate(flushset, dbflags, from, 0);
		free_flushset(flushset, flushset_size);
 	}
	if (lastwascname && !externalcname)
		ns_debug(ns_log_cname, 3, "%s (%s) q(%s %s %s) %s qd(%s)",
			danglingCname, aname,
			(qname && *qname) ? qname : ".",
			p_class(qclass), p_type(qtype),
			sin_ntoa(from), qp->q_domain);

	if (cp > eom) {
		formerrmsg = outofDataAFinal;
		goto formerr;
	}

	if ((qp->q_flags & Q_SYSTEM) && ancount) {
		if ((qp->q_flags & Q_PRIMING) && !check_root()) {
			/* mark server as bad */
			mark_bad(qp, from);
			fast_retry(qp, from, 0);
			return;
		}
		ns_debug(ns_log_default, 3,
			 "resp: leaving, SYSQUERY ancount %d", ancount);
#ifdef BIND_NOTIFY
		if (qp->q_notifyzone != DB_Z_CACHE) {
			struct zoneinfo *zp = &zones[qp->q_notifyzone];

			qp->q_notifyzone = DB_Z_CACHE;
			ns_notify(zp->z_origin, zp->z_class, ns_t_soa);
		}
#endif
		qremove(qp);
		return;
	}

	/*
	 * We might want to cache this negative answer.
	 *
	 * if ancount != 0 and rcode == NOERROR we cannot determine if the
	 * CNAME chain has been processed to completion or not, so just
	 * restart the query. DNS needs a NODATA return code!
	 *
	 * As some servers incorrectly return a NODATA indication when
	 * there is a CNAME chain instead of NXDOMAIN, we requery to get
	 * a definitive answer.
	 */
	if ((hp->rcode == NXDOMAIN && cname == ancount) ||
	    (hp->rcode == NOERROR && ancount == 0 && 
	     (nscount == 0 || soacount != 0)
	     )
	    )
	{
		cache_n_resp(msg, msglen, from, qp->q_name,
			     qp->q_class, qp->q_type);

		if (!qp->q_cmsglen && validanswer) {
			ns_debug(ns_log_default, 3,
				 "resp: leaving NO: auth = %d", hp->aa);
			goto return_msg;
		}
	}

	/*
	 * All messages in here need further processing.  i.e. they
	 * are either CNAMEs or we got referred again.
	 */
	count = 0;
	founddata = 0;
	dname = name;
	/*
	 * XXX - the restart stuff doesn't work if any of the answer RRs
	 * is not cacheable (TTL==0 or unknown RR type), since all of the
	 * answer must pass through the cache and be re-assembled.
	 */
	if (qp->q_cmsglen != 0) {
		ns_debug(ns_log_default, 1, "Cname second pass");
		newmsglen = MIN(EDNS_MESSAGE_SZ, qp->q_cmsglen);
		memcpy(newmsg, qp->q_cmsg, newmsglen);
	} else {
		newmsglen = MIN(EDNS_MESSAGE_SZ, msglen);
		memcpy(newmsg, msg, newmsglen);
	}
	hp = (HEADER *) newmsg;
	hp->ancount = htons(0);
	hp->nscount = htons(0);
	hp->arcount = htons(0);
	hp->rcode = NOERROR;
	dnptrs[0] = newmsg;
	dnptrs[1] = NULL;
	cp = newmsg + HFIXEDSZ;
	/*
	 * Keep in mind that none of this code works when QDCOUNT>1.
	 * cp ends up pointed just past the query section in both cases.
	 */
	/*
	 * Arrange for dname to contain the query name. The query
	 * name can be either the original query name if restart==0
	 * or the target of the last CNAME if we are following a
	 * CNAME chain and were referred.
	 */
	n = dn_expand(newmsg, newmsg + newmsglen, cp, dname, sizeof name);
	if (n < 0) {
		ns_debug(ns_log_default, 1, "dn_expand failed");
		goto servfail;
	}
	if (!res_dnok(dname)) {
		ns_debug(ns_log_default, 1, "bad name (%s)", dname);
		goto servfail;
	}
	cp += n + QFIXEDSZ;
	buflen = (qp->q_stream != NULL) ? NS_MAXMSG : 
					  MIN(EDNS_MESSAGE_SZ, qp->q_udpsize);
	buflen -= (cp - newmsg);
	/*
	 * Reserve space for TSIG / EDNS
	 */
        if (qp->q_tsig != NULL)
                buflen -=  qp->q_tsig->tsig_size;
        if ((qp->q_flags & Q_EDNS) != 0)
                buflen -= 11;
	cname = 0;

 try_again:
	pass++;
	ns_debug(ns_log_default, 1, "resp: nlookup(%s) qtype=%d", dname,
		 qtype);
	foundname = 0;
	fname = "";
	htp = hashtab;		/* lookup relative to root */
	np = nlookup(dname, &htp, &fname, 0);
	ns_debug(ns_log_default, 1, "resp: %s '%s' as '%s' (cname=%d)",
		 np == NULL ? "missed" : "found", dname, fname, cname);
	if (np == NULL || fname != dname)
		goto fetch_ns;

	foundname++;
	answers = cp;
	count = cp - newmsg;
	/*
	 * Look for NXDOMAIN record.
	 */
	for (dp = np->n_data; dp; dp = dp->d_next) {
		if (!stale(dp) && (dp->d_rcode == NXDOMAIN) &&
		    (dp->d_class == (int)qclass)) {
#ifdef RETURNSOA
			n = finddata(np, qclass, T_SOA, hp, &dname,
				     &buflen, &count, pass, 1);
			if ( n != 0) {
				if (count) {
					cp += n;
					buflen -= n;
					newmsglen += n;
					hp->nscount = htons((u_int16_t)count);
				}
				if (hp->rcode == NOERROR_NODATA) {
					hp->rcode = NOERROR;
					goto return_newmsg;
				}
			}
#else
			count = 0;
#endif
			hp->rcode = NXDOMAIN;
			/* 
			 * XXX forcing AA all the time isn't right, but
			 * we have to work that way by default
			 * for compatibility with older servers.
			 */
			if (!NS_OPTION_P(OPTION_NONAUTH_NXDOMAIN))
				hp->aa = 1;
			ns_debug(ns_log_default, 3, "resp: NXDOMAIN aa = %d",
				 hp->aa);
			if ((count == 0) || NS_OPTION_P(OPTION_NORFC2308_TYPE1))
				goto return_newmsg;
			founddata = 1;
			goto fetch_ns;
		}
	}
	n = finddata(np, qclass, qtype, hp, &dname, &buflen, &count, pass, 1);
	if (n == 0)
		goto fetch_ns;		/* NO data available */
	if (hp->rcode) {
		if (hp->rcode == NOERROR_NODATA)
			hp->rcode = NOERROR;
#ifdef RETURNSOA
		if (count) {
			cp += n;
			buflen -= n;
			hp->nscount = htons((u_int16_t)count);
		}
#endif
		if ((count == 0) || NS_OPTION_P(OPTION_NORFC2308_TYPE1))
			goto return_newmsg;
		founddata = 1;
		goto fetch_ns;
	}
	cp += n;
	buflen -= n;
	hp->ancount = htons(ntohs(hp->ancount) + (u_int16_t)count);
	if (fname != dname && qtype != T_CNAME && qtype != T_ANY) {
		cname++;
		goto try_again;
	}
	founddata = 1;

	ns_debug(ns_log_default, 3,
		 "resp: foundname=%d, count=%d, founddata=%d, cname=%d",
		 foundname, count, founddata, cname);

	if (count > 1 && qtype == T_A)
		sort_response(answers, cp, count, &qp->q_from);

 fetch_ns:
	if (hp->tc)
		goto return_newmsg;

	/*
 	 * Look for name servers to refer to and fill in the authority
 	 * section or record the address for forwarding the query
 	 * (recursion desired).
 	 */
	free_nsp(nsp);
	switch (findns(&np, qclass, nsp, &count, 0)) {
	case NXDOMAIN:		/* shouldn't happen */
		ns_debug(ns_log_default, 3, "req: leaving (%s, rcode %d)",
			 dname, hp->rcode);
		if (!foundname)
			hp->rcode = NXDOMAIN;
		if (qclass != C_ANY) {
			if (!cname)
				hp->aa = 1;
			if (np && (!foundname || !founddata)) {
				n = doaddauth(hp, cp, buflen, np, nsp[0]);
				cp += n;
				buflen -= n;
			}
		}
		goto return_newmsg;

	case SERVFAIL:
		goto servfail;
	}

	if (founddata) {
		hp = (HEADER *)newmsg;
		n = add_data(np, nsp, cp, buflen, &count);
		if (n < 0) {
			hp->tc = 1;
			n = (-n);
		}
		cp += n;
		buflen -= n;
		hp->nscount = htons((u_int16_t)count + ntohs(hp->nscount));
		goto return_newmsg;
	}

	/*
	 *  If we get here, we don't have the answer yet and are about
	 *  to iterate to try and get it.  First, infinite loop avoidance.
	 */
	if (qp->q_nqueries++ > MAXQUERIES) {
		ns_debug(ns_log_default, 1,
			 "resp: MAXQUERIES exceeded (%s %s %s)",
			 dname, p_class(qclass), p_type(qtype));
		ns_info(ns_log_default,
		   "MAXQUERIES exceeded, possible data loop in resolving (%s)",
			dname);
		goto servfail;
	}

	/* Reset the query control structure */

	ns_freeqns(qp);
	qp->q_naddr = 0;
	qp->q_curaddr = 0;
	nsfwdadd(qp, NS_ZFWDTAB(qp->q_fzone));

	if (qp->q_domain != NULL)
		(void)freestr(qp->q_domain);
	getname(np, tmpdomain, sizeof tmpdomain);
	qp->q_domain = savestr(tmpdomain, 1);

	if (NS_ZOPTION_P(qp->q_fzone, OPTION_FORWARD_ONLY))
		n = 0;
	else if ((n = nslookup(nsp, qp, dname, "ns_resp")) <= 0) {
		if (n < 0) {
			if (n == -1)
				ns_debug(ns_log_default, 3,
					 "resp: nslookup reports danger");
			if (cname) /* a remote CNAME that does not have data */
				goto return_newmsg;
			goto servfail;
		} else {
			ns_debug(ns_log_default, 3,
				 "resp: no addrs found for NS's");
			/*
			 * Timeout while sysquery looks up the NS addresses.
			 *
			 * Hopefully we'll have them when the client asks
			 * again.
			 *
			 * too bad we can't just wait for the sysquery
			 * response to restart this query (it's too hard).
			 *
			 * We could try to crawl back up the tree looking
			 * for reachable servers, but we may have just
			 * gotten delegated down here by a response with
			 * no A RRs for the servers.  If we blindly tried
			 * this strategy, we bang on the same server forever.
			 */
			goto timeout;
		}
	}
	for (n = 0; (u_int)n < qp->q_naddr; n++)
		qp->q_addr[n].stime.tv_sec = 0;
	qp->q_addr[0].stime = tt;
	if (cname) {
	 	if (qp->q_cname++ == MAXCNAMES) {
			ns_debug(ns_log_default, 3,
				 "resp: leaving, MAXCNAMES exceeded");
			goto servfail;
	 	}
		ns_debug(ns_log_default, 1, "q_cname = %d", qp->q_cname);
		ns_debug(ns_log_default, 3,
			 "resp: building recursive query; nslookup");
		if (qp->q_cmsg == NULL) {
			qp->q_cmsg = qp->q_msg;
			qp->q_cmsglen = qp->q_msglen;
			qp->q_cmsgsize = qp->q_msgsize;
		} else if (qp->q_msg != NULL)
			memput(qp->q_msg, qp->q_msgsize);
		qp->q_msg = (u_char *)memget(PACKETSZ);
		if (qp->q_msg == NULL) {
			ns_notice(ns_log_default, "resp: memget error");
			goto servfail;
		}
		qp->q_msgsize = PACKETSZ;
		n = res_nmkquery(&res, QUERY, dname, qclass, qtype,
				 NULL, 0, NULL, qp->q_msg, PACKETSZ);
		if (n < 0) {
			ns_info(ns_log_default, "resp: res_mkquery(%s) failed",
				dname);
			goto servfail;
		}
		if (qp->q_name != NULL)
			(void)freestr(qp->q_name);
		qp->q_name = savestr(dname, 1);
		qp->q_msglen = n;
		hp = (HEADER *) qp->q_msg;
		hp->rd = 0;
	} else
		hp = (HEADER *) qp->q_msg;
	hp->id = qp->q_nsid = htons(nsid_next());
	hp->rd = (qp->q_addr[0].forwarder ? 1 : 0);
	unsched(qp);
	schedretry(qp, retrytime(qp));
	nsa = Q_NEXTADDR(qp, 0);
	if (ns_wouldlog(ns_log_default, 1)) {
		ns_debug(ns_log_default, 1,
			 "resp: forw -> %s ds=%d nsid=%d id=%d %dms",
			 sin_ntoa(*nsa), ds,
			 ntohs(qp->q_nsid), ntohs(qp->q_id),
			 (qp->q_addr[0].nsdata != NULL)
				 ? qp->q_addr[0].nsdata->d_nstime
				 : -1);
	}
#ifdef DEBUG
	if (debug >= 10)
		res_pquery(&res, qp->q_msg, qp->q_msglen,
			    log_get_stream(packet_channel));
#endif
	key = qp->q_keys[0];
        if (key == NULL)
                key = qp->q_keys[0] = tsig_key_from_addr(nsa->sin_addr);
	if (key != NULL || !qp->q_addr[0].noedns) {
		smsgsize = qp->q_msglen + TSIG_BUF_SIZE + 11;
		smsg = memget(smsgsize);
		smsglen = qp->q_msglen;
		siglen = sizeof(sig);
		memcpy(smsg, qp->q_msg, qp->q_msglen);
	}

	if (!qp->q_addr[0].noedns)
                smsglen += ns_add_opt(smsg, smsg + smsglen, smsgsize, 0, 0,
                                      server_options->edns_udp_size,
				      0, NULL, 0);
	if (key != NULL) {
		n = ns_sign(smsg, &smsglen, smsgsize, NOERROR, key, NULL, 0,
			    sig, &siglen, 0);
		if (n == 0) {
			has_tsig = 1;
			free_tsig(qp->q_nstsig);
			qp->q_nstsig = new_tsig(key, sig, siglen);
		} else {
			has_tsig = 0;
			free_tsig(qp->q_nstsig);
			qp->q_nstsig = NULL;
			INSIST(0);
		}
	} else {
		has_tsig = 0;
		free_tsig(qp->q_nstsig);
		qp->q_nstsig = NULL;
	}

	if (smsg != NULL) {
		oldqbuf = qp->q_msg;
		oldqlen = qp->q_msglen;
		qp->q_msglen = smsglen;
		qp->q_msg = smsg;
	}

	if (qp->q_flags & Q_USEVC) {
		if (tcp_send(qp) != NOERROR) {
			if (!haveComplained(ina_ulong(nsa->sin_addr),
					    (u_long)tcpsendStr))
				ns_info(ns_log_default,
					"ns_resp: tcp_send(%s) failed: %s",
					sin_ntoa(*nsa), strerror(errno));
		}
	} else if (sendto(ds, (char*)qp->q_msg, qp->q_msglen, 0,
		   (struct sockaddr *)nsa,
		   sizeof(struct sockaddr_in)) < 0)
	{
		sendto_errno = errno;
		if (!haveComplained(ina_ulong(nsa->sin_addr),
				    (u_long)sendtoStr))
			ns_info(ns_log_default, "ns_resp: sendto(%s): %s",
				sin_ntoa(*nsa), strerror(errno));
		nameserIncr(nsa->sin_addr, nssSendtoErr);
	}

	if (smsgsize != 0) {
		memput(smsg, smsgsize);
		qp->q_msg = oldqbuf;
		qp->q_msglen = oldqlen;
	}
	hp->rd = 0;	/* leave set to 0 for dup detection */
	nameserIncr(nsa->sin_addr, nssSentFwdR);
	nameserIncr(qp->q_from.sin_addr, nssRcvdFwdR);
	ns_debug(ns_log_default, 3, "resp: Query sent.");
	free_nsp(nsp);
	switch (sendto_errno) {
	case ENETDOWN:
	case ENETUNREACH:
	case EHOSTDOWN:
	case EHOSTUNREACH:
		unsched(qp);
		schedretry(qp, (time_t) 0);
	}
	return;

 formerr:
	if (!haveComplained(ina_ulong(from.sin_addr), (u_long)formerrmsg))
		ns_info(ns_log_resp_checks, "Malformed response from %s (%s)",
			sin_ntoa(from), formerrmsg);
	fast_retry(qp, from, 0);
	free_nsp(nsp);
	return;

 return_msg:
	nameserIncr(from.sin_addr, nssRcvdFwdR);
	nameserIncr(qp->q_from.sin_addr, nssSentFwdR);
	nameserIncr(qp->q_from.sin_addr, nssSentAns);
	if (!hp->aa)
		nameserIncr(qp->q_from.sin_addr, nssSentNaAns);
	if (hp->rcode == NXDOMAIN)
		nameserIncr(qp->q_from.sin_addr, nssSentNXD);
	/* The "standard" return code */
	hp->qr = 1;
	hp->id = qp->q_id;
	hp->rd = 1;
	hp->ra = (NS_OPTION_P(OPTION_NORECURSE) == 0);
	(void) send_msg(msg, msglen, qp);
	qremove(qp);
	free_nsp(nsp);
	return;

 return_newmsg:
	nameserIncr(qp->q_from.sin_addr, nssSentAns);

	if (!hp->aa)
		nameserIncr(qp->q_from.sin_addr, nssSentNaAns);
	if (hp->rcode == NXDOMAIN) 
		nameserIncr(qp->q_from.sin_addr, nssSentNXD);
	n = doaddinfo(hp, cp, buflen);
	cp += n;
	buflen -= n;
	hp->qr = 1;
	hp->id = qp->q_id;
	hp->rd = 1;
	hp->ra = (NS_OPTION_P(OPTION_NORECURSE) == 0);
	(void) send_msg(newmsg, cp - newmsg, qp);
	qremove(qp);
	free_nsp(nsp);
	return;

 refused:
	hp = (HEADER *)(qp->q_cmsglen ? qp->q_cmsg : qp->q_msg);
	hp->rcode = REFUSED;
	hp->qr = 1;
	hp->id = qp->q_id;
	hp->rd = 1;
	hp->ra = (NS_OPTION_P(OPTION_NORECURSE) == 0);
	(void) send_msg((u_char *)hp,
			(qp->q_cmsglen ? qp->q_cmsglen : qp->q_msglen),
			qp);
	qremove(qp);
	free_nsp(nsp);
	return;
	
 servfail:
	nameserIncr(qp->q_from.sin_addr, nssSentFail);
	hp = (HEADER *)(qp->q_cmsglen ? qp->q_cmsg : qp->q_msg);
	hp->rcode = SERVFAIL;
	hp->qr = 1;
	hp->id = qp->q_id;
	hp->rd = 1;
	hp->ra = (NS_OPTION_P(OPTION_NORECURSE) == 0);
	(void) send_msg((u_char *)hp,
			(qp->q_cmsglen ? qp->q_cmsglen : qp->q_msglen),
			qp);
	qremove(qp);
	free_nsp(nsp);
	return;

 timeout:
	if (qp->q_stream)
		sq_remove(qp->q_stream);
	qremove(qp);
	free_nsp(nsp);
	return;
}

#define BOUNDS_CHECK(ptr, count) \
	do { \
		if ((ptr) + (count) > eom) { \
			hp->rcode = FORMERR; \
			return (-1); \
		} \
	} while (0)

static int
rrextract(u_char *msg, int msglen, u_char *rrp, struct databuf **dpp,
	  char *dname, int namelen, struct sockaddr_in from, char **tnamep)
{
	u_char *cp, *eom, *rdatap;
	u_int class, type, dlen;
	int n, n1, n2;
	u_int32_t ttl;
	u_char *cp1, data[MAXDATA*2];
	HEADER *hp = (HEADER *)msg;
	enum context context;

	if (tnamep != NULL)
		*tnamep = NULL;

	*dpp = NULL;
	cp = rrp;
	eom = msg + msglen;
	if ((n = dn_expand(msg, eom, cp, dname, namelen)) < 0) {
		hp->rcode = FORMERR;
		return (-1);
	}
	cp += n;
	BOUNDS_CHECK(cp, 2*INT16SZ + INT32SZ + INT16SZ);
	GETSHORT(type, cp);
	GETSHORT(class, cp);
	if (type != ns_t_opt && class > CLASS_MAX) {
		ns_debug(ns_log_default, 3, "bad class in rrextract");
		hp->rcode = FORMERR;
		return (-1);
	}
	GETLONG(ttl, cp);
	if (ttl > MAXIMUM_TTL) {
		ns_debug(ns_log_default, 5, "%s: converted TTL > %u to 0",
			 dname, MAXIMUM_TTL);
		ttl = 0;
	}
	GETSHORT(dlen, cp);
	BOUNDS_CHECK(cp, dlen);
	rdatap = cp;
	if (!ns_nameok(NULL, dname, class, NULL, response_trans,
		       ns_ownercontext(type, response_trans),
		       dname, from.sin_addr)) {
		hp->rcode = REFUSED;
		return (-1);
	}
	ns_debug(ns_log_default, 3,
		 "rrextract: dname %s type %d class %d ttl %d",
		 dname, type, class, ttl);
	/*
	 * Convert the resource record data into the internal
	 * database format.
	 *
	 * On entry to the switch:
	 *   CP points to the RDATA section of the wire-format RR.
	 *   DLEN is its length.
	 *   The memory area at DATA is available for processing.
	 * 
	 * On exit from the switch:
	 *   CP has been incremented past the RR.
	 *   CP1 points to the RDATA section of the database-format RR.
	 *   N contains the length of the RDATA section of the dbase-format RR.
	 *
	 * The new data at CP1 for length N will be copied into the database,
	 * so it need not be in any particular storage location.
	 */
	switch (type) {
	case T_A:
		if (dlen != INT32SZ) {
			hp->rcode = FORMERR;
			return (-1);
		}
		/*FALLTHROUGH*/
	case T_WKS:
	case T_HINFO:
	case T_TXT:
	case T_X25:
	case T_ISDN:
	case T_NSAP:
	case T_AAAA:
	case T_LOC:
	case T_KEY:
	case ns_t_cert:
	case ns_t_opt:
		cp1 = cp;
		n = dlen;
		cp += n;
		break;

	case T_CNAME:
	case T_MB:
	case T_MG:
	case T_MR:
	case T_NS:
	case T_PTR:
		n = dn_expand(msg, eom, cp, (char *)data, sizeof data);
		if (n < 0) {
			hp->rcode = FORMERR;
			return (-1);
		}
		if (!ns_nameok(NULL, (char *)data, class, NULL, response_trans,
			       type == T_PTR ?ns_ptrcontext(dname) :domain_ctx,
			       dname, from.sin_addr)) {
			hp->rcode = FORMERR;
			return (-1);
		}
		cp += n;
		cp1 = data;
		n = strlen((char *)data) + 1;
		if (tnamep != NULL && (type == T_NS || type == T_MB))
			*tnamep = savestr((char *)cp1, 1);
		break;

	case T_SOA:
		context = hostname_ctx;
		goto soa_rp_minfo;
	case T_RP:
	case T_MINFO:
		context = mailname_ctx;
		/* FALLTHROUGH */
	soa_rp_minfo:
		n = dn_expand(msg, eom, cp, (char *)data, sizeof data);
		if (n < 0) {
			hp->rcode = FORMERR;
			return (-1);
		}
		if (!ns_nameok(NULL, (char *)data, class, NULL, response_trans,
			       context, dname, from.sin_addr)) {
			hp->rcode = FORMERR;
			return (-1);
		}
		cp += n;
		/*
		 * The next use of 'cp' is dn_expand(), so we don't have
		 * to BOUNDS_CHECK() here.
		 */
		cp1 = data + (n = strlen((char *)data) + 1);
		n1 = sizeof(data) - n;
		if (type == T_SOA)
			n1 -= 5 * INT32SZ;
		n = dn_expand(msg, eom, cp, (char *)cp1, n1);
		if (n < 0) {
			hp->rcode = FORMERR;
			return (-1);
		}
		if (type == T_RP)
			context = domain_ctx;
		else
			context = mailname_ctx;
		if (!ns_nameok(NULL, (char *)cp1, class, NULL, response_trans,
			       context, dname, from.sin_addr)) {
			hp->rcode = FORMERR;
			return (-1);
		}
		cp += n;
		cp1 += strlen((char *)cp1) + 1;
		if (type == T_SOA) {
			n = 5 * INT32SZ;
			BOUNDS_CHECK(cp, n);
			memcpy(cp1, cp, n);
			cp += n;
			cp1 += n;
		}
		n = cp1 - data;
		cp1 = data;
		if (tnamep != NULL && type == T_SOA)
			*tnamep = savestr((char *)cp1, 1);
		break;

	case T_NAPTR:
		/* Grab weight and port. */
		BOUNDS_CHECK(cp, INT16SZ*2);
		memcpy(data, cp, INT16SZ*2);
		cp1 = data + INT16SZ*2;
		cp += INT16SZ*2;

		/* Flags */
		BOUNDS_CHECK(cp, 1);
		n = *cp++;
		BOUNDS_CHECK(cp, n);
		*cp1++ = n;
		memcpy(cp1, cp, n);
		cp += n; cp1 += n;

		/* Service */
		BOUNDS_CHECK(cp, 1);
		n = *cp++;
		BOUNDS_CHECK(cp, n);
		*cp1++ = n;
		memcpy(cp1, cp, n);
		cp += n; cp1 += n;

		/* Regexp */
		BOUNDS_CHECK(cp, 1);
		n = *cp++;
		BOUNDS_CHECK(cp, n);
		*cp1++ = n;
		memcpy(cp1, cp, n);
		cp += n; cp1 += n;

		/* Replacement */
		n = dn_expand(msg, eom, cp, (char *)cp1,
			      sizeof data - (cp1 - data));
		if (n < 0) {
			hp->rcode = FORMERR;
			return (-1);
		}
		if (!ns_nameok(NULL, (char *)cp1, class, NULL, response_trans,
			       hostname_ctx, dname, from.sin_addr)) {
			hp->rcode = FORMERR;
			return (-1);
		}
		cp += n;

		if (tnamep != NULL && *cp1 != 0)
			*tnamep = savestr((char *)cp1, 1);

		/* compute end of data */
		cp1 += strlen((char *)cp1) + 1;
		/* compute size of data */
		n = cp1 - data;
		cp1 = data;
		break;

	case T_MX:
	case T_AFSDB:
	case T_RT:
	case T_SRV:
		/* grab preference */
		BOUNDS_CHECK(cp, INT16SZ);
		memcpy(data, cp, INT16SZ);
		cp1 = data + INT16SZ;
		cp += INT16SZ;

		if (type == T_SRV) {
			/* Grab weight and port. */
			BOUNDS_CHECK(cp, INT16SZ*2);
			memcpy(cp1, cp, INT16SZ*2);
			cp1 += INT16SZ*2;
			cp += INT16SZ*2;
		}

		/* get name */
		n = dn_expand(msg, eom, cp, (char *)cp1,
			      sizeof data - (cp1 - data));
		if (n < 0) {
			hp->rcode = FORMERR;
			return (-1);
		}
		if (!ns_nameok(NULL, (char *)cp1, class, NULL, response_trans,
			       hostname_ctx, dname, from.sin_addr)) {
			hp->rcode = FORMERR;
			return (-1);
		}
		cp += n;

		if (tnamep != NULL)
			*tnamep = savestr((char *)cp1, 1);

		/* compute end of data */
		cp1 += strlen((char *)cp1) + 1;
		/* compute size of data */
		n = cp1 - data;
		cp1 = data;
		break;

	case T_PX:
		/* grab preference */
		BOUNDS_CHECK(cp, INT16SZ);
		memcpy(data, cp, INT16SZ);
		cp1 = data + INT16SZ;
		cp += INT16SZ;

		/* get MAP822 name */
		n = dn_expand(msg, eom, cp, (char *)cp1,
			      sizeof data - INT16SZ);
		if (n < 0) {
			hp->rcode = FORMERR;
			return (-1);
		}
		if (!ns_nameok(NULL, (char *)cp1, class, NULL, response_trans,
			       domain_ctx, dname, from.sin_addr)) {
			hp->rcode = FORMERR;
			return (-1);
		}
		cp += n;
		/*
		 * The next use of 'cp' is dn_expand(), so we don't have
		 * to BOUNDS_CHECK() here.
		 */
		cp1 += (n = strlen((char *)cp1) + 1);
		n1 = sizeof(data) - n - INT16SZ;
		n = dn_expand(msg, eom, cp, (char *)cp1, n1);
		if (n < 0) {
			hp->rcode = FORMERR;
			return (-1);
		}
		if (!ns_nameok(NULL, (char *)cp1, class, NULL, response_trans,
			       domain_ctx, dname, from.sin_addr)) {
			hp->rcode = FORMERR;
			return (-1);
		}
		cp += n;
		cp1 += strlen((char *)cp1) + 1;
		n = cp1 - data;
		cp1 = data;
		break;

	case T_SIG: {
		u_int32_t origTTL, exptime, signtime, timetilexp, now;
		u_int8_t alg;

		/* Check signature time, expiration, and adjust TTL.  */
		/* This code is similar to that in db_load.c.  */

		/* Skip coveredType, save alg, skip labels */
		BOUNDS_CHECK(cp, INT16SZ + 1 + 1 + 3*INT32SZ);
		cp1 = cp + INT16SZ;
		alg = *cp1++;
		cp1++;
		GETLONG(origTTL, cp1);
		GETLONG(exptime, cp1);
		GETLONG(signtime, cp1);
		now = time(NULL);	/* Get current time in GMT/UTC */

		/* Don't let bogus name servers increase the signed TTL */
		if (ttl > origTTL) {
			ns_debug(ns_log_default, 3,
				 "shrinking SIG TTL from %lu to origTTL %lu",
				 (unsigned long)ttl, (unsigned long)origTTL);
			ttl = origTTL;
		}

		/*
		 * Check that expire and signature times are internally
		 * consistant.
		 */
		if (!SEQ_GT(exptime, signtime) && exptime != signtime) {
			ns_debug(ns_log_default, 3,
			"ignoring SIG: signature expires before it was signed");
			return ((cp - rrp) + dlen);
		}

		/* Don't let bogus signers "sign" in the future.  */
		if (SEQ_GT(signtime, now)) {
			ns_debug(ns_log_default, 3,
			  "ignoring SIG: signature date %s is in the future",
				 p_secstodate (signtime));
			return ((cp - rrp) + dlen);
		}
		
		/* Ignore received SIG RR's that are already expired.  */
		if (SEQ_GT(now, exptime)) {
			ns_debug(ns_log_default, 3,
				"ignoring SIG: expiration %s is in the past",
				 p_secstodate (exptime));
			return ((cp - rrp) + dlen);
		}

		/* Lop off the TTL at the expiration time.  */
		timetilexp = exptime - now;
		if (timetilexp < ttl) {
			ns_debug(ns_log_default, 3,
				 "shrinking expiring %s SIG TTL from %d to %d",
				 p_secstodate (exptime), ttl, timetilexp);
			ttl = timetilexp;
		}

		/* The following code is copied from named-xfer.c.  */
		cp1 = (u_char *)data;

		/* first just copy over the type_covered, algorithm, */
		/* labels, orig ttl, two timestamps, and the footprint */
		BOUNDS_CHECK(cp, 18);
		memcpy(cp1, cp, 18);
		cp  += 18;
		cp1 += 18;

		/* then the signer's name */
		n = dn_expand(msg, eom, cp, (char *)cp1, (sizeof data) - 18);
		if (n < 0 || n + NS_SIG_SIGNER > (int)dlen) {
			hp->rcode = FORMERR;
			return (-1);
		}
		cp += n;
		cp1 += strlen((char*)cp1)+1;

		/* finally, we copy over the variable-length signature.
		   Its size is the total data length, minus what we copied. */
		n = dlen - (NS_SIG_SIGNER + n);

		if (n > (int)(sizeof data) - (cp1 - (u_char *)data)) {
			hp->rcode = FORMERR;
			return (-1);  /* out of room! */
		}

		switch (alg) {
		    case NS_ALG_MD5RSA:
			if (n < NS_MD5RSA_MIN_SIZE || n > NS_MD5RSA_MAX_SIZE)
				hp->rcode = FORMERR;
			break;

		    case NS_ALG_DSA:
			if (n != NS_DSA_SIG_SIZE)
				hp->rcode = FORMERR;
			break;

		    default:
			break;
		}

		if (hp->rcode == FORMERR)
			return (-1);

		memcpy(cp1, cp, n);
		cp += n;
		cp1 += n;
		
		/* compute size of data */
		n = cp1 - (u_char *)data;
		cp1 = (u_char *)data;
		break;
	    }

	case T_NXT:
		n = dn_expand(msg, eom, cp, (char *)data, sizeof data);
		/*
		 * By testing if n >= dlen, we are requiring that the type
		 * bitmap be at least one octet.  This is reasonable
		 * because we always have to look at the 0 bit to see if
		 * this is a "different format" NXT or not.
		 */
		if (n < 0 || n >= (int)dlen) {
			hp->rcode = FORMERR;
			return (-1);
		}
		if (!ns_nameok(NULL, (char *)data, class, NULL, response_trans,
			       domain_ctx, dname, from.sin_addr)) {
			hp->rcode = FORMERR;
			return (-1);
		}
		cp += n;
		n1 = strlen((char *)data) + 1;
		cp1 = data + n1;
		/*
		 * We don't need to BOUNDS_CHECK() cp here because we've
		 * previously checked that 'dlen' bytes are in bounds, and
		 * we know that n < dlen.
		 */
		n2 = dlen - n;
		/*
		 * The first bit of the first octet determines the format
		 * of the NXT record.  A format for types >= 128 has not
		 * yet been defined, so if bit zero is set, we just copy
		 * what's there because we don't understand it.
		 */
		if ((*cp & 0x80) == 0) {
			/*
			 * Bit zero is not set; this is an ordinary NXT
			 * record.  The bitmap must be at least 4 octets
			 * because the NXT bit should be set.  It should be
			 * less than or equal to 16 octets because this NXT
			 * format is only defined for types < 128.
			 */
			if (n2 < 4 || n2 > 16) {
				hp->rcode = FORMERR;
				return (-1);
			}
		}
		if (n2 > (int)(sizeof data - n1)) {
			hp->rcode = FORMERR;
			return (-1);
		}
		memcpy(cp1, cp, n2);
		cp += n2;
		cp1 += n2;

		/* compute size of data */
		n = cp1 - (u_char *)data;
		cp1 = (u_char *)data;
		break;
	
	default:
		/* treat as opaque data */
		ns_debug(ns_log_default, 3, "unknown type %d", type);
		cp1 = cp;
		n = dlen;
		cp += n;
	}

	if (cp > eom) {
		hp->rcode = FORMERR;
		return (-1);
	}
	if ((u_int)(cp - rdatap) != dlen) {
		ns_debug(ns_log_default, 3,
		     "encoded rdata length is %u, but actual length was %u",
			 dlen, (u_int)(cp - rdatap));
		hp->rcode = FORMERR;
		return (-1);
	}
	if (n > MAXDATA) {
		ns_debug(ns_log_default, 1,
			 "update type %d: %d bytes is too much data",
			 type, n);
		hp->rcode = FORMERR;
		return (-1);
	}

	ttl += tt.tv_sec;
	if (type == ns_t_opt)
		class = 0;	/* Lie. */
	*dpp = savedata(class, type, ttl, cp1, n);
	return (cp - rrp);
}

int
send_msg(u_char *msg, int msglen, struct qinfo *qp) {
	HEADER *hp = (HEADER *) msg;
	u_char *oldmsg;
	int oldlen = 0;
	int msgsize;
	int ret;
	int trunc;
	int adjust = 0;

	if (qp->q_flags & Q_SYSTEM)
		return (1);

	trunc = (qp->q_stream != NULL) ? NS_MAXMSG : qp->q_udpsize;
	if (qp->q_tsig != NULL) 
		adjust +=  qp->q_tsig->tsig_size;
	if ((qp->q_flags & Q_EDNS) != 0)
		adjust += 11;
	if (msglen > trunc - adjust)
		msglen = trunc_adjust(msg, msglen, trunc - adjust);

	if (ns_wouldlog(ns_log_default, 1)) {
		ns_debug(ns_log_default, 1, "send_msg -> %s (%s %d) id=%d",
			 sin_ntoa(qp->q_from), 
			 qp->q_stream == NULL ? "UDP" : "TCP",
			 qp->q_stream == NULL ? qp->q_dfd : qp->q_stream->s_rfd,
			 ntohs(qp->q_id));
	}
#ifdef DEBUG
	if (ns_wouldlog(ns_log_default, 4)) {
		struct qinfo *tqp;

		for (tqp = nsqhead; tqp != NULL; tqp = tqp->q_link) {
			ns_debug(ns_log_default, 4,
				 "qp %#lx q_id: %d  q_nsid: %d q_msglen: %d",
				 (u_long)tqp, tqp->q_id,
				 tqp->q_nsid, tqp->q_msglen);
			ns_debug(ns_log_default, 4,
				 "\tq_naddr: %d q_curaddr: %d",
				 tqp->q_naddr, tqp->q_curaddr);
			ns_debug(ns_log_default, 4,
				 "\tq_next: %#lx q_link: %#lx",
				 (u_long)qp->q_next, (u_long)qp->q_link);
		}
	}
#endif /* DEBUG */

	if (adjust != 0) {
		oldmsg = msg;
		oldlen = msglen;
		msgsize = msglen + adjust;
		msg = memget(msgsize);
		memcpy(msg, oldmsg, oldlen);
	} else
		msgsize = msglen;	/* silence compiler */

	if ((qp->q_flags & Q_EDNS) != 0)
		msglen += ns_add_opt(msg, msg + msglen, msgsize, 0, hp->rcode,
				     server_options->edns_udp_size,
				     0, NULL, 0);
	
	if (qp->q_tsig != NULL) {
		u_char sig[TSIG_SIG_SIZE];
		int siglen = sizeof(sig);

		ret = ns_sign(msg, &msglen, msgsize, NOERROR, qp->q_tsig->key,
			      qp->q_tsig->sig, qp->q_tsig->siglen,
			      sig, &siglen, 0);

		if (ret != 0) {
			INSIST(0);
		}
	}

#ifdef DEBUG
	if (debug >= 6)
		res_pquery(&res, msg, msglen, log_get_stream(packet_channel));
#endif /* DEBUG */
	
	if (qp->q_stream == NULL) {
		/*
		 * Don't send FORMERR to certian well known ports.
		 */
		if (hp->rcode == FORMERR &&
		    drop_port(ntohs(qp->q_from.sin_port)))
				return (-1);
		if (sendto(qp->q_dfd, (char*)msg, msglen, 0,
			   (struct sockaddr *)&qp->q_from,
			   sizeof(qp->q_from)) < 0) {
			if (!haveComplained(ina_ulong(qp->q_from.sin_addr),
					    (u_long)sendtoStr))
#if defined(SPURIOUS_ECONNREFUSED)
                           if (errno != ECONNREFUSED)
#endif
				ns_info(ns_log_default,
					"send_msg: sendto(%s): %s",
					sin_ntoa(qp->q_from),
					strerror(errno));
			nameserIncr(qp->q_from.sin_addr, nssSendtoErr);
			return (1);
		}
	} else
		writestream(qp->q_stream, (u_char*)msg, msglen);

	if (adjust != 0)
		memput(msg, oldlen + adjust);

	return (0);
}

static int
root_server_p(ns_class class) {
	struct zoneinfo *zp = find_zone("", class);

	return (zp != NULL &&
		(zp->z_type == z_master || zp->z_type == z_slave));
}

void
prime_cache(void) {
	int root = root_server_p(ns_c_in);

	ns_debug(ns_log_default, 1, "prime_cache: priming = %d, root = %d",
		 priming, root);
	if (!priming && !root) {
		struct qinfo *qp = sysquery("", ns_c_in, ns_t_ns,
					    NULL, NULL, 0, ns_port,
					    ns_o_query, 0);

		if (qp != NULL) {
			qp->q_flags |= (Q_SYSTEM | Q_PRIMING);
			priming++;
		}
	}
	needs_prime_cache = 0;
}

struct qinfo *
sysquery(const char *dname, int class, int type,
	 struct in_addr *nss, struct dst_key **keys, int nsc,
	 u_int16_t port, int opcode, int distance)
{
	struct qinfo *qp, *oqp;
	HEADER *hp;
	char tmpdomain[MAXDNAME];
	struct namebuf *np = NULL;
	struct databuf *nsp[NSMAX];
	struct hashbuf *htp1;
	struct hashbuf *htp2;
	struct hashbuf *htp3;
	struct sockaddr_in *nsa;
	const char *fname;
	int n, count;
	int sendto_errno = 0;
	u_char *oldqbuf = NULL;
	int oldqlen = 0, has_tsig;
	u_char *smsg = NULL;
	int smsglen, smsgsize = 0, siglen;
	u_char sig[TSIG_SIG_SIZE];
	DST_KEY *key;

	nsp[0] = NULL;
	ns_debug(ns_log_default, 3, "sysquery(%s, %d, %d, %p, %p, %d, %d)",
		 dname, class, type, nss, keys, nsc, ntohs(port));
	qp = qnew(dname, class, type, (nss != NULL && nsc != 0) ? 0 : 1);

	qp->q_distance = distance;

	if (nss != NULL && nsc != 0)
		np = NULL;
	else if (!NS_ZOPTION_P(qp->q_fzone, OPTION_FORWARD_ONLY)) {
		htp1 = hashtab;
		htp2 = hashtab;
		htp3 = fcachetab;
		if (priming && dname[0] == '\0') {
			np = NULL;
		} else if (((np = nlookup(dname, &htp1, &fname, 0)) == NULL) &&
			   ((np = nlookup("", &htp2, &fname, 0)) == NULL) &&
			   ((np = nlookup("", &htp3, &fname, 0)) == NULL)) {
			ns_info(ns_log_default,
				"sysquery: nlookup error on %s?",
				dname);
 err1:
			ns_freeqry(qp);
			return (NULL);
		}

		n = findns(&np, class, nsp, &count, 0);
		switch (n) {
		case NXDOMAIN:
		case SERVFAIL:
			ns_info(ns_log_default,
				"sysquery: findns error (%s) on %s?",
				n == NXDOMAIN ? "NXDOMAIN" : "SERVFAIL",
				dname);
 err2:
			free_nsp(nsp);
			goto err1;
		}
	}

	/* Build new qinfo struct. */
	qp->q_cmsg = qp->q_msg = NULL;
	qp->q_dfd = ds;
	if (nss == NULL || nsc == 0)
		nsfwdadd(qp, NS_ZFWDTAB(qp->q_fzone));
	qp->q_expire = tt.tv_sec + RETRY_TIMEOUT*2;
	qp->q_flags |= Q_SYSTEM;

	getname(np, tmpdomain, sizeof tmpdomain);
	qp->q_domain = savestr(tmpdomain, 1);

	if ((qp->q_msg = (u_char *)memget(PACKETSZ)) == NULL) {
		ns_notice(ns_log_default, "sysquery: memget failed");
		goto err2;
	}
	qp->q_msgsize = PACKETSZ;
	n = res_nmkquery(&res, opcode, dname, class,
			 type, NULL, 0, NULL,
			 qp->q_msg, PACKETSZ);
	if (n < 0) {
		ns_info(ns_log_default,
			"sysquery: res_mkquery(%s) failed", dname);
		goto err2;
	}
	qp->q_msglen = n;
	hp = (HEADER *) qp->q_msg;
	hp->id = qp->q_nsid = htons(nsid_next());
	hp->rd = (qp->q_addr[qp->q_curaddr].forwarder ? 1 : 0);
	hp->aa = (opcode == NS_NOTIFY_OP);

	/* First check for an already pending query for this data. */
	for (oqp = nsqhead; oqp != NULL; oqp = oqp->q_link) {
		if ((oqp != qp)
		    && (oqp->q_msglen == qp->q_msglen)
		    && memcmp(oqp->q_msg+2, qp->q_msg + 2,
			      qp->q_msglen - 2) == 0
		    ) {
#ifdef BIND_NOTIFY
			/* XXX - need fancier test to suppress duplicate
			 *       NOTIFYs to the same server (compare nss?)
			 */
			if (opcode != NS_NOTIFY_OP)
#endif /*BIND_NOTIFY*/
			{
			    ns_debug(ns_log_default, 3,
				     "sysquery: duplicate");
			    goto err2;
			}
		}
	}

	if (nss != NULL && nsc != 0) {
		int i;
		struct qserv *qs;

		for (i = 0, qs = qp->q_addr; i < nsc; i++, qs++) {
			qs->ns_addr.sin_family = AF_INET;
			qs->ns_addr.sin_addr = nss[i];
			qs->ns_addr.sin_port = port;
			if  (keys != NULL)
				qp->q_keys[i] = keys[i];
			qs->ns = NULL;
			qs->nsdata = NULL;
			qs->stime = tt;
			qs->forwarder = 0;
			qs->noedns = 1;		/* XXXMPA */
			qs->lame = 0;
			qs->nretry = 0;
		}
		qp->q_naddr = nsc;
	} else if (!NS_ZOPTION_P(qp->q_fzone, OPTION_FORWARD_ONLY)) {
 fetch_a:
		count = nslookup(nsp, qp, dname, "sysquery");
		if (count <= 0) {
			if (count < 0) {
				if (n == -1)
					ns_info(ns_log_default,
				      "sysquery: nslookup reports danger (%s)",
						dname);
				goto err2;
			} else if (np && NAME(*np)[0] == '\0') {
				/*
				 * It's not too serious if we don't have
				 * the root server addresses if we have to
				 * go through a forwarder anyway.  Don't
				 * bother to log it, since prime_cache()
				 * won't do anything about it as currently
				 * implemented.
				 *
				 * XXX - should we skip setting
				 *       needs_prime_cache as well?
				 *
				 * XXX - what happens when we implement
				 *       selective forwarding?
				 */
				if (!NS_OPTION_P(OPTION_FORWARD_ONLY))
					ns_warning(ns_log_default,
				   "sysquery: no addrs found for root NS (%s)",
						   dname);
				if (class == C_IN && !priming)
					needs_prime_cache = 1;
				goto err2;
			}
			if (np) {
				free_nsp(nsp);
				nsp[0] = NULL;
				np = np_parent(np);
				n = findns(&np, class, nsp, &count, 0);
				switch (n) {
				case NXDOMAIN: /*FALLTHROUGH*/
				case SERVFAIL:
					ns_info(ns_log_default,
					  "sysquery: findns error (%d) on %s?",
						n, dname);
					goto err2;
				}
				getname(np, tmpdomain, sizeof tmpdomain);
				if (qp->q_domain != NULL)
					(void)freestr(qp->q_domain);
				qp->q_domain = savestr(tmpdomain, 1);
				goto fetch_a;
			}
			goto err2;
		}
	}

	schedretry(qp, retrytime(qp));
	qp->q_addr[0].stime = tt;	/* XXX - why not every? */
	nsa = Q_NEXTADDR(qp, 0);

	if (ns_wouldlog(ns_log_default, 1)) {
		ns_debug(ns_log_default, 1,
			 "sysquery: send -> %s dfd=%d nsid=%d id=%d retry=%ld",
			 sin_ntoa(*nsa), qp->q_dfd, 
			 ntohs(qp->q_nsid), ntohs(qp->q_id),
			 (long)qp->q_time);
	}
#ifdef DEBUG
	if (debug >= 10)
		res_pquery(&res, qp->q_msg, qp->q_msglen,
			    log_get_stream(packet_channel));
#endif

	key = qp->q_keys[0];
	if (key == NULL)
		key = qp->q_keys[0] = tsig_key_from_addr(nsa->sin_addr);
	if (key != NULL || !qp->q_addr[0].noedns) {
		smsgsize = qp->q_msglen + TSIG_BUF_SIZE + 11;
		smsg = memget(smsgsize);
		smsglen = qp->q_msglen;
		siglen = sizeof(sig);
		memcpy(smsg, qp->q_msg, qp->q_msglen);
	}
	
	if (!qp->q_addr[0].noedns)
                smsglen += ns_add_opt(smsg, smsg + smsglen, smsgsize, 0, 0,
                                      server_options->edns_udp_size,
				      0, NULL, 0);

	if (key != NULL) {
		n = ns_sign(smsg, &smsglen, smsgsize, NOERROR, key, NULL, 0,
			    sig, &siglen, 0);
		if (n == 0) {
			has_tsig = 1;
			free_tsig(qp->q_nstsig);
			qp->q_nstsig = new_tsig(key, sig, siglen);
		} else {
			INSIST(0);
			has_tsig = 0;
			free_tsig(qp->q_nstsig);
			qp->q_nstsig = NULL;
		}
	} else {
		has_tsig = 0;
		free_tsig(qp->q_nstsig);
		qp->q_nstsig = NULL;
	}

	if (smsgsize != 0) {
		oldqbuf = qp->q_msg;
		oldqlen = qp->q_msglen;
		qp->q_msglen = smsglen;
		qp->q_msg = smsg;
	}

	if (sendto(qp->q_dfd, (char*)qp->q_msg, qp->q_msglen, 0,
		   (struct sockaddr *)nsa,
		   sizeof(struct sockaddr_in)) < 0) {
		sendto_errno = errno;
		if (!haveComplained(ina_ulong(nsa->sin_addr),
				    (u_long)sendtoStr))
			ns_info(ns_log_default, "sysquery: sendto(%s): %s",
				sin_ntoa(*nsa), strerror(errno));
		nameserIncr(nsa->sin_addr, nssSendtoErr);
	}

	if (smsgsize != 0) {
		memput(smsg, smsgsize);
		qp->q_msg = oldqbuf;
		qp->q_msglen = oldqlen;
	}

	nameserIncr(nsa->sin_addr, nssSentSysQ);
	free_nsp(nsp);
	switch (sendto_errno) {
	case ENETDOWN:
	case ENETUNREACH:
	case EHOSTDOWN:
	case EHOSTUNREACH:
		unsched(qp);
		schedretry(qp, (time_t) 0);
	}
	return (qp);
}

/*
 * Check the list of root servers after receiving a response
 * to a query for the root servers.
 */
static int
check_root() {
	struct databuf *dp, *pdp;
	struct namebuf *np;
	int count = 0;

	priming = 0;
	for (np = hashtab->h_tab[0]; np != NULL; np = np->n_next)
		if (NAME(*np)[0] == '\0')
			break;
	if (np == NULL) {
		ns_notice(ns_log_default, "check_root: Can't find root!");
		return (0);
	}
	for (dp = np->n_data; dp != NULL; dp = dp->d_next)
		if (dp->d_type == T_NS)
			count++;
	ns_debug(ns_log_default, 1, "%d root servers", count);
	if (count < server_options->minroots) {
		ns_notice(ns_log_default,
		"check_root: %d root servers after query to root server < min",
			  count);
		return (0);
	}
	pdp = NULL;
	dp = np->n_data;
	while (dp != NULL) {
		if (dp->d_type == T_NS && dp->d_zone == DB_Z_CACHE &&
		    dp->d_ttl < (u_int32_t)tt.tv_sec) {
			ns_debug(ns_log_default, 1,
				 "deleting old root server '%s'",
				 dp->d_data);
			dp = rm_datum(dp, np, pdp, NULL);
			/* SHOULD DELETE FROM HINTS ALSO */
			continue;
		}
		pdp = dp;
		dp = dp->d_next;
	}
	if (check_ns())
		return (1);
	else {
		priming = 1;
		return (0);
	}
}

/* 
 * Check the root to make sure that for each NS record we have a A RR
 */
static int
check_ns() {
	struct databuf *dp, *tdp;
	struct namebuf *np, *tnp;
	struct hashbuf *htp;
	char *dname;
	int found_arr;
	const char *fname;
	time_t curtime;
	int servers = 0, rrsets = 0;

	ns_debug(ns_log_default, 2, "check_ns()");

	curtime = (u_int32_t) tt.tv_sec;
	for (np = hashtab->h_tab[0]; np != NULL; np = np->n_next) {
		if (NAME(*np)[0] != '\0')
			continue;
		for (dp = np->n_data; dp != NULL; dp = dp->d_next) {
			int cnames = 0;

			if (dp->d_rcode)
				continue;

			if (dp->d_type != T_NS)
				continue;

			servers++;

	        	/* look for A records */
			dname = (caddr_t) dp->d_data;
			htp = hashtab;
			tnp = nlookup(dname, &htp, &fname, 0);
			if (tnp == NULL || fname != dname) {
				ns_debug(ns_log_default, 3,
					 "check_ns: %s: not found %s %#lx",
					 dname, fname, (u_long)tnp);
				sysquery(dname, dp->d_class, T_A, NULL, NULL,
					 0, ns_port, QUERY, 0);
				continue;
			}
			/* look for name server addresses */
			found_arr = 0;
			(void)delete_stale(tnp);
			for (tdp = tnp->n_data;
			     tdp != NULL;
			     tdp = tdp->d_next) {
				if (tdp->d_rcode)
					continue;
				if (tdp->d_type == T_CNAME)
					cnames++;
				if (tdp->d_type != T_A ||
				    tdp->d_class != dp->d_class)
					continue;
				if ((tdp->d_zone == DB_Z_CACHE) &&
				    (tdp->d_ttl < (u_int32_t)curtime)) {
					ns_debug(ns_log_default, 3, 
						 "check_ns: stale entry '%s'",
						 NAME(*tnp));
					found_arr = 0;
					break;
				}
				found_arr++;
			}
			if (found_arr)
				rrsets++;
			else if (cnames > 0)
				ns_info(ns_log_default,
					"Root NS %s -> CNAME %s",
					NAME(*np), NAME(*tnp));
			else
				sysquery(dname, dp->d_class, T_A, NULL, NULL,
					 0, ns_port, QUERY, 0);
	        }
	}

	ns_debug(ns_log_default, 2, "check_ns: %d %d", servers, rrsets);
	return ((servers <= 2)
		? (rrsets == servers)
		: ((rrsets * 2) >= servers)
		);
}

/* int findns(npp, class, nsp, countp, flag)
 *	Find NS's or an SOA
 * npp, class:
 *	dname whose most enclosing NS is wanted
 * nsp, countp:
 *	result array and count; array will also be NULL terminated
 * flag:
 *	boolean: we're being called from ADDAUTH, bypass authority checks
 * return value:
 *	NXDOMAIN: we are authoritative for this {dname,class}
 *		  *countp is bogus, but nsp[] has a single SOA returned in it.
 *	SERVFAIL: we are auth but zone isn't loaded; or, no root servers found
 *		  *countp and nsp[] are bogus.
 *	OK: we are not authoritative, and here are the NS records we found.
 *		  *countp and nsp[] return NS records of interest.
 */
int
findns(struct namebuf **npp, int class,
       struct databuf **nsp, int *countp, int flag)
{
	struct namebuf *np = *npp;
	struct databuf *dp;
	struct	databuf **nspp;
	struct hashbuf *htp;
	
	nsp[0] = NULL;

	if (priming && (np == NULL || NAME(*np)[0] == '\0'))
		htp = fcachetab;
	else
		htp = hashtab;

 try_again:
	if (htp == fcachetab && class == C_IN && !priming)
		/*
		 * XXX - do we want to set needs_prime_cache if
		 *       OPTION_FORWARD_ONLY?
		 */
		needs_prime_cache = 1;
	if (np == NULL) {
		/* find the root */
		for (np = htp->h_tab[0]; np != NULL; np = np->n_next)
			if (NAME(*np)[0] == '\0')
				break;
	}
	while (np != NULL) {
		ns_debug(ns_log_default, 5, "findns: np %p '%s'", np,
			 NAME(*np));
		/* Look first for SOA records. */
#ifdef ADDAUTH
		if (!flag)
#endif
		for (dp = np->n_data; dp != NULL; dp = dp->d_next) {
			if (dp->d_zone != DB_Z_CACHE &&
			    ((zones[dp->d_zone].z_type == Z_PRIMARY) ||
			     (zones[dp->d_zone].z_type == Z_SECONDARY)) &&
			    match(dp, class, T_SOA) && dp->d_type == T_SOA) {
				ns_debug(ns_log_default, 3,
					 "findns: SOA found");
				if (zones[dp->d_zone].z_flags & Z_AUTH) {
					*npp = np;
					nsp[0] = dp;
					nsp[1] = NULL;
					DRCNTINC(dp);
					return (NXDOMAIN);
				} else {
					/* XXX:	zone isn't loaded but we're
					 *	primary or slave for it.
					 *	should we fwd this?
					 */
					return (SERVFAIL);
				}
			}
		}

		/* If no SOA records, look for NS records. */
		nspp = &nsp[0];
		*nspp = NULL;
		(void)delete_stale(np);
		for (dp = np->n_data; dp != NULL; dp = dp->d_next) {
			if (!match(dp, class, T_NS))
				continue;
			if (dp->d_rcode)
				continue;
			/*
			 * Don't use records that may become invalid to
			 * reference later when we do the rtt computation.
			 * Never delete our safety-belt information!
			 *
			 * XXX:	this is horribly bogus.
			 */
			if ((dp->d_zone == DB_Z_CACHE) &&
			    (dp->d_ttl < (u_int32_t)tt.tv_sec) &&
			    !(dp->d_flags & DB_F_HINT)) {
				ns_debug(ns_log_default, 1,
					 "findns: stale entry '%s'",
					 NAME(*np));
				/*
				 * We may have already added NS databufs
				 * and are going to throw them away. Fix
				 * reference counts. We don't need to free
				 * them here as we just got them from the
				 * cache.
				 */
				while (nspp > &nsp[0])
					db_detach(--nspp);
				nsp[0] = NULL;
				goto try_parent;
			}
			if (nspp < &nsp[NSMAX-1]) {
				*nspp++ = dp;
				DRCNTINC(dp);
			}
		}

		*countp = nspp - nsp;
		if (*countp > 0) {
			ns_debug(ns_log_default, 3,
				 "findns: %d NS's added for '%s'",
				 *countp, NAME(*np));
			*nspp = NULL;
			*npp = np;
			return (OK);	/* Success, got some NS's */
		}
 try_parent:
		np = np_parent(np);
	}
	if (htp == hashtab) {
		htp = fcachetab;
		goto try_again;
	}
	ns_debug(ns_log_default, 1,
		 "findns: No root nameservers for class %s?", p_class(class));
	if (!NS_OPTION_P(OPTION_FORWARD_ONLY) &&
	    (unsigned)class < MAXCLASS && norootlogged[class] == 0) {
		norootlogged[class] = 1;
		ns_info(ns_log_default, "No root nameservers for class %s",
			p_class(class));
	}
	return (SERVFAIL);
}


/*
 * Extract RR's from the given node that match class and type.
 * Return number of bytes added to response.
 * If no matching data is found, then 0 is returned.
 */
int
finddata(struct namebuf *np, int class, int type,
	 HEADER *hp, char **dnamep, int *lenp, int *countp, int pass,
	 int glueok)
{
	struct databuf *dp;
	char *cp;
	int buflen, n, count = 0;
	char *new_dnamep = NULL;
 	int defer = 0, found_count = 0, choice, i;
 	struct databuf **found = NULL;
	struct databuf **tmpfound = NULL;
	int foundcname;
	int stalecount;
	int ret = 0;

	stalecount = delete_stale(np);

	/* We don't want to return cached SIG records when asked for SIGs,
	 * since we may have an incomplete set.
	 */
	if (type == T_SIG && findMyZone(np, class) == DB_Z_CACHE)
		return(0);

	if (type != T_ANY && type != T_PTR && type != T_NXT) {
		found = memget((stalecount + 1) * sizeof *found);
		tmpfound = memget((stalecount + 1) * sizeof *tmpfound);
		if (found == NULL || tmpfound == NULL)
			ns_panic(ns_log_default, 1, "finddata: out of memory");
		defer = 1;
	}

	buflen = *lenp;
	
#ifdef DEBUG
	if (buflen > PACKETSZ)
		ns_debug(ns_log_default, 1, "finddata(): buflen=%d", buflen);
#endif
	cp = ((char *)hp) + *countp;
	foundcname = 0;
	for (dp = np->n_data; dp != NULL; dp = dp->d_next) {
		if (!wanted(dp, class, type))
			continue;
		if (dp->d_cred == DB_C_ADDITIONAL) {
#ifdef NOADDITIONAL
			continue;
#else
			/* we want to expire additional data very
			 * quickly.  current strategy is to cut 5%
			 * off each time it is accessed.  this makes
			 * stale(dp) true earlier when this datum is
			 * used often.
			 */
			dp->d_ttl = tt.tv_sec
					+
				0.95 * (int) (dp->d_ttl - tt.tv_sec);
#endif
		}
		/* -ve $ing stuff, anant@isi.edu
		 * if we have a -ve $ed record, change the rcode on the
		 * header to reflect that
		 */
		if (dp->d_rcode == NOERROR_NODATA) {
			if (count != 0) {
				/*
				 * This should not happen, yet it does...
				 */
				ns_info(ns_log_default,
				   "NODATA & data for \"%s\" type %d class %d",
					*dnamep, type, class);
				continue;
			}
			if (type == T_ANY && dp->d_type != T_ANY)
				continue;
			hp->rcode = NOERROR_NODATA;
			if (dp->d_size == 0) { /* !RETURNSOA */
				ret = 1;
				goto done;
			}
		}
		if (dp->d_rcode == NXDOMAIN) {
			if (count != 0) {
				/*
				 * This should not happen, yet it might...
				 */
				ns_info(ns_log_default,
			  "NXDOMAIN & data for \"%s\" type %d class %d",
					*dnamep, type, class);
				continue;
			}
			hp->rcode = NXDOMAIN;
			if (dp->d_size == 0) { /* !RETURNSOA */	
				ret = 1;
				goto done;
			}
		}
#ifdef HITCOUNTS
		++dp->d_hitcnt;
		++db_total_hits;
#endif /* HITCOUNTS */

		/* Don't put anything but key or sig RR's in response to
			     requests for key or sig */
		if (((type == T_SIG) || (type == T_KEY)) &&
		    (!((dp->d_type == T_SIG) || (dp->d_type == T_KEY))) )
			continue;

		/* Don't return glue (NS/A/AAAA) */
		if (!glueok && findMyZone(np, class) == DB_Z_CACHE)
			continue;

		if (!defer) {
			if (foundcname != 0 && dp->d_type == T_CNAME)
				continue;

			if ((n = make_rr(*dnamep, dp, (u_char *)cp, buflen, 1,
					 dnptrs, dnptrs_end, 0)) < 0) {
				hp->tc = 1;
				ret = *lenp - buflen;
				goto done;
			}
			if (dp->d_secure != DB_S_SECURE)
				hp->ad = 0;
			cp += n;
			buflen -= n;
			count++;
		
			if (dp->d_type == T_CNAME) {
				foundcname = 1;

#define SETAA(pass, class, dp) \
	(pass == 1 && class != C_ANY && dp->d_zone != DB_Z_CACHE && \
	(zones[dp->d_zone].z_type == z_master || \
	 zones[dp->d_zone].z_type == z_slave) && \
	(zones[dp->d_zone].z_flags & Z_AUTH) != 0)

				if (SETAA(pass, class, dp))
					hp->aa = 1;

#define FOLLOWCNAME(type) \
	(type != T_KEY) && (type != T_SIG) && (type != T_NXT) && (type != T_ANY)
			/* don't alias if querying for key, sig, nxt, or any */

				if (FOLLOWCNAME(type))
					new_dnamep = (char *)dp->d_data;
			}
		} else {
			if (dp->d_type == T_CNAME) {
				foundcname = 1;
				
				if (SETAA(pass, class, dp))
					hp->aa = 1;

			}
			found[found_count++] = dp;
		}
	}

	if (found_count == 0 && count == 0) {
		ret = 0;
		goto done;
	}

	/*
	 * If the query type was SIG or ANY we will have returned the SIG
	 * records already.
	 */
	if (type != T_SIG && type != T_ANY) {
		for (dp = np->n_data; dp != NULL; dp = dp->d_next) {
			if (!wantedsig(dp, class, type))
				continue;
			if (dp->d_cred == DB_C_ADDITIONAL) {
#ifdef NOADDITIONAL
				continue;
#else
				/* we want to expire additional data very
				 * quickly.  current strategy is to cut 5%
				 * off each time it is accessed.  this makes
				 * stale(dp) true earlier when this datum is
				 * used often.
				 */
				dp->d_ttl = tt.tv_sec
						+
					0.95 * (int) (dp->d_ttl - tt.tv_sec);
#endif
			}
			if (!defer) {
				if ((n = make_rr(*dnamep, dp, (u_char *)cp,
						 buflen, 1, dnptrs, dnptrs_end,
						 0)) < 0) {
					hp->tc = 1;
					ret = *lenp - buflen;
					goto done;
				}
				if (dp->d_secure != DB_S_SECURE)
					hp->ad = 0;
				cp += n;
				buflen -= n;
				count++;
			} else
				found[found_count++] = dp;
		}
	}

	if (defer && found_count > 0) {
		int first_sig;
		int non_sig_count;
		int sig_count;		/* number of SIG records in found */
		int idx, jdx;
		enum ordering order;

		order = match_order(np, class, foundcname ? T_CNAME : type);

		/*
		 * shuffle the SIG records down to the bottom of the array
		 * as we need to make sure they get packed last, no matter
		 * what the ordering is. We're sure to maintain the
		 * original ordering within the two sets of records (so
		 * that fixed_order can work).
		 * First we pack the non-SIG records into the temp array.
		 */
		for (idx = jdx = 0 ; idx < found_count ; idx++) {
			if (found[idx]->d_type != T_SIG) {
				tmpfound[jdx++] = found[idx];
			}
		}
		non_sig_count = jdx;
		sig_count = found_count - jdx;
		first_sig = jdx ;
		
		/*
		 * now shift the SIG records down to the end of the array
		 *  and copy in the non-SIG records
		 */
		for (i = idx = found_count - 1 ; i >= 0 ; idx--) {
			if (i < non_sig_count) {
				found[i] = tmpfound[i];
				i--;
			} else if (found[idx]->d_type == T_SIG) {
				found[i--] = found[idx] ;
			}
		}

		foundcname = 0;
		switch (order) {
		case fixed_order:
			for (i = 0; i < found_count; i++) {
				dp = found[i];
				if (foundcname != 0 && dp->d_type == T_CNAME)
					continue;
				if (dp->d_type == T_CNAME) {
					foundcname = 1;
					if (FOLLOWCNAME(type)) {
						new_dnamep = (char *)dp->d_data;
					}
				}
				if ((n = make_rr(*dnamep, dp, (u_char *)cp,
						 buflen, 1,
						 dnptrs, dnptrs_end, 0)) < 0) {
					hp->tc = 1;
					ret = *lenp - buflen;
					goto done;
				}
				if (dp->d_secure != DB_S_SECURE)
					hp->ad = 0;
				cp += n;
				buflen -= n;
				count++;
			}
			break;

		case random_order: {
			/* first we shuffle the non-SIG records */
			int iters = non_sig_count;
			for (i = 0; i < iters; i++) {
				choice = ((u_int)rand()>>3) % non_sig_count;
				non_sig_count--;
				dp = found[choice];
				found[choice] = found[non_sig_count];
				if (foundcname != 0 && dp->d_type == T_CNAME)
					continue;
				if (dp->d_type == T_CNAME) {
					foundcname = 1;
					if (FOLLOWCNAME(type)) {
						new_dnamep = (char *)dp->d_data;
					}
				}
				if ((n = make_rr(*dnamep, dp, (u_char *)cp,
						 buflen, 1,
						 dnptrs, dnptrs_end, 0)) < 0) {
					hp->tc = 1;
					ret = *lenp - buflen;
					goto done;
				}
				if (dp->d_secure != DB_S_SECURE)
					hp->ad = 0;
				cp += n;
				buflen -= n;
				count++;
			}

			/* now shuffle the SIG records */
			iters = sig_count;
			for (i = 0; i < iters; i++) {
				choice = ((u_int)rand()>>3) % sig_count;
				choice += first_sig;
				sig_count--;
				dp = found[choice];
				found[choice] = found[sig_count + first_sig];
				if ((n = make_rr(*dnamep, dp, (u_char *)cp,
						 buflen, 1,
						 dnptrs, dnptrs_end, 0)) < 0) {
					hp->tc = 1;
					ret = *lenp - buflen;
					goto done;
				}
				if (dp->d_secure != DB_S_SECURE)
					hp->ad = 0;
				cp += n;
				buflen -= n;
				count++;
			}
			break;
		}

		case cyclic_order:
			/* first we do the non-SIG records */
			if (non_sig_count > 0)
				choice = ((u_int)rand()>>3) % non_sig_count;
			else
				choice = 0;
			for (i = 0; i < non_sig_count ; i++) {
				dp = found[(i + choice) % non_sig_count];
				if (foundcname != 0 && dp->d_type == T_CNAME)
					continue;
				if (dp->d_type == T_CNAME) {
					foundcname = 1;
					if (FOLLOWCNAME(type)) {
						new_dnamep = (char *)dp->d_data;
					}
				}
				if ((n = make_rr(*dnamep, dp, (u_char *)cp,
						 buflen, 1,
						 dnptrs, dnptrs_end, 0)) < 0) {
					hp->tc = 1;
					ret = *lenp - buflen;
					goto done;
				}
				if (dp->d_secure != DB_S_SECURE)
					hp->ad = 0;
				cp += n;
				buflen -= n;
				count++;
			}

			/* now do the SIG record rotation. */
			if (sig_count > 0) {
				choice = ((u_int)rand()>>3) % sig_count;
				choice += first_sig;
				i = choice;
				do {
					dp = found[i];
					if ((n = make_rr(*dnamep, dp,
							 (u_char *)cp,
							 buflen, 1,
							 dnptrs,
							 dnptrs_end, 0)) < 0) {
						hp->tc = 1;
						ret = *lenp - buflen;
						goto done;
					}
					if (dp->d_secure != DB_S_SECURE)
						hp->ad = 0;
					cp += n;
					buflen -= n;
					count++;
					i++;
					if (i >= found_count)
						i = first_sig;
				} while (i != choice);
			}
			
			break;

		default:
			ns_warning(ns_log_default, "finddata: unknown ordering: %d",
				   order);
			break;
		}
	}
	
	if (new_dnamep != NULL)
		*dnamep = new_dnamep;

	ns_debug(ns_log_default, 3, "finddata: added %d class %d type %d RRs",
		 count, class, type);
	ret = *lenp - buflen;
 done:
	if (found != NULL)
		memput(found, (stalecount + 1) * sizeof *found);
	if (tmpfound != NULL)
		memput(tmpfound, (stalecount + 1) * sizeof *tmpfound);
	*countp = count;
	return (ret);
}

/*
 * Do we want this data record based on the class and type?
 */
static int
wanted(const struct databuf *dp, int class, int type) {
	const u_char *cp;
	int coveredType;
	time_t expiration;
#ifdef DEBUG
	char pclass[15], ptype[15];
#endif

#ifdef DEBUG
	strcpy(pclass, p_class(class));
	strcpy(ptype, p_type(type));
	ns_debug(ns_log_default, 3, "wanted(%p, %s %s) [%s %s]",
		 dp, pclass, ptype,
		 p_class(dp->d_class), p_type(dp->d_type));
#endif

	if (dp->d_class != class && class != C_ANY)
		return (0);
	/*
	 * Must check SIG for expiration below, other matches
	 * return OK here.
	 */
	if (type == dp->d_type && (type != T_SIG))
		return (1);
	/* For a T_ANY query, we do not want to return -ve $ed RRs. */
	if (type == T_ANY && dp->d_rcode == NOERROR_NODATA)
		return (0);

	/* First, look at the type of RR.  */
	switch (dp->d_type) {

		/* Cases to deal with:
			T_ANY search, return all unexpired SIGs.
			T_SIG search, return all unexpired SIGs.
			T_<foo> search, return all unexp SIG <FOO>s.
		 */
	case T_SIG:
		cp = dp->d_data;
		GETSHORT(coveredType, cp);
		cp += INT16SZ + INT32SZ; /* skip alg, labels, & orig TTL */
		GETLONG(expiration,cp);

		if (type == T_ANY || type == T_SIG) {
			if (expiration > time(0))
				return (1);	/* Unexpired matching SIG */
		}
		return (0);		/* We don't return this SIG. */

	case T_ANY:
		return (1);
	case T_CNAME:
		if (dp->d_rcode != NOERROR_NODATA)
			return (1);
		else
			break;
	}
	/* OK, now look at the type of query.  */
	if (type == ns_t_any)
		return (1);
	else if (type == ns_t_mailb)
		switch (dp->d_type) {
		case T_MR:
		case T_MB:
		case T_MG:
		case T_MINFO:
			return (1);
		}
	else if (ns_t_xfr_p(type)) {
		/*
		 * This is used to validate transfer requests, not
		 * generate transfer responses.  Is there an SOA?
		 */
		if (dp->d_type == ns_t_soa && dp->d_zone != DB_Z_CACHE
		    && (zones[dp->d_zone].z_flags & Z_AUTH))
			return (1);
	}
	return (0);
}

static int
wantedsig(const struct databuf *dp, int class, int type) {
	const u_char *cp;
	int coveredType;
	time_t expiration;
#ifdef DEBUG
	char pclass[15], ptype[15];
#endif

#ifdef DEBUG
	strcpy(pclass, p_class(class));
	strcpy(ptype, p_type(type));
	ns_debug(ns_log_default, 3, "wantedtsig(%p, %s %s) [%s %s]",
		 dp, pclass, ptype,
		 p_class(dp->d_class), p_type(dp->d_type));
#endif

	if (dp->d_class != class && class != C_ANY)
		return (0);
	if (dp->d_type != T_SIG || dp->d_rcode != 0)
		return (0);

	cp = dp->d_data;
	GETSHORT(coveredType, cp);
	cp += INT16SZ + INT32SZ; /* skip alg, labels, & orig TTL */
	GETLONG(expiration,cp);
	if (expiration < time(0))
		return (0);

	if (type == T_ANY || type == T_SIG || type == coveredType)
			return (1);
	if (type == ns_t_mailb) {
		switch (coveredType) {
		case T_MR:
		case T_MB:
		case T_MG:
		case T_MINFO:
			return (1);
		}
	}
	return (0);
}

/*
 *  Add RR entries from dpp array to a query/response.
 *  Return the number of bytes added or negative the amount
 *  added if truncation occured.  Typically you are
 *  adding NS records to a response.
 */
int
add_data(struct namebuf *np, struct databuf **dpp,
	 u_char *cp, int buflen, int *countp)
{
	struct databuf *dp;
	char dname[MAXDNAME];
	int n, bytes;

	bytes = *countp = 0;
	getname(np, dname, sizeof(dname));
	for (dp = *dpp++; dp != NULL; dp = *dpp++) {
		if (stale(dp))
			continue;	/* ignore old cache entry */
		if (dp->d_rcode)
			continue;
		if ((n = make_rr(dname, dp, cp, buflen, 1,
				 dnptrs, dnptrs_end, 0)) < 0)
			return (-bytes);	/* Truncation */
		cp += n;
		buflen -= n;
		bytes += n;
		(*countp)++;
	}
	return (bytes);
}

static void
rrsetadd(struct flush_set *flushset, const char *name, struct databuf *dp) {
	struct flush_set *fs = flushset;
	struct db_list *dbl;

	while (fs->fs_name && (
		ns_samename(fs->fs_name,name) != 1 ||
		(fs->fs_class != dp->d_class) ||
		(fs->fs_type != dp->d_type) ||
		(fs->fs_cred != dp->d_cred))) {
		fs++;
	}
	if (!fs->fs_name) {
		fs->fs_name = savestr(name, 1);
		fs->fs_class = dp->d_class;
		fs->fs_type = dp->d_type;
		fs->fs_cred = dp->d_cred;
		fs->fs_list = NULL;
		fs->fs_last = NULL;
	}
	dbl = (struct db_list *)memget(sizeof(struct db_list));
	if (!dbl)
		panic("rrsetadd: out of memory", NULL);
	dbl->db_next = NULL;
	dbl->db_dp = dp;
	DRCNTINC(dbl->db_dp);
	if (fs->fs_last == NULL)
		fs->fs_list = dbl;
	else
		fs->fs_last->db_next = dbl;
	fs->fs_last = dbl;
}

static int
ttlcheck(const char *name, struct db_list *dbl, int update) {
	int type = dbl->db_dp->d_type;
	int class = dbl->db_dp->d_class;
	struct hashbuf *htp = hashtab;
	const char *fname;
	struct namebuf *np;
	struct db_list *dbp = dbl;
	struct databuf *dp;
	u_int32_t ttl = 0;	/* Make gcc happy. */
	int first;


	np = nlookup(name, &htp, &fname, 0);
	if (np == NULL || fname != name || ns_wildcard(NAME(*np)))
		return (1);

	/* check that all the ttl's we have are the same, if not return 1 */
	first = 1;
	for (dp = np->n_data; dp != NULL; dp = dp->d_next) {
		if (!match(dp, class, type))
			continue;
		if (first) {
 			/* we can't update zone data so return early */
			if (dp->d_zone != DB_Z_CACHE)
 				return (0);
			ttl = dp->d_ttl;
			first = 0;
		} else if (ttl != dp->d_ttl)
			return (1);
	}

	/* there are no records of this type in the cache */
	if (first)
		return(1);

	/*
	 * the ttls of all records we have in the cache are the same
	 * if the ttls differ in the new set we don't want it.
	 */

	/* check that all the ttl's we have are the same, if not return 0 */
	first = 1;
	while (dbp) {
		if (first) {
			ttl = dbp->db_dp->d_ttl;
			first = 0;
		} else if (ttl != dbp->db_dp->d_ttl) {
			return(0);
		}
		dbp = dbp->db_next;
	}

  	/* update ttl if required */
 	if (update) {
 		for (dp = np->n_data; dp != NULL; dp = dp->d_next) {
 			if (!match(dp, class, type))
 				continue;
 			if (dp->d_ttl > ttl)
 				break;
 			dp->d_ttl = ttl;
 			fixttl(dp);
 		}
 	}

	return(1);
}

/*
 * lookup rrset in table and compare to dbl
 * tri state result
 * -1: lookup failed
 * 0: rrsets same
 * 1: rrsets differ
 */

static int
rrsetcmp(char * name, struct db_list * dbl, struct hashbuf * table) {
	int type = dbl->db_dp->d_type;
	int class = dbl->db_dp->d_class;
	struct hashbuf *htp = table;
	const char *fname;
	struct namebuf *np;
	struct db_list *dbp = dbl;
	struct databuf *dp;
	int exists = 0;


	np = nlookup(name, &htp, &fname, 0);
	if (np == NULL || fname != name || ns_wildcard(NAME(*np))) {
		ns_debug(ns_log_default, 3, "rrsetcmp: name not in database");
		return (-1);
	}

	/* check that all entries in dbl are in the cache */
	while (dbp) {
		for (dp = np->n_data; dp != NULL; dp = dp->d_next) {
			if (!match(dp, class, type))
				continue;
			exists = 1;
			if (!db_cmp(dp, dbp->db_dp) 
#ifdef NOADDITIONAL
			&& ((dp->d_cred == dbp->db_dp->d_cred) ||
				 (dp->d_cred != DB_C_ADDITIONAL))
#endif
				 )
				break;
		}
		if (!dp) {
			ns_debug(ns_log_default, 3,
				 "rrsetcmp: %srecord%s in database",
				 exists ? "" : "no ", exists ? " not" : "s");
			return (exists ? 1 : -1);
		}
		dbp = dbp->db_next;
	}

	/* Check that all cache entries are in the list. */
	for (dp = np->n_data; dp != NULL; dp = dp->d_next) {
		if (!match(dp, class, type))
			continue;
#ifdef NCACHE
		if (dp->d_rcode)
			return (1);
#endif
		dbp = dbl;
		while (dbp) {
			if (!db_cmp(dp, dbp->db_dp))
				break;
			dbp = dbp->db_next;
		}
		if (!dbp) {
			ns_debug(ns_log_default, 3,
				 "rrsetcmp: record not in rrset");
			return (1);
		}
	}
	ns_debug(ns_log_default, 3, "rrsetcmp: rrsets matched");
	return (0);
}

/*
 * verify incoming answer against what we already have in the hints
 * issue warnings / errors if differences detected.
 */

static void
check_hints(struct flush_set * flushset) {
	struct zoneinfo *zp;
	struct flush_set *fs;
	struct db_list *dbp;

	/* We don't use hints when in forward only mode */
	if (NS_OPTION_P(OPTION_FORWARD_ONLY))
		return;

	/* find "." NS rrset and hence class */
	for (fs = flushset; fs->fs_name != NULL; fs++) {
		if ((fs->fs_name[0] != '\0') || (fs->fs_type != ns_t_ns))
			continue;

		/* see if we are a root server */
		zp = find_zone(fs->fs_name, fs->fs_class);
		if (zp != NULL &&
		    (zp->z_type == z_master || zp->z_type == z_slave))
			return;
		switch (rrsetcmp(fs->fs_name, fs->fs_list, fcachetab)) {
		case -1:
			ns_error(ns_log_default,
			    "check_hints: no NS records for class %d in hints",
				fs->fs_class);
			break;
		case 1:
			ns_warning(ns_log_default,
 "check_hints: root NS list in hints for class %d does not match root NS list",
				fs->fs_class);
			break;
		case 0:
			break;
		default:
			ns_error(ns_log_default,
			    "check_hints: unexpected response from rrsetcmp");
			break;
		}
		break;
	}

	if (fs->fs_name == NULL)	/* no root NS records */
		return;

	dbp = fs->fs_list;
	while (dbp) {
		/* for each NS find A rrset in answer and check */
		for (fs = flushset; fs->fs_name != NULL; fs++) {
			if (ns_samename(fs->fs_name, (char *)dbp->db_dp->d_data) != 1
			    || fs->fs_type != ns_t_a)
				continue;
			switch (rrsetcmp(fs->fs_name, fs->fs_list, fcachetab)) {
			case -1:
				ns_error(ns_log_default,
			"check_hints: no A records for %s class %d in hints",
					fs->fs_name[0] ? fs->fs_name : ".",
					fs->fs_class);
				break;
			case 1:
				ns_warning(ns_log_default,
	 "check_hints: A records for %s class %d do not match hint records",
					fs->fs_name[0] ? fs->fs_name : ".",
					fs->fs_class);
				break;
			case 0:
				break;
			default:
				ns_error(ns_log_default,
				    "check_hints: unexpected response from rrsetcmp");
				break;
			}
			break;
		}

		if (fs->fs_name == NULL)
			ns_debug(ns_log_default, 2,
				"check_hints: no A records for %s",
				dbp->db_dp->d_data);

		dbp = dbp->db_next;
	}
}

static void
rrsetupdate(struct flush_set * flushset, int flags, struct sockaddr_in from,
	    int updatettl) {
	struct flush_set *fs = flushset;
	struct db_list *dbp, *odbp;
	int n;
	void *state = NULL;

	while (fs->fs_name) {
		ns_debug(ns_log_default, 2, "rrsetupdate: %s",
			 fs->fs_name[0] ? fs->fs_name : ".");
		if ((n = rrsetcmp(fs->fs_name, fs->fs_list, hashtab)) &&
		    ttlcheck(fs->fs_name, fs->fs_list, 0)) {
			if (n > 0)
				flushrrset(fs, from);

			dbp = fs->fs_list;
			while (dbp) {
				n = db_set_update(fs->fs_name, dbp->db_dp,
						  &state, flags,
						  &hashtab, from, NULL,
						  0, NULL);
				ns_debug(ns_log_default, 3,
					 "rrsetupdate: %s %d",
					 fs->fs_name[0] ? fs->fs_name : ".",
					 n);
				odbp = dbp;
				dbp = dbp->db_next;
				db_detach(&odbp->db_dp);
				memput(odbp, sizeof *odbp);
			}    
			ns_debug(ns_log_default, 3,
				 "rrsetupdate: %s %d",
				 fs->fs_name[0] ? fs->fs_name : ".", n);
		} else {
			if ((n == 0) && updatettl)
				(void)ttlcheck(fs->fs_name,fs->fs_list, 1);
			dbp = fs->fs_list;
			while (dbp) {
				db_detach(&dbp->db_dp);
				odbp = dbp;
				dbp = dbp->db_next;
				memput(odbp, sizeof *odbp);
			}
		}
		fs->fs_list = NULL;
		fs++;
	}
	n = db_set_update(NULL, NULL, &state, flags, &hashtab, from,
			  NULL, 0, NULL);
}

static void
flushrrset(struct flush_set * fs, struct sockaddr_in from) {
	struct databuf *dp;
	int n;

	ns_debug(ns_log_default, 2, "flushrrset(%s, %s, %s, %d)",
		 fs->fs_name[0]?fs->fs_name:".", p_type(fs->fs_type),
		 p_class(fs->fs_class), fs->fs_cred);
	dp = savedata(fs->fs_class, fs->fs_type, 0, NULL, 0);
	dp->d_zone = DB_Z_CACHE;
	dp->d_cred = fs->fs_cred;
	dp->d_clev = 0;	
	do {
		n = db_update(fs->fs_name, dp, NULL, NULL, DB_DELETE, hashtab,
			      from);
		ns_debug(ns_log_default, 3, "flushrrset: %d", n);
	} while (n == OK);
	db_detach(&dp);
}

static void
free_flushset(struct flush_set *flushset, int flushset_size) {
	struct flush_set *fs;
	struct db_list *dbl;

	for (fs = flushset; fs->fs_name != NULL; fs++) {
		fs->fs_name = freestr(fs->fs_name);
		while ((dbl = fs->fs_list) != NULL) {
			fs->fs_list = dbl->db_next;
			dbl->db_next = NULL;
			db_detach(&dbl->db_dp);
			memput(dbl, sizeof(*dbl));
		}
	}
	memput(flushset, flushset_size);
}

/*
 *  This is best thought of as a "cache invalidate" function.
 *  It is called whenever a piece of data is determined to have
 *  become invalid either through a timeout or a validation
 *  failure.  It is better to have no information, than to
 *  have partial information you pass off as complete.
 */
void
delete_all(struct namebuf *np, int class, int type) {
	struct databuf *dp, *pdp;

	ns_debug(ns_log_default, 3, "delete_all(%p:\"%s\" %s %s)",
		 np, NAME(*np), p_class(class), p_type(type));
	pdp = NULL;
	dp = np->n_data;
	while (dp != NULL) {
		if (dp->d_zone == DB_Z_CACHE && (dp->d_flags & DB_F_HINT) == 0
		    && match(dp, class, type)) {
			dp = rm_datum(dp, np, pdp, NULL);
			continue;
		}
		pdp = dp;
		dp = dp->d_next;
	}
}

/* delete_stale(np)
 *	for all RRs associated with this name, check for staleness (& delete)
 * arguments:
 *	np = pointer to namebuf to be cleaned.
 * returns:
 *	number of RRs associated with this name.
 * side effects:
 *	delete_all() can be called, freeing memory and relinking chains.
 */
int 
delete_stale(np)
	struct namebuf *np;
{
	struct databuf *dp;
	int count;
 again:
	count = 0;
        for (dp = np->n_data; dp != NULL; dp = dp->d_next) {
                if (dp->d_zone == DB_Z_CACHE && stale(dp)) {
                        delete_all(np, dp->d_class, dp->d_type);
                        goto again;
		}
		count++;
 	}
	return (count);
}


/*
 * Adjust answer message so that it fits in outlen. Set tc if required.
 *
 * If outlen = msglen, can be used to verify qdcount, ancount, nscount
 * and arcount.
 *
 * return new length
 */

int
trunc_adjust(u_char *msg, int msglen, int outlen) {
	register HEADER *hp;
	u_int qdcount, ancount, nscount, arcount, dlen;
	u_char *cp = msg, *cp1, *eom_in, *eom_out;
	int n;

	eom_in = msg + msglen;
	eom_out = msg + outlen;

	hp = (HEADER *)msg;
	qdcount = ntohs(hp->qdcount);
	ancount = ntohs(hp->ancount);
	nscount = ntohs(hp->nscount);
	arcount = ntohs(hp->arcount);
	cp += HFIXEDSZ;

	while ((qdcount || ancount || nscount || arcount) &&
	       cp < eom_in && cp < eom_out) {

		cp1 = cp; /* use temporary in case we break */

		n = dn_skipname(cp1, eom_in);
		if (n < 0)
			break;
		cp1 += n + 2 * INT16SZ; /* type, class */

		if (!qdcount) {
			cp1 += INT32SZ;     /* ttl */
			if (cp1 + INT16SZ > eom_in)
				break;
			GETSHORT(dlen, cp1);
			cp1 += dlen;
		}

		if (cp1 > eom_in || cp1 > eom_out)
			break;

		cp = cp1;

		if (qdcount)
			qdcount--;
		else if (ancount)
			ancount--;
		else if (nscount)
			nscount--;
		else
			arcount--;
	}

	if (qdcount || ancount || nscount || arcount) {
		ns_debug(ns_log_default, 1,
			 "trunc_adjust:%s %d %d %d %d %d, %d %d %d %d %d",
			 hp->tc?" tc":"", msglen,
			 ntohs(hp->qdcount), ntohs(hp->ancount),
			 ntohs(hp->nscount), ntohs(hp->arcount),
			 cp-msg, qdcount, ancount, nscount, arcount);
		hp->tc = 1;
		hp->qdcount = htons(ntohs(hp->qdcount) - qdcount);
		hp->ancount = htons(ntohs(hp->ancount) - ancount);
		hp->nscount = htons(ntohs(hp->nscount) - nscount);
		hp->arcount = htons(ntohs(hp->arcount) - arcount);
	}
	ENSURE(cp <= eom_out);
	return (cp - msg);
}

/*
 * mark the server "from" bad in the qp structure so it won't be retried.
 */
static int
mark_noedns(struct qinfo *qp, struct sockaddr_in from, int cache) {
	int i;

	for (i = 0; i < (int)qp->q_naddr; i++)
		if (ina_equal(qp->q_addr[i].ns_addr.sin_addr, from.sin_addr)) {
			if (qp->q_addr[i].noedns)
				return (1);
			if (qp->q_addr[i].nsdata && cache)
				qp->q_addr[i].nsdata->d_noedns = 1;
			qp->q_addr[i].noedns = 1;
			break;
		}
	return (0);
}

static void
mark_bad(struct qinfo *qp, struct sockaddr_in from) {
	int i;

	for (i = 0; i < (int)qp->q_naddr; i++)
		if (ina_equal(qp->q_addr[i].ns_addr.sin_addr, from.sin_addr))
			qp->q_addr[i].nretry = MAXRETRY;
}

static void
mark_lame(struct qinfo *qp, struct sockaddr_in from) {
	int i;

	for (i = 0; i < (int)qp->q_naddr; i++)
		if (ina_equal(qp->q_addr[i].ns_addr.sin_addr, from.sin_addr) &&
		    qp->q_addr[i].ns != NULL) {
			qp->q_addr[i].ns->d_flags |= DB_F_LAME;
			db_lame_add(qp->q_domain,
				    (char*)qp->q_addr[i].ns->d_data, 
				    tt.tv_sec + server_options->lame_ttl);
		}
}

/*
 * Retry the message if and only if from matches where the query was
 * last sent to.  The code does not handle responses sent from the
 * wrong interface an a multihomed server.
 */
static void
fast_retry(struct qinfo *qp, struct sockaddr_in from, int samehost) {
        if (ina_equal(qp->q_addr[qp->q_curaddr].ns_addr.sin_addr,
                   from.sin_addr))
                retry(qp, samehost);
}

static void
add_related_additional(char *name) {
	int i;

	if (num_related >= MAX_RELATED - 1)
		return;
	for (i = 0; i < num_related; i++)
		if (ns_samename(name, related[i]) == 1) {
			(void)freestr(name);
			return;
		}
	related[num_related++] = name;
}

static void
free_related_additional() {
	int i;

	for (i = 0; i < num_related; i++)
		related[i] = freestr(related[i]);
	num_related = 0;
}

static int
related_additional(char *name) {
	int i;

	for (i = 0; i < num_related; i++)
		if (ns_samename(name, related[i]) == 1)
			return (1);
	return (0);
}

static void
freestr_maybe(char **tname) {
	if (tname == NULL || *tname == NULL)
		return;
	*tname = freestr(*tname);
}

/*
 * Match a request namebuf against the configured rrset-order info.  First
 * match wins.  There is an implicit '*.' at the front to the ordering names.
 */
static enum ordering
match_order(const struct namebuf *np, int class, int type) {
	rrset_order_list orders = server_options->ordering;
	rrset_order_element roe;
	
	if (orders == NULL)
		return (DEFAULT_ORDERING);
	
	for (roe = orders->first ; roe != NULL ; roe = roe->next) {
		if (roe->class != C_ANY && roe->class != class)
			continue;
		if (roe->type != T_ANY && roe->type != type)
			continue;

		if (match_name(np, roe->name, strlen(roe->name)) == 0) {
			return (roe->order);
		}
	}

	/* none matched so use default */
	return (DEFAULT_ORDERING);
}

/* Do a simple compare of the NP data against the given NAME, recursively
 * looking at the NP parent if necessary. NAMELEN is the length of the NAME
 * that needs to be matched. Matching happen from right to left. Returns -1
 * on failure, on success the index of the first character of the matched
 * portion of the string is returned. In the first level call a return
 * value of 0 is of interest.
 */
static int
match_name(const struct namebuf *np, const char *name, size_t namelen)
{
	int matched ;
	
	if (name[0] == '*' && name[1] == '\0')
		return 0;

	if (np->n_parent != NULL) { /* recurse to end of np list */
		matched = match_name(np->n_parent,name,namelen);
	} else {
		matched = namelen;
	}
	
	if (matched > 0) {
		int labellen = NAMELEN(*np);
		char pch;
		const char *start;
		
		if (labellen > matched) {
			return -1;
		} else if (labellen < matched) {
			/* string is longer than this namebuf's data, so
			   make sure there's a period before the end of the 
			   match so we don't just match a suffix. */
			start = name + (matched - labellen);
			pch = start[-1];
			if (pch != '.') {
				return -1;
			}
		} else {
			start = name ;
		}

		if (strncasecmp(start, NAME(*np), labellen) == 0) {
			/* looking good. tell our caller what portion of
			   the tail of string has been matched */
			if (start == name)
				return (0) ;
			else 
				return (start - name - 1); /* matched '.' too */
		} else {
			return (-1);
		}
	}

	return (matched);
}