File: util.c

package info (click to toggle)
host 20000331-3
  • links: PTS
  • area: main
  • in suites: woody
  • size: 540 kB
  • ctags: 998
  • sloc: ansic: 7,543; sh: 389; makefile: 133
file content (1757 lines) | stat: -rw-r--r-- 47,001 bytes parent folder | download | duplicates (4)
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
/*
 * Copyright (c) 1985, 1989 Regents of the University of California.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms are permitted
 * provided that: (1) source distributions retain this entire copyright
 * notice and comment, and (2) distributions including binaries display
 * the following acknowledgement:  ``This product includes software
 * developed by the University of California, Berkeley and its contributors''
 * in the documentation or other materials provided with the distribution
 * and in all advertising materials mentioning features or use of this
 * software. 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

#ifndef lint
static char Version[] = "@(#)util.c	e07@nikhef.nl (Eric Wassenaar) 991527";
#endif

#include "host.h"
#include "glob.h"

/*
** PARSE_TYPE -- Decode rr type from input string
** ----------------------------------------------
**
**	Returns:
**		Value of resource record type.
**		-1 if specified record name is invalid.
**
**	Note.	Several types are deprecated or obsolete, but recognized.
**		T_AXFR/T_IXFR is not allowed to be specified as query type.
*/

int
parse_type(str)
input char *str;			/* input string with record type */
{
	register int type;

		/* standard types */

	if (sameword(str, "A"))		return(T_A);
	if (sameword(str, "NS"))	return(T_NS);
	if (sameword(str, "MD"))	return(T_MD);		/* obsolete */
	if (sameword(str, "MF"))	return(T_MF);		/* obsolete */
	if (sameword(str, "CNAME"))	return(T_CNAME);
	if (sameword(str, "SOA"))	return(T_SOA);
	if (sameword(str, "MB"))	return(T_MB);		/* deprecated */
	if (sameword(str, "MG"))	return(T_MG);		/* deprecated */
	if (sameword(str, "MR"))	return(T_MR);		/* deprecated */
	if (sameword(str, "NULL"))	return(T_NULL);		/* obsolete */
	if (sameword(str, "WKS"))	return(T_WKS);
	if (sameword(str, "PTR"))	return(T_PTR);
	if (sameword(str, "HINFO"))	return(T_HINFO);
	if (sameword(str, "MINFO"))	return(T_MINFO);	/* deprecated */
	if (sameword(str, "MX"))	return(T_MX);
	if (sameword(str, "TXT"))	return(T_TXT);

		/* new types */

	if (sameword(str, "RP"))	return(T_RP);
	if (sameword(str, "AFSDB"))	return(T_AFSDB);
	if (sameword(str, "X25"))	return(T_X25);
	if (sameword(str, "ISDN"))	return(T_ISDN);
	if (sameword(str, "RT"))	return(T_RT);
	if (sameword(str, "NSAP"))	return(T_NSAP);
	if (sameword(str, "NSAP-PTR"))	return(T_NSAPPTR);
	if (sameword(str, "SIG"))	return(T_SIG);
	if (sameword(str, "KEY"))	return(T_KEY);
	if (sameword(str, "PX"))	return(T_PX);
	if (sameword(str, "GPOS"))	return(T_GPOS);		/* withdrawn */
	if (sameword(str, "AAAA"))	return(T_AAAA);
	if (sameword(str, "LOC"))	return(T_LOC);
	if (sameword(str, "NXT"))	return(T_NXT);
	if (sameword(str, "EID"))	return(T_EID);
	if (sameword(str, "NIMLOC"))	return(T_NIMLOC);
	if (sameword(str, "SRV"))	return(T_SRV);
	if (sameword(str, "ATMA"))	return(T_ATMA);
	if (sameword(str, "NAPTR"))	return(T_NAPTR);
	if (sameword(str, "KX"))	return(T_KX);
	if (sameword(str, "CERT"))	return(T_CERT);
	if (sameword(str, "A6"))	return(T_A6);
	if (sameword(str, "DNAME"))	return(T_DNAME);
	if (sameword(str, "SINK"))	return(T_SINK);
	if (sameword(str, "OPT"))	return(T_OPT);

		/* nonstandard types */

	if (sameword(str, "UINFO"))	return(T_UINFO);
	if (sameword(str, "UID"))	return(T_UID);
	if (sameword(str, "GID"))	return(T_GID);
	if (sameword(str, "UNSPEC"))	return(T_UNSPEC);

		/* special types */

	if (sameword(str, "ADDRS"))	return(T_ADDRS);
	if (sameword(str, "TKEY"))	return(T_TKEY);
	if (sameword(str, "TSIG"))	return(T_TSIG);

		/* filters */

	if (sameword(str, "IXFR"))	return(-1);		/* illegal */
	if (sameword(str, "AXFR"))	return(-1);		/* illegal */
	if (sameword(str, "MAILB"))	return(T_MAILB);
	if (sameword(str, "MAILA"))	return(T_MAILA);	/* obsolete */
	if (sameword(str, "ANY"))	return(T_ANY);
	if (sameword(str, "*"))		return(T_ANY);

		/* unknown types */

	type = atoi(str);
	if (type >= T_FIRST && type <= T_LAST)
		return(type);

	return(-1);
}

/*
** PARSE_CLASS -- Decode rr class from input string
** ------------------------------------------------
**
**	Returns:
**		Value of resource class.
**		-1 if specified class name is invalid.
**
**	Note.	C_CSNET is obsolete, but recognized.
*/

int
parse_class(str)
input char *str;			/* input string with resource class */
{
	register int class;

	if (sameword(str, "IN"))	return(C_IN);
	if (sameword(str, "INTERNET"))	return(C_IN);
	if (sameword(str, "CS"))	return(C_CSNET);	/* obsolete */
	if (sameword(str, "CSNET"))	return(C_CSNET);	/* obsolete */
	if (sameword(str, "CH"))	return(C_CHAOS);
	if (sameword(str, "CHAOS"))	return(C_CHAOS);
	if (sameword(str, "HS"))	return(C_HS);
	if (sameword(str, "HESIOD"))	return(C_HS);

	if (sameword(str, "ANY"))	return(C_ANY);
	if (sameword(str, "*"))		return(C_ANY);

	class = atoi(str);
	if (class > 0)
		return(class);

	return(-1);
}

