mdig.c 52.7 KB
Newer Older
Mark Andrews's avatar
Mark Andrews committed
1
/*
2
 * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
Mark Andrews's avatar
Mark Andrews committed
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.
Mark Andrews's avatar
Mark Andrews committed
10 11
 */

12
#include <inttypes.h>
13
#include <stdbool.h>
Mark Andrews's avatar
Mark Andrews committed
14 15 16 17 18 19 20 21 22 23 24
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include <isc/app.h>
#include <isc/base64.h>
#include <isc/hash.h>
#include <isc/hex.h>
#include <isc/log.h>
#include <isc/mem.h>
#include <isc/net.h>
25
#include <isc/nonce.h>
Mark Andrews's avatar
Mark Andrews committed
26
#include <isc/parseint.h>
Francis Dupont's avatar
Francis Dupont committed
27
#include <isc/print.h>
28
#include <isc/random.h>
Mark Andrews's avatar
Mark Andrews committed
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
#include <isc/sockaddr.h>
#include <isc/socket.h>
#include <isc/string.h>
#include <isc/task.h>
#include <isc/timer.h>
#include <isc/util.h>

#include <dns/byaddr.h>
#include <dns/dispatch.h>
#include <dns/fixedname.h>
#include <dns/message.h>
#include <dns/name.h>
#include <dns/rdata.h>
#include <dns/rdataset.h>
#include <dns/rdatatype.h>
#include <dns/rdataclass.h>
#include <dns/request.h>
#include <dns/result.h>
#include <dns/view.h>

#include <dns/events.h>
#include <dns/rdataset.h>
#include <dns/resolver.h>
#include <dns/types.h>

#include <dst/result.h>

#include <bind9/getaddresses.h>

#define CHECK(str, x) { \
	if ((x) != ISC_R_SUCCESS) { \
		fprintf(stderr, "mdig: %s failed with %s\n",	\
			(str), isc_result_totext(x));	\
		exit(-1); \
	} \
}

#define RUNCHECK(x) RUNTIME_CHECK((x) == ISC_R_SUCCESS)

#define ADD_STRING(b, s) { 				\
	if (strlen(s) >= isc_buffer_availablelength(b)) \
		return (ISC_R_NOSPACE); 		\
	else 						\
		isc_buffer_putstr(b, s); 		\
}

#define MXNAME (DNS_NAME_MAXTEXT + 1)
#define COMMSIZE 0xffff
#define OUTPUTBUF 32767
#define MAXPORT 0xffff
#define PORT 53
#define MAXTIMEOUT 0xffff
#define TCPTIMEOUT 10
#define UDPTIMEOUT 5
#define MAXTRIES 0xffffffff

static isc_mem_t *mctx;
static dns_requestmgr_t *requestmgr;
87
static const char *batchname;
Mark Andrews's avatar
Mark Andrews committed
88
static FILE *batchfp;
89 90 91 92 93 94 95 96
static bool have_ipv4 = false;
static bool have_ipv6 = false;
static bool have_src = false;
static bool tcp_mode = false;
static bool besteffort = true;
static bool display_short_form = false;
static bool display_headers = true;
static bool display_comments = true;
97
static int display_rrcomments = 0;
98 99 100 101 102 103 104 105 106 107
static bool display_ttlunits = true;
static bool display_ttl = true;
static bool display_class = true;
static bool display_crypto = true;
static bool display_multiline = false;
static bool display_question = true;
static bool display_answer  = true;
static bool display_authority = true;
static bool display_additional = true;
static bool display_unknown_format = false;
Evan Hunt's avatar
Evan Hunt committed
108
static bool yaml = false;
109
static bool continue_on_error = false;
110
static uint32_t display_splitwidth = 0xffffffff;
Mark Andrews's avatar
Mark Andrews committed
111 112 113 114 115 116 117
static isc_sockaddr_t srcaddr;
static char *server;
static isc_sockaddr_t dstaddr;
static in_port_t port = 53;
static isc_dscp_t dscp = -1;
static unsigned char cookie_secret[33];
static int onfly = 0;
118
static char hexcookie[81];
Mark Andrews's avatar
Mark Andrews committed
119 120 121

struct query {
	char textname[MXNAME]; /*% Name we're going to be looking up */
122 123 124 125 126 127 128 129
	bool recurse;
	bool have_aaonly;
	bool have_adflag;
	bool have_cdflag;
	bool have_zflag;
	bool dnssec;
	bool expire;
	bool send_cookie;
130
	char *cookie;
131
	bool nsid;
Mark Andrews's avatar
Mark Andrews committed
132 133
	dns_rdatatype_t rdtype;
	dns_rdataclass_t rdclass;
134 135
	uint16_t udpsize;
	int16_t edns;
Mark Andrews's avatar
Mark Andrews committed
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
	dns_ednsopt_t *ednsopts;
	unsigned int ednsoptscnt;
	unsigned int ednsflags;
	isc_sockaddr_t *ecs_addr;
	unsigned int timeout;
	unsigned int udptimeout;
	unsigned int udpretries;
	ISC_LINK(struct query) link;
};
static struct query default_query;
static ISC_LIST(struct query) queries;

#define EDNSOPTS 100U
/*% opcode text */
static const char * const opcodetext[] = {
	"QUERY",
	"IQUERY",
	"STATUS",
	"RESERVED3",
	"NOTIFY",
	"UPDATE",
	"RESERVED6",
	"RESERVED7",
	"RESERVED8",
	"RESERVED9",
	"RESERVED10",
	"RESERVED11",
	"RESERVED12",
	"RESERVED13",
	"RESERVED14",
	"RESERVED15"
};

/*% return code text */
static const char * const rcodetext[] = {
	"NOERROR",
	"FORMERR",
	"SERVFAIL",
	"NXDOMAIN",
	"NOTIMP",
	"REFUSED",
	"YXDOMAIN",
	"YXRRSET",
	"NXRRSET",
	"NOTAUTH",
	"NOTZONE",
	"RESERVED11",
	"RESERVED12",
	"RESERVED13",
	"RESERVED14",
	"RESERVED15",
	"BADVERS"
};

/*% safe rcodetext[] */
static char *
rcode_totext(dns_rcode_t rcode)
{
	static char buf[sizeof("?65535")];
	union {
		const char *consttext;
		char *deconsttext;
	} totext;

	if (rcode >= (sizeof(rcodetext)/sizeof(rcodetext[0]))) {
		snprintf(buf, sizeof(buf), "?%u", rcode);
		totext.deconsttext = buf;
	} else
		totext.consttext = rcodetext[rcode];
	return totext.deconsttext;
}

