xref: /titanic_51/usr/src/lib/libresolv2/common/resolv/res_debug.c (revision 37714ae43602c675f9dc59b070bfdf9fa702872c)
1 /*
2  * Copyright 2003 Sun Microsystems, Inc.  All rights reserved.
3  * Use is subject to license terms.
4  */
5 
6 /*
7  * Copyright (c) 1985
8  *    The Regents of the University of California.  All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  * 	This product includes software developed by the University of
21  * 	California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  */
38 
39 /*
40  * Portions Copyright (c) 1993 by Digital Equipment Corporation.
41  *
42  * Permission to use, copy, modify, and distribute this software for any
43  * purpose with or without fee is hereby granted, provided that the above
44  * copyright notice and this permission notice appear in all copies, and that
45  * the name of Digital Equipment Corporation not be used in advertising or
46  * publicity pertaining to distribution of the document or software without
47  * specific, written prior permission.
48  *
49  * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
50  * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
51  * OF MERCHANTABILITY AND FITNESS.   IN NO EVENT SHALL DIGITAL EQUIPMENT
52  * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
53  * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
54  * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
55  * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
56  * SOFTWARE.
57  */
58 
59 /*
60  * Portions Copyright (c) 1995 by International Business Machines, Inc.
61  *
62  * International Business Machines, Inc. (hereinafter called IBM) grants
63  * permission under its copyrights to use, copy, modify, and distribute this
64  * Software with or without fee, provided that the above copyright notice and
65  * all paragraphs of this notice appear in all copies, and that the name of IBM
66  * not be used in connection with the marketing of any product incorporating
67  * the Software or modifications thereof, without specific, written prior
68  * permission.
69  *
70  * To the extent it has a right to do so, IBM grants an immunity from suit
71  * under its patents, if any, for the use, sale or manufacture of products to
72  * the extent that such products are used for performing Domain Name System
73  * dynamic updates in TCP/IP networks by means of the Software.  No immunity is
74  * granted for any product per se or for any other function of any product.
75  *
76  * THE SOFTWARE IS PROVIDED "AS IS", AND IBM DISCLAIMS ALL WARRANTIES,
77  * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
78  * PARTICULAR PURPOSE.  IN NO EVENT SHALL IBM BE LIABLE FOR ANY SPECIAL,
79  * DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER ARISING
80  * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE, EVEN
81  * IF IBM IS APPRISED OF THE POSSIBILITY OF SUCH DAMAGES.
82  */
83 
84 /*
85  * Portions Copyright (c) 1996-1999 by Internet Software Consortium.
86  *
87  * Permission to use, copy, modify, and distribute this software for any
88  * purpose with or without fee is hereby granted, provided that the above
89  * copyright notice and this permission notice appear in all copies.
90  *
91  * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS
92  * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
93  * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE
94  * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
95  * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
96  * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
97  * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
98  * SOFTWARE.
99  */
100 
101 #pragma ident	"%Z%%M%	%I%	%E% SMI"
102 
103 #if defined(LIBC_SCCS) && !defined(lint)
104 static const char sccsid[] = "@(#)res_debug.c	8.1 (Berkeley) 6/4/93";
105 static const char rcsid[] = "$Id: res_debug.c,v 8.50 2003/04/16 04:55:40 marka Exp $";
106 #endif /* LIBC_SCCS and not lint */
107 
108 #include "port_before.h"
109 
110 #include <sys/types.h>
111 #include <sys/param.h>
112 #include <sys/socket.h>
113 
114 #include <netinet/in.h>
115 #include <arpa/inet.h>
116 #include <arpa/nameser.h>
117 
118 #include <ctype.h>
119 #include <errno.h>
120 #include <math.h>
121 #include <netdb.h>
122 #include <resolv.h>
123 #include <stdio.h>
124 #include <stdlib.h>
125 #include <string.h>
126 #include <time.h>
127 
128 #include "port_after.h"
129 
130 #ifdef SPRINTF_CHAR
131 # define SPRINTF(x) strlen(sprintf/**/x)
132 #else
133 # define SPRINTF(x) sprintf x
134 #endif
135 
136 extern const char *_res_opcodes[];
137 extern const char *_res_sectioncodes[];
138 
139 #ifdef	ORIGINAL_ISC_CODE
140 #else
141 #pragma weak	__dn_count_labels	=	dn_count_labels
142 #pragma weak	__fp_resstat		=	fp_resstat
143 #pragma weak	__loc_aton		=	loc_aton
144 #pragma weak	__loc_ntoa		=	loc_ntoa
145 #pragma weak	__p_cdname		=	p_cdname
146 #pragma weak	__p_class		=	p_class
147 #pragma weak	__p_secstodate		=	p_secstodate
148 #pragma weak	__p_section		=	p_section
149 #pragma weak	__p_time		=	p_time
150 #pragma weak	__p_type		=	p_type
151 #pragma weak	__sym_ntop		=	sym_ntop
152 #pragma weak	__sym_ntos		=	sym_ntos
153 #pragma weak	__sym_ston		=	sym_ston
154 #endif	/* ORIGINAL_ISC_CODE */
155 
156 /*
157  * Print the current options.
158  */
159 void
160 fp_resstat(const res_state statp, FILE *file) {
161 	u_long mask;
162 
163 	fprintf(file, ";; res options:");
164 	for (mask = 1;  mask != 0;  mask <<= 1)
165 		if (statp->options & mask)
166 			fprintf(file, " %s", p_option(mask));
167 	putc('\n', file);
168 }
169 
170 static void
171 do_section(const res_state statp,
172 	   ns_msg *handle, ns_sect section,
173 	   int pflag, FILE *file)
174 {
175 	int n, sflag, rrnum;
176 	static int buflen = 2048;
177 	char *buf;
178 	ns_opcode opcode;
179 	ns_rr rr;
180 
181 	/*
182 	 * Print answer records.
183 	 */
184 	sflag = (statp->pfcode & pflag);
185 	if (statp->pfcode && !sflag)
186 		return;
187 
188 	buf = malloc(buflen);
189 	if (buf == NULL) {
190 		fprintf(file, ";; memory allocation failure\n");
191 		return;
192 	}
193 
194 	opcode = (ns_opcode) ns_msg_getflag(*handle, ns_f_opcode);
195 	rrnum = 0;
196 	for (;;) {
197 		if (ns_parserr(handle, section, rrnum, &rr)) {
198 			if (errno != ENODEV)
199 				fprintf(file, ";; ns_parserr: %s\n",
200 					strerror(errno));
201 			else if (rrnum > 0 && sflag != 0 &&
202 				 (statp->pfcode & RES_PRF_HEAD1))
203 				putc('\n', file);
204 			goto cleanup;
205 		}
206 		if (rrnum == 0 && sflag != 0 && (statp->pfcode & RES_PRF_HEAD1))
207 			fprintf(file, ";; %s SECTION:\n",
208 				p_section(section, opcode));
209 		if (section == ns_s_qd)
210 			fprintf(file, ";;\t%s, type = %s, class = %s\n",
211 				ns_rr_name(rr),
212 				p_type(ns_rr_type(rr)),
213 				p_class(ns_rr_class(rr)));
214 		else if (section == ns_s_ar && ns_rr_type(rr) == ns_t_opt) {
215 			u_int32_t ttl = ns_rr_ttl(rr);
216 			fprintf(file,
217 				"; EDNS: version: %u, udp=%u, flags=%04x\n",
218 				(ttl>>16)&0xff, ns_rr_class(rr), ttl&0xffff);
219 		} else {
220 			n = ns_sprintrr(handle, &rr, NULL, NULL,
221 					buf, buflen);
222 			if (n < 0) {
223 				if (errno == ENOSPC) {
224 					free(buf);
225 					buf = NULL;
226 					if (buflen < 131072)
227 						buf = malloc(buflen += 1024);
228 					if (buf == NULL) {
229 						fprintf(file,
230 				              ";; memory allocation failure\n");
231 					      return;
232 					}
233 					continue;
234 				}
235 				fprintf(file, ";; ns_sprintrr: %s\n",
236 					strerror(errno));
237 				goto cleanup;
238 			}
239 			fputs(buf, file);
240 			fputc('\n', file);
241 		}
242 		rrnum++;
243 	}
244  cleanup:
245 	if (buf != NULL)
246 		free(buf);
247 }
248 
249 /*
250  * Print the contents of a query.
251  * This is intended to be primarily a debugging routine.
252  */
253 void
254 res_pquery(const res_state statp, const u_char *msg, int len, FILE *file) {
255 	ns_msg handle;
256 	int qdcount, ancount, nscount, arcount;
257 	u_int opcode, rcode, id;
258 
259 	if (ns_initparse(msg, len, &handle) < 0) {
260 		fprintf(file, ";; ns_initparse: %s\n", strerror(errno));
261 		return;
262 	}
263 	opcode = ns_msg_getflag(handle, ns_f_opcode);
264 	rcode = ns_msg_getflag(handle, ns_f_rcode);
265 	id = ns_msg_id(handle);
266 	qdcount = ns_msg_count(handle, ns_s_qd);
267 	ancount = ns_msg_count(handle, ns_s_an);
268 	nscount = ns_msg_count(handle, ns_s_ns);
269 	arcount = ns_msg_count(handle, ns_s_ar);
270 
271 	/*
272 	 * Print header fields.
273 	 */
274 	if ((!statp->pfcode) || (statp->pfcode & RES_PRF_HEADX) || rcode)
275 		fprintf(file,
276 			";; ->>HEADER<<- opcode: %s, status: %s, id: %d\n",
277 			_res_opcodes[opcode], p_rcode(rcode), id);
278 	if ((!statp->pfcode) || (statp->pfcode & RES_PRF_HEADX))
279 		putc(';', file);
280 	if ((!statp->pfcode) || (statp->pfcode & RES_PRF_HEAD2)) {
281 		fprintf(file, "; flags:");
282 		if (ns_msg_getflag(handle, ns_f_qr))
283 			fprintf(file, " qr");
284 		if (ns_msg_getflag(handle, ns_f_aa))
285 			fprintf(file, " aa");
286 		if (ns_msg_getflag(handle, ns_f_tc))
287 			fprintf(file, " tc");
288 		if (ns_msg_getflag(handle, ns_f_rd))
289 			fprintf(file, " rd");
290 		if (ns_msg_getflag(handle, ns_f_ra))
291 			fprintf(file, " ra");
292 		if (ns_msg_getflag(handle, ns_f_z))
293 			fprintf(file, " ??");
294 		if (ns_msg_getflag(handle, ns_f_ad))
295 			fprintf(file, " ad");
296 		if (ns_msg_getflag(handle, ns_f_cd))
297 			fprintf(file, " cd");
298 	}
299 	if ((!statp->pfcode) || (statp->pfcode & RES_PRF_HEAD1)) {
300 		fprintf(file, "; %s: %d",
301 			p_section(ns_s_qd, opcode), qdcount);
302 		fprintf(file, ", %s: %d",
303 			p_section(ns_s_an, opcode), ancount);
304 		fprintf(file, ", %s: %d",
305 			p_section(ns_s_ns, opcode), nscount);
306 		fprintf(file, ", %s: %d",
307 			p_section(ns_s_ar, opcode), arcount);
308 	}
309 	if ((!statp->pfcode) || (statp->pfcode &
310 		(RES_PRF_HEADX | RES_PRF_HEAD2 | RES_PRF_HEAD1))) {
311 		putc('\n',file);
312 	}
313 	/*
314 	 * Print the various sections.
315 	 */
316 	do_section(statp, &handle, ns_s_qd, RES_PRF_QUES, file);
317 	do_section(statp, &handle, ns_s_an, RES_PRF_ANS, file);
318 	do_section(statp, &handle, ns_s_ns, RES_PRF_AUTH, file);
319 	do_section(statp, &handle, ns_s_ar, RES_PRF_ADD, file);
320 	if (qdcount == 0 && ancount == 0 &&
321 	    nscount == 0 && arcount == 0)
322 		putc('\n', file);
323 }
324 
325 const u_char *
326 p_cdnname(const u_char *cp, const u_char *msg, int len, FILE *file) {
327 	char name[MAXDNAME];
328 	int n;
329 
330 	if ((n = dn_expand(msg, msg + len, cp, name, sizeof name)) < 0)
331 		return (NULL);
332 	if (name[0] == '\0')
333 		putc('.', file);
334 	else
335 		fputs(name, file);
336 	return (cp + n);
337 }
338 
339 const u_char *
340 p_cdname(const u_char *cp, const u_char *msg, FILE *file) {
341 	return (p_cdnname(cp, msg, PACKETSZ, file));
342 }
343 
344 /* Return a fully-qualified domain name from a compressed name (with
345    length supplied).  */
346 
347 const u_char *
348 p_fqnname(cp, msg, msglen, name, namelen)
349 	const u_char *cp, *msg;
350 	int msglen;
351 	char *name;
352 	int namelen;
353 {
354 	int n, newlen;
355 
356 	if ((n = dn_expand(msg, cp + msglen, cp, name, namelen)) < 0)
357 		return (NULL);
358 	newlen = strlen(name);
359 	if (newlen == 0 || name[newlen - 1] != '.') {
360 		if (newlen + 1 >= namelen)	/* Lack space for final dot */
361 			return (NULL);
362 		else
363 			strcpy(name + newlen, ".");
364 	}
365 	return (cp + n);
366 }
367 
368 /* XXX:	the rest of these functions need to become length-limited, too. */
369 
370 const u_char *
371 p_fqname(const u_char *cp, const u_char *msg, FILE *file) {
372 	char name[MAXDNAME];
373 	const u_char *n;
374 
375 	n = p_fqnname(cp, msg, MAXCDNAME, name, sizeof name);
376 	if (n == NULL)
377 		return (NULL);
378 	fputs(name, file);
379 	return (n);
380 }
381 
382 /*
383  * Names of RR classes and qclasses.  Classes and qclasses are the same, except
384  * that C_ANY is a qclass but not a class.  (You can ask for records of class
385  * C_ANY, but you can't have any records of that class in the database.)
386  */
387 const struct res_sym __p_class_syms[] = {
388 	{C_IN,		"IN",		(char *)0},
389 	{C_CHAOS,	"CHAOS",	(char *)0},
390 	{C_HS,		"HS",		(char *)0},
391 	{C_HS,		"HESIOD",	(char *)0},
392 	{C_ANY,		"ANY",		(char *)0},
393 	{C_NONE,	"NONE",		(char *)0},
394 	{C_IN, 		(char *)0,	(char *)0}
395 };
396 
397 /*
398  * Names of message sections.
399  */
400 const struct res_sym __p_default_section_syms[] = {
401 	{ns_s_qd,	"QUERY",	(char *)0},
402 	{ns_s_an,	"ANSWER",	(char *)0},
403 	{ns_s_ns,	"AUTHORITY",	(char *)0},
404 	{ns_s_ar,	"ADDITIONAL",	(char *)0},
405 	{0,             (char *)0,	(char *)0}
406 };
407 
408 const struct res_sym __p_update_section_syms[] = {
409 	{S_ZONE,	"ZONE",		(char *)0},
410 	{S_PREREQ,	"PREREQUISITE",	(char *)0},
411 	{S_UPDATE,	"UPDATE",	(char *)0},
412 	{S_ADDT,	"ADDITIONAL",	(char *)0},
413 	{0,             (char *)0,	(char *)0}
414 };
415 
416 const struct res_sym __p_key_syms[] = {
417 	{NS_ALG_MD5RSA,		"RSA",		"RSA KEY with MD5 hash"},
418 	{NS_ALG_DH,		"DH",		"Diffie Hellman"},
419 	{NS_ALG_DSA,		"DSA",		"Digital Signature Algorithm"},
420 	{NS_ALG_EXPIRE_ONLY,	"EXPIREONLY",	"No algorithm"},
421 	{NS_ALG_PRIVATE_OID,	"PRIVATE",	"Algorithm obtained from OID"},
422 	{0,			NULL,		NULL}
423 };
424 
425 const struct res_sym __p_cert_syms[] = {
426 	{cert_t_pkix,	"PKIX",		"PKIX (X.509v3) Certificate"},
427 	{cert_t_spki,	"SPKI",		"SPKI certificate"},
428 	{cert_t_pgp,	"PGP",		"PGP certificate"},
429 	{cert_t_url,	"URL",		"URL Private"},
430 	{cert_t_oid,	"OID",		"OID Private"},
431 	{0,		NULL,		NULL}
432 };
433 
434 /*
435  * Names of RR types and qtypes.  Types and qtypes are the same, except
436  * that T_ANY is a qtype but not a type.  (You can ask for records of type
437  * T_ANY, but you can't have any records of that type in the database.)
438  */
439 const struct res_sym __p_type_syms[] = {
440 	{ns_t_a,	"A",		"address"},
441 	{ns_t_ns,	"NS",		"name server"},
442 	{ns_t_md,	"MD",		"mail destination (deprecated)"},
443 	{ns_t_mf,	"MF",		"mail forwarder (deprecated)"},
444 	{ns_t_cname,	"CNAME",	"canonical name"},
445 	{ns_t_soa,	"SOA",		"start of authority"},
446 	{ns_t_mb,	"MB",		"mailbox"},
447 	{ns_t_mg,	"MG",		"mail group member"},
448 	{ns_t_mr,	"MR",		"mail rename"},
449 	{ns_t_null,	"NULL",		"null"},
450 	{ns_t_wks,	"WKS",		"well-known service (deprecated)"},
451 	{ns_t_ptr,	"PTR",		"domain name pointer"},
452 	{ns_t_hinfo,	"HINFO",	"host information"},
453 	{ns_t_minfo,	"MINFO",	"mailbox information"},
454 	{ns_t_mx,	"MX",		"mail exchanger"},
455 	{ns_t_txt,	"TXT",		"text"},
456 	{ns_t_rp,	"RP",		"responsible person"},
457 	{ns_t_afsdb,	"AFSDB",	"DCE or AFS server"},
458 	{ns_t_x25,	"X25",		"X25 address"},
459 	{ns_t_isdn,	"ISDN",		"ISDN address"},
460 	{ns_t_rt,	"RT",		"router"},
461 	{ns_t_nsap,	"NSAP",		"nsap address"},
462 	{ns_t_nsap_ptr,	"NSAP_PTR",	"domain name pointer"},
463 	{ns_t_sig,	"SIG",		"signature"},
464 	{ns_t_key,	"KEY",		"key"},
465 	{ns_t_px,	"PX",		"mapping information"},
466 	{ns_t_gpos,	"GPOS",		"geographical position (withdrawn)"},
467 	{ns_t_aaaa,	"AAAA",		"IPv6 address"},
468 	{ns_t_loc,	"LOC",		"location"},
469 	{ns_t_nxt,	"NXT",		"next valid name (unimplemented)"},
470 	{ns_t_eid,	"EID",		"endpoint identifier (unimplemented)"},
471 	{ns_t_nimloc,	"NIMLOC",	"NIMROD locator (unimplemented)"},
472 	{ns_t_srv,	"SRV",		"server selection"},
473 	{ns_t_atma,	"ATMA",		"ATM address (unimplemented)"},
474 	{ns_t_tkey,	"TKEY",		"tkey"},
475 	{ns_t_tsig,	"TSIG",		"transaction signature"},
476 	{ns_t_ixfr,	"IXFR",		"incremental zone transfer"},
477 	{ns_t_axfr,	"AXFR",		"zone transfer"},
478 	{ns_t_zxfr,	"ZXFR",		"compressed zone transfer"},
479 	{ns_t_mailb,	"MAILB",	"mailbox-related data (deprecated)"},
480 	{ns_t_maila,	"MAILA",	"mail agent (deprecated)"},
481 	{ns_t_naptr,	"NAPTR",	"URN Naming Authority"},
482 	{ns_t_kx,	"KX",		"Key Exchange"},
483 	{ns_t_cert,	"CERT",		"Certificate"},
484 	{ns_t_a6,	"A6",		"IPv6 Address"},
485 	{ns_t_dname,	"DNAME",	"dname"},
486 	{ns_t_sink,	"SINK",		"Kitchen Sink (experimental)"},
487 	{ns_t_opt,	"OPT",		"EDNS Options"},
488 	{ns_t_any,	"ANY",		"\"any\""},
489 	{0, 		NULL,		NULL}
490 };
491 
492 /*
493  * Names of DNS rcodes.
494  */
495 const struct res_sym __p_rcode_syms[] = {
496 	{ns_r_noerror,	"NOERROR",		"no error"},
497 	{ns_r_formerr,	"FORMERR",		"format error"},
498 	{ns_r_servfail,	"SERVFAIL",		"server failed"},
499 	{ns_r_nxdomain,	"NXDOMAIN",		"no such domain name"},
500 	{ns_r_notimpl,	"NOTIMP",		"not implemented"},
501 	{ns_r_refused,	"REFUSED",		"refused"},
502 	{ns_r_yxdomain,	"YXDOMAIN",		"domain name exists"},
503 	{ns_r_yxrrset,	"YXRRSET",		"rrset exists"},
504 	{ns_r_nxrrset,	"NXRRSET",		"rrset doesn't exist"},
505 	{ns_r_notauth,	"NOTAUTH",		"not authoritative"},
506 	{ns_r_notzone,	"NOTZONE",		"Not in zone"},
507 	{ns_r_max,	"",			""},
508 	{ns_r_badsig,	"BADSIG",		"bad signature"},
509 	{ns_r_badkey,	"BADKEY",		"bad key"},
510 	{ns_r_badtime,	"BADTIME",		"bad time"},
511 	{0, 		NULL,			NULL}
512 };
513 
514 int
515 sym_ston(const struct res_sym *syms, const char *name, int *success) {
516 	for ((void)NULL; syms->name != 0; syms++) {
517 		if (strcasecmp (name, syms->name) == 0) {
518 			if (success)
519 				*success = 1;
520 			return (syms->number);
521 		}
522 	}
523 	if (success)
524 		*success = 0;
525 	return (syms->number);		/* The default value. */
526 }
527 
528 const char *
529 sym_ntos(const struct res_sym *syms, int number, int *success) {
530 #ifdef	SUNW_MT_RESOLVER
531 	char	*unname = sym_ntos_unname;
532 #else
533 	static char unname[20];
534 #endif	/* SUNW_MT_RESOLVER */
535 
536 	for ((void)NULL; syms->name != 0; syms++) {
537 		if (number == syms->number) {
538 			if (success)
539 				*success = 1;
540 			return (syms->name);
541 		}
542 	}
543 
544 	sprintf(unname, "%d", number);		/* XXX nonreentrant */
545 	if (success)
546 		*success = 0;
547 	return (unname);
548 }
549 
550 const char *
551 sym_ntop(const struct res_sym *syms, int number, int *success) {
552 #ifdef	SUNW_MT_RESOLVER
553 	char	*unname = sym_ntop_unname;
554 #else
555 	static char unname[20];
556 #endif	/* SUNW_MT_RESOLVER */
557 
558 	for ((void)NULL; syms->name != 0; syms++) {
559 		if (number == syms->number) {
560 			if (success)
561 				*success = 1;
562 			return (syms->humanname);
563 		}
564 	}
565 	sprintf(unname, "%d", number);		/* XXX nonreentrant */
566 	if (success)
567 		*success = 0;
568 	return (unname);
569 }
570 
571 /*
572  * Return a string for the type.
573  */
574 const char *
575 p_type(int type) {
576 	int success;
577 	const char *result;
578 	static char typebuf[20];
579 
580 	result = sym_ntos(__p_type_syms, type, &success);
581 	if (success)
582 		return (result);
583 	if (type < 0 || type > 0xfff)
584 		return ("BADTYPE");
585 	sprintf(typebuf, "TYPE%d", type);
586 	return (typebuf);
587 }
588 
589 /*
590  * Return a string for the type.
591  */
592 const char *
593 p_section(int section, int opcode) {
594 	const struct res_sym *symbols;
595 
596 	switch (opcode) {
597 	case ns_o_update:
598 		symbols = __p_update_section_syms;
599 		break;
600 	default:
601 		symbols = __p_default_section_syms;
602 		break;
603 	}
604 	return (sym_ntos(symbols, section, (int *)0));
605 }
606 
607 /*
608  * Return a mnemonic for class.
609  */
610 const char *
611 p_class(int class) {
612 	int success;
613 	const char *result;
614 	static char classbuf[20];
615 
616 	result = sym_ntos(__p_class_syms, class, &success);
617 	if (success)
618 		return (result);
619 	if (class < 0 || class > 0xfff)
620 		return ("BADCLASS");
621 	sprintf(classbuf, "CLASS%d", class);
622 	return (classbuf);
623 }
624 
625 /*
626  * Return a mnemonic for an option
627  */
628 const char *
629 #ifdef	ORIGINAL_ISC_CODE
630 p_option(u_long option) {
631 #else
632 p_option(u_int option) {
633 #endif
634 #ifdef	SUNW_MT_RESOLVER
635 	char	*nbuf = p_option_nbuf;
636 #else
637 	static char nbuf[40];
638 #endif	/* SUNW_MT_RESOLVER */
639 
640 	switch (option) {
641 	case RES_INIT:		return "init";
642 	case RES_DEBUG:		return "debug";
643 	case RES_AAONLY:	return "aaonly(unimpl)";
644 	case RES_USEVC:		return "usevc";
645 	case RES_PRIMARY:	return "primry(unimpl)";
646 	case RES_IGNTC:		return "igntc";
647 	case RES_RECURSE:	return "recurs";
648 	case RES_DEFNAMES:	return "defnam";
649 	case RES_STAYOPEN:	return "styopn";
650 	case RES_DNSRCH:	return "dnsrch";
651 	case RES_INSECURE1:	return "insecure1";
652 	case RES_INSECURE2:	return "insecure2";
653 	case RES_NOALIASES:	return "noaliases";
654 	case RES_USE_INET6:	return "inet6";
655 #ifdef RES_USE_EDNS0	/* KAME extension */
656 	case RES_USE_EDNS0:	return "edns0";
657 #endif
658 #ifdef RES_USE_DNAME
659 	case RES_USE_DNAME:	return "dname";
660 #endif
661 #ifdef RES_USE_DNSSEC
662 	case RES_USE_DNSSEC:	return "dnssec";
663 #endif
664 #ifdef RES_NOTLDQUERY
665 	case RES_NOTLDQUERY:	return "no-tld-query";
666 #endif
667 #ifdef	ORIGINAL_ISC_CODE
668 				/* XXX nonreentrant */
669 	default:		sprintf(nbuf, "?0x%lx?", (u_long)option);
670 #else
671 	default:		sprintf(nbuf, "?0x%x?", (u_int)option);
672 #endif
673 				return (nbuf);
674 	}
675 }
676 
677 /*
678  * Return a mnemonic for a time to live.
679  */
680 const char *
681 p_time(u_int32_t value) {
682 #ifdef	SUNW_MT_RESOLVER
683 	char	*nbuf = p_time_nbuf;
684 #else
685 	static char nbuf[40];		/* XXX nonreentrant */
686 #endif	/* SUNW_MT_RESOLVER */
687 
688 	if (ns_format_ttl(value, nbuf, sizeof nbuf) < 0)
689 		sprintf(nbuf, "%u", value);
690 	return (nbuf);
691 }
692 
693 /*
694  * Return a string for the rcode.
695  */
696 const char *
697 p_rcode(int rcode) {
698 	return (sym_ntos(__p_rcode_syms, rcode, (int *)0));
699 }
700 
701 /*
702  * Return a string for a res_sockaddr_union.
703  */
704 const char *
705 p_sockun(union res_sockaddr_union u, char *buf, size_t size) {
706 	char ret[sizeof "ffff:ffff:ffff:ffff:ffff:ffff:123.123.123.123"];
707 
708 	switch (u.sin.sin_family) {
709 	case AF_INET:
710 		inet_ntop(AF_INET, &u.sin.sin_addr, ret, sizeof ret);
711 		break;
712 #ifdef HAS_INET6_STRUCTS
713 	case AF_INET6:
714 		inet_ntop(AF_INET6, &u.sin6.sin6_addr, ret, sizeof ret);
715 		break;
716 #endif
717 	default:
718 		sprintf(ret, "[af%d]", u.sin.sin_family);
719 		break;
720 	}
721 	if (size > 0) {
722 		strncpy(buf, ret, size - 1);
723 		buf[size - 1] = '0';
724 	}
725 	return (buf);
726 }
727 
728 /*
729  * routines to convert between on-the-wire RR format and zone file format.
730  * Does not contain conversion to/from decimal degrees; divide or multiply
731  * by 60*60*1000 for that.
732  */
733 
734 static unsigned int poweroften[10] = {1, 10, 100, 1000, 10000, 100000,
735 				      1000000,10000000,100000000,1000000000};
736 
737 /* takes an XeY precision/size value, returns a string representation. */
738 static const char *
739 precsize_ntoa(prec)
740 	u_int8_t prec;
741 {
742 #ifdef	SUNW_MT_RESOLVER
743 	char	*retbuf = precsize_ntoa_retbuf;
744 #else
745 	static char retbuf[sizeof "90000000.00"];	/* XXX nonreentrant */
746 #endif	/* SUNW_MT_RESOLVER */
747 	unsigned long val;
748 	int mantissa, exponent;
749 
750 	mantissa = (int)((prec >> 4) & 0x0f) % 10;
751 	exponent = (int)((prec >> 0) & 0x0f) % 10;
752 
753 	val = mantissa * poweroften[exponent];
754 
755 	(void) sprintf(retbuf, "%lu.%.2lu", val/100, val%100);
756 	return (retbuf);
757 }
758 
759 /* converts ascii size/precision X * 10**Y(cm) to 0xXY.  moves pointer. */
760 static u_int8_t
761 precsize_aton(const char **strptr) {
762 	unsigned int mval = 0, cmval = 0;
763 	u_int8_t retval = 0;
764 	const char *cp;
765 	int exponent;
766 	int mantissa;
767 
768 	cp = *strptr;
769 
770 	while (isdigit((unsigned char)*cp))
771 		mval = mval * 10 + (*cp++ - '0');
772 
773 	if (*cp == '.') {		/* centimeters */
774 		cp++;
775 		if (isdigit((unsigned char)*cp)) {
776 			cmval = (*cp++ - '0') * 10;
777 			if (isdigit((unsigned char)*cp)) {
778 				cmval += (*cp++ - '0');
779 			}
780 		}
781 	}
782 	cmval = (mval * 100) + cmval;
783 
784 	for (exponent = 0; exponent < 9; exponent++)
785 		if (cmval < poweroften[exponent+1])
786 			break;
787 
788 	mantissa = cmval / poweroften[exponent];
789 	if (mantissa > 9)
790 		mantissa = 9;
791 
792 	retval = (mantissa << 4) | exponent;
793 
794 	*strptr = cp;
795 
796 	return (retval);
797 }
798 
799 /* converts ascii lat/lon to unsigned encoded 32-bit number.  moves pointer. */
800 static u_int32_t
801 latlon2ul(const char **latlonstrptr, int *which) {
802 	const char *cp;
803 	u_int32_t retval;
804 	int deg = 0, min = 0, secs = 0, secsfrac = 0;
805 
806 	cp = *latlonstrptr;
807 
808 	while (isdigit((unsigned char)*cp))
809 		deg = deg * 10 + (*cp++ - '0');
810 
811 	while (isspace((unsigned char)*cp))
812 		cp++;
813 
814 	if (!(isdigit((unsigned char)*cp)))
815 		goto fndhemi;
816 
817 	while (isdigit((unsigned char)*cp))
818 		min = min * 10 + (*cp++ - '0');
819 
820 	while (isspace((unsigned char)*cp))
821 		cp++;
822 
823 	if (!(isdigit((unsigned char)*cp)))
824 		goto fndhemi;
825 
826 	while (isdigit((unsigned char)*cp))
827 		secs = secs * 10 + (*cp++ - '0');
828 
829 	if (*cp == '.') {		/* decimal seconds */
830 		cp++;
831 		if (isdigit((unsigned char)*cp)) {
832 			secsfrac = (*cp++ - '0') * 100;
833 			if (isdigit((unsigned char)*cp)) {
834 				secsfrac += (*cp++ - '0') * 10;
835 				if (isdigit((unsigned char)*cp)) {
836 					secsfrac += (*cp++ - '0');
837 				}
838 			}
839 		}
840 	}
841 
842 	while (!isspace((unsigned char)*cp))	/* if any trailing garbage */
843 		cp++;
844 
845 	while (isspace((unsigned char)*cp))
846 		cp++;
847 
848  fndhemi:
849 	switch (*cp) {
850 	case 'N': case 'n':
851 	case 'E': case 'e':
852 		retval = ((unsigned)1<<31)
853 			+ (((((deg * 60) + min) * 60) + secs) * 1000)
854 			+ secsfrac;
855 		break;
856 	case 'S': case 's':
857 	case 'W': case 'w':
858 		retval = ((unsigned)1<<31)
859 			- (((((deg * 60) + min) * 60) + secs) * 1000)
860 			- secsfrac;
861 		break;
862 	default:
863 		retval = 0;	/* invalid value -- indicates error */
864 		break;
865 	}
866 
867 	switch (*cp) {
868 	case 'N': case 'n':
869 	case 'S': case 's':
870 		*which = 1;	/* latitude */
871 		break;
872 	case 'E': case 'e':
873 	case 'W': case 'w':
874 		*which = 2;	/* longitude */
875 		break;
876 	default:
877 		*which = 0;	/* error */
878 		break;
879 	}
880 
881 	cp++;			/* skip the hemisphere */
882 
883 	while (!isspace((unsigned char)*cp))	/* if any trailing garbage */
884 		cp++;
885 
886 	while (isspace((unsigned char)*cp))	/* move to next field */
887 		cp++;
888 
889 	*latlonstrptr = cp;
890 
891 	return (retval);
892 }
893 
894 /* converts a zone file representation in a string to an RDATA on-the-wire
895  * representation. */
896 int
897 loc_aton(ascii, binary)
898 	const char *ascii;
899 	u_char *binary;
900 {
901 	const char *cp, *maxcp;
902 	u_char *bcp;
903 
904 	u_int32_t latit = 0, longit = 0, alt = 0;
905 	u_int32_t lltemp1 = 0, lltemp2 = 0;
906 	int altmeters = 0, altfrac = 0, altsign = 1;
907 	u_int8_t hp = 0x16;	/* default = 1e6 cm = 10000.00m = 10km */
908 	u_int8_t vp = 0x13;	/* default = 1e3 cm = 10.00m */
909 	u_int8_t siz = 0x12;	/* default = 1e2 cm = 1.00m */
910 	int which1 = 0, which2 = 0;
911 
912 	cp = ascii;
913 	maxcp = cp + strlen(ascii);
914 
915 	lltemp1 = latlon2ul(&cp, &which1);
916 
917 	lltemp2 = latlon2ul(&cp, &which2);
918 
919 	switch (which1 + which2) {
920 	case 3:			/* 1 + 2, the only valid combination */
921 		if ((which1 == 1) && (which2 == 2)) { /* normal case */
922 			latit = lltemp1;
923 			longit = lltemp2;
924 		} else if ((which1 == 2) && (which2 == 1)) { /* reversed */
925 			longit = lltemp1;
926 			latit = lltemp2;
927 		} else {	/* some kind of brokenness */
928 			return (0);
929 		}
930 		break;
931 	default:		/* we didn't get one of each */
932 		return (0);
933 	}
934 
935 	/* altitude */
936 	if (*cp == '-') {
937 		altsign = -1;
938 		cp++;
939 	}
940 
941 	if (*cp == '+')
942 		cp++;
943 
944 	while (isdigit((unsigned char)*cp))
945 		altmeters = altmeters * 10 + (*cp++ - '0');
946 
947 	if (*cp == '.') {		/* decimal meters */
948 		cp++;
949 		if (isdigit((unsigned char)*cp)) {
950 			altfrac = (*cp++ - '0') * 10;
951 			if (isdigit((unsigned char)*cp)) {
952 				altfrac += (*cp++ - '0');
953 			}
954 		}
955 	}
956 
957 	alt = (10000000 + (altsign * (altmeters * 100 + altfrac)));
958 
959 	while (!isspace((unsigned char)*cp) && (cp < maxcp)) /* if trailing garbage or m */
960 		cp++;
961 
962 	while (isspace((unsigned char)*cp) && (cp < maxcp))
963 		cp++;
964 
965 	if (cp >= maxcp)
966 		goto defaults;
967 
968 	siz = precsize_aton(&cp);
969 
970 	while (!isspace((unsigned char)*cp) && (cp < maxcp))	/* if trailing garbage or m */
971 		cp++;
972 
973 	while (isspace((unsigned char)*cp) && (cp < maxcp))
974 		cp++;
975 
976 	if (cp >= maxcp)
977 		goto defaults;
978 
979 	hp = precsize_aton(&cp);
980 
981 	while (!isspace((unsigned char)*cp) && (cp < maxcp))	/* if trailing garbage or m */
982 		cp++;
983 
984 	while (isspace((unsigned char)*cp) && (cp < maxcp))
985 		cp++;
986 
987 	if (cp >= maxcp)
988 		goto defaults;
989 
990 	vp = precsize_aton(&cp);
991 
992  defaults:
993 
994 	bcp = binary;
995 	*bcp++ = (u_int8_t) 0;	/* version byte */
996 	*bcp++ = siz;
997 	*bcp++ = hp;
998 	*bcp++ = vp;
999 	PUTLONG(latit,bcp);
1000 	PUTLONG(longit,bcp);
1001 	PUTLONG(alt,bcp);
1002 
1003 	return (16);		/* size of RR in octets */
1004 }
1005 
1006 /* takes an on-the-wire LOC RR and formats it in a human readable format. */
1007 const char *
1008 loc_ntoa(binary, ascii)
1009 	const u_char *binary;
1010 	char *ascii;
1011 {
1012 	static const char *error = "?";
1013 #ifdef	SUNW_MT_RESOLVER
1014 	char	*tmpbuf = loc_ntoa_tmpbuf;
1015 #else
1016 	static char tmpbuf[sizeof
1017 "1000 60 60.000 N 1000 60 60.000 W -12345678.00m 90000000.00m 90000000.00m 90000000.00m"];
1018 #endif	/* SUNW_MT_RESOLVER */
1019 	const u_char *cp = binary;
1020 
1021 	int latdeg, latmin, latsec, latsecfrac;
1022 	int longdeg, longmin, longsec, longsecfrac;
1023 	char northsouth, eastwest;
1024 	const char *altsign;
1025 	int altmeters, altfrac;
1026 
1027 	const u_int32_t referencealt = 100000 * 100;
1028 
1029 	int32_t latval, longval, altval;
1030 	u_int32_t templ;
1031 	u_int8_t sizeval, hpval, vpval, versionval;
1032 
1033 	char *sizestr, *hpstr, *vpstr;
1034 
1035 	versionval = *cp++;
1036 
1037 	if (ascii == NULL)
1038 		ascii = tmpbuf;
1039 
1040 	if (versionval) {
1041 		(void) sprintf(ascii, "; error: unknown LOC RR version");
1042 		return (ascii);
1043 	}
1044 
1045 	sizeval = *cp++;
1046 
1047 	hpval = *cp++;
1048 	vpval = *cp++;
1049 
1050 	GETLONG(templ, cp);
1051 	latval = (templ - ((unsigned)1<<31));
1052 
1053 	GETLONG(templ, cp);
1054 	longval = (templ - ((unsigned)1<<31));
1055 
1056 	GETLONG(templ, cp);
1057 	if (templ < referencealt) { /* below WGS 84 spheroid */
1058 		altval = referencealt - templ;
1059 		altsign = "-";
1060 	} else {
1061 		altval = templ - referencealt;
1062 		altsign = "";
1063 	}
1064 
1065 	if (latval < 0) {
1066 		northsouth = 'S';
1067 		latval = -latval;
1068 	} else
1069 		northsouth = 'N';
1070 
1071 	latsecfrac = latval % 1000;
1072 	latval = latval / 1000;
1073 	latsec = latval % 60;
1074 	latval = latval / 60;
1075 	latmin = latval % 60;
1076 	latval = latval / 60;
1077 	latdeg = latval;
1078 
1079 	if (longval < 0) {
1080 		eastwest = 'W';
1081 		longval = -longval;
1082 	} else
1083 		eastwest = 'E';
1084 
1085 	longsecfrac = longval % 1000;
1086 	longval = longval / 1000;
1087 	longsec = longval % 60;
1088 	longval = longval / 60;
1089 	longmin = longval % 60;
1090 	longval = longval / 60;
1091 	longdeg = longval;
1092 
1093 	altfrac = altval % 100;
1094 	altmeters = (altval / 100);
1095 
1096 	sizestr = strdup(precsize_ntoa(sizeval));
1097 	hpstr = strdup(precsize_ntoa(hpval));
1098 	vpstr = strdup(precsize_ntoa(vpval));
1099 
1100 	sprintf(ascii,
1101 	    "%d %.2d %.2d.%.3d %c %d %.2d %.2d.%.3d %c %s%d.%.2dm %sm %sm %sm",
1102 		latdeg, latmin, latsec, latsecfrac, northsouth,
1103 		longdeg, longmin, longsec, longsecfrac, eastwest,
1104 		altsign, altmeters, altfrac,
1105 		(sizestr != NULL) ? sizestr : error,
1106 		(hpstr != NULL) ? hpstr : error,
1107 		(vpstr != NULL) ? vpstr : error);
1108 
1109 	if (sizestr != NULL)
1110 		free(sizestr);
1111 	if (hpstr != NULL)
1112 		free(hpstr);
1113 	if (vpstr != NULL)
1114 		free(vpstr);
1115 
1116 	return (ascii);
1117 }
1118 
1119 
1120 /* Return the number of DNS hierarchy levels in the name. */
1121 int
1122 dn_count_labels(const char *name) {
1123 	int i, len, count;
1124 
1125 	len = strlen(name);
1126 	for (i = 0, count = 0; i < len; i++) {
1127 		/* XXX need to check for \. or use named's nlabels(). */
1128 		if (name[i] == '.')
1129 			count++;
1130 	}
1131 
1132 	/* don't count initial wildcard */
1133 	if (name[0] == '*')
1134 		if (count)
1135 			count--;
1136 
1137 	/* don't count the null label for root. */
1138 	/* if terminating '.' not found, must adjust */
1139 	/* count to include last label */
1140 	if (len > 0 && name[len-1] != '.')
1141 		count++;
1142 	return (count);
1143 }
1144 
1145 
1146 /*
1147  * Make dates expressed in seconds-since-Jan-1-1970 easy to read.
1148  * SIG records are required to be printed like this, by the Secure DNS RFC.
1149  */
1150 char *
1151 #ifdef	ORIGINAL_ISC_CODE
1152 p_secstodate (u_long secs) {
1153 #else
1154 p_secstodate (u_int secs) {
1155 #endif
1156 #ifdef	SUNW_MT_RESOLVER
1157 	char	*output = p_secstodate_output;
1158 #else
1159 	/* XXX nonreentrant */
1160 	static char output[15];		/* YYYYMMDDHHMMSS and null */
1161 #endif	/* SUNW_MT_RESOLVER */
1162 	time_t clock = secs;
1163 	struct tm *time;
1164 
1165 #ifdef HAVE_TIME_R
1166 	gmtime_r(&clock, &time);
1167 #else
1168 	time = gmtime(&clock);
1169 #endif
1170 	time->tm_year += 1900;
1171 	time->tm_mon += 1;
1172 	sprintf(output, "%04d%02d%02d%02d%02d%02d",
1173 		time->tm_year, time->tm_mon, time->tm_mday,
1174 		time->tm_hour, time->tm_min, time->tm_sec);
1175 	return (output);
1176 }
1177 
1178 u_int16_t
1179 res_nametoclass(const char *buf, int *successp) {
1180 	unsigned long result;
1181 	char *endptr;
1182 	int success;
1183 
1184 	result = sym_ston(__p_class_syms, buf, &success);
1185 	if (success)
1186 		goto done;
1187 
1188 	if (strncasecmp(buf, "CLASS", 5) != 0 ||
1189 	    !isdigit((unsigned char)buf[5]))
1190 		goto done;
1191 	errno = 0;
1192 	result = strtoul(buf + 5, &endptr, 10);
1193 	if (errno == 0 && *endptr == '\0' && result <= 0xffff)
1194 		success = 1;
1195  done:
1196 	if (successp)
1197 		*successp = success;
1198 	return (result);
1199 }
1200 
1201 u_int16_t
1202 res_nametotype(const char *buf, int *successp) {
1203 	unsigned long result;
1204 	char *endptr;
1205 	int success;
1206 
1207 	result = sym_ston(__p_type_syms, buf, &success);
1208 	if (success)
1209 		goto done;
1210 
1211 	if (strncasecmp(buf, "type", 4) != 0 ||
1212 	    !isdigit((unsigned char)buf[4]))
1213 		goto done;
1214 	errno = 0;
1215 	result = strtoul(buf + 4, &endptr, 10);
1216 	if (errno == 0 && *endptr == '\0' && result <= 0xffff)
1217 		success = 1;
1218  done:
1219 	if (successp)
1220 		*successp = success;
1221 	return (result);
1222 }
1223