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