dig.c 66.9 KB
Newer Older
Brian Wellington's avatar
Brian Wellington committed
1
/*
2
 * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
3
 *
4 5 6
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
7 8 9
 *
 * See the COPYRIGHT file distributed with this work for additional
 * information regarding copyright ownership.
10 11
 */

12
/*! \file */
13

14
#include <ctype.h>
15
#include <inttypes.h>
16
#include <stdbool.h>
17
#include <stdlib.h>
Brian Wellington's avatar
Brian Wellington committed
18
#include <time.h>
19

David Lawrence's avatar
David Lawrence committed
20
#include <isc/app.h>
21
#include <isc/netaddr.h>
22
#include <isc/parseint.h>
23
#include <isc/platform.h>
Mark Andrews's avatar
Mark Andrews committed
24
#include <isc/print.h>
David Lawrence's avatar
David Lawrence committed
25
#include <isc/string.h>
26
#include <isc/task.h>
27
#include <isc/util.h>
David Lawrence's avatar
David Lawrence committed
28

29 30
#include <dns/byaddr.h>
#include <dns/fixedname.h>
31
#include <dns/masterdump.h>
32
#include <dns/message.h>
Brian Wellington's avatar
Brian Wellington committed
33
#include <dns/name.h>
34
#include <dns/rcode.h>
35
#include <dns/rdata.h>
36
#include <dns/rdataclass.h>
37 38
#include <dns/rdataset.h>
#include <dns/rdatatype.h>
39
#include <dns/result.h>
40
#include <dns/tsig.h>
41

Mark Andrews's avatar
Mark Andrews committed
42
#include <dig/dig.h>
43
#include <pk11/site.h>
Mark Andrews's avatar
Mark Andrews committed
44

45 46 47
#define ADD_STRING(b, s)                                        \
	{                                                       \
		if (strlen(s) >= isc_buffer_availablelength(b)) \
48
			return ((ISC_R_NOSPACE));               \
49 50 51
		else                                            \
			isc_buffer_putstr(b, s);                \
	}
52

53
#define DIG_MAX_ADDRESSES 20
54

55
dig_lookup_t *default_lookup = NULL;
56

57
static atomic_uintptr_t batchname = ATOMIC_VAR_INIT(0);
Evan Hunt's avatar
Evan Hunt committed
58 59 60
static FILE *batchfp = NULL;
static char *argv0;
static int addresscount = 0;
61

Brian Wellington's avatar
Brian Wellington committed
62
static char domainopt[DNS_NAME_MAXTEXT];
63
static char hexcookie[81];
64

65 66
static bool short_form = false, printcmd = true, plusquest = false,
	    pluscomm = false, ipv4only = false, ipv6only = false, digrc = true;
67
static uint32_t splitwidth = 0xffffffff;
68

69
/*% opcode text */
70 71 72 73 74
static const char *const opcodetext[] = {
	"QUERY",      "IQUERY",	    "STATUS",	  "RESERVED3",
	"NOTIFY",     "UPDATE",	    "RESERVED6",  "RESERVED7",
	"RESERVED8",  "RESERVED9",  "RESERVED10", "RESERVED11",
	"RESERVED12", "RESERVED13", "RESERVED14", "RESERVED15"
75 76
};

77
static const char *
Evan Hunt's avatar
Evan Hunt committed
78 79
rcode_totext(dns_rcode_t rcode) {
	static char buf[64];
80 81
	isc_buffer_t b;
	isc_result_t result;
82

83 84 85 86 87 88
	memset(buf, 0, sizeof(buf));
	isc_buffer_init(&b, buf + 1, sizeof(buf) - 2);
	result = dns_rcode_totext(rcode, &b);
	RUNTIME_CHECK(result == ISC_R_SUCCESS);
	if (strspn(buf + 1, "0123456789") == strlen(buf + 1)) {
		buf[0] = '?';
89
		return (buf);
90 91
	}
	return (buf + 1);
92 93
}

94
/*% print usage */
95
static void
Evan Hunt's avatar
Evan Hunt committed
96
print_usage(FILE *fp) {
97 98 99 100 101
	fputs("Usage:  dig [@global-server] [domain] [q-type] [q-class] "
	      "{q-opt}\n"
	      "            {global-d-opt} host [@local-server] {local-d-opt}\n"
	      "            [ host [@local-server] {local-d-opt} [...]]\n",
	      fp);
102 103
}

104
#if TARGET_OS_IPHONE
105
static void
Evan Hunt's avatar
Evan Hunt committed
106
usage(void) {
107 108
	fprintf(stderr, "Press <Help> for complete list of options\n");
}
109
#else  /* if TARGET_OS_IPHONE */
Ondřej Surý's avatar
Ondřej Surý committed
110 111
ISC_PLATFORM_NORETURN_PRE static void
usage(void) ISC_PLATFORM_NORETURN_POST;
Francis Dupont's avatar
Francis Dupont committed
112

