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