/* receive response event handler */
static void
recvresponse(isc_task_t *task, isc_event_t *event) {
	dns_requestevent_t *reqev = (dns_requestevent_t *)event;
	isc_result_t result;
213
	dns_message_t *query = NULL, *response = NULL;
Mark Andrews's avatar
Mark Andrews committed
214
	unsigned int parseflags = 0;
Evan Hunt's avatar
Evan Hunt committed
215
	isc_buffer_t *msgbuf = NULL, *buf = NULL;
Mark Andrews's avatar
Mark Andrews committed
216 217 218 219 220 221 222 223
	unsigned int len = OUTPUTBUF;
	dns_master_style_t *style = NULL;
	unsigned int styleflags = 0;
	dns_messagetextflag_t flags;

	UNUSED(task);

	REQUIRE(reqev != NULL);
224
	query = reqev->ev_arg;
Mark Andrews's avatar
Mark Andrews committed
225 226 227 228

	if (reqev->result != ISC_R_SUCCESS) {
		fprintf(stderr, "response failed with %s\n",
			isc_result_totext(reqev->result));
229 230 231 232
		if (continue_on_error)
			goto cleanup;
		else
			exit(-1);
Mark Andrews's avatar
Mark Andrews committed
233 234 235 236 237 238 239 240 241 242
	}

	result = dns_message_create(mctx, DNS_MESSAGE_INTENTPARSE, &response);
	CHECK("dns_message_create", result);

	parseflags |= DNS_MESSAGEPARSE_PRESERVEORDER;
	if (besteffort) {
		parseflags |= DNS_MESSAGEPARSE_BESTEFFORT;
		parseflags |= DNS_MESSAGEPARSE_IGNORETRUNCATION;
	}
Evan Hunt's avatar
Evan Hunt committed
243 244 245


	msgbuf = dns_request_getanswer(reqev->request);
Mark Andrews's avatar
Mark Andrews committed
246 247 248 249
	result = dns_request_getresponse(reqev->request, response, parseflags);
	CHECK("dns_request_getresponse", result);

	styleflags |= DNS_STYLEFLAG_REL_OWNER;
Evan Hunt's avatar
Evan Hunt committed
250 251 252 253 254 255 256 257 258 259 260 261
	if (yaml) {
		dns_master_indentstr = "  ";
		dns_master_indent = 3;
		styleflags |= DNS_STYLEFLAG_YAML;
	} else {
		if (display_comments) {
			styleflags |= DNS_STYLEFLAG_COMMENT;
		}
		if (display_unknown_format) {
			styleflags |= DNS_STYLEFLAG_UNKNOWNFORMAT;
		}
		if (display_rrcomments > 0) {
262 263
			styleflags |= DNS_STYLEFLAG_RRCOMMENT;
		}
Evan Hunt's avatar
Evan Hunt committed
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
		if (display_ttlunits) {
			styleflags |= DNS_STYLEFLAG_TTL_UNITS;
		}
		if (!display_ttl) {
			styleflags |= DNS_STYLEFLAG_NO_TTL;
		}
		if (!display_class) {
			styleflags |= DNS_STYLEFLAG_NO_CLASS;
		}
		if (!display_crypto) {
			styleflags |= DNS_STYLEFLAG_NOCRYPTO;
		}
		if (display_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;
			styleflags |= DNS_STYLEFLAG_COMMENT;
			/* Turn on rrcomments unless explicitly disabled */
			if (display_rrcomments >= 0) {
				styleflags |= DNS_STYLEFLAG_RRCOMMENT;
			}
		}
Mark Andrews's avatar
Mark Andrews committed
289 290
	}
	if (display_multiline || (!display_ttl && !display_class))
291 292 293
		result = dns_master_stylecreate(&style, styleflags,
						24, 24, 24, 32, 80, 8,
						display_splitwidth, mctx);
Mark Andrews's avatar
Mark Andrews committed
294
	else if (!display_ttl || !display_class)
295 296 297
		result = dns_master_stylecreate(&style, styleflags,
						24, 24, 32, 40, 80, 8,
						display_splitwidth, mctx);
Mark Andrews's avatar
Mark Andrews committed
298
	else
299 300 301
		result = dns_master_stylecreate(&style, styleflags,
						24, 32, 40, 48, 80, 8,
						display_splitwidth, mctx);
Mark Andrews's avatar
Mark Andrews committed
302 303 304 305 306 307 308 309 310 311 312 313 314
	CHECK("dns_master_stylecreate2", result);

	flags = 0;
	if (!display_headers) {
		flags |= DNS_MESSAGETEXTFLAG_NOHEADERS;
		flags |= DNS_MESSAGETEXTFLAG_NOCOMMENTS;
	}
	if (!display_comments)
		flags |= DNS_MESSAGETEXTFLAG_NOCOMMENTS;

	result = isc_buffer_allocate(mctx, &buf, len);
	CHECK("isc_buffer_allocate", result);

Evan Hunt's avatar
Evan Hunt committed
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
	if (yaml) {
		char sockstr[ISC_SOCKADDR_FORMATSIZE];
		uint16_t sport;
		char *hash;
		int pf;

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

		if (((response->flags & DNS_MESSAGEFLAG_RD) != 0) &&
		    ((response->flags & DNS_MESSAGEFLAG_RA) != 0))
		{
			printf("    type: RECURSIVE_RESPONSE\n");
		} else {
			printf("    type: AUTH_RESPONSE\n");
		}

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

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

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

			sport = isc_sockaddr_getport(&dstaddr);
			isc_sockaddr_format(&dstaddr, sockstr, sizeof(sockstr));
			hash = strchr(sockstr, '#');
			if (hash != NULL) {
				*hash = '\0';
			}
			printf("    response_address: %s\n", sockstr);
			printf("    response_port: %u\n", sport);
		}

		if (have_src) {
			sport = isc_sockaddr_getport(&srcaddr);
			isc_sockaddr_format(&srcaddr, sockstr, sizeof(sockstr));
			hash = strchr(sockstr, '#');
			if (hash != NULL) {
				*hash = '\0';
			}
			printf("    query_address: %s\n", sockstr);
			printf("    query_port: %u\n", sport);
		}

		printf("    %s:\n", "response_message_data");
		result = dns_message_headertotext(response, style, flags, buf);
	} else if (display_comments && !display_short_form) {
Mark Andrews's avatar
Mark Andrews committed
368
		printf(";; Got answer:\n");
Francis Dupont's avatar
Francis Dupont committed
369

Mark Andrews's avatar
Mark Andrews committed
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
		if (display_headers) {
			printf(";; ->>HEADER<<- opcode: %s, status: %s, "
			       "id: %u\n",
			       opcodetext[response->opcode],
			       rcode_totext(response->rcode),
			       response->id);
			printf(";; flags:");
			if ((response->flags & DNS_MESSAGEFLAG_QR) != 0)
				printf(" qr");
			if ((response->flags & DNS_MESSAGEFLAG_AA) != 0)
				printf(" aa");
			if ((response->flags & DNS_MESSAGEFLAG_TC) != 0)
				printf(" tc");
			if ((response->flags & DNS_MESSAGEFLAG_RD) != 0)
				printf(" rd");
			if ((response->flags & DNS_MESSAGEFLAG_RA) != 0)
				printf(" ra");
			if ((response->flags & DNS_MESSAGEFLAG_AD) != 0)
				printf(" ad");
			if ((response->flags & DNS_MESSAGEFLAG_CD) != 0)
				printf(" cd");
			if ((response->flags & 0x0040U) != 0)
				printf("; MBZ: 0x4");

			printf("; QUERY: %u, ANSWER: %u, "
			       "AUTHORITY: %u, ADDITIONAL: %u\n",
			       response->counts[DNS_SECTION_QUESTION],
			       response->counts[DNS_SECTION_ANSWER],
			       response->counts[DNS_SECTION_AUTHORITY],
			       response->counts[DNS_SECTION_ADDITIONAL]);

			if ((response->flags & DNS_MESSAGEFLAG_RD) != 0 &&
			    (response->flags & DNS_MESSAGEFLAG_RA) == 0)
				printf(";; WARNING: recursion requested "
				       "but not available\n");
		}
	}