113
static void
Evan Hunt's avatar
Evan Hunt committed
114
usage(void) {
115 116
	print_usage(stderr);
	fputs("\nUse \"dig -h\" (or \"dig -h | more\") "
117 118
	      "for complete list of options\n",
	      stderr);
119 120
	exit(1);
}
121
#endif /* if TARGET_OS_IPHONE */
122

123
/*% version */
124
static void
Evan Hunt's avatar
Evan Hunt committed
125
version(void) {
126 127 128
	fputs("DiG " VERSION "\n", stderr);
}

129
/*% help */
130
static void
Evan Hunt's avatar
Evan Hunt committed
131
help(void) {
132
	print_usage(stdout);
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
	fputs("Where:  domain	  is in the Domain Name System\n"
	      "        q-class  is one of (in,hs,ch,...) [default: in]\n"
	      "        q-type   is one of (a,any,mx,ns,soa,hinfo,axfr,txt,...) "
	      "[default:a]\n"
	      "                 (Use ixfr=version for type ixfr)\n"
	      "        q-opt    is one of:\n"
	      "                 -4                  (use IPv4 query transport "
	      "only)\n"
	      "                 -6                  (use IPv6 query transport "
	      "only)\n"
	      "                 -b address[#port]   (bind to source "
	      "address/port)\n"
	      "                 -c class            (specify query class)\n"
	      "                 -f filename         (batch mode)\n"
	      "                 -k keyfile          (specify tsig key file)\n"
	      "                 -m                  (enable memory usage "
	      "debugging)\n"
	      "                 -p port             (specify port number)\n"
	      "                 -q name             (specify query name)\n"
	      "                 -r                  (do not read ~/.digrc)\n"
	      "                 -t type             (specify query type)\n"
	      "                 -u                  (display times in usec "
	      "instead of msec)\n"
	      "                 -x dot-notation     (shortcut for reverse "
	      "lookups)\n"
	      "                 -y [hmac:]name:key  (specify named base64 tsig "
	      "key)\n"
	      "        d-opt    is of the form +keyword[=value], where keyword "
	      "is:\n"
	      "                 +[no]aaflag         (Set AA flag in query "
	      "(+[no]aaflag))\n"
	      "                 +[no]aaonly         (Set AA flag in query "
	      "(+[no]aaflag))\n"
	      "                 +[no]additional     (Control display of "
	      "additional section)\n"
	      "                 +[no]adflag         (Set AD flag in query "
	      "(default on))\n"
	      "                 +[no]all            (Set or clear all display "
	      "flags)\n"
	      "                 +[no]answer         (Control display of answer "
	      "section)\n"
	      "                 +[no]authority      (Control display of "
	      "authority section)\n"
	      "                 +[no]badcookie      (Retry BADCOOKIE "
	      "responses)\n"
	      "                 +[no]besteffort     (Try to parse even illegal "
	      "messages)\n"
	      "                 +bufsize=###        (Set EDNS0 Max UDP packet "
	      "size)\n"
	      "                 +[no]cdflag         (Set checking disabled "
	      "flag in query)\n"
	      "                 +[no]class          (Control display of class "
	      "in records)\n"
	      "                 +[no]cmd            (Control display of "
	      "command line -\n"
	      "                                      global option)\n"
	      "                 +[no]comments       (Control display of packet "
	      "header\n"
	      "                                      and section name "
	      "comments)\n"
	      "                 +[no]cookie         (Add a COOKIE option to "
	      "the request)\n"
	      "                 +[no]crypto         (Control display of "
	      "cryptographic\n"
	      "                                      fields in records)\n"
	      "                 +[no]defname        (Use search list "
	      "(+[no]search))\n"
	      "                 +[no]dnssec         (Request DNSSEC records)\n"
	      "                 +domain=###         (Set default domainname)\n"
	      "                 +[no]dscp[=###]     (Set the DSCP value to ### "
	      "[0..63])\n"
	      "                 +[no]edns[=###]     (Set EDNS version) [0]\n"
	      "                 +ednsflags=###      (Set EDNS flag bits)\n"
	      "                 +[no]ednsnegotiation (Set EDNS version "
	      "negotiation)\n"
	      "                 +ednsopt=###[:value] (Send specified EDNS "
	      "option)\n"
	      "                 +noednsopt          (Clear list of +ednsopt "
	      "options)\n"
	      "                 +[no]expandaaaa     (Expand AAAA records)\n"
	      "                 +[no]expire         (Request time to expire)\n"
	      "                 +[no]fail           (Don't try next server on "
	      "SERVFAIL)\n"
	      "                 +[no]header-only    (Send query without a "
	      "question section)\n"
	      "                 +[no]identify       (ID responders in short "
	      "answers)\n"
Ondřej Surý's avatar
Ondřej Surý committed
220
#ifdef HAVE_LIBIDN2
221 222 223 224
	      "                 +[no]idnin          (Parse IDN names "
	      "[default=on on tty])\n"
	      "                 +[no]idnout         (Convert IDN response "
	      "[default=on on tty])\n"
225
#endif /* ifdef HAVE_LIBIDN2 */
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
	      "                 +[no]ignore         (Don't revert to TCP for "
	      "TC responses.)\n"
	      "                 +[no]keepalive      (Request EDNS TCP "
	      "keepalive)\n"
	      "                 +[no]keepopen       (Keep the TCP socket open "
	      "between "
	      "queries)\n"
	      "                 +[no]mapped         (Allow mapped IPv4 over "
	      "IPv6)\n"
	      "                 +[no]multiline      (Print records in an "
	      "expanded format)\n"
	      "                 +ndots=###          (Set search NDOTS value)\n"
	      "                 +[no]nsid           (Request Name Server ID)\n"
	      "                 +[no]nssearch       (Search all authoritative "
	      "nameservers)\n"
	      "                 +[no]onesoa         (AXFR prints only one soa "
	      "record)\n"
	      "                 +[no]opcode=###     (Set the opcode of the "
	      "request)\n"
	      "                 +padding=###        (Set padding block size "
	      "[0])\n"
	      "                 +[no]qr             (Print question before "
	      "sending)\n"
	      "                 +[no]question       (Control display of "
	      "question section)\n"
	      "                 +[no]raflag         (Set RA flag in query "
	      "(+[no]raflag))\n"
	      "                 +[no]rdflag         (Recursive mode "
	      "(+[no]recurse))\n"
	      "                 +[no]recurse        (Recursive mode "
	      "(+[no]rdflag))\n"
	      "                 +retry=###          (Set number of UDP "
	      "retries) [2]\n"
	      "                 +[no]rrcomments     (Control display of "
	      "per-record "
	      "comments)\n"
	      "                 +[no]search         (Set whether to use "
	      "searchlist)\n"
	      "                 +[no]short          (Display nothing except "
	      "short\n"
	      "                                      form of answers - global "
	      "option)\n"
	      "                 +[no]showsearch     (Search with intermediate "
	      "results)\n"
	      "                 +[no]split=##       (Split hex/base64 fields "
	      "into chunks)\n"
	      "                 +[no]stats          (Control display of "
	      "statistics)\n"
	      "                 +subnet=addr        (Set edns-client-subnet "
	      "option)\n"
	      "                 +[no]tcflag         (Set TC flag in query "
	      "(+[no]tcflag))\n"
	      "                 +[no]tcp            (TCP mode (+[no]vc))\n"
	      "                 +timeout=###        (Set query timeout) [5]\n"
	      "                 +[no]trace          (Trace delegation down "
	      "from root "
	      "[+dnssec])\n"
	      "                 +tries=###          (Set number of UDP "
	      "attempts) [3]\n"
	      "                 +[no]ttlid          (Control display of ttls "
	      "in records)\n"
	      "                 +[no]ttlunits       (Display TTLs in "
	      "human-readable units)\n"
	      "                 +[no]unexpected     (Print replies from "
	      "unexpected sources\n"
	      "                                      default=off)\n"
	      "                 +[no]unknownformat  (Print RDATA in RFC 3597 "
	      "\"unknown\" "
	      "format)\n"
	      "                 +[no]vc             (TCP mode (+[no]tcp))\n"
	      "                 +[no]yaml           (Present the results as "
	      "YAML)\n"
	      "                 +[no]zflag          (Set Z flag in query)\n"
	      "        global d-opts and servers (before host name) affect all "
	      "queries.\n"
	      "        local d-opts and servers (after host name) affect only "
	      "that lookup.\n"
	      "        -h                           (print help and exit)\n"
	      "        -v                           (print version and exit)\n",
	      stdout);
306
}
307

