]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - contrib/bind9/bin/dig/dig.c
MFC: r253983-253984
[FreeBSD/stable/8.git] / contrib / bind9 / bin / dig / dig.c
1 /*
2  * Copyright (C) 2004-2013  Internet Systems Consortium, Inc. ("ISC")
3  * Copyright (C) 2000-2003  Internet Software Consortium.
4  *
5  * Permission to use, copy, modify, and/or distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
10  * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11  * AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
12  * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13  * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
14  * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15  * PERFORMANCE OF THIS SOFTWARE.
16  */
17
18 /* $Id: dig.c,v 1.237.124.4 2011/12/07 17:23:55 each Exp $ */
19
20 /*! \file */
21
22 #include <config.h>
23 #include <stdlib.h>
24 #include <time.h>
25 #include <ctype.h>
26
27 #include <isc/app.h>
28 #include <isc/netaddr.h>
29 #include <isc/parseint.h>
30 #include <isc/print.h>
31 #include <isc/string.h>
32 #include <isc/util.h>
33 #include <isc/task.h>
34
35 #include <dns/byaddr.h>
36 #include <dns/fixedname.h>
37 #include <dns/masterdump.h>
38 #include <dns/message.h>
39 #include <dns/name.h>
40 #include <dns/rdata.h>
41 #include <dns/rdataset.h>
42 #include <dns/rdatatype.h>
43 #include <dns/rdataclass.h>
44 #include <dns/result.h>
45 #include <dns/tsig.h>
46
47 #include <dig/dig.h>
48
49 #define ADD_STRING(b, s) {                              \
50         if (strlen(s) >= isc_buffer_availablelength(b)) \
51                 return (ISC_R_NOSPACE);                 \
52         else                                            \
53                 isc_buffer_putstr(b, s);                \
54 }
55
56 #define DIG_MAX_ADDRESSES 20
57
58 dig_lookup_t *default_lookup = NULL;
59
60 static char *batchname = NULL;
61 static FILE *batchfp = NULL;
62 static char *argv0;
63 static int addresscount = 0;
64
65 static char domainopt[DNS_NAME_MAXTEXT];
66
67 static isc_boolean_t short_form = ISC_FALSE, printcmd = ISC_TRUE,
68         ip6_int = ISC_FALSE, plusquest = ISC_FALSE, pluscomm = ISC_FALSE,
69         multiline = ISC_FALSE, nottl = ISC_FALSE, noclass = ISC_FALSE,
70         onesoa = ISC_FALSE;
71
72 /*% opcode text */
73 static const char * const opcodetext[] = {
74         "QUERY",
75         "IQUERY",
76         "STATUS",
77         "RESERVED3",
78         "NOTIFY",
79         "UPDATE",
80         "RESERVED6",
81         "RESERVED7",
82         "RESERVED8",
83         "RESERVED9",
84         "RESERVED10",
85         "RESERVED11",
86         "RESERVED12",
87         "RESERVED13",
88         "RESERVED14",
89         "RESERVED15"
90 };
91
92 /*% return code text */
93 static const char * const rcodetext[] = {
94         "NOERROR",
95         "FORMERR",
96         "SERVFAIL",
97         "NXDOMAIN",
98         "NOTIMP",
99         "REFUSED",
100         "YXDOMAIN",
101         "YXRRSET",
102         "NXRRSET",
103         "NOTAUTH",
104         "NOTZONE",
105         "RESERVED11",
106         "RESERVED12",
107         "RESERVED13",
108         "RESERVED14",
109         "RESERVED15",
110         "BADVERS"
111 };
112
113 /*% safe rcodetext[] */
114 static char *
115 rcode_totext(dns_rcode_t rcode)
116 {
117         static char buf[sizeof("?65535")];
118         union {
119                 const char *consttext;
120                 char *deconsttext;
121         } totext;
122
123         if (rcode >= (sizeof(rcodetext)/sizeof(rcodetext[0]))) {
124                 snprintf(buf, sizeof(buf), "?%u", rcode);
125                 totext.deconsttext = buf;
126         } else
127                 totext.consttext = rcodetext[rcode];
128         return totext.deconsttext;
129 }
130
131 /*% print usage */
132 static void
133 print_usage(FILE *fp) {
134         fputs(
135 "Usage:  dig [@global-server] [domain] [q-type] [q-class] {q-opt}\n"
136 "            {global-d-opt} host [@local-server] {local-d-opt}\n"
137 "            [ host [@local-server] {local-d-opt} [...]]\n", fp);
138 }
139
140 ISC_PLATFORM_NORETURN_PRE static void
141 usage(void) ISC_PLATFORM_NORETURN_POST;
142
143 static void
144 usage(void) {
145         print_usage(stderr);
146         fputs("\nUse \"dig -h\" (or \"dig -h | more\") "
147               "for complete list of options\n", stderr);
148         exit(1);
149 }
150
151 /*% version */
152 static void
153 version(void) {
154         fputs("DiG " VERSION "\n", stderr);
155 }
156
157 /*% help */
158 static void
159 help(void) {
160         print_usage(stdout);
161         fputs(
162 "Where:  domain   is in the Domain Name System\n"
163 "        q-class  is one of (in,hs,ch,...) [default: in]\n"
164 "        q-type   is one of (a,any,mx,ns,soa,hinfo,axfr,txt,...) [default:a]\n"
165 "                 (Use ixfr=version for type ixfr)\n"
166 "        q-opt    is one of:\n"
167 "                 -x dot-notation     (shortcut for reverse lookups)\n"
168 "                 -i                  (use IP6.INT for IPv6 reverse lookups)\n"
169 "                 -f filename         (batch mode)\n"
170 "                 -b address[#port]   (bind to source address/port)\n"
171 "                 -p port             (specify port number)\n"
172 "                 -q name             (specify query name)\n"
173 "                 -t type             (specify query type)\n"
174 "                 -c class            (specify query class)\n"
175 "                 -k keyfile          (specify tsig key file)\n"
176 "                 -y [hmac:]name:key  (specify named base64 tsig key)\n"
177 "                 -4                  (use IPv4 query transport only)\n"
178 "                 -6                  (use IPv6 query transport only)\n"
179 "                 -m                  (enable memory usage debugging)\n"
180 "        d-opt    is of the form +keyword[=value], where keyword is:\n"
181 "                 +[no]vc             (TCP mode)\n"
182 "                 +[no]tcp            (TCP mode, alternate syntax)\n"
183 "                 +time=###           (Set query timeout) [5]\n"
184 "                 +tries=###          (Set number of UDP attempts) [3]\n"
185 "                 +retry=###          (Set number of UDP retries) [2]\n"
186 "                 +domain=###         (Set default domainname)\n"
187 "                 +bufsize=###        (Set EDNS0 Max UDP packet size)\n"
188 "                 +ndots=###          (Set NDOTS value)\n"
189 "                 +[no]edns[=###]     (Set EDNS version) [0]\n"
190 "                 +[no]search         (Set whether to use searchlist)\n"
191 "                 +[no]showsearch     (Search with intermediate results)\n"
192 "                 +[no]defname        (Ditto)\n"
193 "                 +[no]recurse        (Recursive mode)\n"
194 "                 +[no]ignore         (Don't revert to TCP for TC responses.)"
195 "\n"
196 "                 +[no]fail           (Don't try next server on SERVFAIL)\n"
197 "                 +[no]besteffort     (Try to parse even illegal messages)\n"
198 "                 +[no]aaonly         (Set AA flag in query (+[no]aaflag))\n"
199 "                 +[no]adflag         (Set AD flag in query)\n"
200 "                 +[no]cdflag         (Set CD flag in query)\n"
201 "                 +[no]cl             (Control display of class in records)\n"
202 "                 +[no]cmd            (Control display of command line)\n"
203 "                 +[no]comments       (Control display of comment lines)\n"
204 "                 +[no]question       (Control display of question)\n"
205 "                 +[no]answer         (Control display of answer)\n"
206 "                 +[no]authority      (Control display of authority)\n"
207 "                 +[no]additional     (Control display of additional)\n"
208 "                 +[no]stats          (Control display of statistics)\n"
209 "                 +[no]short          (Disable everything except short\n"
210 "                                      form of answer)\n"
211 "                 +[no]ttlid          (Control display of ttls in records)\n"
212 "                 +[no]all            (Set or clear all display flags)\n"
213 "                 +[no]qr             (Print question before sending)\n"
214 "                 +[no]nssearch       (Search all authoritative nameservers)\n"
215 "                 +[no]identify       (ID responders in short answers)\n"
216 "                 +[no]trace          (Trace delegation down from root)\n"
217 "                 +[no]dnssec         (Request DNSSEC records)\n"
218 "                 +[no]nsid           (Request Name Server ID)\n"
219 #ifdef DIG_SIGCHASE
220 "                 +[no]sigchase       (Chase DNSSEC signatures)\n"
221 "                 +trusted-key=####   (Trusted Key when chasing DNSSEC sigs)\n"
222 #if DIG_SIGCHASE_TD
223 "                 +[no]topdown        (Do DNSSEC validation top down mode)\n"
224 #endif
225 #endif
226 "                 +[no]multiline      (Print records in an expanded format)\n"
227 "                 +[no]onesoa         (AXFR prints only one soa record)\n"
228 "                 +[no]keepopen       (Keep the TCP socket open between queries)\n"
229 "        global d-opts and servers (before host name) affect all queries.\n"
230 "        local d-opts and servers (after host name) affect only that lookup.\n"
231 "        -h                           (print help and exit)\n"
232 "        -v                           (print version and exit)\n",
233         stdout);
234 }
235
236 /*%
237  * Callback from dighost.c to print the received message.
238  */
239 void
240 received(int bytes, isc_sockaddr_t *from, dig_query_t *query) {
241         isc_uint64_t diff;
242         isc_time_t now;
243         time_t tnow;
244         struct tm tmnow;
245         char time_str[100];
246         char fromtext[ISC_SOCKADDR_FORMATSIZE];
247
248         isc_sockaddr_format(from, fromtext, sizeof(fromtext));
249
250         TIME_NOW(&now);
251
252         if (query->lookup->stats && !short_form) {
253                 diff = isc_time_microdiff(&now, &query->time_sent);
254                 printf(";; Query time: %ld msec\n", (long int)diff/1000);
255                 printf(";; SERVER: %s(%s)\n", fromtext, query->servname);
256                 time(&tnow);
257                 tmnow  = *localtime(&tnow);
258                 if (strftime(time_str, sizeof(time_str),
259                              "%a %b %d %H:%M:%S %Z %Y", &tmnow) > 0U)
260                         printf(";; WHEN: %s\n", time_str);
261                 if (query->lookup->doing_xfr) {
262                         printf(";; XFR size: %u records (messages %u, "
263                                "bytes %" ISC_PRINT_QUADFORMAT "u)\n",
264                                query->rr_count, query->msg_count,
265                                query->byte_count);
266                 } else {
267                         printf(";; MSG SIZE  rcvd: %u\n", bytes);
268                 }
269                 if (key != NULL) {
270                         if (!validated)
271                                 puts(";; WARNING -- Some TSIG could not "
272                                      "be validated");
273                 }
274                 if ((key == NULL) && (keysecret[0] != 0)) {
275                         puts(";; WARNING -- TSIG key was not used.");
276                 }
277                 puts("");
278         } else if (query->lookup->identify && !short_form) {
279                 diff = isc_time_microdiff(&now, &query->time_sent);
280                 printf(";; Received %" ISC_PRINT_QUADFORMAT "u bytes "
281                        "from %s(%s) in %d ms\n\n",
282                        query->lookup->doing_xfr ?
283                                 query->byte_count : (isc_uint64_t)bytes,
284                        fromtext, query->userarg,
285                        (int)diff/1000);
286         }
287 }
288
289 /*
290  * Callback from dighost.c to print that it is trying a server.
291  * Not used in dig.
292  * XXX print_trying
293  */
294 void
295 trying(char *frm, dig_lookup_t *lookup) {
296         UNUSED(frm);
297         UNUSED(lookup);
298 }
299
300 /*%
301  * Internal print routine used to print short form replies.
302  */
303 static isc_result_t
304 say_message(dns_rdata_t *rdata, dig_query_t *query, isc_buffer_t *buf) {
305         isc_result_t result;
306         isc_uint64_t diff;
307         isc_time_t now;
308         char store[sizeof("12345678901234567890")];
309
310         if (query->lookup->trace || query->lookup->ns_search_only) {
311                 result = dns_rdatatype_totext(rdata->type, buf);
312                 if (result != ISC_R_SUCCESS)
313                         return (result);
314                 ADD_STRING(buf, " ");
315         }
316         result = dns_rdata_totext(rdata, NULL, buf);
317         if (result == ISC_R_NOSPACE)
318                 return (result);
319         check_result(result, "dns_rdata_totext");
320         if (query->lookup->identify) {
321                 TIME_NOW(&now);
322                 diff = isc_time_microdiff(&now, &query->time_sent);
323                 ADD_STRING(buf, " from server ");
324                 ADD_STRING(buf, query->servname);
325                 snprintf(store, 19, " in %d ms.", (int)diff/1000);
326                 ADD_STRING(buf, store);
327         }
328         ADD_STRING(buf, "\n");
329         return (ISC_R_SUCCESS);
330 }
331
332 /*%
333  * short_form message print handler.  Calls above say_message()
334  */
335 static isc_result_t
336 short_answer(dns_message_t *msg, dns_messagetextflag_t flags,
337              isc_buffer_t *buf, dig_query_t *query)
338 {
339         dns_name_t *name;
340         dns_rdataset_t *rdataset;
341         isc_result_t result, loopresult;
342         dns_name_t empty_name;
343         dns_rdata_t rdata = DNS_RDATA_INIT;
344
345         UNUSED(flags);
346
347         dns_name_init(&empty_name, NULL);
348         result = dns_message_firstname(msg, DNS_SECTION_ANSWER);
349         if (result == ISC_R_NOMORE)
350                 return (ISC_R_SUCCESS);
351         else if (result != ISC_R_SUCCESS)
352                 return (result);
353
354         for (;;) {
355                 name = NULL;
356                 dns_message_currentname(msg, DNS_SECTION_ANSWER, &name);
357
358                 for (rdataset = ISC_LIST_HEAD(name->list);
359                      rdataset != NULL;
360                      rdataset = ISC_LIST_NEXT(rdataset, link)) {
361                         loopresult = dns_rdataset_first(rdataset);
362                         while (loopresult == ISC_R_SUCCESS) {
363                                 dns_rdataset_current(rdataset, &rdata);
364                                 result = say_message(&rdata, query,
365                                                      buf);
366                                 if (result == ISC_R_NOSPACE)
367                                         return (result);
368                                 check_result(result, "say_message");
369                                 loopresult = dns_rdataset_next(rdataset);
370                                 dns_rdata_reset(&rdata);
371                         }
372                 }
373                 result = dns_message_nextname(msg, DNS_SECTION_ANSWER);
374                 if (result == ISC_R_NOMORE)
375                         break;
376                 else if (result != ISC_R_SUCCESS)
377                         return (result);
378         }
379
380         return (ISC_R_SUCCESS);
381 }
382 #ifdef DIG_SIGCHASE
383 isc_result_t
384 printrdataset(dns_name_t *owner_name, dns_rdataset_t *rdataset,
385               isc_buffer_t *target)
386 {
387         isc_result_t result;
388         dns_master_style_t *style = NULL;
389         unsigned int styleflags = 0;
390
391         if (rdataset == NULL || owner_name == NULL || target == NULL)
392                 return(ISC_FALSE);
393
394         styleflags |= DNS_STYLEFLAG_REL_OWNER;
395         if (nottl)
396                 styleflags |= DNS_STYLEFLAG_NO_TTL;
397         if (noclass)
398                 styleflags |= DNS_STYLEFLAG_NO_CLASS;
399         if (multiline) {
400                 styleflags |= DNS_STYLEFLAG_OMIT_OWNER;
401                 styleflags |= DNS_STYLEFLAG_OMIT_CLASS;
402                 styleflags |= DNS_STYLEFLAG_REL_DATA;
403                 styleflags |= DNS_STYLEFLAG_OMIT_TTL;
404                 styleflags |= DNS_STYLEFLAG_TTL;
405                 styleflags |= DNS_STYLEFLAG_MULTILINE;
406                 styleflags |= DNS_STYLEFLAG_COMMENT;
407         }
408         if (multiline || (nottl && noclass))
409                 result = dns_master_stylecreate(&style, styleflags,
410                                                 24, 24, 24, 32, 80, 8, mctx);
411         else if (nottl || noclass)
412                 result = dns_master_stylecreate(&style, styleflags,
413                                                 24, 24, 32, 40, 80, 8, mctx);
414         else
415                 result = dns_master_stylecreate(&style, styleflags,
416                                                 24, 32, 40, 48, 80, 8, mctx);
417         check_result(result, "dns_master_stylecreate");
418
419         result = dns_master_rdatasettotext(owner_name, rdataset, style, target);
420
421         if (style != NULL)
422                 dns_master_styledestroy(&style, mctx);
423
424         return(result);
425 }
426 #endif
427
428 /*
429  * Callback from dighost.c to print the reply from a server
430  */
431 isc_result_t
432 printmessage(dig_query_t *query, dns_message_t *msg, isc_boolean_t headers) {
433         isc_result_t result;
434         dns_messagetextflag_t flags;
435         isc_buffer_t *buf = NULL;
436         unsigned int len = OUTPUTBUF;
437         dns_master_style_t *style = NULL;
438         unsigned int styleflags = 0;
439
440         styleflags |= DNS_STYLEFLAG_REL_OWNER;
441         if (nottl)
442                 styleflags |= DNS_STYLEFLAG_NO_TTL;
443         if (noclass)
444                 styleflags |= DNS_STYLEFLAG_NO_CLASS;
445         if (multiline) {
446                 styleflags |= DNS_STYLEFLAG_OMIT_OWNER;
447                 styleflags |= DNS_STYLEFLAG_OMIT_CLASS;
448                 styleflags |= DNS_STYLEFLAG_REL_DATA;
449                 styleflags |= DNS_STYLEFLAG_OMIT_TTL;
450                 styleflags |= DNS_STYLEFLAG_TTL;
451                 styleflags |= DNS_STYLEFLAG_MULTILINE;
452                 styleflags |= DNS_STYLEFLAG_COMMENT;
453         }
454         if (multiline || (nottl && noclass))
455                 result = dns_master_stylecreate(&style, styleflags,
456                                                 24, 24, 24, 32, 80, 8, mctx);
457         else if (nottl || noclass)
458                 result = dns_master_stylecreate(&style, styleflags,
459                                                 24, 24, 32, 40, 80, 8, mctx);
460         else
461                 result = dns_master_stylecreate(&style, styleflags,
462                                                 24, 32, 40, 48, 80, 8, mctx);
463         check_result(result, "dns_master_stylecreate");
464
465         if (query->lookup->cmdline[0] != 0) {
466                 if (!short_form)
467                         fputs(query->lookup->cmdline, stdout);
468                 query->lookup->cmdline[0]=0;
469         }
470         debug("printmessage(%s %s %s)", headers ? "headers" : "noheaders",
471               query->lookup->comments ? "comments" : "nocomments",
472               short_form ? "short_form" : "long_form");
473
474         flags = 0;
475         if (!headers) {
476                 flags |= DNS_MESSAGETEXTFLAG_NOHEADERS;
477                 flags |= DNS_MESSAGETEXTFLAG_NOCOMMENTS;
478         }
479         if (onesoa && query->lookup->rdtype == dns_rdatatype_axfr)
480                 flags |= (query->msg_count == 0) ? DNS_MESSAGETEXTFLAG_ONESOA :
481                                                    DNS_MESSAGETEXTFLAG_OMITSOA;
482         if (!query->lookup->comments)
483                 flags |= DNS_MESSAGETEXTFLAG_NOCOMMENTS;
484
485         result = isc_buffer_allocate(mctx, &buf, len);
486         check_result(result, "isc_buffer_allocate");
487
488         if (query->lookup->comments && !short_form) {
489                 if (query->lookup->cmdline[0] != 0)
490                         printf("; %s\n", query->lookup->cmdline);
491                 if (msg == query->lookup->sendmsg)
492                         printf(";; Sending:\n");
493                 else
494                         printf(";; Got answer:\n");
495
496                 if (headers) {
497                         printf(";; ->>HEADER<<- opcode: %s, status: %s, "
498                                "id: %u\n",
499                                opcodetext[msg->opcode],
500                                rcode_totext(msg->rcode),
501                                msg->id);
502                         printf(";; flags:");
503                         if ((msg->flags & DNS_MESSAGEFLAG_QR) != 0)
504                                 printf(" qr");
505                         if ((msg->flags & DNS_MESSAGEFLAG_AA) != 0)
506                                 printf(" aa");
507                         if ((msg->flags & DNS_MESSAGEFLAG_TC) != 0)
508                                 printf(" tc");
509                         if ((msg->flags & DNS_MESSAGEFLAG_RD) != 0)
510                                 printf(" rd");
511                         if ((msg->flags & DNS_MESSAGEFLAG_RA) != 0)
512                                 printf(" ra");
513                         if ((msg->flags & DNS_MESSAGEFLAG_AD) != 0)
514                                 printf(" ad");
515                         if ((msg->flags & DNS_MESSAGEFLAG_CD) != 0)
516                                 printf(" cd");
517                         if ((msg->flags & 0x0040U) != 0)
518                                 printf("; MBZ: 0x4");
519
520                         printf("; QUERY: %u, ANSWER: %u, "
521                                "AUTHORITY: %u, ADDITIONAL: %u\n",
522                                msg->counts[DNS_SECTION_QUESTION],
523                                msg->counts[DNS_SECTION_ANSWER],
524                                msg->counts[DNS_SECTION_AUTHORITY],
525                                msg->counts[DNS_SECTION_ADDITIONAL]);
526
527                         if (msg != query->lookup->sendmsg &&
528                             (msg->flags & DNS_MESSAGEFLAG_RD) != 0 &&
529                             (msg->flags & DNS_MESSAGEFLAG_RA) == 0)
530                                 printf(";; WARNING: recursion requested "
531                                        "but not available\n");
532                 }
533                 if (msg != query->lookup->sendmsg &&
534                     query->lookup->edns != -1 && msg->opt == NULL &&
535                     (msg->rcode == dns_rcode_formerr ||
536                      msg->rcode == dns_rcode_notimp))
537                         printf("\n;; WARNING: EDNS query returned status "
538                                "%s - retry with '%s+noedns'\n",
539                                rcode_totext(msg->rcode),
540                                query->lookup->dnssec ? "+nodnssec ": "");
541                 if (msg != query->lookup->sendmsg && extrabytes != 0U)
542                         printf(";; WARNING: Message has %u extra byte%s at "
543                                "end\n", extrabytes, extrabytes != 0 ? "s" : "");
544         }
545
546 repopulate_buffer:
547
548         if (query->lookup->comments && headers && !short_form) {
549                 result = dns_message_pseudosectiontotext(msg,
550                          DNS_PSEUDOSECTION_OPT,
551                          style, flags, buf);
552                 if (result == ISC_R_NOSPACE) {
553 buftoosmall:
554                         len += OUTPUTBUF;
555                         isc_buffer_free(&buf);
556                         result = isc_buffer_allocate(mctx, &buf, len);
557                         if (result == ISC_R_SUCCESS)
558                                 goto repopulate_buffer;
559                         else
560                                 goto cleanup;
561                 }
562                 check_result(result,
563                      "dns_message_pseudosectiontotext");
564         }
565
566         if (query->lookup->section_question && headers) {
567                 if (!short_form) {
568                         result = dns_message_sectiontotext(msg,
569                                                        DNS_SECTION_QUESTION,
570                                                        style, flags, buf);
571                         if (result == ISC_R_NOSPACE)
572                                 goto buftoosmall;
573                         check_result(result, "dns_message_sectiontotext");
574                 }
575         }
576         if (query->lookup->section_answer) {
577                 if (!short_form) {
578                         result = dns_message_sectiontotext(msg,
579                                                        DNS_SECTION_ANSWER,
580                                                        style, flags, buf);
581                         if (result == ISC_R_NOSPACE)
582                                 goto buftoosmall;
583                         check_result(result, "dns_message_sectiontotext");
584                 } else {
585                         result = short_answer(msg, flags, buf, query);
586                         if (result == ISC_R_NOSPACE)
587                                 goto buftoosmall;
588                         check_result(result, "short_answer");
589                 }
590         }
591         if (query->lookup->section_authority) {
592                 if (!short_form) {
593                         result = dns_message_sectiontotext(msg,
594                                                        DNS_SECTION_AUTHORITY,
595                                                        style, flags, buf);
596                         if (result == ISC_R_NOSPACE)
597                                 goto buftoosmall;
598                         check_result(result, "dns_message_sectiontotext");
599                 }
600         }
601         if (query->lookup->section_additional) {
602                 if (!short_form) {
603                         result = dns_message_sectiontotext(msg,
604                                                       DNS_SECTION_ADDITIONAL,
605                                                       style, flags, buf);
606                         if (result == ISC_R_NOSPACE)
607                                 goto buftoosmall;
608                         check_result(result, "dns_message_sectiontotext");
609                         /*
610                          * Only print the signature on the first record.
611                          */
612                         if (headers) {
613                                 result = dns_message_pseudosectiontotext(
614                                                    msg,
615                                                    DNS_PSEUDOSECTION_TSIG,
616                                                    style, flags, buf);
617                                 if (result == ISC_R_NOSPACE)
618                                         goto buftoosmall;
619                                 check_result(result,
620                                           "dns_message_pseudosectiontotext");
621                                 result = dns_message_pseudosectiontotext(
622                                                    msg,
623                                                    DNS_PSEUDOSECTION_SIG0,
624                                                    style, flags, buf);
625                                 if (result == ISC_R_NOSPACE)
626                                         goto buftoosmall;
627                                 check_result(result,
628                                            "dns_message_pseudosectiontotext");
629                         }
630                 }
631         }
632
633         if (headers && query->lookup->comments && !short_form)
634                 printf("\n");
635
636         printf("%.*s", (int)isc_buffer_usedlength(buf),
637                (char *)isc_buffer_base(buf));
638         isc_buffer_free(&buf);
639
640 cleanup:
641         if (style != NULL)
642                 dns_master_styledestroy(&style, mctx);
643         return (result);
644 }
645
646 /*%
647  * print the greeting message when the program first starts up.
648  */
649 static void
650 printgreeting(int argc, char **argv, dig_lookup_t *lookup) {
651         int i;
652         int remaining;
653         static isc_boolean_t first = ISC_TRUE;
654         char append[MXNAME];
655
656         if (printcmd) {
657                 lookup->cmdline[sizeof(lookup->cmdline) - 1] = 0;
658                 snprintf(lookup->cmdline, sizeof(lookup->cmdline),
659                          "%s; <<>> DiG " VERSION " <<>>",
660                          first?"\n":"");
661                 i = 1;
662                 while (i < argc) {
663                         snprintf(append, sizeof(append), " %s", argv[i++]);
664                         remaining = sizeof(lookup->cmdline) -
665                                     strlen(lookup->cmdline) - 1;
666                         strncat(lookup->cmdline, append, remaining);
667                 }
668                 remaining = sizeof(lookup->cmdline) -
669                             strlen(lookup->cmdline) - 1;
670                 strncat(lookup->cmdline, "\n", remaining);
671                 if (first && addresscount != 0) {
672                         snprintf(append, sizeof(append),
673                                  "; (%d server%s found)\n",
674                                  addresscount,
675                                  addresscount > 1 ? "s" : "");
676                         remaining = sizeof(lookup->cmdline) -
677                                     strlen(lookup->cmdline) - 1;
678                         strncat(lookup->cmdline, append, remaining);
679                 }
680                 if (first) {
681                         snprintf(append, sizeof(append),
682                                  ";; global options:%s%s\n",
683                                  short_form ? " +short" : "",
684                                  printcmd ? " +cmd" : "");
685                         first = ISC_FALSE;
686                         remaining = sizeof(lookup->cmdline) -
687                                     strlen(lookup->cmdline) - 1;
688                         strncat(lookup->cmdline, append, remaining);
689                 }
690         }
691 }
692
693 /*%
694  * We're not using isc_commandline_parse() here since the command line
695  * syntax of dig is quite a bit different from that which can be described
696  * by that routine.
697  * XXX doc options
698  */
699
700 static void
701 plus_option(char *option, isc_boolean_t is_batchfile,
702             dig_lookup_t *lookup)
703 {
704         isc_result_t result;
705         char option_store[256];
706         char *cmd, *value, *ptr;
707         isc_uint32_t num;
708         isc_boolean_t state = ISC_TRUE;
709 #ifdef DIG_SIGCHASE
710         size_t n;
711 #endif
712
713         strncpy(option_store, option, sizeof(option_store));
714         option_store[sizeof(option_store)-1]=0;
715         ptr = option_store;
716         cmd = next_token(&ptr,"=");
717         if (cmd == NULL) {
718                 printf(";; Invalid option %s\n", option_store);
719                 return;
720         }
721         value = ptr;
722         if (strncasecmp(cmd, "no", 2)==0) {
723                 cmd += 2;
724                 state = ISC_FALSE;
725         }
726
727 #define FULLCHECK(A) \
728         do { \
729                 size_t _l = strlen(cmd); \
730                 if (_l >= sizeof(A) || strncasecmp(cmd, A, _l) != 0) \
731                         goto invalid_option; \
732         } while (0)
733 #define FULLCHECK2(A, B) \
734         do { \
735                 size_t _l = strlen(cmd); \
736                 if ((_l >= sizeof(A) || strncasecmp(cmd, A, _l) != 0) && \
737                     (_l >= sizeof(B) || strncasecmp(cmd, B, _l) != 0)) \
738                         goto invalid_option; \
739         } while (0)
740
741         switch (cmd[0]) {
742         case 'a':
743                 switch (cmd[1]) {
744                 case 'a': /* aaonly / aaflag */
745                         FULLCHECK2("aaonly", "aaflag");
746                         lookup->aaonly = state;
747                         break;
748                 case 'd':
749                         switch (cmd[2]) {
750                         case 'd': /* additional */
751                                 FULLCHECK("additional");
752                                 lookup->section_additional = state;
753                                 break;
754                         case 'f': /* adflag */
755                         case '\0': /* +ad is a synonym for +adflag */
756                                 FULLCHECK("adflag");
757                                 lookup->adflag = state;
758                                 break;
759                         default:
760                                 goto invalid_option;
761                         }
762                         break;
763                 case 'l': /* all */
764                         FULLCHECK("all");
765                         lookup->section_question = state;
766                         lookup->section_authority = state;
767                         lookup->section_answer = state;
768                         lookup->section_additional = state;
769                         lookup->comments = state;
770                         lookup->stats = state;
771                         printcmd = state;
772                         break;
773                 case 'n': /* answer */
774                         FULLCHECK("answer");
775                         lookup->section_answer = state;
776                         break;
777                 case 'u': /* authority */
778                         FULLCHECK("authority");
779                         lookup->section_authority = state;
780                         break;
781                 default:
782                         goto invalid_option;
783                 }
784                 break;
785         case 'b':
786                 switch (cmd[1]) {
787                 case 'e':/* besteffort */
788                         FULLCHECK("besteffort");
789                         lookup->besteffort = state;
790                         break;
791                 case 'u':/* bufsize */
792                         FULLCHECK("bufsize");
793                         if (value == NULL)
794                                 goto need_value;
795                         if (!state)
796                                 goto invalid_option;
797                         result = parse_uint(&num, value, COMMSIZE,
798                                             "buffer size");
799                         if (result != ISC_R_SUCCESS)
800                                 fatal("Couldn't parse buffer size");
801                         lookup->udpsize = num;
802                         break;
803                 default:
804                         goto invalid_option;
805                 }
806                 break;
807         case 'c':
808                 switch (cmd[1]) {
809                 case 'd':/* cdflag */
810                         switch (cmd[2]) {
811                         case 'f': /* cdflag */
812                         case '\0': /* +cd is a synonym for +cdflag */
813                                 FULLCHECK("cdflag");
814                                 lookup->cdflag = state;
815                                 break;
816                         default:
817                                 goto invalid_option;
818                         }
819                         break;
820                 case 'l': /* cl */
821                         FULLCHECK("cl");
822                         noclass = ISC_TF(!state);
823                         break;
824                 case 'm': /* cmd */
825                         FULLCHECK("cmd");
826                         printcmd = state;
827                         break;
828                 case 'o': /* comments */
829                         FULLCHECK("comments");
830                         lookup->comments = state;
831                         if (lookup == default_lookup)
832                                 pluscomm = state;
833                         break;
834                 default:
835                         goto invalid_option;
836                 }
837                 break;
838         case 'd':
839                 switch (cmd[1]) {
840                 case 'e': /* defname */
841                         FULLCHECK("defname");
842                         if (!lookup->trace) {
843                                 usesearch = state;
844                         }
845                         break;
846                 case 'n': /* dnssec */
847                         FULLCHECK("dnssec");
848                         if (state && lookup->edns == -1)
849                                 lookup->edns = 0;
850                         lookup->dnssec = state;
851                         break;
852                 case 'o': /* domain */
853                         FULLCHECK("domain");
854                         if (value == NULL)
855                                 goto need_value;
856                         if (!state)
857                                 goto invalid_option;
858                         strncpy(domainopt, value, sizeof(domainopt));
859                         domainopt[sizeof(domainopt)-1] = '\0';
860                         break;
861                 default:
862                         goto invalid_option;
863                 }
864                 break;
865         case 'e':
866                 FULLCHECK("edns");
867                 if (!state) {
868                         lookup->edns = -1;
869                         break;
870                 }
871                 if (value == NULL) {
872                         lookup->edns = 0;
873                         break;
874                 }
875                 result = parse_uint(&num, value, 255, "edns");
876                 if (result != ISC_R_SUCCESS)
877                         fatal("Couldn't parse edns");
878                 lookup->edns = num;
879                 break;
880         case 'f': /* fail */
881                 FULLCHECK("fail");
882                 lookup->servfail_stops = state;
883                 break;
884         case 'i':
885                 switch (cmd[1]) {
886                 case 'd': /* identify */
887                         FULLCHECK("identify");
888                         lookup->identify = state;
889                         break;
890                 case 'g': /* ignore */
891                 default: /* Inherits default for compatibility */
892                         FULLCHECK("ignore");
893                         lookup->ignore = ISC_TRUE;
894                 }
895                 break;
896         case 'k':
897                 FULLCHECK("keepopen");
898                 keep_open = state;
899                 break;
900         case 'm': /* multiline */
901                 FULLCHECK("multiline");
902                 multiline = state;
903                 break;
904         case 'n':
905                 switch (cmd[1]) {
906                 case 'd': /* ndots */
907                         FULLCHECK("ndots");
908                         if (value == NULL)
909                                 goto need_value;
910                         if (!state)
911                                 goto invalid_option;
912                         result = parse_uint(&num, value, MAXNDOTS, "ndots");
913                         if (result != ISC_R_SUCCESS)
914                                 fatal("Couldn't parse ndots");
915                         ndots = num;
916                         break;
917                 case 's':
918                         switch (cmd[2]) {
919                         case 'i': /* nsid */
920                                 FULLCHECK("nsid");
921                                 if (state && lookup->edns == -1)
922                                         lookup->edns = 0;
923                                 lookup->nsid = state;
924                                 break;
925                         case 's': /* nssearch */
926                                 FULLCHECK("nssearch");
927                                 lookup->ns_search_only = state;
928                                 if (state) {
929                                         lookup->trace_root = ISC_TRUE;
930                                         lookup->recurse = ISC_TRUE;
931                                         lookup->identify = ISC_TRUE;
932                                         lookup->stats = ISC_FALSE;
933                                         lookup->comments = ISC_FALSE;
934                                         lookup->section_additional = ISC_FALSE;
935                                         lookup->section_authority = ISC_FALSE;
936                                         lookup->section_question = ISC_FALSE;
937                                         lookup->rdtype = dns_rdatatype_ns;
938                                         lookup->rdtypeset = ISC_TRUE;
939                                         short_form = ISC_TRUE;
940                                 }
941                                 break;
942                         default:
943                                 goto invalid_option;
944                         }
945                         break;
946                 default:
947                         goto invalid_option;
948                 }
949                 break;
950         case 'o':
951                 FULLCHECK("onesoa");
952                 onesoa = state;
953                 break;
954         case 'q':
955                 switch (cmd[1]) {
956                 case 'r': /* qr */
957                         FULLCHECK("qr");
958                         qr = state;
959                         break;
960                 case 'u': /* question */
961                         FULLCHECK("question");
962                         lookup->section_question = state;
963                         if (lookup == default_lookup)
964                                 plusquest = state;
965                         break;
966                 default:
967                         goto invalid_option;
968                 }
969                 break;
970         case 'r':
971                 switch (cmd[1]) {
972                 case 'e':
973                         switch (cmd[2]) {
974                         case 'c': /* recurse */
975                                 FULLCHECK("recurse");
976                                 lookup->recurse = state;
977                                 break;
978                         case 't': /* retry / retries */
979                                 FULLCHECK2("retry", "retries");
980                                 if (value == NULL)
981                                         goto need_value;
982                                 if (!state)
983                                         goto invalid_option;
984                                 result = parse_uint(&lookup->retries, value,
985                                                     MAXTRIES - 1, "retries");
986                                 if (result != ISC_R_SUCCESS)
987                                         fatal("Couldn't parse retries");
988                                 lookup->retries++;
989                                 break;
990                         default:
991                                 goto invalid_option;
992                         }
993                         break;
994                 default:
995                         goto invalid_option;
996                 }
997                 break;
998         case 's':
999                 switch (cmd[1]) {
1000                 case 'e': /* search */
1001                         FULLCHECK("search");
1002                         if (!lookup->trace) {
1003                                 usesearch = state;
1004                         }
1005                         break;
1006                 case 'h':
1007                         if (cmd[2] != 'o')
1008                                 goto invalid_option;
1009                         switch (cmd[3]) {
1010                         case 'r': /* short */
1011                                 FULLCHECK("short");
1012                                 short_form = state;
1013                                 if (state) {
1014                                         printcmd = ISC_FALSE;
1015                                         lookup->section_additional = ISC_FALSE;
1016                                         lookup->section_answer = ISC_TRUE;
1017                                         lookup->section_authority = ISC_FALSE;
1018                                         lookup->section_question = ISC_FALSE;
1019                                         lookup->comments = ISC_FALSE;
1020                                         lookup->stats = ISC_FALSE;
1021                                 }
1022                                 break;
1023                         case 'w': /* showsearch */
1024                                 FULLCHECK("showsearch");
1025                                 if (!lookup->trace) {
1026                                         showsearch = state;
1027                                         usesearch = state;
1028                                 }
1029                                 break;
1030                         default:
1031                                 goto invalid_option;
1032                         }
1033                         break;
1034 #ifdef DIG_SIGCHASE
1035                 case 'i': /* sigchase */
1036                         FULLCHECK("sigchase");
1037                         lookup->sigchase = state;
1038                         if (lookup->sigchase)
1039                                 lookup->dnssec = ISC_TRUE;
1040                         break;
1041 #endif
1042                 case 't': /* stats */
1043                         FULLCHECK("stats");
1044                         lookup->stats = state;
1045                         break;
1046                 default:
1047                         goto invalid_option;
1048                 }
1049                 break;
1050         case 't':
1051                 switch (cmd[1]) {
1052                 case 'c': /* tcp */
1053                         FULLCHECK("tcp");
1054                         if (!is_batchfile)
1055                                 lookup->tcp_mode = state;
1056                         break;
1057                 case 'i': /* timeout */
1058                         FULLCHECK("timeout");
1059                         if (value == NULL)
1060                                 goto need_value;
1061                         if (!state)
1062                                 goto invalid_option;
1063                         result = parse_uint(&timeout, value, MAXTIMEOUT,
1064                                             "timeout");
1065                         if (result != ISC_R_SUCCESS)
1066                                 fatal("Couldn't parse timeout");
1067                         if (timeout == 0)
1068                                 timeout = 1;
1069                         break;
1070 #if DIG_SIGCHASE_TD
1071                 case 'o': /* topdown */
1072                         FULLCHECK("topdown");
1073                         lookup->do_topdown = state;
1074                         break;
1075 #endif
1076                 case 'r':
1077                         switch (cmd[2]) {
1078                         case 'a': /* trace */
1079                                 FULLCHECK("trace");
1080                                 lookup->trace = state;
1081                                 lookup->trace_root = state;
1082                                 if (state) {
1083                                         lookup->recurse = ISC_FALSE;
1084                                         lookup->identify = ISC_TRUE;
1085                                         lookup->comments = ISC_FALSE;
1086                                         lookup->stats = ISC_FALSE;
1087                                         lookup->section_additional = ISC_FALSE;
1088                                         lookup->section_authority = ISC_TRUE;
1089                                         lookup->section_question = ISC_FALSE;
1090                                         usesearch = ISC_FALSE;
1091                                 }
1092                                 break;
1093                         case 'i': /* tries */
1094                                 FULLCHECK("tries");
1095                                 if (value == NULL)
1096                                         goto need_value;
1097                                 if (!state)
1098                                         goto invalid_option;
1099                                 result = parse_uint(&lookup->retries, value,
1100                                                     MAXTRIES, "tries");
1101                                 if (result != ISC_R_SUCCESS)
1102                                         fatal("Couldn't parse tries");
1103                                 if (lookup->retries == 0)
1104                                         lookup->retries = 1;
1105                                 break;
1106 #ifdef DIG_SIGCHASE
1107                         case 'u': /* trusted-key */
1108                                 FULLCHECK("trusted-key");
1109                                 if (value == NULL)
1110                                         goto need_value;
1111                                 if (!state)
1112                                         goto invalid_option;
1113                                 n = strlcpy(trustedkey, ptr,
1114                                             sizeof(trustedkey));
1115                                 if (n >= sizeof(trustedkey))
1116                                         fatal("trusted key too large");
1117                                 break;
1118 #endif
1119                         default:
1120                                 goto invalid_option;
1121                         }
1122                         break;
1123                 case 't': /* ttlid */
1124                         FULLCHECK("ttlid");
1125                         nottl = ISC_TF(!state);
1126                         break;
1127                 default:
1128                         goto invalid_option;
1129                 }
1130                 break;
1131         case 'v':
1132                 FULLCHECK("vc");
1133                 if (!is_batchfile)
1134                         lookup->tcp_mode = state;
1135                 break;
1136         default:
1137         invalid_option:
1138         need_value:
1139                 fprintf(stderr, "Invalid option: +%s\n",
1140                          option);
1141                 usage();
1142         }
1143         return;
1144 }
1145
1146 /*%
1147  * #ISC_TRUE returned if value was used
1148  */
1149 static const char *single_dash_opts = "46dhimnv";
1150 static const char *dash_opts = "46bcdfhikmnptvyx";
1151 static isc_boolean_t
1152 dash_option(char *option, char *next, dig_lookup_t **lookup,
1153             isc_boolean_t *open_type_class, isc_boolean_t *need_clone,
1154             isc_boolean_t config_only, int argc, char **argv,
1155             isc_boolean_t *firstarg)
1156 {
1157         char opt, *value, *ptr, *ptr2, *ptr3;
1158         isc_result_t result;
1159         isc_boolean_t value_from_next;
1160         isc_textregion_t tr;
1161         dns_rdatatype_t rdtype;
1162         dns_rdataclass_t rdclass;
1163         char textname[MXNAME];
1164         struct in_addr in4;
1165         struct in6_addr in6;
1166         in_port_t srcport;
1167         char *hash, *cmd;
1168         isc_uint32_t num;
1169
1170         while (strpbrk(option, single_dash_opts) == &option[0]) {
1171                 /*
1172                  * Since the -[46dhimnv] options do not take an argument,
1173                  * account for them (in any number and/or combination)
1174                  * if they appear as the first character(s) of a q-opt.
1175                  */
1176                 opt = option[0];
1177                 switch (opt) {
1178                 case '4':
1179                         if (have_ipv4) {
1180                                 isc_net_disableipv6();
1181                                 have_ipv6 = ISC_FALSE;
1182                         } else {
1183                                 fatal("can't find IPv4 networking");
1184                                 /* NOTREACHED */
1185                                 return (ISC_FALSE);
1186                         }
1187                         break;
1188                 case '6':
1189                         if (have_ipv6) {
1190                                 isc_net_disableipv4();
1191                                 have_ipv4 = ISC_FALSE;
1192                         } else {
1193                                 fatal("can't find IPv6 networking");
1194                                 /* NOTREACHED */
1195                                 return (ISC_FALSE);
1196                         }
1197                         break;
1198                 case 'd':
1199                         ptr = strpbrk(&option[1], dash_opts);
1200                         if (ptr != &option[1]) {
1201                                 cmd = option;
1202                                 FULLCHECK("debug");
1203                                 debugging = ISC_TRUE;
1204                                 return (ISC_FALSE);
1205                         } else
1206                                 debugging = ISC_TRUE;
1207                         break;
1208                 case 'h':
1209                         help();
1210                         exit(0);
1211                         break;
1212                 case 'i':
1213                         ip6_int = ISC_TRUE;
1214                         break;
1215                 case 'm': /* memdebug */
1216                         /* memdebug is handled in preparse_args() */
1217                         break;
1218                 case 'n':
1219                         /* deprecated */
1220                         break;
1221                 case 'v':
1222                         version();
1223                         exit(0);
1224                         break;
1225                 }
1226                 if (strlen(option) > 1U)
1227                         option = &option[1];
1228                 else
1229                         return (ISC_FALSE);
1230         }
1231         opt = option[0];
1232         if (strlen(option) > 1U) {
1233                 value_from_next = ISC_FALSE;
1234                 value = &option[1];
1235         } else {
1236                 value_from_next = ISC_TRUE;
1237                 value = next;
1238         }
1239         if (value == NULL)
1240                 goto invalid_option;
1241         switch (opt) {
1242         case 'b':
1243                 hash = strchr(value, '#');
1244                 if (hash != NULL) {
1245                         result = parse_uint(&num, hash + 1, MAXPORT,
1246                                             "port number");
1247                         if (result != ISC_R_SUCCESS)
1248                                 fatal("Couldn't parse port number");
1249                         srcport = num;
1250                         *hash = '\0';
1251                 } else
1252                         srcport = 0;
1253                 if (have_ipv6 && inet_pton(AF_INET6, value, &in6) == 1) {
1254                         isc_sockaddr_fromin6(&bind_address, &in6, srcport);
1255                         isc_net_disableipv4();
1256                 } else if (have_ipv4 && inet_pton(AF_INET, value, &in4) == 1) {
1257                         isc_sockaddr_fromin(&bind_address, &in4, srcport);
1258                         isc_net_disableipv6();
1259                 } else {
1260                         if (hash != NULL)
1261                                 *hash = '#';
1262                         fatal("invalid address %s", value);
1263                 }
1264                 if (hash != NULL)
1265                         *hash = '#';
1266                 specified_source = ISC_TRUE;
1267                 return (value_from_next);
1268         case 'c':
1269                 if ((*lookup)->rdclassset) {
1270                         fprintf(stderr, ";; Warning, extra class option\n");
1271                 }
1272                 *open_type_class = ISC_FALSE;
1273                 tr.base = value;
1274                 tr.length = strlen(value);
1275                 result = dns_rdataclass_fromtext(&rdclass,
1276                                                  (isc_textregion_t *)&tr);
1277                 if (result == ISC_R_SUCCESS) {
1278                         (*lookup)->rdclass = rdclass;
1279                         (*lookup)->rdclassset = ISC_TRUE;
1280                 } else
1281                         fprintf(stderr, ";; Warning, ignoring "
1282                                 "invalid class %s\n",
1283                                 value);
1284                 return (value_from_next);
1285         case 'f':
1286                 batchname = value;
1287                 return (value_from_next);
1288         case 'k':
1289                 strncpy(keyfile, value, sizeof(keyfile));
1290                 keyfile[sizeof(keyfile)-1]=0;
1291                 return (value_from_next);
1292         case 'p':
1293                 result = parse_uint(&num, value, MAXPORT, "port number");
1294                 if (result != ISC_R_SUCCESS)
1295                         fatal("Couldn't parse port number");
1296                 port = num;
1297                 return (value_from_next);
1298         case 'q':
1299                 if (!config_only) {
1300                         if (*need_clone)
1301                                 (*lookup) = clone_lookup(default_lookup,
1302                                                          ISC_TRUE);
1303                         *need_clone = ISC_TRUE;
1304                         strncpy((*lookup)->textname, value,
1305                                 sizeof((*lookup)->textname));
1306                         (*lookup)->textname[sizeof((*lookup)->textname)-1]=0;
1307                         (*lookup)->trace_root = ISC_TF((*lookup)->trace  ||
1308                                                      (*lookup)->ns_search_only);
1309                         (*lookup)->new_search = ISC_TRUE;
1310                         if (*firstarg) {
1311                                 printgreeting(argc, argv, *lookup);
1312                                 *firstarg = ISC_FALSE;
1313                         }
1314                         ISC_LIST_APPEND(lookup_list, (*lookup), link);
1315                         debug("looking up %s", (*lookup)->textname);
1316                 }
1317                 return (value_from_next);
1318         case 't':
1319                 *open_type_class = ISC_FALSE;
1320                 if (strncasecmp(value, "ixfr=", 5) == 0) {
1321                         rdtype = dns_rdatatype_ixfr;
1322                         result = ISC_R_SUCCESS;
1323                 } else {
1324                         tr.base = value;
1325                         tr.length = strlen(value);
1326                         result = dns_rdatatype_fromtext(&rdtype,
1327                                                 (isc_textregion_t *)&tr);
1328                         if (result == ISC_R_SUCCESS &&
1329                             rdtype == dns_rdatatype_ixfr) {
1330                                 result = DNS_R_UNKNOWN;
1331                         }
1332                 }
1333                 if (result == ISC_R_SUCCESS) {
1334                         if ((*lookup)->rdtypeset) {
1335                                 fprintf(stderr, ";; Warning, "
1336                                                 "extra type option\n");
1337                         }
1338                         if (rdtype == dns_rdatatype_ixfr) {
1339                                 isc_uint32_t serial;
1340                                 (*lookup)->rdtype = dns_rdatatype_ixfr;
1341                                 (*lookup)->rdtypeset = ISC_TRUE;
1342                                 result = parse_uint(&serial, &value[5],
1343                                            MAXSERIAL, "serial number");
1344                                 if (result != ISC_R_SUCCESS)
1345                                         fatal("Couldn't parse serial number");
1346                                 (*lookup)->ixfr_serial = serial;
1347                                 (*lookup)->section_question = plusquest;
1348                                 (*lookup)->comments = pluscomm;
1349                                 (*lookup)->tcp_mode = ISC_TRUE;
1350                         } else {
1351                                 (*lookup)->rdtype = rdtype;
1352                                 (*lookup)->rdtypeset = ISC_TRUE;
1353                                 if (rdtype == dns_rdatatype_axfr) {
1354                                         (*lookup)->section_question = plusquest;
1355                                         (*lookup)->comments = pluscomm;
1356                                 }
1357                                 (*lookup)->ixfr_serial = ISC_FALSE;
1358                         }
1359                 } else
1360                         fprintf(stderr, ";; Warning, ignoring "
1361                                  "invalid type %s\n",
1362                                  value);
1363                 return (value_from_next);
1364         case 'y':
1365                 ptr = next_token(&value,":");   /* hmac type or name */
1366                 if (ptr == NULL) {
1367                         usage();
1368                 }
1369                 ptr2 = next_token(&value, ":"); /* name or secret */
1370                 if (ptr2 == NULL)
1371                         usage();
1372                 ptr3 = next_token(&value,":"); /* secret or NULL */
1373                 if (ptr3 != NULL) {
1374                         parse_hmac(ptr);
1375                         ptr = ptr2;
1376                         ptr2 = ptr3;
1377                 } else  {
1378                         hmacname = DNS_TSIG_HMACMD5_NAME;
1379                         digestbits = 0;
1380                 }
1381                 strncpy(keynametext, ptr, sizeof(keynametext));
1382                 keynametext[sizeof(keynametext)-1]=0;
1383                 strncpy(keysecret, ptr2, sizeof(keysecret));
1384                 keysecret[sizeof(keysecret)-1]=0;
1385                 return (value_from_next);
1386         case 'x':
1387                 if (*need_clone)
1388                         *lookup = clone_lookup(default_lookup, ISC_TRUE);
1389                 *need_clone = ISC_TRUE;
1390                 if (get_reverse(textname, sizeof(textname), value,
1391                                 ip6_int, ISC_FALSE) == ISC_R_SUCCESS) {
1392                         strncpy((*lookup)->textname, textname,
1393                                 sizeof((*lookup)->textname));
1394                         debug("looking up %s", (*lookup)->textname);
1395                         (*lookup)->trace_root = ISC_TF((*lookup)->trace  ||
1396                                                 (*lookup)->ns_search_only);
1397                         (*lookup)->ip6_int = ip6_int;
1398                         if (!(*lookup)->rdtypeset)
1399                                 (*lookup)->rdtype = dns_rdatatype_ptr;
1400                         if (!(*lookup)->rdclassset)
1401                                 (*lookup)->rdclass = dns_rdataclass_in;
1402                         (*lookup)->new_search = ISC_TRUE;
1403                         if (*firstarg) {
1404                                 printgreeting(argc, argv, *lookup);
1405                                 *firstarg = ISC_FALSE;
1406                         }
1407                         ISC_LIST_APPEND(lookup_list, *lookup, link);
1408                 } else {
1409                         fprintf(stderr, "Invalid IP address %s\n", value);
1410                         exit(1);
1411                 }
1412                 return (value_from_next);
1413         invalid_option:
1414         default:
1415                 fprintf(stderr, "Invalid option: -%s\n", option);
1416                 usage();
1417         }
1418         /* NOTREACHED */
1419         return (ISC_FALSE);
1420 }
1421
1422 /*%
1423  * Because we may be trying to do memory allocation recording, we're going
1424  * to need to parse the arguments for the -m *before* we start the main
1425  * argument parsing routine.
1426  *
1427  * I'd prefer not to have to do this, but I am not quite sure how else to
1428  * fix the problem.  Argument parsing in dig involves memory allocation
1429  * by its nature, so it can't be done in the main argument parser.
1430  */
1431 static void
1432 preparse_args(int argc, char **argv) {
1433         int rc;
1434         char **rv;
1435         char *option;
1436
1437         rc = argc;
1438         rv = argv;
1439         for (rc--, rv++; rc > 0; rc--, rv++) {
1440                 if (rv[0][0] != '-')
1441                         continue;
1442                 option = &rv[0][1];
1443                 while (strpbrk(option, single_dash_opts) == &option[0]) {
1444                         if (option[0] == 'm') {
1445                                 memdebugging = ISC_TRUE;
1446                                 isc_mem_debugging = ISC_MEM_DEBUGTRACE |
1447                                         ISC_MEM_DEBUGRECORD;
1448                                 return;
1449                         }
1450                         option = &option[1];
1451                 }
1452         }
1453 }
1454
1455 static void
1456 parse_args(isc_boolean_t is_batchfile, isc_boolean_t config_only,
1457            int argc, char **argv) {
1458         isc_result_t result;
1459         isc_textregion_t tr;
1460         isc_boolean_t firstarg = ISC_TRUE;
1461         dig_lookup_t *lookup = NULL;
1462         dns_rdatatype_t rdtype;
1463         dns_rdataclass_t rdclass;
1464         isc_boolean_t open_type_class = ISC_TRUE;
1465         char batchline[MXNAME];
1466         int bargc;
1467         char *bargv[64];
1468         int rc;
1469         char **rv;
1470 #ifndef NOPOSIX
1471         char *homedir;
1472         char rcfile[256];
1473 #endif
1474         char *input;
1475         int i;
1476         isc_boolean_t need_clone = ISC_TRUE;
1477
1478         /*
1479          * The semantics for parsing the args is a bit complex; if
1480          * we don't have a host yet, make the arg apply globally,
1481          * otherwise make it apply to the latest host.  This is
1482          * a bit different than the previous versions, but should
1483          * form a consistent user interface.
1484          *
1485          * First, create a "default lookup" which won't actually be used
1486          * anywhere, except for cloning into new lookups
1487          */
1488
1489         debug("parse_args()");
1490         if (!is_batchfile) {
1491                 debug("making new lookup");
1492                 default_lookup = make_empty_lookup();
1493
1494 #ifndef NOPOSIX
1495                 /*
1496                  * Treat ${HOME}/.digrc as a special batchfile
1497                  */
1498                 INSIST(batchfp == NULL);
1499                 homedir = getenv("HOME");
1500                 if (homedir != NULL) {
1501                         unsigned int n;
1502                         n = snprintf(rcfile, sizeof(rcfile), "%s/.digrc",
1503                                      homedir);
1504                         if (n < sizeof(rcfile))
1505                                 batchfp = fopen(rcfile, "r");
1506                 }
1507                 if (batchfp != NULL) {
1508                         while (fgets(batchline, sizeof(batchline),
1509                                      batchfp) != 0) {
1510                                 debug("config line %s", batchline);
1511                                 bargc = 1;
1512                                 input = batchline;
1513                                 bargv[bargc] = next_token(&input, " \t\r\n");
1514                                 while ((bargv[bargc] != NULL) &&
1515                                        (bargc < 62)) {
1516                                         bargc++;
1517                                         bargv[bargc] =
1518                                                 next_token(&input, " \t\r\n");
1519                                 }
1520
1521                                 bargv[0] = argv[0];
1522                                 argv0 = argv[0];
1523
1524                                 for(i = 0; i < bargc; i++)
1525                                         debug(".digrc argv %d: %s",
1526                                               i, bargv[i]);
1527                                 parse_args(ISC_TRUE, ISC_TRUE, bargc,
1528                                            (char **)bargv);
1529                         }
1530                         fclose(batchfp);
1531                 }
1532 #endif
1533         }
1534
1535         if (is_batchfile && !config_only) {
1536                 /* Processing '-f batchfile'. */
1537                 lookup = clone_lookup(default_lookup, ISC_TRUE);
1538                 need_clone = ISC_FALSE;
1539         } else
1540                 lookup = default_lookup;
1541
1542         rc = argc;
1543         rv = argv;
1544         for (rc--, rv++; rc > 0; rc--, rv++) {
1545                 debug("main parsing %s", rv[0]);
1546                 if (strncmp(rv[0], "%", 1) == 0)
1547                         break;
1548                 if (strncmp(rv[0], "@", 1) == 0) {
1549                         addresscount = getaddresses(lookup, &rv[0][1], NULL);
1550                 } else if (rv[0][0] == '+') {
1551                         plus_option(&rv[0][1], is_batchfile,
1552                                     lookup);
1553                 } else if (rv[0][0] == '-') {
1554                         if (rc <= 1) {
1555                                 if (dash_option(&rv[0][1], NULL,
1556                                                 &lookup, &open_type_class,
1557                                                 &need_clone, config_only,
1558                                                 argc, argv, &firstarg)) {
1559                                         rc--;
1560                                         rv++;
1561                                 }
1562                         } else {
1563                                 if (dash_option(&rv[0][1], rv[1],
1564                                                 &lookup, &open_type_class,
1565                                                 &need_clone, config_only,
1566                                                 argc, argv, &firstarg)) {
1567                                         rc--;
1568                                         rv++;
1569                                 }
1570                         }
1571                 } else {
1572                         /*
1573                          * Anything which isn't an option
1574                          */
1575                         if (open_type_class) {
1576                                 if (strncasecmp(rv[0], "ixfr=", 5) == 0) {
1577                                         rdtype = dns_rdatatype_ixfr;
1578                                         result = ISC_R_SUCCESS;
1579                                 } else {
1580                                         tr.base = rv[0];
1581                                         tr.length = strlen(rv[0]);
1582                                         result = dns_rdatatype_fromtext(&rdtype,
1583                                                 (isc_textregion_t *)&tr);
1584                                         if (result == ISC_R_SUCCESS &&
1585                                             rdtype == dns_rdatatype_ixfr) {
1586                                                 fprintf(stderr, ";; Warning, "
1587                                                         "ixfr requires a "
1588                                                         "serial number\n");
1589                                                 continue;
1590                                         }
1591                                 }
1592                                 if (result == ISC_R_SUCCESS) {
1593                                         if (lookup->rdtypeset) {
1594                                                 fprintf(stderr, ";; Warning, "
1595                                                         "extra type option\n");
1596                                         }
1597                                         if (rdtype == dns_rdatatype_ixfr) {
1598                                                 isc_uint32_t serial;
1599                                                 lookup->rdtype =
1600                                                         dns_rdatatype_ixfr;
1601                                                 lookup->rdtypeset = ISC_TRUE;
1602                                                 result = parse_uint(&serial,
1603                                                                     &rv[0][5],
1604                                                                     MAXSERIAL,
1605                                                               "serial number");
1606                                                 if (result != ISC_R_SUCCESS)
1607                                                         fatal("Couldn't parse "
1608                                                               "serial number");
1609                                                 lookup->ixfr_serial = serial;
1610                                                 lookup->section_question =
1611                                                         plusquest;
1612                                                 lookup->comments = pluscomm;
1613                                                 lookup->tcp_mode = ISC_TRUE;
1614                                         } else {
1615                                                 lookup->rdtype = rdtype;
1616                                                 lookup->rdtypeset = ISC_TRUE;
1617                                                 if (rdtype ==
1618                                                     dns_rdatatype_axfr) {
1619                                                     lookup->section_question =
1620                                                                 plusquest;
1621                                                     lookup->comments = pluscomm;
1622                                                 }
1623                                                 lookup->ixfr_serial = ISC_FALSE;
1624                                         }
1625                                         continue;
1626                                 }
1627                                 result = dns_rdataclass_fromtext(&rdclass,
1628                                                      (isc_textregion_t *)&tr);
1629                                 if (result == ISC_R_SUCCESS) {
1630                                         if (lookup->rdclassset) {
1631                                                 fprintf(stderr, ";; Warning, "
1632                                                         "extra class option\n");
1633                                         }
1634                                         lookup->rdclass = rdclass;
1635                                         lookup->rdclassset = ISC_TRUE;
1636                                         continue;
1637                                 }
1638                         }
1639
1640                         if (!config_only) {
1641                                 if (need_clone)
1642                                         lookup = clone_lookup(default_lookup,
1643                                                                       ISC_TRUE);
1644                                 need_clone = ISC_TRUE;
1645                                 strncpy(lookup->textname, rv[0],
1646                                         sizeof(lookup->textname));
1647                                 lookup->textname[sizeof(lookup->textname)-1]=0;
1648                                 lookup->trace_root = ISC_TF(lookup->trace  ||
1649                                                      lookup->ns_search_only);
1650                                 lookup->new_search = ISC_TRUE;
1651                                 if (firstarg) {
1652                                         printgreeting(argc, argv, lookup);
1653                                         firstarg = ISC_FALSE;
1654                                 }
1655                                 ISC_LIST_APPEND(lookup_list, lookup, link);
1656                                 debug("looking up %s", lookup->textname);
1657                         }
1658                         /* XXX Error message */
1659                 }
1660         }
1661
1662         /*
1663          * If we have a batchfile, seed the lookup list with the
1664          * first entry, then trust the callback in dighost_shutdown
1665          * to get the rest
1666          */
1667         if ((batchname != NULL) && !(is_batchfile)) {
1668                 if (strcmp(batchname, "-") == 0)
1669                         batchfp = stdin;
1670                 else
1671                         batchfp = fopen(batchname, "r");
1672                 if (batchfp == NULL) {
1673                         perror(batchname);
1674                         if (exitcode < 8)
1675                                 exitcode = 8;
1676                         fatal("couldn't open specified batch file");
1677                 }
1678                 /* XXX Remove code dup from shutdown code */
1679         next_line:
1680                 if (fgets(batchline, sizeof(batchline), batchfp) != 0) {
1681                         bargc = 1;
1682                         debug("batch line %s", batchline);
1683                         if (batchline[0] == '\r' || batchline[0] == '\n'
1684                             || batchline[0] == '#' || batchline[0] == ';')
1685                                 goto next_line;
1686                         input = batchline;
1687                         bargv[bargc] = next_token(&input, " \t\r\n");
1688                         while ((bargv[bargc] != NULL) && (bargc < 14)) {
1689                                 bargc++;
1690                                 bargv[bargc] = next_token(&input, " \t\r\n");
1691                         }
1692
1693                         bargv[0] = argv[0];
1694                         argv0 = argv[0];
1695
1696                         for(i = 0; i < bargc; i++)
1697                                 debug("batch argv %d: %s", i, bargv[i]);
1698                         parse_args(ISC_TRUE, ISC_FALSE, bargc, (char **)bargv);
1699                         return;
1700                 }
1701                 return;
1702         }
1703         /*
1704          * If no lookup specified, search for root
1705          */
1706         if ((lookup_list.head == NULL) && !config_only) {
1707                 if (need_clone)
1708                         lookup = clone_lookup(default_lookup, ISC_TRUE);
1709                 need_clone = ISC_TRUE;
1710                 lookup->trace_root = ISC_TF(lookup->trace ||
1711                                             lookup->ns_search_only);
1712                 lookup->new_search = ISC_TRUE;
1713                 strcpy(lookup->textname, ".");
1714                 lookup->rdtype = dns_rdatatype_ns;
1715                 lookup->rdtypeset = ISC_TRUE;
1716                 if (firstarg) {
1717                         printgreeting(argc, argv, lookup);
1718                         firstarg = ISC_FALSE;
1719                 }
1720                 ISC_LIST_APPEND(lookup_list, lookup, link);
1721         }
1722         if (!need_clone)
1723                 destroy_lookup(lookup);
1724 }
1725
1726 /*
1727  * Callback from dighost.c to allow program-specific shutdown code.
1728  * Here, we're possibly reading from a batch file, then shutting down
1729  * for real if there's nothing in the batch file to read.
1730  */
1731 void
1732 dighost_shutdown(void) {
1733         char batchline[MXNAME];
1734         int bargc;
1735         char *bargv[16];
1736         char *input;
1737         int i;
1738
1739         if (batchname == NULL) {
1740                 isc_app_shutdown();
1741                 return;
1742         }
1743
1744         fflush(stdout);
1745         if (feof(batchfp)) {
1746                 batchname = NULL;
1747                 isc_app_shutdown();
1748                 if (batchfp != stdin)
1749                         fclose(batchfp);
1750                 return;
1751         }
1752
1753         if (fgets(batchline, sizeof(batchline), batchfp) != 0) {
1754                 debug("batch line %s", batchline);
1755                 bargc = 1;
1756                 input = batchline;
1757                 bargv[bargc] = next_token(&input, " \t\r\n");
1758                 while ((bargv[bargc] != NULL) && (bargc < 14)) {
1759                         bargc++;
1760                         bargv[bargc] = next_token(&input, " \t\r\n");
1761                 }
1762
1763                 bargv[0] = argv0;
1764
1765                 for(i = 0; i < bargc; i++)
1766                         debug("batch argv %d: %s", i, bargv[i]);
1767                 parse_args(ISC_TRUE, ISC_FALSE, bargc, (char **)bargv);
1768                 start_lookup();
1769         } else {
1770                 batchname = NULL;
1771                 if (batchfp != stdin)
1772                         fclose(batchfp);
1773                 isc_app_shutdown();
1774                 return;
1775         }
1776 }
1777
1778 /*% Main processing routine for dig */
1779 int
1780 main(int argc, char **argv) {
1781         isc_result_t result;
1782
1783         ISC_LIST_INIT(lookup_list);
1784         ISC_LIST_INIT(server_list);
1785         ISC_LIST_INIT(search_list);
1786
1787         debug("main()");
1788         preparse_args(argc, argv);
1789         progname = argv[0];
1790         result = isc_app_start();
1791         check_result(result, "isc_app_start");
1792         setup_libs();
1793         parse_args(ISC_FALSE, ISC_FALSE, argc, argv);
1794         setup_system();
1795         if (domainopt[0] != '\0') {
1796                 set_search_domain(domainopt);
1797                 usesearch = ISC_TRUE;
1798         }
1799         result = isc_app_onrun(mctx, global_task, onrun_callback, NULL);
1800         check_result(result, "isc_app_onrun");
1801         isc_app_run();
1802         destroy_lookup(default_lookup);
1803         if (batchname != NULL) {
1804                 if (batchfp != stdin)
1805                         fclose(batchfp);
1806                 batchname = NULL;
1807         }
1808 #ifdef DIG_SIGCHASE
1809         clean_trustedkey();
1810 #endif
1811         cancel_all();
1812         destroy_libs();
1813         isc_app_finish();
1814         return (exitcode);
1815 }