INADDR_NONE no longer used.
[platform/upstream/c-ares.git] / adig.c
1 /* Copyright 1998 by the Massachusetts Institute of Technology.
2  *
3  * $Id$
4  *
5  * Permission to use, copy, modify, and distribute this
6  * software and its documentation for any purpose and without
7  * fee is hereby granted, provided that the above copyright
8  * notice appear in all copies and that both that copyright
9  * notice and this permission notice appear in supporting
10  * documentation, and that the name of M.I.T. not be used in
11  * advertising or publicity pertaining to distribution of the
12  * software without specific, written prior permission.
13  * M.I.T. makes no representations about the suitability of
14  * this software for any purpose.  It is provided "as is"
15  * without express or implied warranty.
16  */
17
18 #include "setup.h"
19 #include <sys/types.h>
20
21 #if defined(WIN32) && !defined(WATT32)
22 #include "nameser.h"
23 #else
24 #ifdef HAVE_SYS_TIME_H
25 #include <sys/time.h>
26 #endif
27 #include <sys/socket.h>
28 #include <netinet/in.h>
29 #include <arpa/inet.h>
30 #include <arpa/nameser.h>
31 #ifdef HAVE_UNISTD_H
32 #include <unistd.h>
33 #endif
34 #include <netdb.h>
35 #endif
36 #ifdef HAVE_GETOPT_H
37 #include <getopt.h>
38 #endif
39
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <ctype.h>
44 #include <errno.h>
45
46 #include "ares.h"
47 #include "ares_dns.h"
48 #include "inet_ntop.h"
49
50 #ifdef WATT32
51 #undef WIN32  /* Redefined in MingW headers */
52 #endif
53
54 /* Mac OS X portability check */
55 #ifndef T_SRV
56 #define T_SRV 33 /* server selection */
57 #endif
58
59 #ifndef optind
60 extern int optind;
61 extern char *optarg;
62 #endif
63
64 struct nv {
65   const char *name;
66   int value;
67 };
68
69 static const struct nv flags[] = {
70   { "usevc",            ARES_FLAG_USEVC },
71   { "primary",          ARES_FLAG_PRIMARY },
72   { "igntc",            ARES_FLAG_IGNTC },
73   { "norecurse",        ARES_FLAG_NORECURSE },
74   { "stayopen",         ARES_FLAG_STAYOPEN },
75   { "noaliases",        ARES_FLAG_NOALIASES }
76 };
77 static const int nflags = sizeof(flags) / sizeof(flags[0]);
78
79 static const struct nv classes[] = {
80   { "IN",       C_IN },
81   { "CHAOS",    C_CHAOS },
82   { "HS",       C_HS },
83   { "ANY",      C_ANY }
84 };
85 static const int nclasses = sizeof(classes) / sizeof(classes[0]);
86
87 static const struct nv types[] = {
88   { "A",        T_A },
89   { "NS",       T_NS },
90   { "MD",       T_MD },
91   { "MF",       T_MF },
92   { "CNAME",    T_CNAME },
93   { "SOA",      T_SOA },
94   { "MB",       T_MB },
95   { "MG",       T_MG },
96   { "MR",       T_MR },
97   { "NULL",     T_NULL },
98   { "WKS",      T_WKS },
99   { "PTR",      T_PTR },
100   { "HINFO",    T_HINFO },
101   { "MINFO",    T_MINFO },
102   { "MX",       T_MX },
103   { "TXT",      T_TXT },
104   { "RP",       T_RP },
105   { "AFSDB",    T_AFSDB },
106   { "X25",      T_X25 },
107   { "ISDN",     T_ISDN },
108   { "RT",       T_RT },
109   { "NSAP",     T_NSAP },
110   { "NSAP_PTR", T_NSAP_PTR },
111   { "SIG",      T_SIG },
112   { "KEY",      T_KEY },
113   { "PX",       T_PX },
114   { "GPOS",     T_GPOS },
115   { "AAAA",     T_AAAA },
116   { "LOC",      T_LOC },
117   { "SRV",      T_SRV },
118   { "AXFR",     T_AXFR },
119   { "MAILB",    T_MAILB },
120   { "MAILA",    T_MAILA },
121   { "ANY",      T_ANY }
122 };
123 static const int ntypes = sizeof(types) / sizeof(types[0]);
124
125 static const char *opcodes[] = {
126   "QUERY", "IQUERY", "STATUS", "(reserved)", "NOTIFY",
127   "(unknown)", "(unknown)", "(unknown)", "(unknown)",
128   "UPDATEA", "UPDATED", "UPDATEDA", "UPDATEM", "UPDATEMA",
129   "ZONEINIT", "ZONEREF"
130 };
131
132 static const char *rcodes[] = {
133   "NOERROR", "FORMERR", "SERVFAIL", "NXDOMAIN", "NOTIMP", "REFUSED",
134   "(unknown)", "(unknown)", "(unknown)", "(unknown)", "(unknown)",
135   "(unknown)", "(unknown)", "(unknown)", "(unknown)", "NOCHANGE"
136 };
137
138 static void callback(void *arg, int status, unsigned char *abuf, int alen);
139 static const unsigned char *display_question(const unsigned char *aptr,
140                                              const unsigned char *abuf,
141                                              int alen);
142 static const unsigned char *display_rr(const unsigned char *aptr,
143                                        const unsigned char *abuf, int alen);
144 static const char *type_name(int type);
145 static const char *class_name(int dnsclass);
146 static void usage(void);
147
148 int main(int argc, char **argv)
149 {
150   ares_channel channel;
151   int c, i, optmask = ARES_OPT_FLAGS, dnsclass = C_IN, type = T_A;
152   int status, nfds, count;
153   struct ares_options options;
154   struct hostent *hostent;
155   fd_set read_fds, write_fds;
156   struct timeval *tvp, tv;
157
158 #ifdef USE_WINSOCK
159   WORD wVersionRequested = MAKEWORD(USE_WINSOCK,USE_WINSOCK);
160   WSADATA wsaData;
161   WSAStartup(wVersionRequested, &wsaData);
162 #endif
163
164   options.flags = ARES_FLAG_NOCHECKRESP;
165   options.servers = NULL;
166   options.nservers = 0;
167   while ((c = getopt(argc, argv, "df:s:c:t:T:U:")) != -1)
168     {
169       switch (c)
170         {
171         case 'd':
172 #ifdef WATT32
173           dbug_init();
174 #endif
175           break;
176
177         case 'f':
178           /* Add a flag. */
179           for (i = 0; i < nflags; i++)
180             {
181               if (strcmp(flags[i].name, optarg) == 0)
182                 break;
183             }
184           if (i == nflags)
185             usage();
186           options.flags |= flags[i].value;
187           break;
188
189         case 's':
190           /* Add a server, and specify servers in the option mask. */
191           hostent = gethostbyname(optarg);
192           if (!hostent || hostent->h_addrtype != AF_INET)
193             {
194               fprintf(stderr, "adig: server %s not found.\n", optarg);
195               return 1;
196             }
197           options.servers = realloc(options.servers, (options.nservers + 1)
198                                     * sizeof(struct in_addr));
199           if (!options.servers)
200             {
201               fprintf(stderr, "Out of memory!\n");
202               return 1;
203             }
204           memcpy(&options.servers[options.nservers], hostent->h_addr,
205                  sizeof(struct in_addr));
206           options.nservers++;
207           optmask |= ARES_OPT_SERVERS;
208           break;
209
210         case 'c':
211           /* Set the query class. */
212           for (i = 0; i < nclasses; i++)
213             {
214               if (strcasecmp(classes[i].name, optarg) == 0)
215                 break;
216             }
217           if (i == nclasses)
218             usage();
219           dnsclass = classes[i].value;
220           break;
221
222         case 't':
223           /* Set the query type. */
224           for (i = 0; i < ntypes; i++)
225             {
226               if (strcasecmp(types[i].name, optarg) == 0)
227                 break;
228             }
229           if (i == ntypes)
230             usage();
231           type = types[i].value;
232           break;
233
234         case 'T':
235           /* Set the TCP port number. */
236           if (!ISDIGIT(*optarg))
237             usage();
238           options.tcp_port = (unsigned short)strtol(optarg, NULL, 0);
239           optmask |= ARES_OPT_TCP_PORT;
240           break;
241
242         case 'U':
243           /* Set the UDP port number. */
244           if (!ISDIGIT(*optarg))
245             usage();
246           options.udp_port = (unsigned short)strtol(optarg, NULL, 0);
247           optmask |= ARES_OPT_UDP_PORT;
248           break;
249         }
250     }
251   argc -= optind;
252   argv += optind;
253   if (argc == 0)
254     usage();
255
256   status = ares_init_options(&channel, &options, optmask);
257
258   if (status != ARES_SUCCESS)
259     {
260       fprintf(stderr, "ares_init_options: %s\n",
261               ares_strerror(status));
262       return 1;
263     }
264
265   /* Initiate the queries, one per command-line argument.  If there is
266    * only one query to do, supply NULL as the callback argument;
267    * otherwise, supply the query name as an argument so we can
268    * distinguish responses for the user when printing them out.
269    */
270   if (argc == 1)
271     ares_query(channel, *argv, dnsclass, type, callback, (char *) NULL);
272   else
273     {
274       for (; *argv; argv++)
275         ares_query(channel, *argv, dnsclass, type, callback, *argv);
276     }
277
278   /* Wait for all queries to complete. */
279   while (1)
280     {
281       FD_ZERO(&read_fds);
282       FD_ZERO(&write_fds);
283       nfds = ares_fds(channel, &read_fds, &write_fds);
284       if (nfds == 0)
285         break;
286       tvp = ares_timeout(channel, NULL, &tv);
287       count = select(nfds, &read_fds, &write_fds, NULL, tvp);
288       if (count < 0 && SOCKERRNO != EINVAL)
289         {
290           perror("select");
291           return 1;
292         }
293       ares_process(channel, &read_fds, &write_fds);
294     }
295
296   ares_destroy(channel);
297   return 0;
298 }
299
300 static void callback(void *arg, int status, unsigned char *abuf, int alen)
301 {
302   char *name = (char *) arg;
303   int id, qr, opcode, aa, tc, rd, ra, rcode;
304   unsigned int qdcount, ancount, nscount, arcount, i;
305   const unsigned char *aptr;
306
307   /* Display the query name if given. */
308   if (name)
309     printf("Answer for query %s:\n", name);
310
311   /* Display an error message if there was an error, but only stop if
312    * we actually didn't get an answer buffer.
313    */
314   if (status != ARES_SUCCESS)
315     {
316       printf("%s\n", ares_strerror(status));
317       if (!abuf)
318         return;
319     }
320
321   /* Won't happen, but check anyway, for safety. */
322   if (alen < HFIXEDSZ)
323     return;
324
325   /* Parse the answer header. */
326   id = DNS_HEADER_QID(abuf);
327   qr = DNS_HEADER_QR(abuf);
328   opcode = DNS_HEADER_OPCODE(abuf);
329   aa = DNS_HEADER_AA(abuf);
330   tc = DNS_HEADER_TC(abuf);
331   rd = DNS_HEADER_RD(abuf);
332   ra = DNS_HEADER_RA(abuf);
333   rcode = DNS_HEADER_RCODE(abuf);
334   qdcount = DNS_HEADER_QDCOUNT(abuf);
335   ancount = DNS_HEADER_ANCOUNT(abuf);
336   nscount = DNS_HEADER_NSCOUNT(abuf);
337   arcount = DNS_HEADER_ARCOUNT(abuf);
338
339   /* Display the answer header. */
340   printf("id: %d\n", id);
341   printf("flags: %s%s%s%s%s\n",
342          qr ? "qr " : "",
343          aa ? "aa " : "",
344          tc ? "tc " : "",
345          rd ? "rd " : "",
346          ra ? "ra " : "");
347   printf("opcode: %s\n", opcodes[opcode]);
348   printf("rcode: %s\n", rcodes[rcode]);
349
350   /* Display the questions. */
351   printf("Questions:\n");
352   aptr = abuf + HFIXEDSZ;
353   for (i = 0; i < qdcount; i++)
354     {
355       aptr = display_question(aptr, abuf, alen);
356       if (aptr == NULL)
357         return;
358     }
359
360   /* Display the answers. */
361   printf("Answers:\n");
362   for (i = 0; i < ancount; i++)
363     {
364       aptr = display_rr(aptr, abuf, alen);
365       if (aptr == NULL)
366         return;
367     }
368
369   /* Display the NS records. */
370   printf("NS records:\n");
371   for (i = 0; i < nscount; i++)
372     {
373       aptr = display_rr(aptr, abuf, alen);
374       if (aptr == NULL)
375         return;
376     }
377
378   /* Display the additional records. */
379   printf("Additional records:\n");
380   for (i = 0; i < arcount; i++)
381     {
382       aptr = display_rr(aptr, abuf, alen);
383       if (aptr == NULL)
384         return;
385     }
386 }
387
388 static const unsigned char *display_question(const unsigned char *aptr,
389                                              const unsigned char *abuf,
390                                              int alen)
391 {
392   char *name;
393   int type, dnsclass, status;
394   long len;
395
396   /* Parse the question name. */
397   status = ares_expand_name(aptr, abuf, alen, &name, &len);
398   if (status != ARES_SUCCESS)
399     return NULL;
400   aptr += len;
401
402   /* Make sure there's enough data after the name for the fixed part
403    * of the question.
404    */
405   if (aptr + QFIXEDSZ > abuf + alen)
406     {
407       ares_free_string(name);
408       return NULL;
409     }
410
411   /* Parse the question type and class. */
412   type = DNS_QUESTION_TYPE(aptr);
413   dnsclass = DNS_QUESTION_CLASS(aptr);
414   aptr += QFIXEDSZ;
415
416   /* Display the question, in a format sort of similar to how we will
417    * display RRs.
418    */
419   printf("\t%-15s.\t", name);
420   if (dnsclass != C_IN)
421     printf("\t%s", class_name(dnsclass));
422   printf("\t%s\n", type_name(type));
423   ares_free_string(name);
424   return aptr;
425 }
426
427 static const unsigned char *display_rr(const unsigned char *aptr,
428                                        const unsigned char *abuf, int alen)
429 {
430   const unsigned char *p;
431   char *name;
432   int type, dnsclass, ttl, dlen, status;
433   long len;
434   char addr[46];
435
436   /* Parse the RR name. */
437   status = ares_expand_name(aptr, abuf, alen, &name, &len);
438   if (status != ARES_SUCCESS)
439     return NULL;
440   aptr += len;
441
442   /* Make sure there is enough data after the RR name for the fixed
443    * part of the RR.
444    */
445   if (aptr + RRFIXEDSZ > abuf + alen)
446     {
447       ares_free_string(name);
448       return NULL;
449     }
450
451   /* Parse the fixed part of the RR, and advance to the RR data
452    * field. */
453   type = DNS_RR_TYPE(aptr);
454   dnsclass = DNS_RR_CLASS(aptr);
455   ttl = DNS_RR_TTL(aptr);
456   dlen = DNS_RR_LEN(aptr);
457   aptr += RRFIXEDSZ;
458   if (aptr + dlen > abuf + alen)
459     {
460       ares_free_string(name);
461       return NULL;
462     }
463
464   /* Display the RR name, class, and type. */
465   printf("\t%-15s.\t%d", name, ttl);
466   if (dnsclass != C_IN)
467     printf("\t%s", class_name(dnsclass));
468   printf("\t%s", type_name(type));
469   ares_free_string(name);
470
471   /* Display the RR data.  Don't touch aptr. */
472   switch (type)
473     {
474     case T_CNAME:
475     case T_MB:
476     case T_MD:
477     case T_MF:
478     case T_MG:
479     case T_MR:
480     case T_NS:
481     case T_PTR:
482       /* For these types, the RR data is just a domain name. */
483       status = ares_expand_name(aptr, abuf, alen, &name, &len);
484       if (status != ARES_SUCCESS)
485         return NULL;
486       printf("\t%s.", name);
487       ares_free_string(name);
488       break;
489
490     case T_HINFO:
491       /* The RR data is two length-counted character strings. */
492       p = aptr;
493       len = *p;
494       if (p + len + 1 > aptr + dlen)
495         return NULL;
496       printf("\t%.*s", (int)len, p + 1);
497       p += len + 1;
498       len = *p;
499       if (p + len + 1 > aptr + dlen)
500         return NULL;
501       printf("\t%.*s", (int)len, p + 1);
502       break;
503
504     case T_MINFO:
505       /* The RR data is two domain names. */
506       p = aptr;
507       status = ares_expand_name(p, abuf, alen, &name, &len);
508       if (status != ARES_SUCCESS)
509         return NULL;
510       printf("\t%s.", name);
511       ares_free_string(name);
512       p += len;
513       status = ares_expand_name(p, abuf, alen, &name, &len);
514       if (status != ARES_SUCCESS)
515         return NULL;
516       printf("\t%s.", name);
517       ares_free_string(name);
518       break;
519
520     case T_MX:
521       /* The RR data is two bytes giving a preference ordering, and
522        * then a domain name.
523        */
524       if (dlen < 2)
525         return NULL;
526       printf("\t%d", DNS__16BIT(aptr));
527       status = ares_expand_name(aptr + 2, abuf, alen, &name, &len);
528       if (status != ARES_SUCCESS)
529         return NULL;
530       printf("\t%s.", name);
531       ares_free_string(name);
532       break;
533
534     case T_SOA:
535       /* The RR data is two domain names and then five four-byte
536        * numbers giving the serial number and some timeouts.
537        */
538       p = aptr;
539       status = ares_expand_name(p, abuf, alen, &name, &len);
540       if (status != ARES_SUCCESS)
541         return NULL;
542       printf("\t%s.\n", name);
543       ares_free_string(name);
544       p += len;
545       status = ares_expand_name(p, abuf, alen, &name, &len);
546       if (status != ARES_SUCCESS)
547         return NULL;
548       printf("\t\t\t\t\t\t%s.\n", name);
549       ares_free_string(name);
550       p += len;
551       if (p + 20 > aptr + dlen)
552         return NULL;
553       printf("\t\t\t\t\t\t( %lu %lu %lu %lu %lu )",
554              (unsigned long)DNS__32BIT(p), (unsigned long)DNS__32BIT(p+4),
555              (unsigned long)DNS__32BIT(p+8), (unsigned long)DNS__32BIT(p+12),
556              (unsigned long)DNS__32BIT(p+16));
557       break;
558
559     case T_TXT:
560       /* The RR data is one or more length-counted character
561        * strings. */
562       p = aptr;
563       while (p < aptr + dlen)
564         {
565           len = *p;
566           if (p + len + 1 > aptr + dlen)
567             return NULL;
568           printf("\t%.*s", (int)len, p + 1);
569           p += len + 1;
570         }
571       break;
572
573     case T_A:
574       /* The RR data is a four-byte Internet address. */
575       if (dlen != 4)
576         return NULL;
577       printf("\t%s", ares_inet_ntop(AF_INET,aptr,addr,sizeof(addr)));
578       break;
579
580     case T_AAAA:
581       /* The RR data is a 16-byte IPv6 address. */
582       if (dlen != 16)
583         return NULL;
584       printf("\t%s", ares_inet_ntop(AF_INET6,aptr,addr,sizeof(addr)));
585       break;
586
587     case T_WKS:
588       /* Not implemented yet */
589       break;
590
591     case T_SRV:
592       /* The RR data is three two-byte numbers representing the
593        * priority, weight, and port, followed by a domain name.
594        */
595
596       printf("\t%d", DNS__16BIT(aptr));
597       printf(" %d", DNS__16BIT(aptr + 2));
598       printf(" %d", DNS__16BIT(aptr + 4));
599
600       status = ares_expand_name(aptr + 6, abuf, alen, &name, &len);
601       if (status != ARES_SUCCESS)
602         return NULL;
603       printf("\t%s.", name);
604       ares_free_string(name);
605       break;
606
607     default:
608       printf("\t[Unknown RR; cannot parse]");
609       break;
610     }
611   printf("\n");
612
613   return aptr + dlen;
614 }
615
616 static const char *type_name(int type)
617 {
618   int i;
619
620   for (i = 0; i < ntypes; i++)
621     {
622       if (types[i].value == type)
623         return types[i].name;
624     }
625   return "(unknown)";
626 }
627
628 static const char *class_name(int dnsclass)
629 {
630   int i;
631
632   for (i = 0; i < nclasses; i++)
633     {
634       if (classes[i].value == dnsclass)
635         return classes[i].name;
636     }
637   return "(unknown)";
638 }
639
640 static void usage(void)
641 {
642   fprintf(stderr, "usage: adig [-f flag] [-s server] [-c class] "
643           "[-t type] [-p port] name ...\n");
644   exit(1);
645 }