308
/*%
Michael Sawyer's avatar
Michael Sawyer committed
309 310
 * Callback from dighost.c to print the received message.
 */
311
static void
Evan Hunt's avatar
Evan Hunt committed
312 313 314
received(unsigned int bytes, isc_sockaddr_t *from, dig_query_t *query) {
	uint64_t diff;
	time_t tnow;
Evan Hunt's avatar
Evan Hunt committed
315
	struct tm tmnow;
316 317
#ifdef WIN32
	wchar_t time_str[100];
318
#else  /* ifdef WIN32 */
Evan Hunt's avatar
Evan Hunt committed
319
	char time_str[100];
320
#endif /* ifdef WIN32 */
321 322 323
	char fromtext[ISC_SOCKADDR_FORMATSIZE];

	isc_sockaddr_format(from, fromtext, sizeof(fromtext));
324

Evan Hunt's avatar
Evan Hunt committed
325 326 327 328 329
	if (short_form || yaml) {
		return;
	}

	if (query->lookup->stats) {
Mark Andrews's avatar
Mark Andrews committed
330
		diff = isc_time_microdiff(&query->time_recv, &query->time_sent);
331
		if (query->lookup->use_usec) {
332
			printf(";; Query time: %ld usec\n", (long)diff);
333
		} else {
334
			printf(";; Query time: %ld msec\n", (long)diff / 1000);
335
		}
336
		printf(";; SERVER: %s(%s)\n", fromtext, query->servname);
337
		time(&tnow);
Witold Krecicki's avatar
Witold Krecicki committed
338
#if !defined(WIN32)
339
		(void)localtime_r(&tnow, &tmnow);
340
#else  /* if !defined(WIN32) */
341
		tmnow = *localtime(&tnow);
342
#endif /* if !defined(WIN32) */
343

344 345 346 347 348
#ifdef WIN32
		/*
		 * On Windows, time zone name ("%Z") may be a localized
		 * wide-character string, which strftime() handles incorrectly.
		 */
349
		if (wcsftime(time_str, sizeof(time_str) / sizeof(time_str[0]),
Evan Hunt's avatar
Evan Hunt committed
350 351
			     L"%a %b %d %H:%M:%S %Z %Y", &tmnow) > 0U)
		{
352
			printf(";; WHEN: %ls\n", time_str);
Evan Hunt's avatar
Evan Hunt committed
353
		}
354
#else  /* ifdef WIN32 */
Evan Hunt's avatar
Evan Hunt committed
355
		if (strftime(time_str, sizeof(time_str),
Evan Hunt's avatar
Evan Hunt committed
356 357
			     "%a %b %d %H:%M:%S %Z %Y", &tmnow) > 0U)
		{
Evan Hunt's avatar
Evan Hunt committed
358
			printf(";; WHEN: %s\n", time_str);
Evan Hunt's avatar
Evan Hunt committed
359
		}
360
#endif /* ifdef WIN32 */
361
		if (query->lookup->doing_xfr) {
362
			printf(";; XFR size: %u records (messages %u, "
363
			       "bytes %" PRIu64 ")\n",
364 365
			       query->rr_count, query->msg_count,
			       query->byte_count);
366
		} else {
367
			printf(";; MSG SIZE  rcvd: %u\n", bytes);
368
		}
369
		if (tsigkey != NULL) {
Evan Hunt's avatar
Evan Hunt committed
370
			if (!validated) {
371 372
				puts(";; WARNING -- Some TSIG could not "
				     "be validated");
Evan Hunt's avatar
Evan Hunt committed
373
			}
374
		}
375
		if ((tsigkey == NULL) && (keysecret[0] != 0)) {
376
			puts(";; WARNING -- TSIG key was not used.");
377
		}
378
		puts("");
Evan Hunt's avatar
Evan Hunt committed
379
	} else if (query->lookup->identify) {
Mark Andrews's avatar
Mark Andrews committed
380
		diff = isc_time_microdiff(&query->time_recv, &query->time_sent);
Evan Hunt's avatar
Evan Hunt committed
381
		if (query->lookup->use_usec) {
382
			printf(";; Received %" PRIu64 " bytes "
383
			       "from %s(%s) in %ld us\n\n",
384 385 386
			       query->lookup->doing_xfr ? query->byte_count
							: (uint64_t)bytes,
			       fromtext, query->userarg, (long)diff);
Evan Hunt's avatar
Evan Hunt committed
387
		} else {
388
			printf(";; Received %" PRIu64 " bytes "
389
			       "from %s(%s) in %ld ms\n\n",
390 391 392
			       query->lookup->doing_xfr ? query->byte_count
							: (uint64_t)bytes,
			       fromtext, query->userarg, (long)diff / 1000);
Evan Hunt's avatar
Evan Hunt committed
393
		}
394 395 396
	}
}