repopulate_buffer:

	if (display_comments && display_headers && !display_short_form) {
		result = dns_message_pseudosectiontotext(response,
							 DNS_PSEUDOSECTION_OPT,
							 style, flags, buf);
		if (result == ISC_R_NOSPACE) {
buftoosmall:
			len += OUTPUTBUF;
			isc_buffer_free(&buf);
			result = isc_buffer_allocate(mctx, &buf, len);
			if (result == ISC_R_SUCCESS)
				goto repopulate_buffer;
			else
				goto cleanup;
		}
		CHECK("dns_message_pseudosectiontotext", result);
	}

	if (display_question && display_headers && !display_short_form) {
		result = dns_message_sectiontotext(response,
						   DNS_SECTION_QUESTION,
						   style, flags, buf);
		if (result == ISC_R_NOSPACE)
			goto buftoosmall;
		CHECK("dns_message_sectiontotext", result);
	}

	if (display_answer && !display_short_form) {
		result = dns_message_sectiontotext(response,
						   DNS_SECTION_ANSWER,
						   style, flags, buf);
		if (result == ISC_R_NOSPACE)
			goto buftoosmall;
		CHECK("dns_message_sectiontotext", result);
	} else if (display_answer) {
		dns_name_t *name;
		dns_rdataset_t *rdataset;
		isc_result_t loopresult;
		dns_name_t empty_name;
		dns_rdata_t rdata = DNS_RDATA_INIT;
		unsigned int answerstyleflags = 0;

		if (!display_crypto)
			answerstyleflags |= DNS_STYLEFLAG_NOCRYPTO;
453 454
		if (display_unknown_format)
			answerstyleflags |= DNS_STYLEFLAG_UNKNOWNFORMAT;
Mark Andrews's avatar
Mark Andrews committed
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536

		dns_name_init(&empty_name, NULL);
		result = dns_message_firstname(response, DNS_SECTION_ANSWER);
		if (result != ISC_R_NOMORE)
			CHECK("dns_message_firstname", result);

		for (;;) {
			if (result == ISC_R_NOMORE)
				break;
			CHECK("dns_message_nextname", result);
			name = NULL;
			dns_message_currentname(response,
						DNS_SECTION_ANSWER,
						&name);

			for (rdataset = ISC_LIST_HEAD(name->list);
			     rdataset != NULL;
			     rdataset = ISC_LIST_NEXT(rdataset, link)) {
				loopresult = dns_rdataset_first(rdataset);
				while (loopresult == ISC_R_SUCCESS) {
					dns_rdataset_current(rdataset, &rdata);
					result = dns_rdata_tofmttext(
							&rdata,
							NULL,
							answerstyleflags,
							0, 60, " ", buf);
					if (result == ISC_R_NOSPACE)
						goto buftoosmall;
					CHECK("dns_rdata_tofmttext", result);
					loopresult =
					    dns_rdataset_next(rdataset);
					dns_rdata_reset(&rdata);
					if (strlen("\n") >=
					    isc_buffer_availablelength(buf))
						goto buftoosmall;
					isc_buffer_putstr(buf, "\n");
				}
			}
			result = dns_message_nextname(response,
						      DNS_SECTION_ANSWER);
		}
	}

	if (display_authority && !display_short_form) {
		result = dns_message_sectiontotext(response,
						   DNS_SECTION_AUTHORITY,
						   style, flags, buf);
		if (result == ISC_R_NOSPACE)
			goto buftoosmall;
		CHECK("dns_message_sectiontotext", result);
	}

	if (display_additional && !display_short_form) {
		result = dns_message_sectiontotext(response,
						   DNS_SECTION_ADDITIONAL,
						   style, flags, buf);
		if (result == ISC_R_NOSPACE)
			goto buftoosmall;
		CHECK("dns_message_sectiontotext", result);
	}


	if (display_additional && !display_short_form && display_headers) {
		/*
		 * Only print the signature on the first record.
		 */
		result =
		    dns_message_pseudosectiontotext(response,
						    DNS_PSEUDOSECTION_TSIG,
						    style, flags, buf);
		if (result == ISC_R_NOSPACE)
			goto buftoosmall;
		CHECK("dns_message_pseudosectiontotext", result);
		result =
		    dns_message_pseudosectiontotext(response,
						    DNS_PSEUDOSECTION_SIG0,
						    style, flags, buf);
		if (result == ISC_R_NOSPACE)
			goto buftoosmall;
		CHECK("dns_message_pseudosectiontotext", result);
	}

Evan Hunt's avatar
Evan Hunt committed
537 538 539
	if (display_headers && display_comments &&
	    !display_short_form && !yaml)
	{
Mark Andrews's avatar
Mark Andrews committed
540
		printf("\n");
Evan Hunt's avatar
Evan Hunt committed
541
	}
Mark Andrews's avatar
Mark Andrews committed
542 543 544 545 546 547 548 549 550

	printf("%.*s", (int)isc_buffer_usedlength(buf),
	       (char *)isc_buffer_base(buf));
	isc_buffer_free(&buf);

cleanup:
	fflush(stdout);
	if (style != NULL)
		dns_master_styledestroy(&style, mctx);
551 552 553 554
	if (query != NULL)
		dns_message_destroy(&query);
	if (response != NULL)
		dns_message_destroy(&response);