/*
** IN_ADDR_ARPA -- Convert dotted quad string to reverse in-addr.arpa
** ------------------------------------------------------------------
**
**	Returns:
**		Pointer to appropriate reverse in-addr.arpa name
**		with trailing dot to force absolute domain name.
**		NULL in case of invalid dotted quad input string.
*/

char *
in_addr_arpa(dottedquad)
input char *dottedquad;			/* input string with dotted quad */
{
	static char addrbuf[4*4 + sizeof(ARPA_ROOT) + 2];
	unsigned int a[4];
	register int n;

	n = sscanf(dottedquad, "%u.%u.%u.%u", &a[0], &a[1], &a[2], &a[3]);
	switch (n)
	{
	    case 4:
		(void) sprintf(addrbuf, "%u.%u.%u.%u.%s.",
			a[3]&0xff, a[2]&0xff, a[1]&0xff, a[0]&0xff, ARPA_ROOT);
		break;

	    case 3:
		(void) sprintf(addrbuf, "%u.%u.%u.%s.",
			a[2]&0xff, a[1]&0xff, a[0]&0xff, ARPA_ROOT);
		break;

	    case 2:
		(void) sprintf(addrbuf, "%u.%u.%s.",
			a[1]&0xff, a[0]&0xff, ARPA_ROOT);
		break;

	    case 1:
		(void) sprintf(addrbuf, "%u.%s.",
			a[0]&0xff, ARPA_ROOT);
		break;

	    default:
		return(NULL);
	}

	while (--n >= 0)
		if (a[n] > 255)
			return(NULL);

	return(addrbuf);
}

/*
** NSAP_INT -- Convert dotted nsap address string to reverse nsap.int
** ------------------------------------------------------------------
**
**	Returns:
**		Pointer to appropriate reverse nsap.int name
**		with trailing dot to force absolute domain name.
**		NULL in case of invalid nsap address input string.
*/

char *
nsap_int(name)
input char *name;			/* input string with dotted nsap */
{
	static char addrbuf[4*MAXNSAP + sizeof(NSAP_ROOT) + 2];
	register int n;
	register int i;

	/* skip optional leading hex indicator */
	if (samehead(name, "0x"))
		name += 2;

	for (n = 0, i = strlength(name)-1; i >= 0; --i)
	{
		/* skip optional interspersed separators */
		if (name[i] == '.' || name[i] == '+' || name[i] == '/')
			continue;

		/* must consist of hex digits only */
		if (!is_xdigit(name[i]))
			return(NULL);

		/* but not too many */
		if (n >= 4*MAXNSAP)
			return(NULL);

		addrbuf[n++] = name[i];
		addrbuf[n++] = '.';
	}

	/* must have an even number of hex digits */ 
	if (n == 0 || (n % 4) != 0)
		return(NULL);

	(void) sprintf(&addrbuf[n], "%s.", NSAP_ROOT);
	return(addrbuf);
}

/*
** PRINT_HOST -- Print host name and address of hostent struct
** -----------------------------------------------------------
**
**	Returns:
**		None.
*/

void
print_host(heading, hp)
input char *heading;			/* header string */
input struct hostent *hp;		/* location of hostent struct */
{
	register char **ap;

	printf("%s: %s", heading, hp->h_name);

	for (ap = hp->h_addr_list; ap && *ap; ap++)
	{
		if (ap == hp->h_addr_list)
			printf("\nAddress:");

		printf(" %s", inet_ntoa(incopy(*ap)));
	}

	for (ap = hp->h_aliases; ap && *ap && **ap; ap++)
	{
		if (ap == hp->h_aliases)
			printf("\nAliases:");

		printf(" %s", *ap);
	}

	printf("\n\n");
}

/*
** SHOW_RES -- Show resolver database information
** ----------------------------------------------
**
**	Returns:
**		None.
**
**	Inputs:
**		The resolver database _res is localized in the resolver.
*/

void
show_res()
{
	register int i;
	register char **domain;

/*
 * The default domain is defined by the "domain" entry in /etc/resolv.conf
 * if not overridden by the environment variable "LOCALDOMAIN".
 * If still not defined, gethostname() may yield a fully qualified host name.
 */
	printf("Default domain:");
	if (_res.defdname[0] != '\0')
		printf(" %s", _res.defdname);
	printf("\n");

/*
 * The search domains are extracted from the default domain label components,
 * but may be overridden by "search" directives in /etc/resolv.conf
 * since 4.8.3.
 */
	printf("Search domains:");
	for (domain = _res.dnsrch; *domain; domain++)
		printf(" %s", *domain);
	printf("\n");

/*
 * The routine res_send() will do _res.retry tries to contact each of the
 * _res.nscount nameserver addresses before giving up when using datagrams.
 * The first try will timeout after _res.retrans seconds. Each following
 * try will timeout after ((_res.retrans << try) / _res.nscount) seconds.
 * Note. When we contact an explicit server the addresses will be replaced
 * by the multiple addresses of the same server.
 * When doing a zone transfer _res.retrans is used for the connect timeout.
 */
	printf("Timeout per retry: %d secs\n", _res.retrans);
	printf("Number of retries: %d\n", _res.retry);

	printf("Number of addresses: %d\n", _res.nscount);
	for (i = 0; i < _res.nscount; i++)
		printf("%s\n", inet_ntoa(nslist(i).sin_addr));

/*
 * The resolver options are initialized by res_init() to contain the
 * defaults settings (RES_RECURSE | RES_DEFNAMES | RES_DNSRCH)
 * The various options have the following meaning:
 *
 *	RES_INIT	set after res_init() has been called
 *	RES_DEBUG	let the resolver modules print debugging info
 *	RES_AAONLY	want authoritative answers only (not implemented)
 *	RES_USEVC	use tcp virtual circuit instead of udp datagrams
 *	RES_PRIMARY	use primary nameserver only (not implemented)
 *	RES_IGNTC	ignore datagram truncation; don't switch to tcp
 *	RES_RECURSE	forward query if answer not locally available
 *	RES_DEFNAMES	add default domain to queryname without dot
 *	RES_STAYOPEN	keep tcp socket open for subsequent queries
 *	RES_DNSRCH	append search domains even to queryname with dot
 */
	printf("Options set:");
	if (bitset(RES_INIT,      _res.options)) printf(" INIT");
	if (bitset(RES_DEBUG,     _res.options)) printf(" DEBUG");
	if (bitset(RES_AAONLY,    _res.options)) printf(" AAONLY");
	if (bitset(RES_USEVC,     _res.options)) printf(" USEVC");
	if (bitset(RES_PRIMARY,   _res.options)) printf(" PRIMARY");
	if (bitset(RES_IGNTC,     _res.options)) printf(" IGNTC");
	if (bitset(RES_RECURSE,   _res.options)) printf(" RECURSE");
	if (bitset(RES_DEFNAMES,  _res.options)) printf(" DEFNAMES");
	if (bitset(RES_STAYOPEN,  _res.options)) printf(" STAYOPEN");
	if (bitset(RES_DNSRCH,    _res.options)) printf(" DNSRCH");
	printf("\n");

	printf("Options clr:");
	if (!bitset(RES_INIT,     _res.options)) printf(" INIT");
	if (!bitset(RES_DEBUG,    _res.options)) printf(" DEBUG");
	if (!bitset(RES_AAONLY,   _res.options)) printf(" AAONLY");
	if (!bitset(RES_USEVC,    _res.options)) printf(" USEVC");
	if (!bitset(RES_PRIMARY,  _res.options)) printf(" PRIMARY");
	if (!bitset(RES_IGNTC,    _res.options)) printf(" IGNTC");
	if (!bitset(RES_RECURSE,  _res.options)) printf(" RECURSE");
	if (!bitset(RES_DEFNAMES, _res.options)) printf(" DEFNAMES");
	if (!bitset(RES_STAYOPEN, _res.options)) printf(" STAYOPEN");
	if (!bitset(RES_DNSRCH,   _res.options)) printf(" DNSRCH");
	printf("\n");

/*
 * The new BIND 4.9.3 has additional features which are not (yet) used.
 */
	printf("\n");
}