Michael Sawyer's avatar
Michael Sawyer committed
397 398 399
/*
 * Callback from dighost.c to print that it is trying a server.
 * Not used in dig.
400
 * XXX print_trying
Michael Sawyer's avatar
Michael Sawyer committed
401
 */
402
static void
Evan Hunt's avatar
Evan Hunt committed
403
trying(char *frm, dig_lookup_t *lookup) {
404 405
	UNUSED(frm);
	UNUSED(lookup);
406
}
407

408
/*%
Michael Sawyer's avatar
Michael Sawyer committed
409 410
 * Internal print routine used to print short form replies.
 */
411
static isc_result_t
Evan Hunt's avatar
Evan Hunt committed
412
say_message(dns_rdata_t *rdata, dig_query_t *query, isc_buffer_t *buf) {
413
	isc_result_t result;
Evan Hunt's avatar
Evan Hunt committed
414 415
	uint64_t diff;
	char store[sizeof(" in 18446744073709551616 us.")];
416
	unsigned int styleflags = 0;
417

418 419
	if (query->lookup->trace || query->lookup->ns_search_only) {
		result = dns_rdatatype_totext(rdata->type, buf);
420
		if (result != ISC_R_SUCCESS) {
421
			return (result);
422
		}
423
		ADD_STRING(buf, " ");
424
	}
425

Evan Hunt's avatar
Evan Hunt committed
426
	/* Turn on rrcomments if explicitly enabled */
427
	if (query->lookup->rrcomments > 0) {
428
		styleflags |= DNS_STYLEFLAG_RRCOMMENT;
429 430
	}
	if (query->lookup->nocrypto) {
431
		styleflags |= DNS_STYLEFLAG_NOCRYPTO;
432 433
	}
	if (query->lookup->print_unknown_format) {
434
		styleflags |= DNS_STYLEFLAG_UNKNOWNFORMAT;
435 436
	}
	if (query->lookup->expandaaaa) {
437
		styleflags |= DNS_STYLEFLAG_EXPANDAAAA;
438
	}
439 440
	result = dns_rdata_tofmttext(rdata, NULL, styleflags, 0, splitwidth,
				     " ", buf);
Evan Hunt's avatar
Evan Hunt committed
441
	if (result == ISC_R_NOSPACE) {
442
		return (result);
Evan Hunt's avatar
Evan Hunt committed
443
	}
444
	check_result(result, "dns_rdata_totext");
445
	if (query->lookup->identify) {
Mark Andrews's avatar
Mark Andrews committed
446
		diff = isc_time_microdiff(&query->time_recv, &query->time_sent);
447 448
		ADD_STRING(buf, " from server ");
		ADD_STRING(buf, query->servname);
449
		if (query->lookup->use_usec) {
450 451
			snprintf(store, sizeof(store), " in %" PRIu64 " us.",
				 diff);
452
		} else {
453 454
			snprintf(store, sizeof(store), " in %" PRIu64 " ms.",
				 diff / 1000);
455
		}
456
		ADD_STRING(buf, store);
457
	}
458
	ADD_STRING(buf, "\n");
459
	return (ISC_R_SUCCESS);
460 461
}