Mark Andrews's avatar
Mark Andrews committed
555 556 557 558 559 560 561 562 563 564 565
	dns_request_destroy(&reqev->request);
	isc_event_free(&event);

	if (--onfly == 0)
		isc_app_shutdown();
	return;
}

/*%
 * Add EDNS0 option record to a message.  Currently, the only supported
 * options are UDP buffer size, the DO bit, and EDNS options
566
 * (e.g., NSID, COOKIE, client-subnet)
Mark Andrews's avatar
Mark Andrews committed
567 568
 */
static void
569
add_opt(dns_message_t *msg, uint16_t udpsize, uint16_t edns,
Evan Hunt's avatar
Evan Hunt committed
570
	unsigned int flags, dns_ednsopt_t *opts, size_t count)
Mark Andrews's avatar
Mark Andrews committed
571 572 573 574 575
{
	dns_rdataset_t *rdataset = NULL;
	isc_result_t result;

	result = dns_message_buildopt(msg, &rdataset, edns, udpsize, flags,
Evan Hunt's avatar
Evan Hunt committed
576
				      opts, count);
Mark Andrews's avatar
Mark Andrews committed
577 578 579 580 581 582 583 584 585 586 587 588 589
	CHECK("dns_message_buildopt", result);
	result = dns_message_setopt(msg, rdataset);
	CHECK("dns_message_setopt", result);
}

static void
compute_cookie(unsigned char *cookie, size_t len) {
	/* XXXMPA need to fix, should be per server. */
	INSIST(len >= 8U);
	memmove(cookie, cookie_secret, 8);
}

static isc_result_t
Evan Hunt's avatar
Evan Hunt committed
590
sendquery(struct query *query, isc_task_t *task) {
Mark Andrews's avatar
Mark Andrews committed
591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648
	dns_request_t *request;
	dns_message_t *message;
	dns_name_t *qname;
	dns_rdataset_t *qrdataset;
	isc_result_t result;
	dns_fixedname_t queryname;
	isc_buffer_t buf;
	unsigned int options;

	onfly++;

	dns_fixedname_init(&queryname);
	isc_buffer_init(&buf, query->textname, strlen(query->textname));
	isc_buffer_add(&buf, strlen(query->textname));
	result = dns_name_fromtext(dns_fixedname_name(&queryname), &buf,
				   dns_rootname, 0, NULL);
	CHECK("dns_name_fromtext", result);

	message = NULL;
	result = dns_message_create(mctx, DNS_MESSAGE_INTENTRENDER, &message);
	CHECK("dns_message_create", result);

	message->opcode = dns_opcode_query;
	if (query->recurse)
		message->flags |= DNS_MESSAGEFLAG_RD;
	if (query->have_aaonly)
		message->flags |= DNS_MESSAGEFLAG_AA;
	if (query->have_adflag)
		message->flags |= DNS_MESSAGEFLAG_AD;
	if (query->have_cdflag)
		message->flags |= DNS_MESSAGEFLAG_CD;
	if (query->have_zflag)
		message->flags |= 0x0040U;
	message->rdclass = query->rdclass;
	message->id = (unsigned short)(random() & 0xFFFF);

	qname = NULL;
	result = dns_message_gettempname(message, &qname);
	CHECK("dns_message_gettempname", result);

	qrdataset = NULL;
	result = dns_message_gettemprdataset(message, &qrdataset);
	CHECK("dns_message_gettemprdataset", result);

	dns_name_init(qname, NULL);
	dns_name_clone(dns_fixedname_name(&queryname), qname);
	dns_rdataset_makequestion(qrdataset, query->rdclass,
				  query->rdtype);
	ISC_LIST_APPEND(qname->list, qrdataset, link);
	dns_message_addname(message, qname, DNS_SECTION_QUESTION);

	if (query->udpsize > 0 || query->dnssec ||
	    query->edns > -1 || query->ecs_addr != NULL)
	{
		dns_ednsopt_t opts[EDNSOPTS + DNS_EDNSOPTIONS];
		unsigned int flags;
		int i = 0;
		char ecsbuf[20];
649
		unsigned char cookie[40];
Mark Andrews's avatar
Mark Andrews committed
650 651 652 653 654 655 656 657 658 659 660 661 662 663 664

		if (query->udpsize == 0)
			query->udpsize = 4096;
		if (query->edns < 0)
			query->edns = 0;

		if (query->nsid) {
			INSIST(i < DNS_EDNSOPTIONS);
			opts[i].code = DNS_OPT_NSID;
			opts[i].length = 0;
			opts[i].value = NULL;
			i++;
		}

		if (query->ecs_addr != NULL) {
665 666
			uint8_t addr[16], family;
			uint32_t plen;
Mark Andrews's avatar
Mark Andrews committed
667 668 669 670 671 672 673
			struct sockaddr *sa;
			struct sockaddr_in *sin;
			struct sockaddr_in6 *sin6;
			size_t addrl;
			isc_buffer_t b;

			sa = &query->ecs_addr->type.sa;
674
			plen = query->ecs_addr->length;
Mark Andrews's avatar
Mark Andrews committed
675 676

			/* Round up prefix len to a multiple of 8 */
677
			addrl = (plen + 7) / 8;
Mark Andrews's avatar
Mark Andrews committed
678 679 680

			INSIST(i < DNS_EDNSOPTIONS);
			opts[i].code = DNS_OPT_CLIENT_SUBNET;
681
			opts[i].length = (uint16_t) addrl + 4;
Mark Andrews's avatar
Mark Andrews committed
682 683 684
			CHECK("isc_buffer_allocate", result);
			isc_buffer_init(&b, ecsbuf, sizeof(ecsbuf));
			if (sa->sa_family == AF_INET) {
685
				family = 1;
Mark Andrews's avatar
Mark Andrews committed
686
				sin = (struct sockaddr_in *) sa;
Evan Hunt's avatar
Evan Hunt committed
687
				memmove(addr, &sin->sin_addr, 4);
688 689
				if ((plen % 8) != 0)
					addr[addrl-1] &=
690
						~0U << (8 - (plen % 8));
Mark Andrews's avatar
Mark Andrews committed
691
			} else {
692
				family = 2;
Mark Andrews's avatar
Mark Andrews committed
693
				sin6 = (struct sockaddr_in6 *) sa;
Evan Hunt's avatar
Evan Hunt committed
694
				memmove(addr, &sin6->sin6_addr, 16);
Mark Andrews's avatar
Mark Andrews committed
695 696
			}

697 698
			/* Mask off last address byte */
			if (addrl > 0 && (plen % 8) != 0)
699
				addr[addrl - 1] &= ~0U << (8 - (plen % 8));
700 701 702 703 704 705 706 707 708 709 710 711

			/* family */
			isc_buffer_putuint16(&b, family);
			/* source prefix-length */
			isc_buffer_putuint8(&b, plen);
			/* scope prefix-length */
			isc_buffer_putuint8(&b, 0);
			/* address */
			if (addrl > 0)
				isc_buffer_putmem(&b, addr,
						  (unsigned)addrl);

712
			opts[i].value = (uint8_t *) ecsbuf;
Mark Andrews's avatar
Mark Andrews committed
713 714 715
			i++;
		}

716
		if (query->send_cookie) {
Mark Andrews's avatar
Mark Andrews committed
717
			INSIST(i < DNS_EDNSOPTIONS);
718 719
			opts[i].code = DNS_OPT_COOKIE;
			if (query->cookie != NULL) {
Mark Andrews's avatar
Mark Andrews committed
720 721
				isc_buffer_t b;

722 723
				isc_buffer_init(&b, cookie, sizeof(cookie));
				result = isc_hex_decodestring(query->cookie,
Mark Andrews's avatar
Mark Andrews committed
724 725 726 727 728
							      &b);
				CHECK("isc_hex_decodestring", result);
				opts[i].value = isc_buffer_base(&b);
				opts[i].length = isc_buffer_usedlength(&b);
			} else {
729
				compute_cookie(cookie, 8);
Mark Andrews's avatar
Mark Andrews committed
730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760
				opts[i].length = 8;
				opts[i].value = cookie;
			}
			i++;
		}

		if (query->expire) {
			INSIST(i < DNS_EDNSOPTIONS);
			opts[i].code = DNS_OPT_EXPIRE;
			opts[i].length = 0;
			opts[i].value = NULL;
			i++;
		}

		if (query->ednsoptscnt != 0) {
			memmove(&opts[i], query->ednsopts,
				sizeof(dns_ednsopt_t) * query->ednsoptscnt);
			i += query->ednsoptscnt;
		}

		flags = query->ednsflags;
		flags &= ~DNS_MESSAGEEXTFLAG_DO;
		if (query->dnssec)
			flags |= DNS_MESSAGEEXTFLAG_DO;
		add_opt(message, query->udpsize, query->edns, flags, opts, i);
	}

	options = 0;
	if (tcp_mode)
		options |= DNS_REQUESTOPT_TCP | DNS_REQUESTOPT_SHARE;
	request = NULL;
761 762 763 764 765 766
	result = dns_request_createvia(requestmgr, message,
				       have_src ? &srcaddr : NULL, &dstaddr,
				       dscp, options, NULL,
				       query->timeout, query->udptimeout,
				       query->udpretries, task,
				       recvresponse, message, &request);
Mark Andrews's avatar
Mark Andrews committed
767 768 769 770 771 772
	CHECK("dns_request_createvia4", result);

	return ISC_R_SUCCESS;
}

