Initial import from FreeBSD RELENG_4:
[dragonfly.git] / lib / libc / net / 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  * Portions Copyright (c) 1996 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)
97 static char sccsid[] = "@(#)res_debug.c 8.1 (Berkeley) 6/4/93";
98 static char rcsid[] = "$FreeBSD: src/lib/libc/net/res_debug.c,v 1.18.2.1 2001/06/15 22:08:28 ume Exp $";
99 #endif /* LIBC_SCCS and not lint */
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 <stdio.h>
115 #include <stdlib.h>
116 #include <string.h>
117 #include <time.h>
118
119 #define SPRINTF(x) sprintf x
120
121 extern const char *_res_opcodes[];
122 extern const char *_res_resultcodes[];
123 extern const char *_res_sectioncodes[];
124
125 /*
126  * Print the current options.
127  */
128 void
129 fp_resstat(struct __res_state *statp, FILE *file) {
130         u_long mask;
131
132         fprintf(file, ";; res options:");
133         if (!statp)
134                 statp = &_res;
135         for (mask = 1;  mask != 0;  mask <<= 1)
136                 if (statp->options & mask)
137                         fprintf(file, " %s", p_option(mask));
138         putc('\n', file);
139 }
140
141 static void
142 do_section(ns_msg *handle, ns_sect section, int pflag, FILE *file) {
143         int n, sflag, rrnum;
144         char buf[2048]; /* XXX need to malloc */
145         ns_opcode opcode;
146         ns_rr rr;
147
148         /*
149          * Print answer records.
150          */
151         sflag = (_res.pfcode & pflag);
152         if (_res.pfcode && !sflag)
153                 return;
154
155         opcode = ns_msg_getflag(*handle, ns_f_opcode);
156         rrnum = 0;
157         for (;;) {
158                 if (ns_parserr(handle, section, rrnum, &rr)) {
159                         if (errno != ENODEV)
160                                 fprintf(file, ";; ns_parserr: %s\n",
161                                         strerror(errno));
162                         else if (rrnum > 0 && sflag != 0 &&
163                                  (_res.pfcode & RES_PRF_HEAD1))
164                                 putc('\n', file);
165                         return;
166                 }
167                 if (rrnum == 0 && sflag != 0 && (_res.pfcode & RES_PRF_HEAD1))
168                         fprintf(file, ";; %s SECTION:\n",
169                                 p_section(section, opcode));
170                 if (section == ns_s_qd)
171                         fprintf(file, ";;\t%s, type = %s, class = %s\n",
172                                 ns_rr_name(rr),
173                                 p_type(ns_rr_type(rr)),
174                                 p_class(ns_rr_class(rr)));
175                 else {
176                         n = ns_sprintrr(handle, &rr, NULL, NULL,
177                                         buf, sizeof buf);
178                         if (n < 0) {
179                                 fprintf(file, ";; ns_sprintrr: %s\n",
180                                         strerror(errno));
181                                 return;
182                         }
183                         fputs(buf, file);
184                         fputc('\n', file);
185                 }
186                 rrnum++;
187         }
188 }
189
190 void
191 p_query(const u_char *msg) {
192         fp_query(msg, stdout);
193 }
194
195 void
196 fp_query(const u_char *msg, FILE *file) {
197         fp_nquery(msg, PACKETSZ, file);
198 }
199
200 /*
201  * Print the contents of a query.
202  * This is intended to be primarily a debugging routine.
203  */
204 void
205 fp_nquery(const u_char *msg, int len, FILE *file) {
206         ns_msg handle;
207         int n, qdcount, ancount, nscount, arcount;
208         u_int opcode, rcode, id;
209
210         if ((_res.options & RES_INIT) == 0 && res_init() == -1)
211                 return;
212
213         if (ns_initparse(msg, len, &handle) < 0) {
214                 fprintf(file, ";; ns_initparse: %s\n", strerror(errno));
215                 return;
216         }
217         opcode = ns_msg_getflag(handle, ns_f_opcode);
218         rcode = ns_msg_getflag(handle, ns_f_rcode);
219         id = ns_msg_id(handle);
220         qdcount = ns_msg_count(handle, ns_s_qd);
221         ancount = ns_msg_count(handle, ns_s_an);
222         nscount = ns_msg_count(handle, ns_s_ns);
223         arcount = ns_msg_count(handle, ns_s_ar);
224
225         /*
226          * Print header fields.
227          */
228         if ((!_res.pfcode) || (_res.pfcode & RES_PRF_HEADX) || rcode)
229                 fprintf(file,
230                         ";; ->>HEADER<<- opcode: %s, status: %s, id: %d\n",
231                         _res_opcodes[opcode], _res_resultcodes[rcode], id);
232         if ((!_res.pfcode) || (_res.pfcode & RES_PRF_HEADX))
233                 putc(';', file);
234         if ((!_res.pfcode) || (_res.pfcode & RES_PRF_HEAD2)) {
235                 fprintf(file, "; flags:");
236                 if (ns_msg_getflag(handle, ns_f_qr))
237                         fprintf(file, " qr");
238                 if (ns_msg_getflag(handle, ns_f_aa))
239                         fprintf(file, " aa");
240                 if (ns_msg_getflag(handle, ns_f_tc))
241                         fprintf(file, " tc");
242                 if (ns_msg_getflag(handle, ns_f_rd))
243                         fprintf(file, " rd");
244                 if (ns_msg_getflag(handle, ns_f_ra))
245                         fprintf(file, " ra");
246                 if (ns_msg_getflag(handle, ns_f_z))
247                         fprintf(file, " ??");
248                 if (ns_msg_getflag(handle, ns_f_ad))
249                         fprintf(file, " ad");
250                 if (ns_msg_getflag(handle, ns_f_cd))
251                         fprintf(file, " cd");
252         }
253         if ((!_res.pfcode) || (_res.pfcode & RES_PRF_HEAD1)) {
254                 fprintf(file, "; %s: %d",
255                         p_section(ns_s_qd, opcode), qdcount);
256                 fprintf(file, ", %s: %d",
257                         p_section(ns_s_an, opcode), ancount);
258                 fprintf(file, ", %s: %d",
259                         p_section(ns_s_ns, opcode), nscount);
260                 fprintf(file, ", %s: %d",
261                         p_section(ns_s_ar, opcode), arcount);
262         }
263         if ((!_res.pfcode) || (_res.pfcode & 
264                 (RES_PRF_HEADX | RES_PRF_HEAD2 | RES_PRF_HEAD1))) {
265                 putc('\n',file);
266         }
267         /*
268          * Print the various sections.
269          */
270         do_section(&handle, ns_s_qd, RES_PRF_QUES, file);
271         do_section(&handle, ns_s_an, RES_PRF_ANS, file);
272         do_section(&handle, ns_s_ns, RES_PRF_AUTH, file);
273         do_section(&handle, ns_s_ar, RES_PRF_ADD, file);
274         if (qdcount == 0 && ancount == 0 &&
275             nscount == 0 && arcount == 0)
276                 putc('\n', file);
277 }
278
279 const u_char *
280 p_cdnname(const u_char *cp, const u_char *msg, int len, FILE *file) {
281         char name[MAXDNAME];
282         int n;
283
284         if ((n = dn_expand(msg, msg + len, cp, name, sizeof name)) < 0)
285                 return (NULL);
286         if (name[0] == '\0')
287                 putc('.', file);
288         else
289                 fputs(name, file);
290         return (cp + n);
291 }
292
293 const u_char *
294 p_cdname(const u_char *cp, const u_char *msg, FILE *file) {
295         return (p_cdnname(cp, msg, PACKETSZ, file));
296 }
297
298 /* Return a fully-qualified domain name from a compressed name (with
299    length supplied).  */
300
301 const u_char *
302 p_fqnname(cp, msg, msglen, name, namelen)
303         const u_char *cp, *msg;
304         int msglen;
305         char *name;
306         int namelen;
307 {
308         int n, newlen;
309
310         if ((n = dn_expand(msg, cp + msglen, cp, name, namelen)) < 0)
311                 return (NULL);
312         newlen = strlen(name);
313         if (newlen == 0 || name[newlen - 1] != '.') {
314                 if (newlen + 1 >= namelen)      /* Lack space for final dot */
315                         return (NULL);
316                 else
317                         strcpy(name + newlen, ".");
318         }
319         return (cp + n);
320 }
321
322 /* XXX: the rest of these functions need to become length-limited, too. */
323
324 const u_char *
325 p_fqname(const u_char *cp, const u_char *msg, FILE *file) {
326         char name[MAXDNAME];
327         const u_char *n;
328
329         n = p_fqnname(cp, msg, MAXCDNAME, name, sizeof name);
330         if (n == NULL)
331                 return (NULL);
332         fputs(name, file);
333         return (n);
334 }
335
336 /*
337  * Names of RR classes and qclasses.  Classes and qclasses are the same, except
338  * that C_ANY is a qclass but not a class.  (You can ask for records of class
339  * C_ANY, but you can't have any records of that class in the database.)
340  */
341 const struct res_sym __p_class_syms[] = {
342         {C_IN,          "IN"},
343         {C_CHAOS,       "CHAOS"},
344         {C_HS,          "HS"},
345         {C_HS,          "HESIOD"},
346         {C_ANY,         "ANY"},
347         {C_NONE,        "NONE"},
348         {C_IN,          (char *)0}
349 };
350
351 /*
352  * Names of message sections.
353  */
354 const struct res_sym __p_default_section_syms[] = {
355         {ns_s_qd,       "QUERY"},
356         {ns_s_an,       "ANSWER"},
357         {ns_s_ns,       "AUTHORITY"},
358         {ns_s_ar,       "ADDITIONAL"},
359         {0,             (char *)0}
360 };
361
362 const struct res_sym __p_update_section_syms[] = {
363         {S_ZONE,        "ZONE"},
364         {S_PREREQ,      "PREREQUISITE"},
365         {S_UPDATE,      "UPDATE"},
366         {S_ADDT,        "ADDITIONAL"},
367         {0,             (char *)0}
368 };
369
370 /*
371  * Names of RR types and qtypes.  Types and qtypes are the same, except
372  * that T_ANY is a qtype but not a type.  (You can ask for records of type
373  * T_ANY, but you can't have any records of that type in the database.)
374  */
375 const struct res_sym __p_type_syms[] = {
376         {T_A,           "A",            "address"},
377         {T_NS,          "NS",           "name server"},
378         {T_MD,          "MD",           "mail destination (deprecated)"},
379         {T_MF,          "MF",           "mail forwarder (deprecated)"},
380         {T_CNAME,       "CNAME",        "canonical name"},
381         {T_SOA,         "SOA",          "start of authority"},
382         {T_MB,          "MB",           "mailbox"},
383         {T_MG,          "MG",           "mail group member"},
384         {T_MR,          "MR",           "mail rename"},
385         {T_NULL,        "NULL",         "null"},
386         {T_WKS,         "WKS",          "well-known service (deprecated)"},
387         {T_PTR,         "PTR",          "domain name pointer"},
388         {T_HINFO,       "HINFO",        "host information"},
389         {T_MINFO,       "MINFO",        "mailbox information"},
390         {T_MX,          "MX",           "mail exchanger"},
391         {T_TXT,         "TXT",          "text"},
392         {T_RP,          "RP",           "responsible person"},
393         {T_AFSDB,       "AFSDB",        "DCE or AFS server"},
394         {T_X25,         "X25",          "X25 address"},
395         {T_ISDN,        "ISDN",         "ISDN address"},
396         {T_RT,          "RT",           "router"},
397         {T_NSAP,        "NSAP",         "nsap address"},
398         {T_NSAP_PTR,    "NSAP_PTR",     "domain name pointer"},
399         {T_SIG,         "SIG",          "signature"},
400         {T_KEY,         "KEY",          "key"},
401         {T_PX,          "PX",           "mapping information"},
402         {T_GPOS,        "GPOS",         "geographical position (withdrawn)"},
403         {T_AAAA,        "AAAA",         "IPv6 address"},
404         {T_LOC,         "LOC",          "location"},
405         {T_NXT,         "NXT",          "next valid name (unimplemented)"},
406         {T_EID,         "EID",          "endpoint identifier (unimplemented)"},
407         {T_NIMLOC,      "NIMLOC",       "NIMROD locator (unimplemented)"},
408         {T_SRV,         "SRV",          "server selection"},
409         {T_ATMA,        "ATMA",         "ATM address (unimplemented)"},
410         {T_IXFR,        "IXFR",         "incremental zone transfer"},
411         {T_AXFR,        "AXFR",         "zone transfer"},
412         {T_MAILB,       "MAILB",        "mailbox-related data (deprecated)"},
413         {T_MAILA,       "MAILA",        "mail agent (deprecated)"},
414         {T_NAPTR,       "NAPTR",        "URN Naming Authority"},
415         {T_ANY,         "ANY",          "\"any\""},
416         {0,             NULL,           NULL}
417 };
418
419 int
420 sym_ston(const struct res_sym *syms, const char *name, int *success) {
421         for ((void)NULL; syms->name != 0; syms++) {
422                 if (strcasecmp (name, syms->name) == 0) {
423                         if (success)
424                                 *success = 1;
425                         return (syms->number);
426                 }
427         }
428         if (success)
429                 *success = 0;
430         return (syms->number);          /* The default value. */
431 }
432
433 const char *
434 sym_ntos(const struct res_sym *syms, int number, int *success) {
435         static char unname[20];
436
437         for ((void)NULL; syms->name != 0; syms++) {
438                 if (number == syms->number) {
439                         if (success)
440                                 *success = 1;
441                         return (syms->name);
442                 }
443         }
444
445         sprintf(unname, "%d", number);
446         if (success)
447                 *success = 0;
448         return (unname);
449 }
450
451 const char *
452 sym_ntop(const struct res_sym *syms, int number, int *success) {
453         static char unname[20];
454
455         for ((void)NULL; syms->name != 0; syms++) {
456                 if (number == syms->number) {
457                         if (success)
458                                 *success = 1;
459                         return (syms->humanname);
460                 }
461         }
462         sprintf(unname, "%d", number);
463         if (success)
464                 *success = 0;
465         return (unname);
466 }
467
468 /*
469  * Return a string for the type.
470  */
471 const char *
472 p_type(int type) {
473         return (sym_ntos(__p_type_syms, type, (int *)0));
474 }
475
476 /*
477  * Return a string for the type.
478  */
479 const char *
480 p_section(int section, int opcode) {
481         const struct res_sym *symbols;
482
483         switch (opcode) {
484         case ns_o_update:
485                 symbols = __p_update_section_syms;
486                 break;
487         default:
488                 symbols = __p_default_section_syms;
489                 break;
490         }
491         return (sym_ntos(symbols, section, (int *)0));
492 }
493
494 /*
495  * Return a mnemonic for class.
496  */
497 const char *
498 p_class(int class) {
499         return (sym_ntos(__p_class_syms, class, (int *)0));
500 }
501
502 /*
503  * Return a mnemonic for an option
504  */
505 const char *
506 p_option(u_long option) {
507         static char nbuf[40];
508
509         switch (option) {
510         case RES_INIT:          return "init";
511         case RES_DEBUG:         return "debug";
512         case RES_AAONLY:        return "aaonly(unimpl)";
513         case RES_USEVC:         return "usevc";
514         case RES_PRIMARY:       return "primry(unimpl)";
515         case RES_IGNTC:         return "igntc";
516         case RES_RECURSE:       return "recurs";
517         case RES_DEFNAMES:      return "defnam";
518         case RES_STAYOPEN:      return "styopn";
519         case RES_DNSRCH:        return "dnsrch";
520         case RES_INSECURE1:     return "insecure1";
521         case RES_INSECURE2:     return "insecure2";
522         case RES_NOALIASES:     return "noaliases";
523         case RES_USE_INET6:     return "inet6";
524         case RES_NOTLDQUERY:    return "no-tld-query";
525         case RES_USE_EDNS0:     return "edns0";
526         default:                sprintf(nbuf, "?0x%lx?", (u_long)option);
527                                 return (nbuf);
528         }
529 }
530
531 /*
532  * Return a mnemonic for a time to live.
533  */
534 const char *
535 p_time(u_int32_t value) {
536         static char nbuf[40];
537
538         if (ns_format_ttl(value, nbuf, sizeof nbuf) < 0)
539                 sprintf(nbuf, "%u", value);
540         return (nbuf);
541 }
542
543
544 /*
545  * routines to convert between on-the-wire RR format and zone file format.
546  * Does not contain conversion to/from decimal degrees; divide or multiply
547  * by 60*60*1000 for that.
548  */
549
550 static unsigned int poweroften[10] = {1, 10, 100, 1000, 10000, 100000,
551                                       1000000,10000000,100000000,1000000000};
552
553 /* takes an XeY precision/size value, returns a string representation. */
554 static const char *
555 precsize_ntoa(prec)
556         u_int8_t prec;
557 {
558         static char retbuf[sizeof "90000000.00"];
559         unsigned long val;
560         int mantissa, exponent;
561
562         mantissa = (int)((prec >> 4) & 0x0f) % 10;
563         exponent = (int)((prec >> 0) & 0x0f) % 10;
564
565         val = mantissa * poweroften[exponent];
566
567         (void) sprintf(retbuf, "%ld.%.2ld", val/100, val%100);
568         return (retbuf);
569 }
570
571 /* converts ascii size/precision X * 10**Y(cm) to 0xXY.  moves pointer. */
572 static u_int8_t
573 precsize_aton(strptr)
574         char **strptr;
575 {
576         unsigned int mval = 0, cmval = 0;
577         u_int8_t retval = 0;
578         char *cp;
579         int exponent;
580         int mantissa;
581
582         cp = *strptr;
583
584         while (isdigit((unsigned char)*cp))
585                 mval = mval * 10 + (*cp++ - '0');
586
587         if (*cp == '.') {               /* centimeters */
588                 cp++;
589                 if (isdigit((unsigned char)*cp)) {
590                         cmval = (*cp++ - '0') * 10;
591                         if (isdigit((unsigned char)*cp)) {
592                                 cmval += (*cp++ - '0');
593                         }
594                 }
595         }
596         cmval = (mval * 100) + cmval;
597
598         for (exponent = 0; exponent < 9; exponent++)
599                 if (cmval < poweroften[exponent+1])
600                         break;
601
602         mantissa = cmval / poweroften[exponent];
603         if (mantissa > 9)
604                 mantissa = 9;
605
606         retval = (mantissa << 4) | exponent;
607
608         *strptr = cp;
609
610         return (retval);
611 }
612
613 /* converts ascii lat/lon to unsigned encoded 32-bit number.  moves pointer. */
614 static u_int32_t
615 latlon2ul(latlonstrptr,which)
616         char **latlonstrptr;
617         int *which;
618 {
619         char *cp;
620         u_int32_t retval;
621         int deg = 0, min = 0, secs = 0, secsfrac = 0;
622
623         cp = *latlonstrptr;
624
625         while (isdigit((unsigned char)*cp))
626                 deg = deg * 10 + (*cp++ - '0');
627
628         while (isspace((unsigned char)*cp))
629                 cp++;
630
631         if (!(isdigit((unsigned char)*cp)))
632                 goto fndhemi;
633
634         while (isdigit((unsigned char)*cp))
635                 min = min * 10 + (*cp++ - '0');
636
637         while (isspace((unsigned char)*cp))
638                 cp++;
639
640         if (!(isdigit((unsigned char)*cp)))
641                 goto fndhemi;
642
643         while (isdigit((unsigned char)*cp))
644                 secs = secs * 10 + (*cp++ - '0');
645
646         if (*cp == '.') {               /* decimal seconds */
647                 cp++;
648                 if (isdigit((unsigned char)*cp)) {
649                         secsfrac = (*cp++ - '0') * 100;
650                         if (isdigit((unsigned char)*cp)) {
651                                 secsfrac += (*cp++ - '0') * 10;
652                                 if (isdigit((unsigned char)*cp)) {
653                                         secsfrac += (*cp++ - '0');
654                                 }
655                         }
656                 }
657         }
658
659         while (!isspace((unsigned char)*cp))   /* if any trailing garbage */
660                 cp++;
661
662         while (isspace((unsigned char)*cp))
663                 cp++;
664
665  fndhemi:
666         switch (*cp) {
667         case 'N': case 'n':
668         case 'E': case 'e':
669                 retval = ((unsigned)1<<31)
670                         + (((((deg * 60) + min) * 60) + secs) * 1000)
671                         + secsfrac;
672                 break;
673         case 'S': case 's':
674         case 'W': case 'w':
675                 retval = ((unsigned)1<<31)
676                         - (((((deg * 60) + min) * 60) + secs) * 1000)
677                         - secsfrac;
678                 break;
679         default:
680                 retval = 0;     /* invalid value -- indicates error */
681                 break;
682         }
683
684         switch (*cp) {
685         case 'N': case 'n':
686         case 'S': case 's':
687                 *which = 1;     /* latitude */
688                 break;
689         case 'E': case 'e':
690         case 'W': case 'w':
691                 *which = 2;     /* longitude */
692                 break;
693         default:
694                 *which = 0;     /* error */
695                 break;
696         }
697
698         cp++;                   /* skip the hemisphere */
699
700         while (!isspace((unsigned char)*cp))   /* if any trailing garbage */
701                 cp++;
702
703         while (isspace((unsigned char)*cp))    /* move to next field */
704                 cp++;
705
706         *latlonstrptr = cp;
707
708         return (retval);
709 }
710
711 /* converts a zone file representation in a string to an RDATA on-the-wire
712  * representation. */
713 int
714 loc_aton(ascii, binary)
715         const char *ascii;
716         u_char *binary;
717 {
718         const char *cp, *maxcp;
719         u_char *bcp;
720
721         u_int32_t latit = 0, longit = 0, alt = 0;
722         u_int32_t lltemp1 = 0, lltemp2 = 0;
723         int altmeters = 0, altfrac = 0, altsign = 1;
724         u_int8_t hp = 0x16;     /* default = 1e6 cm = 10000.00m = 10km */
725         u_int8_t vp = 0x13;     /* default = 1e3 cm = 10.00m */
726         u_int8_t siz = 0x12;    /* default = 1e2 cm = 1.00m */
727         int which1 = 0, which2 = 0;
728
729         cp = ascii;
730         maxcp = cp + strlen(ascii);
731
732         lltemp1 = latlon2ul(&cp, &which1);
733
734         lltemp2 = latlon2ul(&cp, &which2);
735
736         switch (which1 + which2) {
737         case 3:                 /* 1 + 2, the only valid combination */
738                 if ((which1 == 1) && (which2 == 2)) { /* normal case */
739                         latit = lltemp1;
740                         longit = lltemp2;
741                 } else if ((which1 == 2) && (which2 == 1)) { /* reversed */
742                         longit = lltemp1;
743                         latit = lltemp2;
744                 } else {        /* some kind of brokenness */
745                         return (0);
746                 }
747                 break;
748         default:                /* we didn't get one of each */
749                 return (0);
750         }
751
752         /* altitude */
753         if (*cp == '-') {
754                 altsign = -1;
755                 cp++;
756         }
757     
758         if (*cp == '+')
759                 cp++;
760
761         while (isdigit((unsigned char)*cp))
762                 altmeters = altmeters * 10 + (*cp++ - '0');
763
764         if (*cp == '.') {               /* decimal meters */
765                 cp++;
766                 if (isdigit((unsigned char)*cp)) {
767                         altfrac = (*cp++ - '0') * 10;
768                         if (isdigit((unsigned char)*cp)) {
769                                 altfrac += (*cp++ - '0');
770                         }
771                 }
772         }
773
774         alt = (10000000 + (altsign * (altmeters * 100 + altfrac)));
775
776         while (!isspace((unsigned char)*cp) && (cp < maxcp)) /* if trailing garbage or m */
777                 cp++;
778
779         while (isspace((unsigned char)*cp) && (cp < maxcp))
780                 cp++;
781
782         if (cp >= maxcp)
783                 goto defaults;
784
785         siz = precsize_aton(&cp);
786         
787         while (!isspace((unsigned char)*cp) && (cp < maxcp))   /* if trailing garbage or m */
788                 cp++;
789
790         while (isspace((unsigned char)*cp) && (cp < maxcp))
791                 cp++;
792
793         if (cp >= maxcp)
794                 goto defaults;
795
796         hp = precsize_aton(&cp);
797
798         while (!isspace((unsigned char)*cp) && (cp < maxcp))   /* if trailing garbage or m */
799                 cp++;
800
801         while (isspace((unsigned char)*cp) && (cp < maxcp))
802                 cp++;
803
804         if (cp >= maxcp)
805                 goto defaults;
806
807         vp = precsize_aton(&cp);
808
809  defaults:
810
811         bcp = binary;
812         *bcp++ = (u_int8_t) 0;  /* version byte */
813         *bcp++ = siz;
814         *bcp++ = hp;
815         *bcp++ = vp;
816         PUTLONG(latit,bcp);
817         PUTLONG(longit,bcp);
818         PUTLONG(alt,bcp);
819     
820         return (16);            /* size of RR in octets */
821 }
822
823 /* takes an on-the-wire LOC RR and formats it in a human readable format. */
824 const char *
825 loc_ntoa(binary, ascii)
826         const u_char *binary;
827         char *ascii;
828 {
829         static char *error = "?";
830         const u_char *cp = binary;
831
832         int latdeg, latmin, latsec, latsecfrac;
833         int longdeg, longmin, longsec, longsecfrac;
834         char northsouth, eastwest;
835         int altmeters, altfrac, altsign;
836
837         const u_int32_t referencealt = 100000 * 100;
838
839         int32_t latval, longval, altval;
840         u_int32_t templ;
841         u_int8_t sizeval, hpval, vpval, versionval;
842     
843         char *sizestr, *hpstr, *vpstr;
844
845         versionval = *cp++;
846
847         if (versionval) {
848                 (void) sprintf(ascii, "; error: unknown LOC RR version");
849                 return (ascii);
850         }
851
852         sizeval = *cp++;
853
854         hpval = *cp++;
855         vpval = *cp++;
856
857         GETLONG(templ, cp);
858         latval = (templ - ((unsigned)1<<31));
859
860         GETLONG(templ, cp);
861         longval = (templ - ((unsigned)1<<31));
862
863         GETLONG(templ, cp);
864         if (templ < referencealt) { /* below WGS 84 spheroid */
865                 altval = referencealt - templ;
866                 altsign = -1;
867         } else {
868                 altval = templ - referencealt;
869                 altsign = 1;
870         }
871
872         if (latval < 0) {
873                 northsouth = 'S';
874                 latval = -latval;
875         } else
876                 northsouth = 'N';
877
878         latsecfrac = latval % 1000;
879         latval = latval / 1000;
880         latsec = latval % 60;
881         latval = latval / 60;
882         latmin = latval % 60;
883         latval = latval / 60;
884         latdeg = latval;
885
886         if (longval < 0) {
887                 eastwest = 'W';
888                 longval = -longval;
889         } else
890                 eastwest = 'E';
891
892         longsecfrac = longval % 1000;
893         longval = longval / 1000;
894         longsec = longval % 60;
895         longval = longval / 60;
896         longmin = longval % 60;
897         longval = longval / 60;
898         longdeg = longval;
899
900         altfrac = altval % 100;
901         altmeters = (altval / 100) * altsign;
902
903         if ((sizestr = strdup(precsize_ntoa(sizeval))) == NULL)
904                 sizestr = error;
905         if ((hpstr = strdup(precsize_ntoa(hpval))) == NULL)
906                 hpstr = error;
907         if ((vpstr = strdup(precsize_ntoa(vpval))) == NULL)
908                 vpstr = error;
909
910         sprintf(ascii,
911               "%d %.2d %.2d.%.3d %c %d %.2d %.2d.%.3d %c %d.%.2dm %sm %sm %sm",
912                 latdeg, latmin, latsec, latsecfrac, northsouth,
913                 longdeg, longmin, longsec, longsecfrac, eastwest,
914                 altmeters, altfrac, sizestr, hpstr, vpstr);
915
916         if (sizestr != error)
917                 free(sizestr);
918         if (hpstr != error)
919                 free(hpstr);
920         if (vpstr != error)
921                 free(vpstr);
922
923         return (ascii);
924 }
925
926
927 /* Return the number of DNS hierarchy levels in the name. */
928 int
929 dn_count_labels(const char *name) {
930         int i, len, count;
931
932         len = strlen(name);
933         for (i = 0, count = 0; i < len; i++) {
934                 /* XXX need to check for \. or use named's nlabels(). */
935                 if (name[i] == '.')
936                         count++;
937         }
938
939         /* don't count initial wildcard */
940         if (name[0] == '*')
941                 if (count)
942                         count--;
943
944         /* don't count the null label for root. */
945         /* if terminating '.' not found, must adjust */
946         /* count to include last label */
947         if (len > 0 && name[len-1] != '.')
948                 count++;
949         return (count);
950 }
951
952
953 /* 
954  * Make dates expressed in seconds-since-Jan-1-1970 easy to read.  
955  * SIG records are required to be printed like this, by the Secure DNS RFC.
956  */
957 char *
958 p_secstodate (u_long secs) {
959         static char output[15];         /* YYYYMMDDHHMMSS and null */
960         time_t clock = secs;
961         struct tm *time;
962         
963         time = gmtime(&clock);
964         time->tm_year += 1900;
965         time->tm_mon += 1;
966         sprintf(output, "%04d%02d%02d%02d%02d%02d",
967                 time->tm_year, time->tm_mon, time->tm_mday,
968                 time->tm_hour, time->tm_min, time->tm_sec);
969         return (output);
970 }
971
972 /*
973  * Weak aliases for applications that use certain private entry points,
974  * and fail to include <resolv.h>.
975  */
976 #undef fp_resstat
977 __weak_reference(__fp_resstat, fp_resstat);
978 #undef p_query
979 __weak_reference(__p_query, p_query);
980 #undef p_fqnname
981 __weak_reference(__p_fqnname, p_fqnname);
982 #undef sym_ston
983 __weak_reference(__sym_ston, sym_ston);
984 #undef sym_ntos
985 __weak_reference(__sym_ntos, sym_ntos);
986 #undef sym_ntop
987 __weak_reference(__sym_ntop, sym_ntop);
988 #undef dn_count_labels
989 __weak_reference(__dn_count_labels, dn_count_labels);
990 #undef p_secstodate
991 __weak_reference(__p_secstodate, p_secstodate);