462
/*%
Michael Sawyer's avatar
Michael Sawyer committed
463 464
 * short_form message print handler.  Calls above say_message()
 */
465
static isc_result_t
466
short_answer(dns_message_t *msg, dns_messagetextflag_t flags, isc_buffer_t *buf,
Evan Hunt's avatar
Evan Hunt committed
467 468
	     dig_query_t *query) {
	dns_name_t *name;
469
	dns_rdataset_t *rdataset;
Evan Hunt's avatar
Evan Hunt committed
470 471 472
	isc_result_t result, loopresult;
	dns_name_t empty_name;
	dns_rdata_t rdata = DNS_RDATA_INIT;
473

474
	UNUSED(flags);
475

476
	dns_name_init(&empty_name, NULL);
477
	result = dns_message_firstname(msg, DNS_SECTION_ANSWER);
478
	if (result == ISC_R_NOMORE) {
479
		return (ISC_R_SUCCESS);
480
	} else if (result != ISC_R_SUCCESS) {
481
		return (result);
482
	}
483 484 485

	for (;;) {
		name = NULL;
486
		dns_message_currentname(msg, DNS_SECTION_ANSWER, &name);
487

488
		for (rdataset = ISC_LIST_HEAD(name->list); rdataset != NULL;
Evan Hunt's avatar
Evan Hunt committed
489 490
		     rdataset = ISC_LIST_NEXT(rdataset, link))
		{
491 492 493
			loopresult = dns_rdataset_first(rdataset);
			while (loopresult == ISC_R_SUCCESS) {
				dns_rdataset_current(rdataset, &rdata);
Evan Hunt's avatar
Evan Hunt committed
494
				result = say_message(&rdata, query, buf);
495
				if (result == ISC_R_NOSPACE) {
496
					return (result);
497
				}
498 499
				check_result(result, "say_message");
				loopresult = dns_rdataset_next(rdataset);
500
				dns_rdata_reset(&rdata);
501
			}
502
		}
503
		result = dns_message_nextname(msg, DNS_SECTION_ANSWER);
504
		if (result == ISC_R_NOMORE) {
505
			break;
506
		} else if (result != ISC_R_SUCCESS) {
507
			return (result);
508
		}
509
	}
510

511
	return (ISC_R_SUCCESS);
512 513
}

514
static bool
Evan Hunt's avatar
Evan Hunt committed
515 516
isdotlocal(dns_message_t *msg) {
	isc_result_t result;
517 518
	static unsigned char local_ndata[] = { "\005local\0" };
	static unsigned char local_offsets[] = { 0, 6 };
Evan Hunt's avatar
Evan Hunt committed
519 520
	static dns_name_t local = DNS_NAME_INITABSOLUTE(local_ndata,
							local_offsets);
521 522 523

	for (result = dns_message_firstname(msg, DNS_SECTION_QUESTION);
	     result == ISC_R_SUCCESS;
Evan Hunt's avatar
Evan Hunt committed
524 525
	     result = dns_message_nextname(msg, DNS_SECTION_QUESTION))
	{
526 527
		dns_name_t *name = NULL;
		dns_message_currentname(msg, DNS_SECTION_QUESTION, &name);
528
		if (dns_name_issubdomain(name, &local)) {
529
			return (true);
530
		}
531
	}
532
	return (false);
533 534
}

Michael Sawyer's avatar
Michael Sawyer committed
535 536 537
/*
 * Callback from dighost.c to print the reply from a server
 */