static void
Evan Hunt's avatar
Evan Hunt committed
773
sendqueries(isc_task_t *task, isc_event_t *event) {
Mark Andrews's avatar
Mark Andrews committed
774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820
	struct query *query = (struct query *)event->ev_arg;

	isc_event_free(&event);

	while (query != NULL) {
		struct query *next = ISC_LIST_NEXT(query, link);

		sendquery(query, task);
		query = next;
	}

	if (onfly == 0)
		isc_app_shutdown();
	return;
}

ISC_PLATFORM_NORETURN_PRE static void
usage(void) ISC_PLATFORM_NORETURN_POST;

static void
usage(void) {
	fputs("Usage: mdig @server {global-opt} host\n"
	      "           {local-opt} [ host {local-opt} [...]]\n",
	      stderr);
	fputs("\nUse \"mdig -h\" (or \"mdig -h | more\") "
	      "for complete list of options\n",
	      stderr);
	exit(1);
}

/*% help */
static void
help(void) {
	fputs("Usage: mdig @server {global-opt} host\n"
	      "           {local-opt} [ host {local-opt} [...]]\n",
	      stdout);
	fputs(
"Where:\n"
" anywhere opt    is one of:\n"
"                 -f filename         (batch mode)\n"
"                 -h                  (print help and exit)\n"
"                 -v                  (print version and exit)\n"
" global 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"
"                 -p port             (specify port number)\n"
821
"                 -m                  (enable memory usage debugging)\n"
Mark Andrews's avatar
Mark Andrews committed
822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839
"                 +[no]dscp[=###]     (Set the DSCP value to ### [0..63])\n"
"                 +[no]vc             (TCP mode)\n"
"                 +[no]tcp            (TCP mode, alternate syntax)\n"
"                 +[no]besteffort     (Try to parse even illegal messages)\n"
"                 +[no]cl             (Control display of class in records)\n"
"                 +[no]comments       (Control display of comment lines)\n"
"                 +[no]rrcomments     (Control display of per-record "
				       "comments)\n"
"                 +[no]crypto         (Control display of cryptographic "
				       "fields in records)\n"
"                 +[no]question       (Control display of question)\n"
"                 +[no]answer         (Control display of answer)\n"
"                 +[no]authority      (Control display of authority)\n"
"                 +[no]additional     (Control display of additional)\n"
"                 +[no]short          (Disable everything except short\n"
"                                      form of answer)\n"
"                 +[no]ttlid          (Control display of ttls in records)\n"
"                 +[no]ttlunits       (Display TTLs in human-readable units)\n"
840
"                 +[no]unknownformat  (Print RDATA in RFC 3597 \"unknown\" format)\n"
Mark Andrews's avatar
Mark Andrews committed
841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864
"                 +[no]all            (Set or clear all display flags)\n"
"                 +[no]multiline      (Print records in an expanded format)\n"
"                 +[no]split=##       (Split hex/base64 fields into chunks)\n"
" local opt       is one of:\n"
"                 -c class            (specify query class)\n"
"                 -t type             (specify query type)\n"
"                 -x dot-notation     (shortcut for reverse lookups)\n"
"                 +timeout=###        (Set query timeout) [UDP=5,TCP=10]\n"
"                 +udptimeout=###     (Set timeout before UDP retry)\n"
"                 +tries=###          (Set number of UDP attempts) [3]\n"
"                 +retry=###          (Set number of UDP retries) [2]\n"
"                 +bufsize=###        (Set EDNS0 Max UDP packet size)\n"
"                 +subnet=addr        (Set edns-client-subnet option)\n"
"                 +[no]edns[=###]     (Set EDNS version) [0]\n"
"                 +ednsflags=###      (Set EDNS flag bits)\n"
"                 +ednsopt=###[:value] (Send specified EDNS option)\n"
"                 +noednsopt          (Clear list of +ednsopt options)\n"
"                 +[no]recurse        (Recursive mode)\n"
"                 +[no]aaonly         (Set AA flag in query (+[no]aaflag))\n"
"                 +[no]adflag         (Set AD flag in query)\n"
"                 +[no]cdflag         (Set CD flag in query)\n"
"                 +[no]zflag          (Set Z flag in query)\n"
"                 +[no]dnssec         (Request DNSSEC records)\n"
"                 +[no]expire         (Request time to expire)\n"
865
"                 +[no]cookie[=###]   (Send a COOKIE option)\n"
Mark Andrews's avatar
Mark Andrews committed
866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887
"                 +[no]nsid           (Request Name Server ID)\n",
	stdout);
}