/*
** PRINT_STATS -- Print resource record statistics
** -----------------------------------------------
**
**	Returns:
**		None.
**
**	Inputs:
**		The record_stats[] counts have been updated by print_rrec().
**		The total_stats[]  counts have been updated by list_zone().
*/

void
print_stats(stats, nzones, name, filter, class)
input int stats[];			/* count of resource records per type */
input int nzones;			/* number of zones processed */
input char *name;			/* name of zone we are listing */
input int filter;			/* type of records we want to see */
input int class;			/* class of records we want to see */
{
	register int type;
	int nrecords;
	int total;

	for (total = 0, type = T_FIRST; type <= T_LAST; type++)
	{
		nrecords = stats[type];
		total += nrecords;

		if (nrecords > 0 || ((filter != T_ANY) && want_type(type, filter)))
		{
			printf("Found %d %s record%s", nrecords,
				pr_type(type), plural(nrecords));

			if (class != C_IN)
				printf(" in class %s", pr_class(class));

			if (nzones > 0)
				printf(" in %d zone%s", nzones, plural(nzones));

			printf(" within %s\n", name);
		}
	}

	if (total > 0)
	{
		printf("Found %d resource record%s", total, plural(total));

		if (class != C_IN)
			printf(" in class %s", pr_class(class));

		if (nzones > 0)
			printf(" in %d zone%s", nzones, plural(nzones));

		printf(" within %s\n", name);
	}
}

/*
** CLEAR_STATS -- Clear resource record statistics
** -----------------------------------------------
**
**	Returns:
**		None.
*/

void
clear_stats(stats)
output int stats[];			/* count of resource records per type */
{
	register int type;

	for (type = T_FIRST; type <= T_LAST; type++)
		stats[type] = 0;
}

/*
** SHOW_TYPES -- Show resource record types wanted
** -----------------------------------------------
**
**	Returns:
**		None.
*/

void
show_types(name, filter, class)
input char *name;			/* name we want to query about */
input int filter;			/* type of records we want to see */
input int class;			/* class of records we want to see */
{
	register int type;

	if (filter >= T_NONE)
	{
		printf("Query about %s for record types", name);

		if (filter == T_ANY)
			printf(" %s", pr_type(T_ANY));
		else
			for (type = T_FIRST; type <= T_LAST; type++)
				if (want_type(type, filter))
					printf(" %s", pr_type(type));

		if (class != C_IN)
			printf(" in class %s", pr_class(class));

		printf("\n");
	}
}

/*
** NS_ERROR -- Print error message from errno and h_errno
** ------------------------------------------------------
**
**	Returns:
**		None.
**
** If BIND res_send() fails, it will leave errno in either of the first
** two following states when using datagrams. Note that this depends on
** the proper handling of connected datagram sockets, which is usually
** true if BSD >= 43 (see res_send.c for details; it may need a patch).
** Note. If the 4.8 version succeeds, it may leave errno as EAFNOSUPPORT
** if it has disconnected a previously connected datagram socket, since
** the dummy address used to disconnect does not have a proper family set.
** Always clear errno after getting a reply, or patch res_send().
** Our private version of res_send() will leave also other error statuses.
*/

