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