ISC_PLATFORM_NORETURN_PRE static void
fatal(const char *format, ...)
ISC_FORMAT_PRINTF(1, 2) ISC_PLATFORM_NORETURN_POST;

static void
fatal(const char *format, ...) {
	va_list args;

	fflush(stdout);
	fprintf(stderr, "mdig: ");
	va_start(args, format);
	vfprintf(stderr, format, args);
	va_end(args);
	fprintf(stderr, "\n");
	exit(-2);
}

static isc_result_t
888
parse_uint_helper(uint32_t *uip, const char *value, uint32_t max,
Mark Andrews's avatar
Mark Andrews committed
889
		  const char *desc, int base) {
890
	uint32_t n;
Mark Andrews's avatar
Mark Andrews committed
891 892 893 894 895 896 897 898 899 900 901 902 903
	isc_result_t result = isc_parse_uint32(&n, value, base);
	if (result == ISC_R_SUCCESS && n > max)
		result = ISC_R_RANGE;
	if (result != ISC_R_SUCCESS) {
		printf("invalid %s '%s': %s\n", desc,
		       value, isc_result_totext(result));
		return (result);
	}
	*uip = n;
	return (ISC_R_SUCCESS);
}

static isc_result_t
904
parse_uint(uint32_t *uip, const char *value, uint32_t max,
Mark Andrews's avatar
Mark Andrews committed
905 906 907 908 909
	   const char *desc) {
	return (parse_uint_helper(uip, value, max, desc, 10));
}

static isc_result_t
910
parse_xint(uint32_t *uip, const char *value, uint32_t max,
Mark Andrews's avatar
Mark Andrews committed
911 912 913 914
	   const char *desc) {
	return (parse_uint_helper(uip, value, max, desc, 0));
}

915 916
static void
newopts(struct query *query) {
Ondřej Surý's avatar
Ondřej Surý committed
917 918 919 920 921 922 923 924 925 926
	size_t len = sizeof(query->ednsopts[0]) * EDNSOPTS;
	size_t i;

	query->ednsopts = isc_mem_allocate(mctx, len);

	for (i = 0; i < EDNSOPTS; i++) {
		query->ednsopts[i].code = 0;
		query->ednsopts[i].length = 0;
		query->ednsopts[i].value = NULL;
	}
927
}
Mark Andrews's avatar
Mark Andrews committed
928 929 930

static void
save_opt(struct query *query, char *code, char *value) {
931
	uint32_t num;
Mark Andrews's avatar
Mark Andrews committed
932 933 934
	isc_buffer_t b;
	isc_result_t result;

935 936 937 938 939
	if (query->ednsopts == NULL) {
		newopts(query);
	}

	if (query->ednsoptscnt == EDNSOPTS) {
Mark Andrews's avatar
Mark Andrews committed
940
		fatal("too many ednsopts");
941
	}
Mark Andrews's avatar
Mark Andrews committed
942 943

	result = parse_uint(&num, code, 65535, "ednsopt");
944
	if (result != ISC_R_SUCCESS) {
Mark Andrews's avatar
Mark Andrews committed
945
		fatal("bad edns code point: %s", code);
946
	}
Mark Andrews's avatar
Mark Andrews committed
947

948 949 950
	query->ednsopts[query->ednsoptscnt].code = num;
	query->ednsopts[query->ednsoptscnt].length = 0;
	query->ednsopts[query->ednsoptscnt].value = NULL;
Mark Andrews's avatar
Mark Andrews committed
951 952 953

	if (value != NULL) {
		char *buf;
954
		buf = isc_mem_allocate(mctx, strlen(value) / 2 + 1);
Mark Andrews's avatar
Mark Andrews committed
955 956 957
		isc_buffer_init(&b, buf, strlen(value)/2 + 1);
		result = isc_hex_decodestring(value, &b);
		CHECK("isc_hex_decodestring", result);
958 959 960 961
		query->ednsopts[query->ednsoptscnt].value =
						isc_buffer_base(&b);
		query->ednsopts[query->ednsoptscnt].length =
						isc_buffer_usedlength(&b);
Mark Andrews's avatar
Mark Andrews committed
962 963 964 965 966 967 968 969 970 971 972
	}

	query->ednsoptscnt++;
}

static isc_result_t
parse_netprefix(isc_sockaddr_t **sap, const char *value) {
	isc_result_t result = ISC_R_SUCCESS;
	isc_sockaddr_t *sa = NULL;
	struct in_addr in4;
	struct in6_addr in6;
973
	uint32_t netmask = 0xffffffff;
Mark Andrews's avatar
Mark Andrews committed
974
	char *slash = NULL;
975
	bool parsed = false;
976
	char buf[sizeof("xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:XXX.XXX.XXX.XXX/128")];
Mark Andrews's avatar
Mark Andrews committed
977

978 979 980 981 982
	if (strlcpy(buf, value, sizeof(buf)) >= sizeof(buf))
		fatal("invalid prefix '%s'\n", value);

	slash = strchr(buf, '/');
	if (slash != NULL) {
983
		*slash = '\0';
Mark Andrews's avatar
Mark Andrews committed
984 985
		result = isc_parse_uint32(&netmask, slash + 1, 10);
		if (result != ISC_R_SUCCESS) {
986
			fatal("invalid prefix length in '%s': %s\n",
Mark Andrews's avatar
Mark Andrews committed
987 988
			      value, isc_result_totext(result));
		}
989 990
	} else if (strcmp(value, "0") == 0) {
		netmask = 0;
Mark Andrews's avatar
Mark Andrews committed
991 992 993
	}

	sa = isc_mem_allocate(mctx, sizeof(*sa));
994
	if (inet_pton(AF_INET6, buf, &in6) == 1) {
995
		parsed = true;
996
		isc_sockaddr_fromin6(sa, &in6, 0);
997
		if (netmask > 128)
Mark Andrews's avatar
Mark Andrews committed
998
			netmask = 128;
999
	} else if (inet_pton(AF_INET, buf, &in4) == 1) {
1000
		parsed = true;
Mark Andrews's avatar
Mark Andrews committed
1001
		isc_sockaddr_fromin(sa, &in4, 0);
1002
		if (netmask > 32)
Mark Andrews's avatar
Mark Andrews committed
1003
			netmask = 32;
1004
	} else if (netmask != 0xffffffff) {
Mark Andrews's avatar
Mark Andrews committed
1005 1006
		int i;

1007
		for (i = 0; i < 3 && strlen(buf) < sizeof(buf) - 2; i++) {
Mark Andrews's avatar
Mark Andrews committed
1008
			strlcat(buf, ".0", sizeof(buf));
Francis Dupont's avatar
Francis Dupont committed
1009
			if (inet_pton(AF_INET, buf, &in4) == 1) {
1010
				parsed = true;
Mark Andrews's avatar
Mark Andrews committed
1011 1012 1013 1014 1015
				isc_sockaddr_fromin(sa, &in4, 0);
				break;
			}
		}

1016 1017
		if (netmask > 32)
			netmask = 32;
Mark Andrews's avatar
Mark Andrews committed
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
	}

	if (!parsed)
		fatal("invalid address '%s'", value);

	sa->length = netmask;
	*sap = sa;

	return (ISC_R_SUCCESS);
}