void
ns_error(name, type, class, host) 
input char *name;			/* full name we queried about */
input int type;				/* record type we queried about */
input int class;			/* record class we queried about */
input char *host;			/* set if explicit server was used */
{
	static char *auth = "Authoritative answer";

/*
 * Print the message associated with the network related errno values.
 */
	switch (errno)
	{
	    case ECONNREFUSED:
		/*
		 * The contacted host does not have a nameserver running.
		 * The standard res_send() also returns this if none of
		 * the intended hosts could be reached via datagrams.
		 */
		if (host != NULL)
			errmsg("Nameserver %s not running", host);
		else
			errmsg("Nameserver not running");
		break;

	    case ETIMEDOUT:
		/*
		 * The contacted server did not give any reply at all
		 * within the specified time frame.
		 */
		if (host != NULL)
			errmsg("Nameserver %s not responding", host);
		else
			errmsg("Nameserver not responding");
		break;

	    case ENETDOWN:
	    case ENETUNREACH:
	    case EHOSTDOWN:
	    case EHOSTUNREACH:
		/*
		 * The host to be contacted or its network can not be reached.
		 * Our private res_send() also returns this using datagrams.
		 */
		if (host != NULL)
			errmsg("Nameserver %s not reachable", host);
		else
			errmsg("Nameserver not reachable");
		break;
	}

/*
 * Print the message associated with the particular nameserver error.
 */
	switch (h_errno)
	{
	    case HOST_NOT_FOUND:
		/*
		 * The specified name does definitely not exist at all.
		 * In this case the answer is always authoritative.
		 * Nameserver status: NXDOMAIN
		 */
		if (class != C_IN)
			errmsg("%s does not exist in class %s (%s)",
				name, pr_class(class), auth);
		else if (host != NULL)
			errmsg("%s does not exist at %s (%s)",
				name, host, auth);
		else
			errmsg("%s does not exist (%s)",
				name, auth);
		break;

	    case NO_HOST:
		/*
		 * The specified name does not exist, but the answer
		 * was not authoritative, so it is still undecided.
		 * Nameserver status: NXDOMAIN
		 */
		if (class != C_IN)
			errmsg("%s does not exist in class %s, try again",
				name, pr_class(class));
		else if (host != NULL)
			errmsg("%s does not exist at %s, try again",
				name, host);
		else
			errmsg("%s does not exist, try again",
				name);
		break;

	    case NO_DATA:
		/*
		 * The name is valid, but the specified type does not exist.
		 * This status is here returned only in case authoritative.
		 * Nameserver status: NOERROR
		 */
		if (class != C_IN)
			errmsg("%s has no %s record in class %s (%s)",
				name, pr_type(type), pr_class(class), auth);
		else if (host != NULL)
			errmsg("%s has no %s record at %s (%s)",
				name, pr_type(type), host, auth);
		else
			errmsg("%s has no %s record (%s)",
				name, pr_type(type), auth);
		break;

	    case NO_RREC:
		/*
		 * The specified type does not exist, but we don't know whether
		 * the name is valid or not. The answer was not authoritative.
		 * Perhaps recursion was off, and no data was cached locally.
		 * Nameserver status: NOERROR
		 */
		if (class != C_IN)
			errmsg("%s %s record in class %s currently not present",
				name, pr_type(type), pr_class(class));
		else if (host != NULL)
			errmsg("%s %s record currently not present at %s",
				name, pr_type(type), host);
		else
			errmsg("%s %s record currently not present",
				name, pr_type(type));
		break;

	    case TRY_AGAIN:
		/*
		 * Some intermediate failure, e.g. connect timeout,
		 * or some local operating system transient errors.
		 * General failure to reach any appropriate servers.
		 * The status SERVFAIL now yields a separate error code.
		 * Nameserver status: (SERVFAIL)
		 */
		if (class != C_IN)
			errmsg("%s %s record in class %s not found, try again",
				name, pr_type(type), pr_class(class));
		else if (host != NULL)
			errmsg("%s %s record not found at %s, try again",
				name, pr_type(type), host);
		else
			errmsg("%s %s record not found, try again",
				name, pr_type(type));
		break;

	    case SERVER_FAILURE:
		/*
		 * Explicit server failure status. This will be returned upon
		 * some internal server errors, forwarding failures, or when
		 * the server is not authoritative for a specific class.
		 * Also if the zone data has expired at a secondary server.
		 * Nameserver status: SERVFAIL
		 */
		if (class != C_IN)
			errmsg("%s %s record in class %s not found, server failure",
				name, pr_type(type), pr_class(class));
		else if (host != NULL)
			errmsg("%s %s record not found at %s, server failure",
				name, pr_type(type), host);
		else
			errmsg("%s %s record not found, server failure",
				name, pr_type(type));
		break;

	    case NO_RECOVERY:
		/*
		 * Some irrecoverable format error, or server refusal.
		 * The status REFUSED now yields a separate error code.
		 * Nameserver status: (REFUSED) FORMERR NOTIMP NOCHANGE
		 */
		if (class != C_IN)
			errmsg("%s %s record in class %s not found, no recovery",
				name, pr_type(type), pr_class(class));
		else if (host != NULL)
			errmsg("%s %s record not found at %s, no recovery",
				name, pr_type(type), host);
		else
			errmsg("%s %s record not found, no recovery",
				name, pr_type(type));
		break;

	    case QUERY_REFUSED:
		/*
		 * The server explicitly refused to answer the query.
		 * Servers can be configured to disallow zone transfers.
		 * Nameserver status: REFUSED
		 */
		if (class != C_IN)
			errmsg("%s %s record in class %s query refused",
				name, pr_type(type), pr_class(class));
		else if (host != NULL)
			errmsg("%s %s record query refused by %s",
				name, pr_type(type), host);
		else
			errmsg("%s %s record query refused",
				name, pr_type(type));
		break;

	    default:
		/*
		 * Unknown cause for server failure.
		 */
		if (class != C_IN)
			errmsg("%s %s record in class %s not found",
				name, pr_type(type), pr_class(class));
		else if (host != NULL)
			errmsg("%s %s record not found at %s",
				name, pr_type(type), host);
		else
			errmsg("%s %s record not found",
				name, pr_type(type));
		break;
	}
}

/*
** DECODE_ERROR -- Convert nameserver error code to error message
** --------------------------------------------------------------
**
**	Returns:
**		Pointer to appropriate error message.
*/

char *
decode_error(rcode)
input int rcode;			/* error code from bp->rcode */
{
	switch (rcode)
	{
	    case NOERROR: 	return("no error");
	    case FORMERR:	return("format error");
	    case SERVFAIL:	return("server failure");
	    case NXDOMAIN:	return("non-existent domain");
	    case NOTIMP:	return("not implemented");
	    case REFUSED:	return("query refused");
	    case NOCHANGE:	return("no change");
	}

	return("unknown error");
}

/*
** PRINT_ANSWER -- Print result status after nameserver query
** ----------------------------------------------------------
**
**	Returns:
**		None.
**
**	Conditions:
**		The size of the answer buffer must have been
**		checked before to be of sufficient length,
**		i.e. to contain at least the buffer header.
*/

void
print_answer(answerbuf, answerlen)
input querybuf *answerbuf;		/* location of answer buffer */
input int answerlen;			/* length of answer buffer */
{
	HEADER *bp;
	int ancount;
	bool failed;

	bp = (HEADER *)answerbuf;
	ancount = ntohs((u_short)bp->ancount);
	failed = (bp->rcode != NOERROR || ancount == 0);

	printf("%s", verbose ? "" : dbprefix);

	printf("Query %s", failed ? "failed" : "done");

	if (bp->tc || (answerlen > PACKETSZ))
		printf(", %d byte%s", answerlen, plural(answerlen));

	if (bp->tc)
	{
		if (answerlen > sizeof(querybuf))
			printf(" (truncated to %d)", sizeof(querybuf));
		else
			printf(" (truncated)");
	}

	printf(", %d answer%s", ancount, plural(ancount));

	printf(", %s", bp->aa ? "authoritative " : "");

	printf("status: %s\n", decode_error((int)bp->rcode));
}

