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