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