/*
** PR_ERROR -- Print error message about encountered inconsistencies
** -----------------------------------------------------------------
**
**	We are supposed to have an error condition which is fatal
**	for normal continuation, and the message is always printed.
**
**	Returns:
**		None.
**
**	Side effects:
**		Increments the global error count.
*/

void /*VARARGS1*/
pr_error(fmt, a, b, c, d)
input char *fmt;			/* format of message */
input char *a, *b, *c, *d;		/* optional arguments */
{
	(void) fprintf(stderr, " *** ");
	(void) fprintf(stderr, fmt, a, b, c, d);
	(void) fprintf(stderr, "\n");

	/* flag an error */
	errorcount++;
}

/*
** PR_WARNING -- Print warning message about encountered inconsistencies
** ---------------------------------------------------------------------
**
**	We are supposed to have an error condition which is non-fatal
**	for normal continuation, and the message is suppressed in case
**	quiet mode has been selected.
**
**	Returns:
**		None.
*/

void /*VARARGS1*/
pr_warning(fmt, a, b, c, d)
input char *fmt;			/* format of message */
input char *a, *b, *c, *d;		/* optional arguments */
{
	if (!quiet)
	{
		(void) fprintf(stderr, " !!! ");
		(void) fprintf(stderr, fmt, a, b, c, d);
		(void) fprintf(stderr, "\n");
	}
}

/*
** PR_TIMESTAMP -- Print timestamps for special debugging
** ------------------------------------------------------
**
**	Returns:
**		None.
*/

void /*VARARGS1*/
pr_timestamp(fmt, a, b, c, d)
input char *fmt;			/* format of message */
input char *a, *b, *c, *d;		/* optional arguments */
{
	if (timing)
	{
		time_t now = time((time_t *)NULL);

		(void) fprintf(stderr, " @@@ ");
		(void) fprintf(stderr, "%s ", pr_date((int)now));
		(void) fprintf(stderr, fmt, a, b, c, d);
		(void) fprintf(stderr, "\n");
	}
}

/*
** WANT_TYPE -- Indicate whether the rr type matches the desired filter
** --------------------------------------------------------------------
**
**	Returns:
**		TRUE if the resource record type matches the filter.
**		FALSE otherwise.
**
**	In regular mode, the querytype is used to formulate the query,
**	and the filter is set to T_ANY to filter out any response.
**	In listmode, we get everything, so the filter is set to the
**	querytype to filter out the proper responses.
**	Note that T_NONE is the default querytype in listmode.
*/

bool
want_type(type, filter)
input int type;				/* resource record type */
input int filter;			/* type of records we want to see */
{
	if (type == filter)
		return(TRUE);

	if (filter == T_ANY)
		return(TRUE);

	if (filter == T_NONE &&
	   (type == T_A || type == T_NS || type == T_PTR))
		return(TRUE);

	if (filter == T_MAILB &&
	   (type == T_MB || type == T_MR || type == T_MG || type == T_MINFO))
		return(TRUE);

	if (filter == T_MAILA &&
	   (type == T_MD || type == T_MF))
		return(TRUE);

	return(FALSE);
}

/*
** WANT_CLASS -- Indicate whether the rr class matches the desired filter
** ----------------------------------------------------------------------
**
**	Returns:
**		TRUE if the resource record class matches the filter.
**		FALSE otherwise.
**
**	In regular mode, the queryclass is used to formulate the query,
**	and the filter is set to C_ANY to filter out any response.
**	In listmode, we get everything, so the filter is set to the
**	queryclass to filter out the proper responses.
**	Note that C_IN is the default queryclass in listmode.
*/

bool
want_class(class, filter)
input int class;			/* resource record class */
input int filter;			/* class of records we want to see */
{
	if (class == filter)
		return(TRUE);

	if (filter == C_ANY)
		return(TRUE);

	return(FALSE);
}

/*
** INDOMAIN -- Check whether a name belongs to a zone
** --------------------------------------------------
**
**	Returns:
**		TRUE if the given name lies anywhere in the zone, or
**		if the given name is the same as the zone and may be so.
**		FALSE otherwise.
*/

bool
indomain(name, domain, equal)
input char *name;			/* the name under consideration */
input char *domain;			/* the name of the zone */
input bool equal;			/* set if name may be same as zone */
{
	register char *dot;

	if (sameword(name, domain))
		return(equal);

	if (sameword(domain, "."))
		return(TRUE);

	dot = index(name, '.');
	while (dot != NULL)
	{
		if (!is_quoted(dot, name))
		{
			if (sameword(dot+1, domain))
				return(TRUE);
		}

		dot = index(dot+1, '.');
	}

	return(FALSE);
}

/*
** SAMEDOMAIN -- Check whether a name belongs to a zone
** ----------------------------------------------------
**
**	Returns:
**		TRUE if the given name lies directly in the zone, or
**		if the given name is the same as the zone and may be so.
**		FALSE otherwise.
*/

bool
samedomain(name, domain, equal)
input char *name;			/* the name under consideration */
input char *domain;			/* the name of the zone */
input bool equal;			/* set if name may be same as zone */
{
	register char *dot;

	if (sameword(name, domain))
		return(equal);

	dot = index(name, '.');
	while (dot != NULL)
	{
		if (!is_quoted(dot, name))
		{
			if (sameword(dot+1, domain))
				return(TRUE);

			return(FALSE);
		}

		dot = index(dot+1, '.');
	}

	if (sameword(domain, "."))
		return(TRUE);

	return(FALSE);
}

/*
** GLUERECORD -- Check whether a name is a glue record
** ---------------------------------------------------
**
**	Returns:
**		TRUE is this is a glue record.
**		FALSE otherwise.
**
**	The name is supposed to be the name of an address record.
**	If it lies directly in the given zone, it is considered
**	an ordinary host within that zone, and not a glue record.
**	If it does not belong to the given zone at all, is it
**	here considered to be a glue record.
**	If it lies in the given zone, but not directly, it is
**	considered a glue record if it belongs to any of the known
**	delegated zones of the given zone.
**	In the root zone itself are no hosts, only glue records.
*/

