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