/*%
 * Append 'len' bytes of 'text' at '*p', failing with
 * ISC_R_NOSPACE if that would advance p past 'end'.
 */
static isc_result_t
append(const char *text, int len, char **p, char *end) {
	if (len > end - *p)
		return (ISC_R_NOSPACE);
	memmove(*p, text, len);
	*p += len;
	return (ISC_R_SUCCESS);
}

static isc_result_t
reverse_octets(const char *in, char **p, char *end) {
1044
	const char *dot = strchr(in, '.');
Mark Andrews's avatar
Mark Andrews committed
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
	int len;
	if (dot != NULL) {
		isc_result_t result;
		result = reverse_octets(dot + 1, p, end);
		CHECK("reverse_octets", result);
		result = append(".", 1, p, end);
		CHECK("append", result);
		len = (int)(dot - in);
	} else {
		len = strlen(in);
	}
	return (append(in, len, p, end));
}

static void
1060
get_reverse(char *reverse, size_t len, const char *value)
Mark Andrews's avatar
Mark Andrews committed
1061 1062 1063 1064 1065 1066
{
	int r;
	isc_result_t result;
	isc_netaddr_t addr;

	addr.family = AF_INET6;
Francis Dupont's avatar
Francis Dupont committed
1067
	r = inet_pton(AF_INET6, value, &addr.type.in6);
Mark Andrews's avatar
Mark Andrews committed
1068 1069 1070 1071 1072 1073
	if (r > 0) {
		/* This is a valid IPv6 address. */
		dns_fixedname_t fname;
		dns_name_t *name;
		unsigned int options = 0;

1074
		name = dns_fixedname_initname(&fname);
1075
		result = dns_byaddr_createptrname(&addr, options, name);
Mark Andrews's avatar
Mark Andrews committed
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
		CHECK("dns_byaddr_createptrname2", result);
		dns_name_format(name, reverse, (unsigned int)len);
		return;
	} else {
		/*
		 * Not a valid IPv6 address.  Assume IPv4.
		 * Construct the in-addr.arpa name by blindly
		 * reversing octets whether or not they look like
		 * integers, so that this can be used for RFC2317
		 * names and such.
		 */
		char *p = reverse;
		char *end = reverse + len;
		result = reverse_octets(value, &p, end);
		CHECK("reverse_octets", result);
		/* Append .in-addr.arpa. and a terminating NUL. */
		result = append(".in-addr.arpa.", 15, &p, end);
		CHECK("append", result);
		return;
	}
}

/*%
 * We're not using isc_commandline_parse() here since the command line
 * syntax of mdig is quite a bit different from that which can be described
 * by that routine.
 * XXX doc options
 */