bool
gluerecord(name, domain, zone, nzones)
input char *name;			/* the name under consideration */
input char *domain;			/* name of zone being processed */
input char *zone[];			/* list of known delegated zones */
input int nzones;			/* number of known delegated zones */
{
	register char *dot;
	register int n;

	if (sameword(domain, "."))
		return(TRUE);

	if (samedomain(name, domain, TRUE))
		return(FALSE);

	if (!indomain(name, domain, TRUE))
		return(TRUE);

	if (zone == NULL)
		return(FALSE);

#ifdef obsolete
	for (n = 0; n < nzones; n++)
		if (indomain(name, zone[n], TRUE))
			return(TRUE);
#endif

	n = zone_index(name, FALSE);
	if (n < nzones)
		return(TRUE);

	dot = index(name, '.');
	while (dot != NULL)
	{
		if (!is_quoted(dot, name))
		{
			n = zone_index(dot+1, FALSE);
			if (n < nzones)
				return(TRUE);
		}

		dot = index(dot+1, '.');
	}

	return(FALSE);
}

/*
** MATCHLABELS -- Determine number of matching domain name labels
** --------------------------------------------------------------
**
**	Returns:
**		Number of shared trailing label components in both names.
**
**	Note. This routine is currently used only to compare nameserver
**	names in the RHS of NS records, so there is no need to check
**	for embedded quoted dots.
*/

int
matchlabels(name, domain)
input char *name;			/* domain name to check */
input char *domain;			/* domain name to compare against */
{
	register int i, j;
	int matched = 0;

	i = strlength(name);
	j = strlength(domain);

	while (--i >= 0 && --j >= 0)
	{
		if (lowercase(name[i]) != lowercase(domain[j]))
			break;
		if (domain[j] == '.')
			matched++;
		else if (j == 0 && (i == 0 || name[i-1] == '.'))
			matched++;
	}

	return(matched);
}

/*
** PR_DOMAIN -- Convert domain name according to printing options
** --------------------------------------------------------------
**
**	Returns:
**		Pointer to new domain name, if conversion was done.
**		Pointer to original name, if no conversion necessary.
*/

char *
pr_domain(name, listing)
input char *name;			/* domain name to be printed */
input bool listing;			/* set if this is a zone listing */
{
	char *newname;			/* converted domain name */

/*
 * Print reverse nsap.int name in forward notation, unless prohibited.
 */
	if (revnsap && !dotprint)
	{
		newname = pr_nsap(name);
		if (newname != name)
			return(newname);
	}

/*
 * Print domain names with trailing dot if necessary.
 */
	if (listing || dotprint)
	{
		newname = pr_dotname(name);
		if (newname != name)
			return(newname);
	}

/*
 * No conversion was required, use original name.
 */
	return(name);
}

/*
** PR_DOTNAME -- Return domain name with trailing dot
** --------------------------------------------------
**
**	Returns:
**		Pointer to new domain name, if dot was added.
**		Pointer to original name, if dot was already present.
*/

char *
pr_dotname(name)
input char *name;			/* domain name to append to */
{
	static char buf[MAXDNAME+2];	/* buffer to store new domain name */
	register int n;

	n = strlength(name);
	if (n > 0 && name[n-1] == '.')
		return(name);

	if (n > MAXDNAME)
		n = MAXDNAME;

#ifdef obsolete
	(void) sprintf(buf, "%.*s.", MAXDNAME, name);
#endif
	bcopy(name, buf, n);
	buf[n] = '.';
	buf[n+1] = '\0';
	return(buf);
}

/*
** PR_NSAP -- Convert reverse nsap.int to dotted forward notation
** --------------------------------------------------------------
**
**	Returns:
**		Pointer to new dotted nsap, if converted.
**		Pointer to original name otherwise.
*/

char *
pr_nsap(name)
input char *name;			/* potential reverse nsap.int name */
{
	static char buf[3*MAXNSAP+1];
	register char *p;
	register int n;
	register int i;

	/* must begin with single hex digits separated by dots */
	for (i = 0; is_xdigit(name[i]) && name[i+1] == '.'; i += 2)
		continue;

	/* must have an even number of hex digits */ 
	if (i == 0 || (i % 4) != 0)
		return(name);

	/* but not too many */
	if (i > 4*MAXNSAP)
		return(name);

	/* must end in the appropriate root domain */
	if (!sameword(&name[i], NSAP_ROOT))
		return(name);

	for (p = buf, n = 0; i >= 4; i -= 4, n++)
	{
		*p++ = name[i-2];
		*p++ = name[i-4];

		/* add dots for readability */
		if ((n % 2) == 0 && (i - 4) > 0)
			*p++ = '.';
	}
	*p = '\0';

	return(buf);
}

/*
** PR_TYPE -- Return name of resource record type
** ----------------------------------------------
**
**	Returns:
**		Pointer to name of resource record type.
**
**	Note.	All possible (even obsolete) types are recognized.
*/