538
static isc_result_t
539
printmessage(dig_query_t *query, const isc_buffer_t *msgbuf, dns_message_t *msg,
Evan Hunt's avatar
Evan Hunt committed
540 541
	     bool headers) {
	isc_result_t result;
542
	dns_messagetextflag_t flags;
Evan Hunt's avatar
Evan Hunt committed
543 544 545 546 547
	isc_buffer_t *buf = NULL;
	unsigned int len = OUTPUTBUF;
	dns_master_style_t *style = NULL;
	unsigned int styleflags = 0;
	bool isquery = (msg == query->lookup->sendmsg);
Evan Hunt's avatar
Evan Hunt committed
548 549

	UNUSED(msgbuf);
550 551

	styleflags |= DNS_STYLEFLAG_REL_OWNER;
Evan Hunt's avatar
Evan Hunt committed
552
	if (yaml) {
553 554
		msg->indent.string = "  ";
		msg->indent.count = 3;
Evan Hunt's avatar
Evan Hunt committed
555 556 557 558 559 560 561 562 563 564
		styleflags |= DNS_STYLEFLAG_YAML;
	} else {
		if (query->lookup->comments) {
			styleflags |= DNS_STYLEFLAG_COMMENT;
		}
		if (query->lookup->print_unknown_format) {
			styleflags |= DNS_STYLEFLAG_UNKNOWNFORMAT;
		}
		/* Turn on rrcomments if explicitly enabled */
		if (query->lookup->rrcomments > 0) {
Evan Hunt's avatar
Evan Hunt committed
565
			styleflags |= DNS_STYLEFLAG_RRCOMMENT;
Evan Hunt's avatar
Evan Hunt committed
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
		}
		if (query->lookup->ttlunits) {
			styleflags |= DNS_STYLEFLAG_TTL_UNITS;
		}
		if (query->lookup->nottl) {
			styleflags |= DNS_STYLEFLAG_NO_TTL;
		}
		if (query->lookup->noclass) {
			styleflags |= DNS_STYLEFLAG_NO_CLASS;
		}
		if (query->lookup->nocrypto) {
			styleflags |= DNS_STYLEFLAG_NOCRYPTO;
		}
		if (query->lookup->expandaaaa) {
			styleflags |= DNS_STYLEFLAG_EXPANDAAAA;
		}
		if (query->lookup->multiline) {
			styleflags |= DNS_STYLEFLAG_OMIT_OWNER;
			styleflags |= DNS_STYLEFLAG_OMIT_CLASS;
			styleflags |= DNS_STYLEFLAG_REL_DATA;
			styleflags |= DNS_STYLEFLAG_OMIT_TTL;
			styleflags |= DNS_STYLEFLAG_TTL;
			styleflags |= DNS_STYLEFLAG_MULTILINE;
			/* Turn on rrcomments unless explicitly disabled */
			if (query->lookup->rrcomments >= 0) {
				styleflags |= DNS_STYLEFLAG_RRCOMMENT;
			}
		}
594
	}
595
	if (query->lookup->multiline ||
Evan Hunt's avatar
Evan Hunt committed
596 597
	    (query->lookup->nottl && query->lookup->noclass))
	{
598 599
		result = dns_master_stylecreate(&style, styleflags, 24, 24, 24,
						32, 80, 8, splitwidth, mctx);
Evan Hunt's avatar
Evan Hunt committed
600
	} else if (query->lookup->nottl || query->lookup->noclass) {
601 602
		result = dns_master_stylecreate(&style, styleflags, 24, 24, 32,
						40, 80, 8, splitwidth, mctx);
Evan Hunt's avatar
Evan Hunt committed
603
	} else {
604 605
		result = dns_master_stylecreate(&style, styleflags, 24, 32, 40,
						48, 80, 8, splitwidth, mctx);
Evan Hunt's avatar
Evan Hunt committed
606
	}
607
	check_result(result, "dns_master_stylecreate");
608

609
	if (query->lookup->cmdline[0] != 0) {
610
		if (!short_form && printcmd) {
611
			fputs(query->lookup->cmdline, stdout);
612
		}
Evan Hunt's avatar
Evan Hunt committed
613
		query->lookup->cmdline[0] = '\0';
614
	}
615 616 617
	debug("printmessage(%s %s %s)", headers ? "headers" : "noheaders",
	      query->lookup->comments ? "comments" : "nocomments",
	      short_form ? "short_form" : "long_form");
618 619 620 621 622 623

	flags = 0;
	if (!headers) {
		flags |= DNS_MESSAGETEXTFLAG_NOHEADERS;
		flags |= DNS_MESSAGETEXTFLAG_NOCOMMENTS;
	}
624
	if (query->lookup->onesoa &&
625
	    query->lookup->rdtype == dns_rdatatype_axfr) {
626 627
		flags |= (query->msg_count == 0) ? DNS_MESSAGETEXTFLAG_ONESOA
						 : DNS_MESSAGETEXTFLAG_OMITSOA;
628 629
	}
	if (!query->lookup->comments) {
630
		flags |= DNS_MESSAGETEXTFLAG_NOCOMMENTS;
631
	}
632

633
	isc_buffer_allocate(mctx, &buf, len);
634

Evan Hunt's avatar
Evan Hunt committed
635 636
	if (yaml) {
		enum { Q = 0x1, R = 0x2 }; /* Q:query; R:ecursive */
Evan Hunt's avatar
Evan Hunt committed
637
		unsigned int tflag = 0;
Evan Hunt's avatar
Evan Hunt committed
638
		isc_sockaddr_t saddr;
Evan Hunt's avatar
Evan Hunt committed
639 640 641 642
		char sockstr[ISC_SOCKADDR_FORMATSIZE];
		uint16_t sport;
		char *hash;
		int pf;
Evan Hunt's avatar
Evan Hunt committed
643 644 645 646 647 648 649 650 651 652 653

		printf("-\n");
		printf("  type: MESSAGE\n");
		printf("  message:\n");

		if (isquery) {
			tflag |= Q;
			if ((msg->flags & DNS_MESSAGEFLAG_RD) != 0) {
				tflag |= R;
			}
		} else if (((msg->flags & DNS_MESSAGEFLAG_RD) != 0) &&
Evan Hunt's avatar
Evan Hunt committed
654 655
			   ((msg->flags & DNS_MESSAGEFLAG_RA) != 0))
		{
Evan Hunt's avatar
Evan Hunt committed
656 657 658
			tflag |= R;
		}

659
		if (tflag == (Q | R)) {
Evan Hunt's avatar
Evan Hunt committed
660 661 662 663 664 665 666 667 668 669 670
			printf("    type: RECURSIVE_QUERY\n");
		} else if (tflag == Q) {
			printf("    type: AUTH_QUERY\n");
		} else if (tflag == R) {
			printf("    type: RECURSIVE_RESPONSE\n");
		} else {
			printf("    type: AUTH_RESPONSE\n");
		}

		if (!isc_time_isepoch(&query->time_sent)) {
			char tbuf[100];
671 672
			isc_time_formatISO8601ms(&query->time_sent, tbuf,
						 sizeof(tbuf));
Evan Hunt's avatar
Evan Hunt committed
673 674 675 676 677
			printf("    query_time: !!timestamp %s\n", tbuf);
		}

		if (!isquery && !isc_time_isepoch(&query->time_recv)) {
			char tbuf[100];
678 679
			isc_time_formatISO8601ms(&query->time_recv, tbuf,
						 sizeof(tbuf));
Evan Hunt's avatar
Evan Hunt committed
680 681 682 683 684 685 686 687 688 689 690 691 692 693 694
			printf("    response_time: !!timestamp %s\n", tbuf);
		}

		printf("    message_size: %ub\n",
		       isc_buffer_usedlength(msgbuf));

		pf = isc_sockaddr_pf(&query->sockaddr);
		if (pf == PF_INET || pf == PF_INET6) {
			printf("    socket_family: %s\n",
			       pf == PF_INET ? "INET" : "INET6");

			printf("    socket_protocol: %s\n",
			       query->lookup->tcp_mode ? "TCP" : "UDP");

			sport = isc_sockaddr_getport(&query->sockaddr);
695 696
			isc_sockaddr_format(&query->sockaddr, sockstr,
					    sizeof(sockstr));
Evan Hunt's avatar
Evan Hunt committed
697 698 699 700 701 702 703 704 705 706 707 708 709
			hash = strchr(sockstr, '#');
			if (hash != NULL) {
				*hash = '\0';
			}
			if (strcmp(sockstr, "::") == 0) {
				strlcat(sockstr, "0", sizeof(sockstr));
			}

			printf("    response_address: %s\n", sockstr);
			printf("    response_port: %u\n", sport);
		}

		if (query->sock != NULL &&
710
		    isc_socket_getsockname(query->sock, &saddr) ==
Evan Hunt's avatar
Evan Hunt committed
711 712
			    ISC_R_SUCCESS)
		{
Evan Hunt's avatar
Evan Hunt committed
713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731
			sport = isc_sockaddr_getport(&saddr);
			isc_sockaddr_format(&saddr, sockstr, sizeof(sockstr));
			hash = strchr(sockstr, '#');
			if (hash != NULL) {
				*hash = '\0';
			}
			if (strcmp(sockstr, "::") == 0) {
				strlcat(sockstr, "0", sizeof(sockstr));
			}

			printf("    query_address: %s\n", sockstr);
			printf("    query_port: %u\n", sport);
		}

		printf("    %s:\n", isquery ? "query_message_data"
					    : "response_message_data");
		result = dns_message_headertotext(msg, style, flags, buf);
	} else if (query->lookup->comments && !short_form) {
		if (query->lookup->cmdline[0] != '\0' && printcmd) {
732
			printf("; %s\n", query->lookup->cmdline);
Evan Hunt's avatar
Evan Hunt committed
733 734
		}
		if (msg == query->lookup->sendmsg) {
735
			printf(";; Sending:\n");
Evan Hunt's avatar
Evan Hunt committed
736
		} else {
737
			printf(";; Got answer:\n");
Evan Hunt's avatar
Evan Hunt committed
738
		}
739

740
		if (headers) {
741 742 743 744 745 746
			if (isdotlocal(msg)) {
				printf(";; WARNING: .local is reserved for "
				       "Multicast DNS\n;; You are currently "
				       "testing what happens when an mDNS "
				       "query is leaked to DNS\n");
			}
747 748
			printf(";; ->>HEADER<<- opcode: %s, status: %s, "
			       "id: %u\n",
749
			       opcodetext[msg->opcode],
750
			       rcode_totext(msg->rcode), msg->id);
751
			printf(";; flags:");
752
			if ((msg->flags & DNS_MESSAGEFLAG_QR) != 0) {
753
				printf(" qr");
754 755
			}
			if ((msg->flags & DNS_MESSAGEFLAG_AA) != 0) {
756
				printf(" aa");
757 758
			}
			if ((msg->flags & DNS_MESSAGEFLAG_TC) != 0) {
759
				printf(" tc");
760 761
			}
			if ((msg->flags & DNS_MESSAGEFLAG_RD) != 0) {
762
				printf(" rd");
763 764
			}
			if ((msg->flags & DNS_MESSAGEFLAG_RA) != 0) {
765
				printf(" ra");
766 767
			}
			if ((msg->flags & DNS_MESSAGEFLAG_AD) != 0) {
768
				printf(" ad");
769 770
			}
			if ((msg->flags & DNS_MESSAGEFLAG_CD) != 0) {
771
				printf(" cd");
772 773
			}
			if ((msg->flags & 0x0040U) != 0) {
774
				printf("; MBZ: 0x4");
775
			}
776

777 778 779 780 781 782
			printf("; QUERY: %u, ANSWER: %u, "
			       "AUTHORITY: %u, ADDITIONAL: %u\n",
			       msg->counts[DNS_SECTION_QUESTION],
			       msg->counts[DNS_SECTION_ANSWER],
			       msg->counts[DNS_SECTION_AUTHORITY],
			       msg->counts[DNS_SECTION_ADDITIONAL]);
783

784 785
			if (msg != query->lookup->sendmsg &&
			    (msg->flags & DNS_MESSAGEFLAG_RD) != 0 &&
Evan Hunt's avatar
Evan Hunt committed
786 787
			    (msg->flags & DNS_MESSAGEFLAG_RA) == 0)
			{
Mark Andrews's avatar
Mark Andrews committed
788
				printf(";; WARNING: recursion requested "
789
				       "but not available\n");
790
			}
791
		}
792 793 794
		if (msg != query->lookup->sendmsg &&
		    query->lookup->edns != -1 && msg->opt == NULL &&
		    (msg->rcode == dns_rcode_formerr ||
Evan Hunt's avatar
Evan Hunt committed
795 796
		     msg->rcode == dns_rcode_notimp))
		{
797
			printf("\n;; WARNING: EDNS query returned status "
798 799
			       "%s - retry with '%s+noedns'\n",
			       rcode_totext(msg->rcode),
800
			       query->lookup->dnssec ? "+nodnssec " : "");
801 802
		}
		if (msg != query->lookup->sendmsg && extrabytes != 0U) {
Evan Hunt's avatar
Evan Hunt committed
803
			printf(";; WARNING: Message has %u extra byte%s at "
804 805
			       "end\n",
			       extrabytes, extrabytes != 0 ? "s" : "");
806
		}
807
	}
808

809
repopulate_buffer:
Ben Cottrell's avatar
Ben Cottrell committed
810

811
	if (query->lookup->comments && headers && !short_form) {
812 813
		result = dns_message_pseudosectiontotext(
			msg, DNS_PSEUDOSECTION_OPT, style, flags, buf);
814
		if (result == ISC_R_NOSPACE) {
815
		buftoosmall:
816 817
			len += OUTPUTBUF;
			isc_buffer_free(&buf);
818 819
			isc_buffer_allocate(mctx, &buf, len);
			goto repopulate_buffer;
820
		}
821
		check_result(result, "dns_message_pseudosectiontotext");
Ben Cottrell's avatar
Ben Cottrell committed
822 823
	}

824 825
	if (query->lookup->section_question && headers) {
		if (!short_form) {
826 827
			result = dns_message_sectiontotext(
				msg, DNS_SECTION_QUESTION, style, flags, buf);
828
			if (result == ISC_R_NOSPACE) {
829
				goto buftoosmall;
830
			}
831 832
			check_result(result, "dns_message_sectiontotext");
		}
833
	}
834 835
	if (query->lookup->section_answer) {
		if (!short_form) {
836 837
			result = dns_message_sectiontotext(
				msg, DNS_SECTION_ANSWER, style, flags, buf);
838
			if (result == ISC_R_NOSPACE) {
839
				goto buftoosmall;
840
			}
841
			check_result(result, "dns_message_sectiontotext");
842
		} else {
843
			result = short_answer(msg, flags, buf, query);
844
			if (result == ISC_R_NOSPACE) {
845
				goto buftoosmall;
846
			}
847
			check_result(result, "short_answer");
848
		}
849
	}
850 851
	if (query->lookup->section_authority) {
		if (!short_form) {
852 853
			result = dns_message_sectiontotext(
				msg, DNS_SECTION_AUTHORITY, style, flags, buf);
854
			if (result == ISC_R_NOSPACE) {
855
				goto buftoosmall;
856
			}
857 858
			check_result(result, "dns_message_sectiontotext");
		}
859
	}