static void
1106
plus_option(char *option, struct query *query, bool global)
Mark Andrews's avatar
Mark Andrews committed
1107 1108
{
	isc_result_t result;
1109
	char *cmd, *value, *last = NULL, *code;
1110
	uint32_t num;
1111
	bool state = true;
Mark Andrews's avatar
Mark Andrews committed
1112 1113
	size_t n;

1114 1115
	INSIST(option != NULL);

1116 1117
	if ((cmd = strtok_r(option, "=", &last)) == NULL) {
		printf(";; Invalid option %s\n", option);
Mark Andrews's avatar
Mark Andrews committed
1118 1119 1120 1121
		return;
	}
	if (strncasecmp(cmd, "no", 2) == 0) {
		cmd += 2;
1122
		state = false;
Mark Andrews's avatar
Mark Andrews committed
1123
	}
1124 1125
	/* parse the rest of the string */
	value = strtok_r(NULL, "", &last);
Mark Andrews's avatar
Mark Andrews committed
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175

#define FULLCHECK(A) \
	do { \
		size_t _l = strlen(cmd); \
		if (_l >= sizeof(A) || strncasecmp(cmd, A, _l) != 0) \
			goto invalid_option; \
	} while (0)
#define FULLCHECK2(A, B) \
	do { \
		size_t _l = strlen(cmd); \
		if ((_l >= sizeof(A) || strncasecmp(cmd, A, _l) != 0) && \
		    (_l >= sizeof(B) || strncasecmp(cmd, B, _l) != 0)) \
			goto invalid_option; \
	} while (0)
#define GLOBAL() \
	do { \
		if (!global) \
			goto global_option; \
	} while (0)

	switch (cmd[0]) {
	case 'a':
		switch (cmd[1]) {
		case 'a': /* aaonly / aaflag */
			FULLCHECK2("aaonly", "aaflag");
			query->have_aaonly = state;
			break;
		case 'd':
			switch (cmd[2]) {
			case 'd': /* additional */
				FULLCHECK("additional");
				display_additional = state;
				break;
			case 'f': /* adflag */
			case '\0': /* +ad is a synonym for +adflag */
				FULLCHECK("adflag");
				query->have_adflag = state;
				break;
			default:
				goto invalid_option;
			}
			break;
		case 'l': /* all */
			FULLCHECK("all");
			GLOBAL();
			display_question = state;
			display_answer = state;
			display_authority = state;
			display_additional = state;
			display_comments = state;
1176
			display_rrcomments = state ? 1 : -1;
Mark Andrews's avatar
Mark Andrews committed
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232
			break;
		case 'n': /* answer */
			FULLCHECK("answer");
			GLOBAL();
			display_answer = state;
			break;
		case 'u': /* authority */
			FULLCHECK("authority");
			GLOBAL();
			display_authority = state;
			break;
		default:
			goto invalid_option;
		}
		break;
	case 'b':
		switch (cmd[1]) {
		case 'e':/* besteffort */
			FULLCHECK("besteffort");
			GLOBAL();
			besteffort = state;
			break;
		case 'u':/* bufsize */
			FULLCHECK("bufsize");
			if (value == NULL)
				goto need_value;
			if (!state)
				goto invalid_option;
			result = parse_uint(&num, value, COMMSIZE,
					    "buffer size");
			CHECK("parse_uint(buffer size)", result);
			query->udpsize = num;
			break;
		default:
			goto invalid_option;
		}
		break;
	case 'c':
		switch (cmd[1]) {
		case 'd':/* cdflag */
			switch (cmd[2]) {
			case 'f': /* cdflag */
			case '\0': /* +cd is a synonym for +cdflag */
				FULLCHECK("cdflag");
				query->have_cdflag = state;
				break;
			default:
				goto invalid_option;
			}
			break;
		case 'l': /* cl */
			FULLCHECK("cl");
			GLOBAL();
			display_class = state;
			break;
		case 'o': /* comments */
1233 1234 1235 1236 1237 1238
			switch (cmd[2]) {
			case 'm':
				FULLCHECK("comments");
				GLOBAL();
				display_comments = state;
				break;
1239 1240 1241 1242 1243
			case 'n':
				FULLCHECK("continue");
				GLOBAL();
				continue_on_error = state;
				break;
1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260
			case 'o':
				FULLCHECK("cookie");
				if (state && query->edns == -1)
					query->edns = 0;
				query->send_cookie = state;
				if (value != NULL) {
					n = strlcpy(hexcookie, value,
						    sizeof(hexcookie));
					if (n >= sizeof(hexcookie))
						fatal("COOKIE data too large");
					query->cookie = hexcookie;
				} else
					query->cookie = NULL;
				break;
			default:
				goto invalid_option;
			}
Mark Andrews's avatar
Mark Andrews committed
1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345
			break;
		case 'r':
			FULLCHECK("crypto");
			GLOBAL();
			display_crypto = state;
			break;
		default:
			goto invalid_option;
		}
		break;
	case 'd':
		switch (cmd[1]) {
		case 'n': /* dnssec */
			FULLCHECK("dnssec");
			if (state && query->edns == -1)
				query->edns = 0;
			query->dnssec = state;
			break;
		case 's': /* dscp */
			FULLCHECK("dscp");
			GLOBAL();
			if (!state) {
				dscp = -1;
				break;
			}
			if (value == NULL)
				goto need_value;
			result = parse_uint(&num, value, 0x3f, "DSCP");
			CHECK("parse_uint(DSCP)", result);
			dscp = num;
			break;
		default:
			goto invalid_option;
		}
		break;
	case 'e':
		switch (cmd[1]) {
		case 'd':
			switch(cmd[2]) {
			case 'n':
				switch (cmd[3]) {
				case 's':
					switch (cmd[4]) {
					case 0:
						FULLCHECK("edns");
						if (!state) {
							query->edns = -1;
							break;
						}
						if (value == NULL) {
							query->edns = 0;
							break;
						}
						result = parse_uint(&num,
								    value,
								    255,
								    "edns");
						CHECK("parse_uint(edns)",
						      result);
						query->edns = num;
						break;
					case 'f':
						FULLCHECK("ednsflags");
						if (!state) {
							query->ednsflags = 0;
							break;
						}
						if (value == NULL) {
							query->ednsflags = 0;
							break;
						}
						result = parse_xint(&num,
								    value,
								    0xffff,
								  "ednsflags");
						CHECK("parse_xint(ednsflags)",
						      result);
						query->ednsflags = num;
						break;
					case 'o':
						FULLCHECK("ednsopt");
						if (!state) {
							query->ednsoptscnt = 0;
							break;
						}
1346 1347 1348 1349 1350 1351 1352
						code = NULL;
						if (value != NULL) {
							code = strtok_r(value,
									":",
									&last);
						}
						if (code == NULL) {
Mark Andrews's avatar
Mark Andrews committed
1353 1354 1355
							fatal("ednsopt no "
							      "code point "
							      "specified");
1356 1357
						}
						value = strtok_r(NULL, "\0",
Ondřej Surý's avatar
Ondřej Surý committed
1358
								 &last);
Mark Andrews's avatar
Mark Andrews committed
1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424
						save_opt(query, code, value);
						break;
					default:
						goto invalid_option;
					}
					break;
				default:
					goto invalid_option;
				}
				break;
			default:
				goto invalid_option;
			}
			break;
		case 'x':
			FULLCHECK("expire");
			query->expire = state;
			break;
		default:
			goto invalid_option;
		}
		break;
	case 'm': /* multiline */
		FULLCHECK("multiline");
		GLOBAL();
		display_multiline = state;
		break;
	case 'n':
		FULLCHECK("nsid");
		if (state && query->edns == -1)
			query->edns = 0;
		query->nsid = state;
		break;
	case 'q':
		FULLCHECK("question");
		GLOBAL();
		display_question = state;
		break;
	case 'r':
		switch (cmd[1]) {
		case 'e':
			switch (cmd[2]) {
			case 'c': /* recurse */
				FULLCHECK("recurse");
				query->recurse = state;
				break;
			case 't': /* retry / retries */
				FULLCHECK2("retry", "retries");
				if (value == NULL)
					goto need_value;
				if (!state)
					goto invalid_option;
				result = parse_uint(&query->udpretries,
						    value,
						    MAXTRIES - 1,
						    "udpretries");
				CHECK("parse_uint(udpretries)", result);
				query->udpretries++;
				break;
			default:
				goto invalid_option;
			}
			break;
		case 'r':
			FULLCHECK("rrcomments");
			GLOBAL();
1425
			display_rrcomments = state ? 1 : -1;
Mark Andrews's avatar
Mark Andrews committed
1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437
			break;
		default:
			goto invalid_option;
		}
		break;
	case 's':
		switch (cmd[1]) {
		case 'h':
			FULLCHECK("short");
			GLOBAL();
			display_short_form = state;
			if (state) {
1438 1439 1440 1441 1442
				display_question = false;
				display_answer = true;
				display_authority = false;
				display_additional = false;
				display_comments = false;
1443
				display_rrcomments = -1;
Mark Andrews's avatar
Mark Andrews committed
1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458
			}
			break;
		case 'p': /* split */
			FULLCHECK("split");
			GLOBAL();
			if (value != NULL && !state)
				goto invalid_option;
			if (!state) {
				display_splitwidth = 0;
				break;
			} else if (value == NULL)
				break;

			result = parse_uint(&display_splitwidth, value,
					    1023, "split");
Mark Andrews's avatar
Mark Andrews committed
1459
			if ((display_splitwidth % 4) != 0) {
Mark Andrews's avatar
Mark Andrews committed
1460 1461 1462 1463
				display_splitwidth =
				    ((display_splitwidth + 3) / 4) * 4;
				fprintf(stderr, ";; Warning, split must be "
						"a multiple of 4; adjusting "