char *
pr_type(type)
input int type;				/* resource record type */
{
	static char buf[30];		/* sufficient for 64-bit values */

	switch (type)
	{
		/* standard types */

	    case T_A:       return("A");	/* internet address */
	    case T_NS:      return("NS");	/* authoritative server */
	    case T_MD:      return("MD");	/* mail destination */
	    case T_MF:      return("MF");	/* mail forwarder */
	    case T_CNAME:   return("CNAME");	/* canonical name */
	    case T_SOA:     return("SOA");	/* start of auth zone */
	    case T_MB:      return("MB");	/* mailbox domain name */
	    case T_MG:      return("MG");	/* mail group member */
	    case T_MR:      return("MR");	/* mail rename name */
	    case T_NULL:    return("NULL");	/* null resource record */
	    case T_WKS:     return("WKS");	/* well known service */
	    case T_PTR:     return("PTR");	/* domain name pointer */
	    case T_HINFO:   return("HINFO");	/* host information */
	    case T_MINFO:   return("MINFO");	/* mailbox information */
	    case T_MX:      return("MX");	/* mail routing info */
	    case T_TXT:     return("TXT");	/* descriptive text */

		/* new types */

	    case T_RP:      return("RP");	/* responsible person */
	    case T_AFSDB:   return("AFSDB");	/* afs database location */
	    case T_X25:     return("X25");	/* x25 address */
	    case T_ISDN:    return("ISDN");	/* isdn address */
	    case T_RT:      return("RT");	/* route through host */
	    case T_NSAP:    return("NSAP");	/* nsap address */
	    case T_NSAPPTR: return("NSAP-PTR");	/* nsap pointer */
	    case T_SIG:     return("SIG");	/* security signature */
	    case T_KEY:     return("KEY");	/* security key */
	    case T_PX:      return("PX");	/* rfc822 - x400 mapping */
	    case T_GPOS:    return("GPOS");	/* geographical position */
	    case T_AAAA:    return("AAAA");	/* ip v6 address */
	    case T_LOC:     return("LOC");	/* geographical location */
	    case T_NXT:     return("NXT");	/* next valid name */
	    case T_EID:     return("EID");	/* endpoint identifier */
	    case T_NIMLOC:  return("NIMLOC");	/* nimrod locator */
	    case T_SRV:     return("SRV");	/* service info */
	    case T_ATMA:    return("ATMA");	/* atm address */
	    case T_NAPTR:   return("NAPTR");	/* naming authority urn */
	    case T_KX:      return("KX");	/* key exchange info */
	    case T_CERT:    return("CERT");	/* security certificate */
	    case T_A6:      return("A6");
	    case T_DNAME:   return("DNAME");
	    case T_SINK:    return("SINK");
	    case T_OPT:     return("OPT");

		/* nonstandard types */

	    case T_UINFO:   return("UINFO");	/* user information */
	    case T_UID:     return("UID");	/* user ident */
	    case T_GID:     return("GID");	/* group ident */
	    case T_UNSPEC:  return("UNSPEC");	/* unspecified binary data */

		/* special types */

	    case T_ADDRS:   return("ADDRS");
	    case T_TKEY:    return("TKEY");	/* transaction key */
	    case T_TSIG:    return("TSIG");	/* transaction signature */

		/* filters */

	    case T_IXFR:    return("IXFR");	/* incremental zone transfer */
	    case T_AXFR:    return("AXFR");	/* zone transfer */
	    case T_MAILB:   return("MAILB");	/* matches MB/MR/MG/MINFO */
	    case T_MAILA:   return("MAILA");	/* matches MD/MF */
	    case T_ANY:     return("ANY");	/* matches any type */

	    case T_NONE:    return("resource");	/* not yet determined */
	}

	/* unknown type */
	(void) sprintf(buf, "%d", type);
	return(buf);
}

/*
** PR_CLASS -- Return name of resource record class
** ------------------------------------------------
**
**	Returns:
**		Pointer to name of resource record class.
*/

char *
pr_class(class)
input int class;			/* resource record class */
{
	static char buf[30];		/* sufficient for 64-bit values */

	switch (class)
	{
	    case C_IN:      return("IN");	/* internet */
	    case C_CSNET:   return("CS");	/* csnet */
	    case C_CHAOS:   return("CH");	/* chaosnet */
	    case C_HS:      return("HS");	/* hesiod */
	    case C_ANY:     return("ANY");	/* any class */
	}

	/* unknown class */
	(void) sprintf(buf, "%d", class);
	return(buf);
}

/*
** EXPAND_NAME -- Expand compressed domain name in a resource record
** -----------------------------------------------------------------
**
**	Returns:
**		Number of bytes advanced in answer buffer.
**		-1 if there was a format error.
**
**	It is assumed that the specified buffer is of a fixed size
**	MAXDNAME+1 that should be sufficient to store the data.
*/

int
expand_name(name, type, cp, msg, eom, namebuf)
input char *name;			/* name of resource record */
input int type;				/* type of resource record */
input u_char *cp;			/* current position in answer buf */
input u_char *msg, *eom;		/* begin and end of answer buf */
output char *namebuf;			/* location of buf to expand name in */
{
	register int n;

	n = dn_expand(msg, eom, cp, (nbuf_t *)namebuf, MAXDNAME);
	if (n < 0)
	{
		pr_error("expand error in %s record for %s, offset %s",
			pr_type(type), name, dtoa(cp - msg));
		seth_errno(NO_RECOVERY);
		return(-1);
	}

	/* should not be necessary, but who knows */
	namebuf[MAXDNAME] = '\0';

	/* change root to single dot */
	if (namebuf[0] == '\0')
	{
		namebuf[0] = '.';
		namebuf[1] = '\0';
	}

	return(n);
}

/*
** CHECK_SIZE -- Check whether resource record is of sufficient length
** -------------------------------------------------------------------
**
**	Returns:
**		Requested size if current record is long enough.
**		-1 if current record does not have this many bytes.
**
**	Note that HINFO records are very often incomplete since only
**	one of the two data fields has been filled in and the second
**	field is missing. So we generate only a warning message.
*/

int
check_size(name, type, cp, msg, eor, size)
input char *name;			/* name of resource record */
input int type;				/* type of resource record */
input u_char *cp;			/* current position in answer buf */
input u_char *msg;			/* begin of answer buf */
input u_char *eor;			/* predicted position of next record */
input int size;				/* required record size remaining */
{
	if (cp + size > eor)
	{
		if (type != T_HINFO)
			pr_error("incomplete %s record for %s, offset %s",
				pr_type(type), name, dtoa(cp - msg));
		else
			pr_warning("incomplete %s record for %s",
				pr_type(type), name);
		seth_errno(NO_RECOVERY);
		return(-1);
	}

	return(size);
}

/*
** VALID_NAME -- Check whether domain name contains invalid characters
** -------------------------------------------------------------------
**
**	Returns:
**		TRUE if the name is valid.
**		FALSE otherwise.
**
**	The total size of a compound name should not exceed MAXDNAME.
**	We assume that this is true. Its individual components between
**	dots should not be longer than 64. This is not checked here.
**
**	Only alphanumeric characters and dash '-' may be used (dash
**	only in the middle). We only check the individual characters.
**	Strictly speaking, this restriction is only for ``host names''.
**	The underscore is illegal, at least not recommended, but is
**	so abundant that it requires special processing.
**
**	If the domain name represents a mailbox specification, the
**	first label up to the first (unquoted) dot is the local part
**	of a mail address, which should adhere to the RFC 822 specs.
**	This first dot takes the place of the RFC 822 '@' sign.
**
**	The label '*' can in principle be used anywhere to indicate
**	wildcarding. It is valid only in the LHS resource record name,
**	in definitions in zone files only as the first component.
**	Used primarily in wildcard MX record definitions.
**
**	Note. This routine is much too liberal.
*/

char *specials = ".()<>@,;:\\\"[]";	/* RFC 822 specials */

bool
valid_name(name, wildcard, localpart, underscore)
input char *name;			/* domain name to check */
input bool wildcard;			/* set if wildcard is allowed */
input bool localpart;			/* set if this is a mailbox spec */
input bool underscore;			/* set if underscores are allowed */
{
	bool backslash = FALSE;
	bool quoting = FALSE;
	register char *p;
	register char c;

	for (p = name; (c = *p) != '\0'; p++)
	{
		/* special check for local part in mailbox */
		if (localpart)
		{
			if (backslash)
				backslash = FALSE;	/* escape this char */
			else if (c == '\\')
				backslash = TRUE;	/* escape next char */
			else if (c == '"')
				quoting = !quoting;	/* start/stop quoting */
			else if (quoting)
				continue;		/* allow quoted chars */
			else if (c == '.')
				localpart = FALSE;	/* instead of '@' */
			else if (c == '@')
				return(FALSE);		/* should be '.' */
			else if (in_string(specials, c))
				return(FALSE);		/* must be escaped */
			else if (is_space(c))
				return(FALSE);		/* must be escaped */
			continue;
		}

		/* basic character set */
		if (is_alnum(c) || ((c == '-') && in_label(p, name)))
			continue;

		/* start of a new label component */
		if ((c == '.') && in_label(p, name))
			continue;

		/* allow '*' for use in wildcard names */
		if ((c == '*') && (p == name && p[1] == '.') && wildcard)
			continue;

		/* ignore underscore in certain circumstances */
		if ((c == '_') && underscore && !illegal)
			continue;

		/* silently allowed widespread exceptions */
		if (illegal && in_string(illegal, c))
			continue;

		return(FALSE);
	}

	/* must be beyond the local part in a mailbox */
	if (localpart)
		return(FALSE);

	/* cannot be a dotted quad */
	if (inet_addr(name) != NOT_DOTTED_QUAD)
		return(FALSE);

	/* all tests passed */
	return(TRUE);
}

/* 
** CANONICAL -- Check whether domain name is a canonical host name
** ---------------------------------------------------------------
**
**	Returns:
**		Nonzero if the name is definitely not canonical.
**		0 if it is canonical, or if it remains undecided.
*/

int
canonical(name)
input char *name;			/* the domain name to check */
{
	struct hostent *hp;
	int status;
	int save_errno;
	int save_herrno;
	
/*
 * Preserve state when querying, to avoid clobbering current values.
 */
	save_errno = errno;
	save_herrno = h_errno;

	hp = geth_byname(name);
	status = h_errno;

	seterrno(save_errno);
	seth_errno(save_herrno);

/*
 * Indicate negative result only after definitive lookup failures.
 */
	if (hp == NULL)
	{
		/* authoritative denial -- not existing or no A record */
		if (status == NO_DATA || status == HOST_NOT_FOUND)
			return(status);

		/* nameserver failure -- still undecided, assume ok */
		return(0);
	}

/*
 * The given name exists and there is an associated A record.
 * The name of this A record should be the name we queried about.
 * If this is not the case we probably supplied a CNAME.
 */
	status = sameword(hp->h_name, name) ? 0 : HOST_NOT_CANON;
	return(status);
}

/* 
** MAPREVERSE -- Check whether address maps back to given domain
** -------------------------------------------------------------
**
**	Returns:
**		NULL if address could definitively not be mapped.
**		Given name if the address maps back properly, or
**		in case of transient nameserver failures.
**		Reverse name if it differs from the given name.
*/

char *
mapreverse(name, inaddr)
input char *name;			/* domain name of A record */
input struct in_addr inaddr;		/* address of A record to check */
{
	struct hostent *hp;
	int status;
	int save_errno;
	int save_herrno;
	register int i;
	
/*
 * Preserve state when querying, to avoid clobbering current values.
 */
	save_errno = errno;
	save_herrno = h_errno;

	hp = geth_byaddr((char *)&inaddr, INADDRSZ, AF_INET);
	status = h_errno;

	seterrno(save_errno);
	seth_errno(save_herrno);

/*
 * Indicate negative result only after definitive lookup failures.
 */
	if (hp == NULL)
	{
		/* authoritative denial -- not existing or no PTR record */
		if (status == NO_DATA || status == HOST_NOT_FOUND)
			return(NULL);

		/* nameserver failure -- still undecided, assume ok */
		return(name);
	}

/*
 * Check whether the ``official'' host name matches.
 * This is the name in the first (or only) PTR record encountered.
 */
	if (sameword(hp->h_name, name))
		return(name);

/*
 * If not, a match may be found among the aliases.
 * They are available (as of BIND 4.9) in case multipe PTR records are used.
 */
	for (i = 0; hp->h_aliases[i]; i++)
	{
		if (sameword(hp->h_aliases[i], name))
			return(name);
	}

/*
 * The reverse mapping did not yield the given name.
 */
	return((char *)hp->h_name);
}

/* 
** ANYRECORD -- Check whether domain name has any resource records
** ---------------------------------------------------------------
**
**	Returns:
**		Nonzero if there are no resource records available.
**		0 if there are, or if it remains undecided.
*/

int
anyrecord(name)
input char *name;			/* the domain name to check */
{
	querybuf answer;
	register int n;
	int status;
	int save_errno;
	int save_herrno;
	
/*
 * Preserve state when querying, to avoid clobbering current values.
 */
	save_errno = errno;
	save_herrno = h_errno;

	n = get_info(&answer, name, T_ANY, queryclass);
	status = h_errno;

	seterrno(save_errno);
	seth_errno(save_herrno);

/*
 * Indicate negative result only after definitive lookup failures.
 */
	if (n < 0)
	{
		/* authoritative denial -- not existing or no ANY record */
		if (status == NO_DATA || status == HOST_NOT_FOUND)
			return(status);

		/* nameserver failure -- still undecided, assume ok */
		return(0);
	}

/*
 * The domain name exists, and there are resource records available.
 */
	return(0);
}

/* 
** COMPARE_NAME -- Compare two names wrt alphabetical order
** --------------------------------------------------------
**
**	Returns:
**		Value of case-insensitive comparison.
*/

int
compare_name(a, b)
input const ptr_t *a;			/* first name */
input const ptr_t *b;			/* second name */
{
	return(strcasecmp(*(char **)a, *(char **)b));
}