Home | History | Annotate | Line # | Download | only in delv
delv.c revision 1.4.4.1
      1 /*	$NetBSD: delv.c,v 1.4.4.1 2024/02/29 12:28:10 martin Exp $	*/
      2 
      3 /*
      4  * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
      5  *
      6  * SPDX-License-Identifier: MPL-2.0
      7  *
      8  * This Source Code Form is subject to the terms of the Mozilla Public
      9  * License, v. 2.0. If a copy of the MPL was not distributed with this
     10  * file, you can obtain one at https://mozilla.org/MPL/2.0/.
     11  *
     12  * See the COPYRIGHT file distributed with this work for additional
     13  * information regarding copyright ownership.
     14  */
     15 
     16 #include <arpa/inet.h>
     17 #include <bind.keys.h>
     18 #include <inttypes.h>
     19 #include <netdb.h>
     20 #include <netinet/in.h>
     21 #include <signal.h>
     22 #include <stdbool.h>
     23 #include <stdio.h>
     24 #include <stdlib.h>
     25 #include <string.h>
     26 #include <sys/socket.h>
     27 #include <sys/types.h>
     28 #include <unistd.h>
     29 
     30 #include <isc/app.h>
     31 #include <isc/attributes.h>
     32 #include <isc/base64.h>
     33 #include <isc/buffer.h>
     34 #include <isc/hex.h>
     35 #include <isc/log.h>
     36 #include <isc/managers.h>
     37 #include <isc/md.h>
     38 #include <isc/mem.h>
     39 #include <isc/netmgr.h>
     40 #include <isc/parseint.h>
     41 #include <isc/print.h>
     42 #include <isc/result.h>
     43 #include <isc/sockaddr.h>
     44 #include <isc/string.h>
     45 #include <isc/task.h>
     46 #include <isc/timer.h>
     47 #include <isc/util.h>
     48 
     49 #include <dns/byaddr.h>
     50 #include <dns/client.h>
     51 #include <dns/fixedname.h>
     52 #include <dns/keytable.h>
     53 #include <dns/keyvalues.h>
     54 #include <dns/log.h>
     55 #include <dns/masterdump.h>
     56 #include <dns/name.h>
     57 #include <dns/rdata.h>
     58 #include <dns/rdataclass.h>
     59 #include <dns/rdataset.h>
     60 #include <dns/rdatastruct.h>
     61 #include <dns/rdatatype.h>
     62 #include <dns/secalg.h>
     63 #include <dns/view.h>
     64 
     65 #include <dst/dst.h>
     66 
     67 #include <isccfg/log.h>
     68 #include <isccfg/namedconf.h>
     69 
     70 #include <irs/resconf.h>
     71 
     72 #define CHECK(r)                             \
     73 	do {                                 \
     74 		result = (r);                \
     75 		if (result != ISC_R_SUCCESS) \
     76 			goto cleanup;        \
     77 	} while (0)
     78 
     79 #define MAXNAME (DNS_NAME_MAXTEXT + 1)
     80 
     81 /* Variables used internally by delv. */
     82 char *progname;
     83 static isc_mem_t *mctx = NULL;
     84 static isc_log_t *lctx = NULL;
     85 
     86 /* Configurables */
     87 static char *server = NULL;
     88 static const char *port = "53";
     89 static isc_sockaddr_t *srcaddr4 = NULL, *srcaddr6 = NULL;
     90 static isc_sockaddr_t a4, a6;
     91 static char *curqname = NULL, *qname = NULL;
     92 static bool classset = false;
     93 static dns_rdatatype_t qtype = dns_rdatatype_none;
     94 static bool typeset = false;
     95 
     96 static unsigned int styleflags = 0;
     97 static uint32_t splitwidth = 0xffffffff;
     98 static bool showcomments = true, showdnssec = true, showtrust = true,
     99 	    rrcomments = true, noclass = false, nocrypto = false, nottl = false,
    100 	    multiline = false, short_form = false, print_unknown_format = false,
    101 	    yaml = false;
    102 
    103 static bool resolve_trace = false, validator_trace = false,
    104 	    message_trace = false;
    105 
    106 static bool use_ipv4 = true, use_ipv6 = true;
    107 
    108 static bool cdflag = false, no_sigs = false, root_validation = true;
    109 
    110 static bool use_tcp = false;
    111 
    112 static char *anchorfile = NULL;
    113 static char *trust_anchor = NULL;
    114 static int num_keys = 0;
    115 
    116 static dns_fixedname_t afn;
    117 static dns_name_t *anchor_name = NULL;
    118 
    119 /* Default bind.keys contents */
    120 static char anchortext[] = TRUST_ANCHORS;
    121 
    122 /*
    123  * Static function prototypes
    124  */
    125 static isc_result_t
    126 get_reverse(char *reverse, size_t len, char *value, bool strict);
    127 
    128 static isc_result_t
    129 parse_uint(uint32_t *uip, const char *value, uint32_t max, const char *desc);
    130 
    131 static void
    132 usage(void) {
    133 	fprintf(stderr,
    134 		"Usage:  delv [@server] {q-opt} {d-opt} [domain] [q-type] "
    135 		"[q-class]\n"
    136 		"Where:  domain	  is in the Domain Name System\n"
    137 		"        q-class  is one of (in,hs,ch,...) [default: in]\n"
    138 		"        q-type   is one of "
    139 		"(a,any,mx,ns,soa,hinfo,axfr,txt,...) "
    140 		"[default:a]\n"
    141 		"        q-opt    is one of:\n"
    142 		"                 -4                  (use IPv4 query "
    143 		"transport "
    144 		"only)\n"
    145 		"                 -6                  (use IPv6 query "
    146 		"transport "
    147 		"only)\n"
    148 		"                 -a anchor-file      (specify root trust "
    149 		"anchor)\n"
    150 		"                 -b address[#port]   (bind to source "
    151 		"address/port)\n"
    152 		"                 -c class            (option included for "
    153 		"compatibility;\n"
    154 		"                 -d level            (set debugging level)\n"
    155 		"                 -h                  (print help and exit)\n"
    156 		"                 -i                  (disable DNSSEC "
    157 		"validation)\n"
    158 		"                 -m                  (enable memory usage "
    159 		"debugging)\n"
    160 		"                 -p port             (specify port number)\n"
    161 		"                 -q name             (specify query name)\n"
    162 		"                 -t type             (specify query type)\n"
    163 		"                                      only IN is supported)\n"
    164 		"                 -v                  (print version and "
    165 		"exit)\n"
    166 		"                 -x dot-notation     (shortcut for reverse "
    167 		"lookups)\n"
    168 		"        d-opt    is of the form +keyword[=value], where "
    169 		"keyword "
    170 		"is:\n"
    171 		"                 +[no]all            (Set or clear all "
    172 		"display "
    173 		"flags)\n"
    174 		"                 +[no]class          (Control display of "
    175 		"class)\n"
    176 		"                 +[no]comments       (Control display of "
    177 		"comment lines)\n"
    178 		"                 +[no]crypto         (Control display of "
    179 		"cryptographic\n"
    180 		"                                      fields in records)\n"
    181 		"                 +[no]dlv            (Obsolete)\n"
    182 		"                 +[no]dnssec         (Display DNSSEC "
    183 		"records)\n"
    184 		"                 +[no]mtrace         (Trace messages "
    185 		"received)\n"
    186 		"                 +[no]multiline      (Print records in an "
    187 		"expanded format)\n"
    188 		"                 +[no]root           (DNSSEC validation trust "
    189 		"anchor)\n"
    190 		"                 +[no]rrcomments     (Control display of "
    191 		"per-record "
    192 		"comments)\n"
    193 		"                 +[no]rtrace         (Trace resolver "
    194 		"fetches)\n"
    195 		"                 +[no]short          (Short form answer)\n"
    196 		"                 +[no]split=##       (Split hex/base64 fields "
    197 		"into chunks)\n"
    198 		"                 +[no]tcp            (TCP mode)\n"
    199 		"                 +[no]ttl            (Control display of ttls "
    200 		"in records)\n"
    201 		"                 +[no]trust          (Control display of "
    202 		"trust "
    203 		"level)\n"
    204 		"                 +[no]unknownformat  (Print RDATA in RFC 3597 "
    205 		"\"unknown\" format)\n"
    206 		"                 +[no]vtrace         (Trace validation "
    207 		"process)\n"
    208 		"                 +[no]yaml           (Present the results as "
    209 		"YAML)\n");
    210 	exit(1);
    211 }
    212 
    213 noreturn static void
    214 fatal(const char *format, ...) ISC_FORMAT_PRINTF(1, 2);
    215 
    216 static void
    217 fatal(const char *format, ...) {
    218 	va_list args;
    219 
    220 	fflush(stdout);
    221 	fprintf(stderr, "%s: ", progname);
    222 	va_start(args, format);
    223 	vfprintf(stderr, format, args);
    224 	va_end(args);
    225 	fprintf(stderr, "\n");
    226 	exit(1);
    227 }
    228 
    229 static void
    230 warn(const char *format, ...) ISC_FORMAT_PRINTF(1, 2);
    231 
    232 static void
    233 warn(const char *format, ...) {
    234 	va_list args;
    235 
    236 	fflush(stdout);
    237 	fprintf(stderr, "%s: warning: ", progname);
    238 	va_start(args, format);
    239 	vfprintf(stderr, format, args);
    240 	va_end(args);
    241 	fprintf(stderr, "\n");
    242 }
    243 
    244 static isc_logcategory_t categories[] = { { "delv", 0 }, { NULL, 0 } };
    245 #define LOGCATEGORY_DEFAULT (&categories[0])
    246 #define LOGMODULE_DEFAULT   (&modules[0])
    247 
    248 static isc_logmodule_t modules[] = { { "delv", 0 }, { NULL, 0 } };
    249 
    250 static void
    251 delv_log(int level, const char *fmt, ...) ISC_FORMAT_PRINTF(2, 3);
    252 
    253 static void
    254 delv_log(int level, const char *fmt, ...) {
    255 	va_list ap;
    256 	char msgbuf[2048];
    257 
    258 	if (!isc_log_wouldlog(lctx, level)) {
    259 		return;
    260 	}
    261 
    262 	va_start(ap, fmt);
    263 
    264 	vsnprintf(msgbuf, sizeof(msgbuf), fmt, ap);
    265 	isc_log_write(lctx, LOGCATEGORY_DEFAULT, LOGMODULE_DEFAULT, level, "%s",
    266 		      msgbuf);
    267 	va_end(ap);
    268 }
    269 
    270 static int loglevel = 0;
    271 
    272 static void
    273 setup_logging(FILE *errout) {
    274 	isc_result_t result;
    275 	isc_logdestination_t destination;
    276 	isc_logconfig_t *logconfig = NULL;
    277 
    278 	isc_log_create(mctx, &lctx, &logconfig);
    279 	isc_log_registercategories(lctx, categories);
    280 	isc_log_registermodules(lctx, modules);
    281 	isc_log_setcontext(lctx);
    282 	dns_log_init(lctx);
    283 	dns_log_setcontext(lctx);
    284 	cfg_log_init(lctx);
    285 
    286 	destination.file.stream = errout;
    287 	destination.file.name = NULL;
    288 	destination.file.versions = ISC_LOG_ROLLNEVER;
    289 	destination.file.maximum_size = 0;
    290 	isc_log_createchannel(logconfig, "stderr", ISC_LOG_TOFILEDESC,
    291 			      ISC_LOG_DYNAMIC, &destination,
    292 			      ISC_LOG_PRINTPREFIX);
    293 
    294 	isc_log_setdebuglevel(lctx, loglevel);
    295 	isc_log_settag(logconfig, ";; ");
    296 
    297 	result = isc_log_usechannel(logconfig, "stderr",
    298 				    ISC_LOGCATEGORY_DEFAULT, NULL);
    299 	if (result != ISC_R_SUCCESS) {
    300 		fatal("Couldn't attach to log channel 'stderr'");
    301 	}
    302 
    303 	if (resolve_trace && loglevel < 1) {
    304 		isc_log_createchannel(logconfig, "resolver", ISC_LOG_TOFILEDESC,
    305 				      ISC_LOG_DEBUG(1), &destination,
    306 				      ISC_LOG_PRINTPREFIX);
    307 
    308 		result = isc_log_usechannel(logconfig, "resolver",
    309 					    DNS_LOGCATEGORY_RESOLVER,
    310 					    DNS_LOGMODULE_RESOLVER);
    311 		if (result != ISC_R_SUCCESS) {
    312 			fatal("Couldn't attach to log channel 'resolver'");
    313 		}
    314 	}
    315 
    316 	if (validator_trace && loglevel < 3) {
    317 		isc_log_createchannel(logconfig, "validator",
    318 				      ISC_LOG_TOFILEDESC, ISC_LOG_DEBUG(3),
    319 				      &destination, ISC_LOG_PRINTPREFIX);
    320 
    321 		result = isc_log_usechannel(logconfig, "validator",
    322 					    DNS_LOGCATEGORY_DNSSEC,
    323 					    DNS_LOGMODULE_VALIDATOR);
    324 		if (result != ISC_R_SUCCESS) {
    325 			fatal("Couldn't attach to log channel 'validator'");
    326 		}
    327 	}
    328 
    329 	if (message_trace && loglevel < 10) {
    330 		isc_log_createchannel(logconfig, "messages", ISC_LOG_TOFILEDESC,
    331 				      ISC_LOG_DEBUG(10), &destination,
    332 				      ISC_LOG_PRINTPREFIX);
    333 
    334 		result = isc_log_usechannel(logconfig, "messages",
    335 					    DNS_LOGCATEGORY_RESOLVER,
    336 					    DNS_LOGMODULE_PACKETS);
    337 		if (result != ISC_R_SUCCESS) {
    338 			fatal("Couldn't attach to log channel 'messagse'");
    339 		}
    340 	}
    341 }
    342 
    343 static void
    344 print_status(dns_rdataset_t *rdataset) {
    345 	char buf[1024] = { 0 };
    346 
    347 	REQUIRE(rdataset != NULL);
    348 
    349 	if (!showtrust || !dns_rdataset_isassociated(rdataset)) {
    350 		return;
    351 	}
    352 
    353 	buf[0] = '\0';
    354 
    355 	if ((rdataset->attributes & DNS_RDATASETATTR_NEGATIVE) != 0) {
    356 		strlcat(buf, "negative response", sizeof(buf));
    357 		strlcat(buf, (yaml ? "_" : ", "), sizeof(buf));
    358 	}
    359 
    360 	switch (rdataset->trust) {
    361 	case dns_trust_none:
    362 		strlcat(buf, "untrusted", sizeof(buf));
    363 		break;
    364 	case dns_trust_pending_additional:
    365 		strlcat(buf, "signed additional data", sizeof(buf));
    366 		if (!yaml) {
    367 			strlcat(buf, ", ", sizeof(buf));
    368 		}
    369 		strlcat(buf, "pending validation", sizeof(buf));
    370 		break;
    371 	case dns_trust_pending_answer:
    372 		strlcat(buf, "signed answer", sizeof(buf));
    373 		if (!yaml) {
    374 			strlcat(buf, ", ", sizeof(buf));
    375 		}
    376 		strlcat(buf, "pending validation", sizeof(buf));
    377 		break;
    378 	case dns_trust_additional:
    379 		strlcat(buf, "unsigned additional data", sizeof(buf));
    380 		break;
    381 	case dns_trust_glue:
    382 		strlcat(buf, "glue data", sizeof(buf));
    383 		break;
    384 	case dns_trust_answer:
    385 		if (root_validation) {
    386 			strlcat(buf, "unsigned answer", sizeof(buf));
    387 		} else {
    388 			strlcat(buf, "answer not validated", sizeof(buf));
    389 		}
    390 		break;
    391 	case dns_trust_authauthority:
    392 		strlcat(buf, "authority data", sizeof(buf));
    393 		break;
    394 	case dns_trust_authanswer:
    395 		strlcat(buf, "authoritative", sizeof(buf));
    396 		break;
    397 	case dns_trust_secure:
    398 		strlcat(buf, "fully validated", sizeof(buf));
    399 		break;
    400 	case dns_trust_ultimate:
    401 		strlcat(buf, "ultimate trust", sizeof(buf));
    402 		break;
    403 	}
    404 
    405 	if (yaml) {
    406 		char *p;
    407 
    408 		/* Convert spaces to underscores for YAML */
    409 		for (p = buf; p != NULL && *p != '\0'; p++) {
    410 			if (*p == ' ') {
    411 				*p = '_';
    412 			}
    413 		}
    414 
    415 		printf("  - %s:\n", buf);
    416 	} else {
    417 		printf("; %s\n", buf);
    418 	}
    419 }
    420 
    421 static isc_result_t
    422 printdata(dns_rdataset_t *rdataset, dns_name_t *owner,
    423 	  dns_master_style_t *style) {
    424 	isc_result_t result = ISC_R_SUCCESS;
    425 	static dns_trust_t trust;
    426 	static bool first = true;
    427 	isc_buffer_t target;
    428 	isc_region_t r;
    429 	char *t = NULL;
    430 	int len = 2048;
    431 
    432 	if (!dns_rdataset_isassociated(rdataset)) {
    433 		char namebuf[DNS_NAME_FORMATSIZE];
    434 		dns_name_format(owner, namebuf, sizeof(namebuf));
    435 		delv_log(ISC_LOG_DEBUG(4), "WARN: empty rdataset %s", namebuf);
    436 		return (ISC_R_SUCCESS);
    437 	}
    438 
    439 	if (!showdnssec && rdataset->type == dns_rdatatype_rrsig) {
    440 		return (ISC_R_SUCCESS);
    441 	}
    442 
    443 	if (first || rdataset->trust != trust) {
    444 		if (!first && showtrust && !short_form && !yaml) {
    445 			putchar('\n');
    446 		}
    447 		print_status(rdataset);
    448 		trust = rdataset->trust;
    449 		first = false;
    450 	}
    451 
    452 	do {
    453 		t = isc_mem_get(mctx, len);
    454 
    455 		isc_buffer_init(&target, t, len);
    456 		if (short_form) {
    457 			dns_rdata_t rdata = DNS_RDATA_INIT;
    458 			for (result = dns_rdataset_first(rdataset);
    459 			     result == ISC_R_SUCCESS;
    460 			     result = dns_rdataset_next(rdataset))
    461 			{
    462 				if ((rdataset->attributes &
    463 				     DNS_RDATASETATTR_NEGATIVE) != 0)
    464 				{
    465 					continue;
    466 				}
    467 
    468 				dns_rdataset_current(rdataset, &rdata);
    469 				result = dns_rdata_tofmttext(
    470 					&rdata, dns_rootname, styleflags, 0,
    471 					splitwidth, " ", &target);
    472 				if (result != ISC_R_SUCCESS) {
    473 					break;
    474 				}
    475 
    476 				if (isc_buffer_availablelength(&target) < 1) {
    477 					result = ISC_R_NOSPACE;
    478 					break;
    479 				}
    480 
    481 				isc_buffer_putstr(&target, "\n");
    482 
    483 				dns_rdata_reset(&rdata);
    484 			}
    485 		} else {
    486 			dns_indent_t indent = { "  ", 2 };
    487 			if (!yaml && (rdataset->attributes &
    488 				      DNS_RDATASETATTR_NEGATIVE) != 0)
    489 			{
    490 				isc_buffer_putstr(&target, "; ");
    491 			}
    492 			result = dns_master_rdatasettotext(
    493 				owner, rdataset, style, yaml ? &indent : NULL,
    494 				&target);
    495 		}
    496 
    497 		if (result == ISC_R_NOSPACE) {
    498 			isc_mem_put(mctx, t, len);
    499 			len += 1024;
    500 		} else if (result == ISC_R_NOMORE) {
    501 			result = ISC_R_SUCCESS;
    502 		} else {
    503 			CHECK(result);
    504 		}
    505 	} while (result == ISC_R_NOSPACE);
    506 
    507 	isc_buffer_usedregion(&target, &r);
    508 	printf("%.*s", (int)r.length, (char *)r.base);
    509 
    510 cleanup:
    511 	if (t != NULL) {
    512 		isc_mem_put(mctx, t, len);
    513 	}
    514 
    515 	return (ISC_R_SUCCESS);
    516 }
    517 
    518 static isc_result_t
    519 setup_style(dns_master_style_t **stylep) {
    520 	isc_result_t result;
    521 	dns_master_style_t *style = NULL;
    522 
    523 	REQUIRE(stylep != NULL && *stylep == NULL);
    524 
    525 	styleflags |= DNS_STYLEFLAG_REL_OWNER;
    526 	if (yaml) {
    527 		styleflags |= DNS_STYLEFLAG_YAML;
    528 	} else {
    529 		if (showcomments) {
    530 			styleflags |= DNS_STYLEFLAG_COMMENT;
    531 		}
    532 		if (print_unknown_format) {
    533 			styleflags |= DNS_STYLEFLAG_UNKNOWNFORMAT;
    534 		}
    535 		if (rrcomments) {
    536 			styleflags |= DNS_STYLEFLAG_RRCOMMENT;
    537 		}
    538 		if (nottl) {
    539 			styleflags |= DNS_STYLEFLAG_NO_TTL;
    540 		}
    541 		if (noclass) {
    542 			styleflags |= DNS_STYLEFLAG_NO_CLASS;
    543 		}
    544 		if (nocrypto) {
    545 			styleflags |= DNS_STYLEFLAG_NOCRYPTO;
    546 		}
    547 		if (multiline) {
    548 			styleflags |= DNS_STYLEFLAG_MULTILINE;
    549 			styleflags |= DNS_STYLEFLAG_COMMENT;
    550 		}
    551 	}
    552 
    553 	if (multiline || (nottl && noclass)) {
    554 		result = dns_master_stylecreate(&style, styleflags, 24, 24, 24,
    555 						32, 80, 8, splitwidth, mctx);
    556 	} else if (nottl || noclass) {
    557 		result = dns_master_stylecreate(&style, styleflags, 24, 24, 32,
    558 						40, 80, 8, splitwidth, mctx);
    559 	} else {
    560 		result = dns_master_stylecreate(&style, styleflags, 24, 32, 40,
    561 						48, 80, 8, splitwidth, mctx);
    562 	}
    563 
    564 	if (result == ISC_R_SUCCESS) {
    565 		*stylep = style;
    566 	}
    567 	return (result);
    568 }
    569 
    570 static isc_result_t
    571 convert_name(dns_fixedname_t *fn, dns_name_t **name, const char *text) {
    572 	isc_result_t result;
    573 	isc_buffer_t b;
    574 	dns_name_t *n;
    575 	unsigned int len;
    576 
    577 	REQUIRE(fn != NULL && name != NULL && text != NULL);
    578 	len = strlen(text);
    579 
    580 	isc_buffer_constinit(&b, text, len);
    581 	isc_buffer_add(&b, len);
    582 	n = dns_fixedname_initname(fn);
    583 
    584 	result = dns_name_fromtext(n, &b, dns_rootname, 0, NULL);
    585 	if (result != ISC_R_SUCCESS) {
    586 		delv_log(ISC_LOG_ERROR, "failed to convert QNAME %s: %s", text,
    587 			 isc_result_totext(result));
    588 		return (result);
    589 	}
    590 
    591 	*name = n;
    592 	return (ISC_R_SUCCESS);
    593 }
    594 
    595 static isc_result_t
    596 key_fromconfig(const cfg_obj_t *key, dns_client_t *client) {
    597 	dns_rdata_dnskey_t dnskey;
    598 	dns_rdata_ds_t ds;
    599 	uint32_t rdata1, rdata2, rdata3;
    600 	const char *datastr = NULL, *keynamestr = NULL, *atstr = NULL;
    601 	unsigned char data[4096];
    602 	isc_buffer_t databuf;
    603 	unsigned char rrdata[4096];
    604 	isc_buffer_t rrdatabuf;
    605 	isc_region_t r;
    606 	dns_fixedname_t fkeyname;
    607 	dns_name_t *keyname;
    608 	isc_result_t result;
    609 	bool match_root = false;
    610 	enum {
    611 		INITIAL_KEY,
    612 		STATIC_KEY,
    613 		INITIAL_DS,
    614 		STATIC_DS,
    615 		TRUSTED
    616 	} anchortype;
    617 	const cfg_obj_t *obj;
    618 
    619 	keynamestr = cfg_obj_asstring(cfg_tuple_get(key, "name"));
    620 	CHECK(convert_name(&fkeyname, &keyname, keynamestr));
    621 
    622 	if (!root_validation) {
    623 		return (ISC_R_SUCCESS);
    624 	}
    625 
    626 	if (anchor_name) {
    627 		match_root = dns_name_equal(keyname, anchor_name);
    628 	}
    629 
    630 	if (!match_root) {
    631 		return (ISC_R_SUCCESS);
    632 	}
    633 
    634 	if (!root_validation) {
    635 		return (ISC_R_SUCCESS);
    636 	}
    637 
    638 	delv_log(ISC_LOG_DEBUG(3), "adding trust anchor %s", trust_anchor);
    639 
    640 	/* if DNSKEY, flags; if DS, key tag */
    641 	rdata1 = cfg_obj_asuint32(cfg_tuple_get(key, "rdata1"));
    642 
    643 	/* if DNSKEY, protocol; if DS, algorithm */
    644 	rdata2 = cfg_obj_asuint32(cfg_tuple_get(key, "rdata2"));
    645 
    646 	/* if DNSKEY, algorithm; if DS, digest type */
    647 	rdata3 = cfg_obj_asuint32(cfg_tuple_get(key, "rdata3"));
    648 
    649 	/* What type of trust anchor is this? */
    650 	obj = cfg_tuple_get(key, "anchortype");
    651 	if (cfg_obj_isvoid(obj)) {
    652 		/*
    653 		 * "anchortype" is not defined, this must be a static-key
    654 		 * configured with trusted-keys.
    655 		 */
    656 		anchortype = STATIC_KEY;
    657 	} else {
    658 		atstr = cfg_obj_asstring(obj);
    659 		if (strcasecmp(atstr, "static-key") == 0) {
    660 			anchortype = STATIC_KEY;
    661 		} else if (strcasecmp(atstr, "static-ds") == 0) {
    662 			anchortype = STATIC_DS;
    663 		} else if (strcasecmp(atstr, "initial-key") == 0) {
    664 			anchortype = INITIAL_KEY;
    665 		} else if (strcasecmp(atstr, "initial-ds") == 0) {
    666 			anchortype = INITIAL_DS;
    667 		} else {
    668 			delv_log(ISC_LOG_ERROR,
    669 				 "key '%s': invalid initialization method '%s'",
    670 				 keynamestr, atstr);
    671 			result = ISC_R_FAILURE;
    672 			goto cleanup;
    673 		}
    674 	}
    675 
    676 	isc_buffer_init(&databuf, data, sizeof(data));
    677 	isc_buffer_init(&rrdatabuf, rrdata, sizeof(rrdata));
    678 
    679 	if (rdata1 > 0xffff) {
    680 		CHECK(ISC_R_RANGE);
    681 	}
    682 	if (rdata2 > 0xff) {
    683 		CHECK(ISC_R_RANGE);
    684 	}
    685 	if (rdata3 > 0xff) {
    686 		CHECK(ISC_R_RANGE);
    687 	}
    688 
    689 	switch (anchortype) {
    690 	case STATIC_KEY:
    691 	case INITIAL_KEY:
    692 	case TRUSTED:
    693 		dnskey.common.rdclass = dns_rdataclass_in;
    694 		dnskey.common.rdtype = dns_rdatatype_dnskey;
    695 		dnskey.mctx = NULL;
    696 
    697 		ISC_LINK_INIT(&dnskey.common, link);
    698 
    699 		dnskey.flags = (uint16_t)rdata1;
    700 		dnskey.protocol = (uint8_t)rdata2;
    701 		dnskey.algorithm = (uint8_t)rdata3;
    702 
    703 		datastr = cfg_obj_asstring(cfg_tuple_get(key, "data"));
    704 		CHECK(isc_base64_decodestring(datastr, &databuf));
    705 		isc_buffer_usedregion(&databuf, &r);
    706 		dnskey.datalen = r.length;
    707 		dnskey.data = r.base;
    708 
    709 		CHECK(dns_rdata_fromstruct(NULL, dnskey.common.rdclass,
    710 					   dnskey.common.rdtype, &dnskey,
    711 					   &rrdatabuf));
    712 		CHECK(dns_client_addtrustedkey(client, dns_rdataclass_in,
    713 					       dns_rdatatype_dnskey, keyname,
    714 					       &rrdatabuf));
    715 		break;
    716 	case INITIAL_DS:
    717 	case STATIC_DS:
    718 		ds.common.rdclass = dns_rdataclass_in;
    719 		ds.common.rdtype = dns_rdatatype_ds;
    720 		ds.mctx = NULL;
    721 
    722 		ISC_LINK_INIT(&ds.common, link);
    723 
    724 		ds.key_tag = (uint16_t)rdata1;
    725 		ds.algorithm = (uint8_t)rdata2;
    726 		ds.digest_type = (uint8_t)rdata3;
    727 
    728 		datastr = cfg_obj_asstring(cfg_tuple_get(key, "data"));
    729 		CHECK(isc_hex_decodestring(datastr, &databuf));
    730 		isc_buffer_usedregion(&databuf, &r);
    731 
    732 		switch (ds.digest_type) {
    733 		case DNS_DSDIGEST_SHA1:
    734 			if (r.length != ISC_SHA1_DIGESTLENGTH) {
    735 				CHECK(ISC_R_UNEXPECTEDEND);
    736 			}
    737 			break;
    738 		case DNS_DSDIGEST_SHA256:
    739 			if (r.length != ISC_SHA256_DIGESTLENGTH) {
    740 				CHECK(ISC_R_UNEXPECTEDEND);
    741 			}
    742 			break;
    743 		case DNS_DSDIGEST_SHA384:
    744 			if (r.length != ISC_SHA384_DIGESTLENGTH) {
    745 				CHECK(ISC_R_UNEXPECTEDEND);
    746 			}
    747 			break;
    748 		}
    749 
    750 		ds.length = r.length;
    751 		ds.digest = r.base;
    752 
    753 		CHECK(dns_rdata_fromstruct(NULL, ds.common.rdclass,
    754 					   ds.common.rdtype, &ds, &rrdatabuf));
    755 		CHECK(dns_client_addtrustedkey(client, dns_rdataclass_in,
    756 					       dns_rdatatype_ds, keyname,
    757 					       &rrdatabuf));
    758 	}
    759 
    760 	num_keys++;
    761 
    762 cleanup:
    763 	if (result == DST_R_NOCRYPTO) {
    764 		cfg_obj_log(key, lctx, ISC_LOG_ERROR, "no crypto support");
    765 	} else if (result == DST_R_UNSUPPORTEDALG) {
    766 		cfg_obj_log(key, lctx, ISC_LOG_WARNING,
    767 			    "skipping trusted key '%s': %s", keynamestr,
    768 			    isc_result_totext(result));
    769 		result = ISC_R_SUCCESS;
    770 	} else if (result != ISC_R_SUCCESS) {
    771 		cfg_obj_log(key, lctx, ISC_LOG_ERROR,
    772 			    "failed to add trusted key '%s': %s", keynamestr,
    773 			    isc_result_totext(result));
    774 		result = ISC_R_FAILURE;
    775 	}
    776 
    777 	return (result);
    778 }
    779 
    780 static isc_result_t
    781 load_keys(const cfg_obj_t *keys, dns_client_t *client) {
    782 	const cfg_listelt_t *elt, *elt2;
    783 	const cfg_obj_t *key, *keylist;
    784 	isc_result_t result = ISC_R_SUCCESS;
    785 
    786 	for (elt = cfg_list_first(keys); elt != NULL; elt = cfg_list_next(elt))
    787 	{
    788 		keylist = cfg_listelt_value(elt);
    789 
    790 		for (elt2 = cfg_list_first(keylist); elt2 != NULL;
    791 		     elt2 = cfg_list_next(elt2))
    792 		{
    793 			key = cfg_listelt_value(elt2);
    794 			CHECK(key_fromconfig(key, client));
    795 		}
    796 	}
    797 
    798 cleanup:
    799 	if (result == DST_R_NOCRYPTO) {
    800 		result = ISC_R_SUCCESS;
    801 	}
    802 	return (result);
    803 }
    804 
    805 static isc_result_t
    806 setup_dnsseckeys(dns_client_t *client) {
    807 	isc_result_t result;
    808 	cfg_parser_t *parser = NULL;
    809 	const cfg_obj_t *trusted_keys = NULL;
    810 	const cfg_obj_t *managed_keys = NULL;
    811 	const cfg_obj_t *trust_anchors = NULL;
    812 	cfg_obj_t *bindkeys = NULL;
    813 	const char *filename = anchorfile;
    814 
    815 	if (!root_validation) {
    816 		return (ISC_R_SUCCESS);
    817 	}
    818 
    819 	if (filename == NULL) {
    820 		filename = SYSCONFDIR "/bind.keys";
    821 	}
    822 
    823 	if (trust_anchor == NULL) {
    824 		trust_anchor = isc_mem_strdup(mctx, ".");
    825 	}
    826 
    827 	if (trust_anchor != NULL) {
    828 		CHECK(convert_name(&afn, &anchor_name, trust_anchor));
    829 	}
    830 
    831 	CHECK(cfg_parser_create(mctx, dns_lctx, &parser));
    832 
    833 	if (access(filename, R_OK) != 0) {
    834 		if (anchorfile != NULL) {
    835 			fatal("Unable to read key file '%s'", anchorfile);
    836 		}
    837 	} else {
    838 		result = cfg_parse_file(parser, filename, &cfg_type_bindkeys,
    839 					&bindkeys);
    840 		if (result != ISC_R_SUCCESS) {
    841 			if (anchorfile != NULL) {
    842 				fatal("Unable to load keys from '%s'",
    843 				      anchorfile);
    844 			}
    845 		}
    846 	}
    847 
    848 	if (bindkeys == NULL) {
    849 		isc_buffer_t b;
    850 
    851 		isc_buffer_init(&b, anchortext, sizeof(anchortext) - 1);
    852 		isc_buffer_add(&b, sizeof(anchortext) - 1);
    853 		cfg_parser_reset(parser);
    854 		result = cfg_parse_buffer(parser, &b, NULL, 0,
    855 					  &cfg_type_bindkeys, 0, &bindkeys);
    856 		if (result != ISC_R_SUCCESS) {
    857 			fatal("Unable to parse built-in keys");
    858 		}
    859 	}
    860 
    861 	INSIST(bindkeys != NULL);
    862 	cfg_map_get(bindkeys, "trusted-keys", &trusted_keys);
    863 	cfg_map_get(bindkeys, "managed-keys", &managed_keys);
    864 	cfg_map_get(bindkeys, "trust-anchors", &trust_anchors);
    865 
    866 	if (trusted_keys != NULL) {
    867 		CHECK(load_keys(trusted_keys, client));
    868 	}
    869 	if (managed_keys != NULL) {
    870 		CHECK(load_keys(managed_keys, client));
    871 	}
    872 	if (trust_anchors != NULL) {
    873 		CHECK(load_keys(trust_anchors, client));
    874 	}
    875 	result = ISC_R_SUCCESS;
    876 
    877 	if (num_keys == 0) {
    878 		fatal("No trusted keys were loaded");
    879 	}
    880 
    881 cleanup:
    882 	if (bindkeys != NULL) {
    883 		cfg_obj_destroy(parser, &bindkeys);
    884 	}
    885 	if (parser != NULL) {
    886 		cfg_parser_destroy(&parser);
    887 	}
    888 	if (result != ISC_R_SUCCESS) {
    889 		delv_log(ISC_LOG_ERROR, "setup_dnsseckeys: %s",
    890 			 isc_result_totext(result));
    891 	}
    892 	return (result);
    893 }
    894 
    895 static isc_result_t
    896 addserver(dns_client_t *client) {
    897 	struct addrinfo hints, *res, *cur;
    898 	int gaierror;
    899 	struct in_addr in4;
    900 	struct in6_addr in6;
    901 	isc_sockaddr_t *sa;
    902 	isc_sockaddrlist_t servers;
    903 	uint32_t destport;
    904 	isc_result_t result;
    905 	dns_name_t *name = NULL;
    906 
    907 	result = parse_uint(&destport, port, 0xffff, "port");
    908 	if (result != ISC_R_SUCCESS) {
    909 		fatal("Couldn't parse port number");
    910 	}
    911 
    912 	ISC_LIST_INIT(servers);
    913 
    914 	if (inet_pton(AF_INET, server, &in4) == 1) {
    915 		if (!use_ipv4) {
    916 			fatal("Use of IPv4 disabled by -6");
    917 		}
    918 		sa = isc_mem_get(mctx, sizeof(*sa));
    919 		ISC_LINK_INIT(sa, link);
    920 		isc_sockaddr_fromin(sa, &in4, destport);
    921 		ISC_LIST_APPEND(servers, sa, link);
    922 	} else if (inet_pton(AF_INET6, server, &in6) == 1) {
    923 		if (!use_ipv6) {
    924 			fatal("Use of IPv6 disabled by -4");
    925 		}
    926 		sa = isc_mem_get(mctx, sizeof(*sa));
    927 		ISC_LINK_INIT(sa, link);
    928 		isc_sockaddr_fromin6(sa, &in6, destport);
    929 		ISC_LIST_APPEND(servers, sa, link);
    930 	} else {
    931 		memset(&hints, 0, sizeof(hints));
    932 		if (!use_ipv6) {
    933 			hints.ai_family = AF_INET;
    934 		} else if (!use_ipv4) {
    935 			hints.ai_family = AF_INET6;
    936 		} else {
    937 			hints.ai_family = AF_UNSPEC;
    938 		}
    939 		hints.ai_socktype = SOCK_DGRAM;
    940 		hints.ai_protocol = IPPROTO_UDP;
    941 		gaierror = getaddrinfo(server, port, &hints, &res);
    942 		if (gaierror != 0) {
    943 			delv_log(ISC_LOG_ERROR, "getaddrinfo failed: %s",
    944 				 gai_strerror(gaierror));
    945 			return (ISC_R_FAILURE);
    946 		}
    947 
    948 		result = ISC_R_SUCCESS;
    949 		for (cur = res; cur != NULL; cur = cur->ai_next) {
    950 			if (cur->ai_family != AF_INET &&
    951 			    cur->ai_family != AF_INET6)
    952 			{
    953 				continue;
    954 			}
    955 			sa = isc_mem_get(mctx, sizeof(*sa));
    956 			memset(sa, 0, sizeof(*sa));
    957 			ISC_LINK_INIT(sa, link);
    958 			memmove(&sa->type, cur->ai_addr, cur->ai_addrlen);
    959 			sa->length = (unsigned int)cur->ai_addrlen;
    960 			ISC_LIST_APPEND(servers, sa, link);
    961 		}
    962 		freeaddrinfo(res);
    963 		CHECK(result);
    964 	}
    965 
    966 	CHECK(dns_client_setservers(client, dns_rdataclass_in, name, &servers));
    967 
    968 cleanup:
    969 	while (!ISC_LIST_EMPTY(servers)) {
    970 		sa = ISC_LIST_HEAD(servers);
    971 		ISC_LIST_UNLINK(servers, sa, link);
    972 		isc_mem_put(mctx, sa, sizeof(*sa));
    973 	}
    974 
    975 	if (result != ISC_R_SUCCESS) {
    976 		delv_log(ISC_LOG_ERROR, "addserver: %s",
    977 			 isc_result_totext(result));
    978 	}
    979 
    980 	return (result);
    981 }
    982 
    983 static isc_result_t
    984 findserver(dns_client_t *client) {
    985 	isc_result_t result;
    986 	irs_resconf_t *resconf = NULL;
    987 	isc_sockaddrlist_t *nameservers;
    988 	isc_sockaddr_t *sa, *next;
    989 	uint32_t destport;
    990 
    991 	result = parse_uint(&destport, port, 0xffff, "port");
    992 	if (result != ISC_R_SUCCESS) {
    993 		fatal("Couldn't parse port number");
    994 	}
    995 
    996 	result = irs_resconf_load(mctx, "/etc/resolv.conf", &resconf);
    997 	if (result != ISC_R_SUCCESS && result != ISC_R_FILENOTFOUND) {
    998 		delv_log(ISC_LOG_ERROR, "irs_resconf_load: %s",
    999 			 isc_result_totext(result));
   1000 		goto cleanup;
   1001 	}
   1002 
   1003 	/* Get nameservers from resolv.conf */
   1004 	nameservers = irs_resconf_getnameservers(resconf);
   1005 	for (sa = ISC_LIST_HEAD(*nameservers); sa != NULL; sa = next) {
   1006 		next = ISC_LIST_NEXT(sa, link);
   1007 
   1008 		/* Set destination port */
   1009 		if (sa->type.sa.sa_family == AF_INET && use_ipv4) {
   1010 			sa->type.sin.sin_port = htons(destport);
   1011 			continue;
   1012 		}
   1013 		if (sa->type.sa.sa_family == AF_INET6 && use_ipv6) {
   1014 			sa->type.sin6.sin6_port = htons(destport);
   1015 			continue;
   1016 		}
   1017 
   1018 		/* Incompatible protocol family */
   1019 		ISC_LIST_UNLINK(*nameservers, sa, link);
   1020 		isc_mem_put(mctx, sa, sizeof(*sa));
   1021 	}
   1022 
   1023 	/* None found, use localhost */
   1024 	if (ISC_LIST_EMPTY(*nameservers)) {
   1025 		if (use_ipv4) {
   1026 			struct in_addr localhost;
   1027 			localhost.s_addr = htonl(INADDR_LOOPBACK);
   1028 			sa = isc_mem_get(mctx, sizeof(*sa));
   1029 			isc_sockaddr_fromin(sa, &localhost, destport);
   1030 
   1031 			ISC_LINK_INIT(sa, link);
   1032 			ISC_LIST_APPEND(*nameservers, sa, link);
   1033 		}
   1034 
   1035 		if (use_ipv6) {
   1036 			sa = isc_mem_get(mctx, sizeof(*sa));
   1037 			isc_sockaddr_fromin6(sa, &in6addr_loopback, destport);
   1038 
   1039 			ISC_LINK_INIT(sa, link);
   1040 			ISC_LIST_APPEND(*nameservers, sa, link);
   1041 		}
   1042 	}
   1043 
   1044 	result = dns_client_setservers(client, dns_rdataclass_in, NULL,
   1045 				       nameservers);
   1046 	if (result != ISC_R_SUCCESS) {
   1047 		delv_log(ISC_LOG_ERROR, "dns_client_setservers: %s",
   1048 			 isc_result_totext(result));
   1049 	}
   1050 
   1051 cleanup:
   1052 	if (resconf != NULL) {
   1053 		irs_resconf_destroy(&resconf);
   1054 	}
   1055 	return (result);
   1056 }
   1057 
   1058 static isc_result_t
   1059 parse_uint(uint32_t *uip, const char *value, uint32_t max, const char *desc) {
   1060 	uint32_t n;
   1061 	isc_result_t result = isc_parse_uint32(&n, value, 10);
   1062 	if (result == ISC_R_SUCCESS && n > max) {
   1063 		result = ISC_R_RANGE;
   1064 	}
   1065 	if (result != ISC_R_SUCCESS) {
   1066 		printf("invalid %s '%s': %s\n", desc, value,
   1067 		       isc_result_totext(result));
   1068 		return (result);
   1069 	}
   1070 	*uip = n;
   1071 	return (ISC_R_SUCCESS);
   1072 }
   1073 
   1074 static void
   1075 plus_option(char *option) {
   1076 	isc_result_t result;
   1077 	char *cmd, *value, *last = NULL;
   1078 	bool state = true;
   1079 
   1080 	INSIST(option != NULL);
   1081 
   1082 	cmd = strtok_r(option, "=", &last);
   1083 	if (cmd == NULL) {
   1084 		printf(";; Invalid option %s\n", option);
   1085 		return;
   1086 	}
   1087 	if (strncasecmp(cmd, "no", 2) == 0) {
   1088 		cmd += 2;
   1089 		state = false;
   1090 	}
   1091 
   1092 	value = strtok_r(NULL, "\0", &last);
   1093 
   1094 #define FULLCHECK(A)                                                 \
   1095 	do {                                                         \
   1096 		size_t _l = strlen(cmd);                             \
   1097 		if (_l >= sizeof(A) || strncasecmp(cmd, A, _l) != 0) \
   1098 			goto invalid_option;                         \
   1099 	} while (0)
   1100 
   1101 	switch (cmd[0]) {
   1102 	case 'a': /* all */
   1103 		FULLCHECK("all");
   1104 		showcomments = state;
   1105 		rrcomments = state;
   1106 		showtrust = state;
   1107 		break;
   1108 	case 'c':
   1109 		switch (cmd[1]) {
   1110 		case 'd': /* cdflag */
   1111 			FULLCHECK("cdflag");
   1112 			cdflag = state;
   1113 			break;
   1114 		case 'l': /* class */
   1115 			FULLCHECK("class");
   1116 			noclass = !state;
   1117 			break;
   1118 		case 'o': /* comments */
   1119 			FULLCHECK("comments");
   1120 			showcomments = state;
   1121 			break;
   1122 		case 'r': /* crypto */
   1123 			FULLCHECK("crypto");
   1124 			nocrypto = !state;
   1125 			break;
   1126 		default:
   1127 			goto invalid_option;
   1128 		}
   1129 		break;
   1130 	case 'd':
   1131 		switch (cmd[1]) {
   1132 		case 'l': /* dlv */
   1133 			FULLCHECK("dlv");
   1134 			if (state) {
   1135 				fprintf(stderr, "Invalid option: "
   1136 						"+dlv is obsolete\n");
   1137 				exit(1);
   1138 			}
   1139 			break;
   1140 		case 'n': /* dnssec */
   1141 			FULLCHECK("dnssec");
   1142 			showdnssec = state;
   1143 			break;
   1144 		default:
   1145 			goto invalid_option;
   1146 		}
   1147 		break;
   1148 	case 'm':
   1149 		switch (cmd[1]) {
   1150 		case 't': /* mtrace */
   1151 			message_trace = state;
   1152 			if (state) {
   1153 				resolve_trace = state;
   1154 			}
   1155 			break;
   1156 		case 'u': /* multiline */
   1157 			FULLCHECK("multiline");
   1158 			multiline = state;
   1159 			break;
   1160 		default:
   1161 			goto invalid_option;
   1162 		}
   1163 		break;
   1164 	case 'r':
   1165 		switch (cmd[1]) {
   1166 		case 'o': /* root */
   1167 			FULLCHECK("root");
   1168 			if (state && no_sigs) {
   1169 				break;
   1170 			}
   1171 			root_validation = state;
   1172 			if (value != NULL) {
   1173 				trust_anchor = isc_mem_strdup(mctx, value);
   1174 			}
   1175 			break;
   1176 		case 'r': /* rrcomments */
   1177 			FULLCHECK("rrcomments");
   1178 			rrcomments = state;
   1179 			break;
   1180 		case 't': /* rtrace */
   1181 			FULLCHECK("rtrace");
   1182 			resolve_trace = state;
   1183 			break;
   1184 		default:
   1185 			goto invalid_option;
   1186 		}
   1187 		break;
   1188 	case 's':
   1189 		switch (cmd[1]) {
   1190 		case 'h': /* short */
   1191 			FULLCHECK("short");
   1192 			short_form = state;
   1193 			if (short_form) {
   1194 				multiline = false;
   1195 				showcomments = false;
   1196 				showtrust = false;
   1197 				showdnssec = false;
   1198 			}
   1199 			break;
   1200 		case 'p': /* split */
   1201 			FULLCHECK("split");
   1202 			if (value != NULL && !state) {
   1203 				goto invalid_option;
   1204 			}
   1205 			if (!state) {
   1206 				splitwidth = 0;
   1207 				break;
   1208 			} else if (value == NULL) {
   1209 				break;
   1210 			}
   1211 
   1212 			result = parse_uint(&splitwidth, value, 1023, "split");
   1213 			if (splitwidth % 4 != 0) {
   1214 				splitwidth = ((splitwidth + 3) / 4) * 4;
   1215 				warn("split must be a multiple of 4; "
   1216 				     "adjusting to %d",
   1217 				     splitwidth);
   1218 			}
   1219 			/*
   1220 			 * There is an adjustment done in the
   1221 			 * totext_<rrtype>() functions which causes
   1222 			 * splitwidth to shrink.  This is okay when we're
   1223 			 * using the default width but incorrect in this
   1224 			 * case, so we correct for it
   1225 			 */
   1226 			if (splitwidth) {
   1227 				splitwidth += 3;
   1228 			}
   1229 			if (result != ISC_R_SUCCESS) {
   1230 				fatal("Couldn't parse split");
   1231 			}
   1232 			break;
   1233 		default:
   1234 			goto invalid_option;
   1235 		}
   1236 		break;
   1237 	case 'u':
   1238 		FULLCHECK("unknownformat");
   1239 		print_unknown_format = state;
   1240 		break;
   1241 	case 't':
   1242 		switch (cmd[1]) {
   1243 		case 'c': /* tcp */
   1244 			FULLCHECK("tcp");
   1245 			use_tcp = state;
   1246 			break;
   1247 		case 'r': /* trust */
   1248 			FULLCHECK("trust");
   1249 			showtrust = state;
   1250 			break;
   1251 		case 't': /* ttl */
   1252 			FULLCHECK("ttl");
   1253 			nottl = !state;
   1254 			break;
   1255 		default:
   1256 			goto invalid_option;
   1257 		}
   1258 		break;
   1259 	case 'v': /* vtrace */
   1260 		FULLCHECK("vtrace");
   1261 		validator_trace = state;
   1262 		if (state) {
   1263 			resolve_trace = state;
   1264 		}
   1265 		break;
   1266 	case 'y': /* yaml */
   1267 		FULLCHECK("yaml");
   1268 		yaml = state;
   1269 		if (state) {
   1270 			rrcomments = false;
   1271 		}
   1272 		break;
   1273 	default:
   1274 	invalid_option:
   1275 		/*
   1276 		 * We can also add a "need_value:" case here if we ever
   1277 		 * add a plus-option that requires a specified value
   1278 		 */
   1279 		fprintf(stderr, "Invalid option: +%s\n", option);
   1280 		usage();
   1281 	}
   1282 	return;
   1283 }
   1284 
   1285 /*
   1286  * options: "46a:b:c:d:himp:q:t:vx:";
   1287  */
   1288 static const char *single_dash_opts = "46himv";
   1289 static const char *dash_opts = "46abcdhimpqtvx";
   1290 
   1291 static bool
   1292 dash_option(char *option, char *next, bool *open_type_class) {
   1293 	char opt, *value;
   1294 	isc_result_t result;
   1295 	bool value_from_next;
   1296 	isc_textregion_t tr;
   1297 	dns_rdatatype_t rdtype;
   1298 	dns_rdataclass_t rdclass;
   1299 	char textname[MAXNAME];
   1300 	struct in_addr in4;
   1301 	struct in6_addr in6;
   1302 	in_port_t srcport;
   1303 	uint32_t num;
   1304 	char *hash;
   1305 
   1306 	while (strpbrk(option, single_dash_opts) == &option[0]) {
   1307 		/*
   1308 		 * Since the -[46himv] options do not take an argument,
   1309 		 * account for them (in any number and/or combination)
   1310 		 * if they appear as the first character(s) of a q-opt.
   1311 		 */
   1312 		opt = option[0];
   1313 		switch (opt) {
   1314 		case '4':
   1315 			if (isc_net_probeipv4() != ISC_R_SUCCESS) {
   1316 				fatal("IPv4 networking not available");
   1317 			}
   1318 			if (use_ipv6) {
   1319 				isc_net_disableipv6();
   1320 				use_ipv6 = false;
   1321 			}
   1322 			break;
   1323 		case '6':
   1324 			if (isc_net_probeipv6() != ISC_R_SUCCESS) {
   1325 				fatal("IPv6 networking not available");
   1326 			}
   1327 			if (use_ipv4) {
   1328 				isc_net_disableipv4();
   1329 				use_ipv4 = false;
   1330 			}
   1331 			break;
   1332 		case 'h':
   1333 			usage();
   1334 			exit(0);
   1335 		case 'i':
   1336 			no_sigs = true;
   1337 			root_validation = false;
   1338 			break;
   1339 		case 'm':
   1340 			/* handled in preparse_args() */
   1341 			break;
   1342 		case 'v':
   1343 			fprintf(stderr, "delv %s\n", PACKAGE_VERSION);
   1344 			exit(0);
   1345 		default:
   1346 			UNREACHABLE();
   1347 		}
   1348 		if (strlen(option) > 1U) {
   1349 			option = &option[1];
   1350 		} else {
   1351 			return (false);
   1352 		}
   1353 	}
   1354 	opt = option[0];
   1355 	if (strlen(option) > 1U) {
   1356 		value_from_next = false;
   1357 		value = &option[1];
   1358 	} else {
   1359 		value_from_next = true;
   1360 		value = next;
   1361 	}
   1362 	if (value == NULL) {
   1363 		goto invalid_option;
   1364 	}
   1365 	switch (opt) {
   1366 	case 'a':
   1367 		anchorfile = isc_mem_strdup(mctx, value);
   1368 		return (value_from_next);
   1369 	case 'b':
   1370 		hash = strchr(value, '#');
   1371 		if (hash != NULL) {
   1372 			result = parse_uint(&num, hash + 1, 0xffff, "port");
   1373 			if (result != ISC_R_SUCCESS) {
   1374 				fatal("Couldn't parse port number");
   1375 			}
   1376 			srcport = num;
   1377 			*hash = '\0';
   1378 		} else {
   1379 			srcport = 0;
   1380 		}
   1381 
   1382 		if (inet_pton(AF_INET, value, &in4) == 1) {
   1383 			if (srcaddr4 != NULL) {
   1384 				fatal("Only one local address per family "
   1385 				      "can be specified\n");
   1386 			}
   1387 			isc_sockaddr_fromin(&a4, &in4, srcport);
   1388 			srcaddr4 = &a4;
   1389 		} else if (inet_pton(AF_INET6, value, &in6) == 1) {
   1390 			if (srcaddr6 != NULL) {
   1391 				fatal("Only one local address per family "
   1392 				      "can be specified\n");
   1393 			}
   1394 			isc_sockaddr_fromin6(&a6, &in6, srcport);
   1395 			srcaddr6 = &a6;
   1396 		} else {
   1397 			if (hash != NULL) {
   1398 				*hash = '#';
   1399 			}
   1400 			fatal("Invalid address %s", value);
   1401 		}
   1402 		if (hash != NULL) {
   1403 			*hash = '#';
   1404 		}
   1405 		return (value_from_next);
   1406 	case 'c':
   1407 		if (classset) {
   1408 			warn("extra query class");
   1409 		}
   1410 
   1411 		*open_type_class = false;
   1412 		tr.base = value;
   1413 		tr.length = strlen(value);
   1414 		result = dns_rdataclass_fromtext(&rdclass,
   1415 						 (isc_textregion_t *)&tr);
   1416 		if (result == ISC_R_SUCCESS) {
   1417 			classset = true;
   1418 		} else if (rdclass != dns_rdataclass_in) {
   1419 			warn("ignoring non-IN query class");
   1420 		} else {
   1421 			warn("ignoring invalid class");
   1422 		}
   1423 		return (value_from_next);
   1424 	case 'd':
   1425 		result = parse_uint(&num, value, 99, "debug level");
   1426 		if (result != ISC_R_SUCCESS) {
   1427 			fatal("Couldn't parse debug level");
   1428 		}
   1429 		loglevel = num;
   1430 		return (value_from_next);
   1431 	case 'p':
   1432 		port = value;
   1433 		return (value_from_next);
   1434 	case 'q':
   1435 		if (curqname != NULL) {
   1436 			warn("extra query name");
   1437 			isc_mem_free(mctx, curqname);
   1438 		}
   1439 		curqname = isc_mem_strdup(mctx, value);
   1440 		return (value_from_next);
   1441 	case 't':
   1442 		*open_type_class = false;
   1443 		tr.base = value;
   1444 		tr.length = strlen(value);
   1445 		result = dns_rdatatype_fromtext(&rdtype,
   1446 						(isc_textregion_t *)&tr);
   1447 		if (result == ISC_R_SUCCESS) {
   1448 			if (typeset) {
   1449 				warn("extra query type");
   1450 			}
   1451 			if (rdtype == dns_rdatatype_ixfr ||
   1452 			    rdtype == dns_rdatatype_axfr)
   1453 			{
   1454 				fatal("Transfer not supported");
   1455 			}
   1456 			qtype = rdtype;
   1457 			typeset = true;
   1458 		} else {
   1459 			warn("ignoring invalid type");
   1460 		}
   1461 		return (value_from_next);
   1462 	case 'x':
   1463 		result = get_reverse(textname, sizeof(textname), value, false);
   1464 		if (result == ISC_R_SUCCESS) {
   1465 			if (curqname != NULL) {
   1466 				isc_mem_free(mctx, curqname);
   1467 				warn("extra query name");
   1468 			}
   1469 			curqname = isc_mem_strdup(mctx, textname);
   1470 			if (typeset) {
   1471 				warn("extra query type");
   1472 			}
   1473 			qtype = dns_rdatatype_ptr;
   1474 			typeset = true;
   1475 		} else {
   1476 			fprintf(stderr, "Invalid IP address %s\n", value);
   1477 			exit(1);
   1478 		}
   1479 		return (value_from_next);
   1480 	invalid_option:
   1481 	default:
   1482 		fprintf(stderr, "Invalid option: -%s\n", option);
   1483 		usage();
   1484 	}
   1485 	UNREACHABLE();
   1486 	return (false);
   1487 }
   1488 
   1489 /*
   1490  * Check for -m first to determine whether to enable
   1491  * memory debugging when setting up the memory context.
   1492  */
   1493 static void
   1494 preparse_args(int argc, char **argv) {
   1495 	bool ipv4only = false, ipv6only = false;
   1496 	char *option;
   1497 
   1498 	for (argc--, argv++; argc > 0; argc--, argv++) {
   1499 		if (argv[0][0] != '-') {
   1500 			continue;
   1501 		}
   1502 
   1503 		option = &argv[0][1];
   1504 		while (strpbrk(option, single_dash_opts) == &option[0]) {
   1505 			switch (option[0]) {
   1506 			case 'm':
   1507 				isc_mem_debugging = ISC_MEM_DEBUGTRACE |
   1508 						    ISC_MEM_DEBUGRECORD;
   1509 				break;
   1510 			case '4':
   1511 				if (ipv6only) {
   1512 					fatal("only one of -4 and -6 allowed");
   1513 				}
   1514 				ipv4only = true;
   1515 				break;
   1516 			case '6':
   1517 				if (ipv4only) {
   1518 					fatal("only one of -4 and -6 allowed");
   1519 				}
   1520 				ipv6only = true;
   1521 				break;
   1522 			}
   1523 			option = &option[1];
   1524 		}
   1525 
   1526 		if (strlen(option) == 0U) {
   1527 			continue;
   1528 		}
   1529 
   1530 		/* Look for dash value option. */
   1531 		if (strpbrk(option, dash_opts) != &option[0] ||
   1532 		    strlen(option) > 1U)
   1533 		{
   1534 			/* Error or value in option. */
   1535 			continue;
   1536 		}
   1537 
   1538 		/* Dash value is next argument so we need to skip it. */
   1539 		argc--;
   1540 		argv++;
   1541 
   1542 		/* Handle missing argument */
   1543 		if (argc == 0) {
   1544 			break;
   1545 		}
   1546 	}
   1547 }
   1548 
   1549 /*
   1550  * Argument parsing is based on dig, but simplified: only one
   1551  * QNAME/QCLASS/QTYPE tuple can be specified, and options have
   1552  * been removed that aren't applicable to delv. The interface
   1553  * should be familiar to dig users, however.
   1554  */
   1555 static void
   1556 parse_args(int argc, char **argv) {
   1557 	isc_result_t result;
   1558 	isc_textregion_t tr;
   1559 	dns_rdatatype_t rdtype;
   1560 	dns_rdataclass_t rdclass;
   1561 	bool open_type_class = true;
   1562 
   1563 	for (; argc > 0; argc--, argv++) {
   1564 		if (argv[0][0] == '@') {
   1565 			server = &argv[0][1];
   1566 		} else if (argv[0][0] == '+') {
   1567 			plus_option(&argv[0][1]);
   1568 		} else if (argv[0][0] == '-') {
   1569 			if (argc <= 1) {
   1570 				if (dash_option(&argv[0][1], NULL,
   1571 						&open_type_class))
   1572 				{
   1573 					argc--;
   1574 					argv++;
   1575 				}
   1576 			} else {
   1577 				if (dash_option(&argv[0][1], argv[1],
   1578 						&open_type_class))
   1579 				{
   1580 					argc--;
   1581 					argv++;
   1582 				}
   1583 			}
   1584 		} else {
   1585 			/*
   1586 			 * Anything which isn't an option
   1587 			 */
   1588 			if (open_type_class) {
   1589 				tr.base = argv[0];
   1590 				tr.length = strlen(argv[0]);
   1591 				result = dns_rdatatype_fromtext(
   1592 					&rdtype, (isc_textregion_t *)&tr);
   1593 				if (result == ISC_R_SUCCESS) {
   1594 					if (typeset) {
   1595 						warn("extra query type");
   1596 					}
   1597 					if (rdtype == dns_rdatatype_ixfr ||
   1598 					    rdtype == dns_rdatatype_axfr)
   1599 					{
   1600 						fatal("Transfer not supported");
   1601 					}
   1602 					qtype = rdtype;
   1603 					typeset = true;
   1604 					continue;
   1605 				}
   1606 				result = dns_rdataclass_fromtext(
   1607 					&rdclass, (isc_textregion_t *)&tr);
   1608 				if (result == ISC_R_SUCCESS) {
   1609 					if (classset) {
   1610 						warn("extra query class");
   1611 					} else if (rdclass != dns_rdataclass_in)
   1612 					{
   1613 						warn("ignoring non-IN "
   1614 						     "query class");
   1615 					}
   1616 					continue;
   1617 				}
   1618 			}
   1619 
   1620 			if (curqname == NULL) {
   1621 				curqname = isc_mem_strdup(mctx, argv[0]);
   1622 			}
   1623 		}
   1624 	}
   1625 
   1626 	/*
   1627 	 * If no qname or qtype specified, search for root/NS
   1628 	 * If no qtype specified, use A
   1629 	 */
   1630 	if (!typeset) {
   1631 		qtype = dns_rdatatype_a;
   1632 	}
   1633 
   1634 	if (curqname == NULL) {
   1635 		qname = isc_mem_strdup(mctx, ".");
   1636 
   1637 		if (!typeset) {
   1638 			qtype = dns_rdatatype_ns;
   1639 		}
   1640 	} else {
   1641 		qname = curqname;
   1642 	}
   1643 }
   1644 
   1645 static isc_result_t
   1646 append_str(const char *text, int len, char **p, char *end) {
   1647 	if (len > end - *p) {
   1648 		return (ISC_R_NOSPACE);
   1649 	}
   1650 	memmove(*p, text, len);
   1651 	*p += len;
   1652 	return (ISC_R_SUCCESS);
   1653 }
   1654 
   1655 static isc_result_t
   1656 reverse_octets(const char *in, char **p, char *end) {
   1657 	char *dot = strchr(in, '.');
   1658 	int len;
   1659 	if (dot != NULL) {
   1660 		isc_result_t result;
   1661 		result = reverse_octets(dot + 1, p, end);
   1662 		if (result != ISC_R_SUCCESS) {
   1663 			return (result);
   1664 		}
   1665 		result = append_str(".", 1, p, end);
   1666 		if (result != ISC_R_SUCCESS) {
   1667 			return (result);
   1668 		}
   1669 		len = (int)(dot - in);
   1670 	} else {
   1671 		len = strlen(in);
   1672 	}
   1673 	return (append_str(in, len, p, end));
   1674 }
   1675 
   1676 static isc_result_t
   1677 get_reverse(char *reverse, size_t len, char *value, bool strict) {
   1678 	int r;
   1679 	isc_result_t result;
   1680 	isc_netaddr_t addr;
   1681 
   1682 	addr.family = AF_INET6;
   1683 	r = inet_pton(AF_INET6, value, &addr.type.in6);
   1684 	if (r > 0) {
   1685 		/* This is a valid IPv6 address. */
   1686 		dns_fixedname_t fname;
   1687 		dns_name_t *name;
   1688 		unsigned int options = 0;
   1689 
   1690 		name = dns_fixedname_initname(&fname);
   1691 		result = dns_byaddr_createptrname(&addr, options, name);
   1692 		if (result != ISC_R_SUCCESS) {
   1693 			return (result);
   1694 		}
   1695 		dns_name_format(name, reverse, (unsigned int)len);
   1696 		return (ISC_R_SUCCESS);
   1697 	} else {
   1698 		/*
   1699 		 * Not a valid IPv6 address.  Assume IPv4.
   1700 		 * If 'strict' is not set, construct the
   1701 		 * in-addr.arpa name by blindly reversing
   1702 		 * octets whether or not they look like integers,
   1703 		 * so that this can be used for RFC2317 names
   1704 		 * and such.
   1705 		 */
   1706 		char *p = reverse;
   1707 		char *end = reverse + len;
   1708 		if (strict && inet_pton(AF_INET, value, &addr.type.in) != 1) {
   1709 			return (DNS_R_BADDOTTEDQUAD);
   1710 		}
   1711 		result = reverse_octets(value, &p, end);
   1712 		if (result != ISC_R_SUCCESS) {
   1713 			return (result);
   1714 		}
   1715 		result = append_str(".in-addr.arpa.", 15, &p, end);
   1716 		if (result != ISC_R_SUCCESS) {
   1717 			return (result);
   1718 		}
   1719 		return (ISC_R_SUCCESS);
   1720 	}
   1721 }
   1722 
   1723 int
   1724 main(int argc, char *argv[]) {
   1725 	dns_client_t *client = NULL;
   1726 	isc_result_t result;
   1727 	dns_fixedname_t qfn;
   1728 	dns_name_t *query_name, *response_name;
   1729 	char namestr[DNS_NAME_FORMATSIZE];
   1730 	dns_rdataset_t *rdataset;
   1731 	dns_namelist_t namelist;
   1732 	unsigned int resopt;
   1733 	isc_appctx_t *actx = NULL;
   1734 	isc_nm_t *netmgr = NULL;
   1735 	isc_taskmgr_t *taskmgr = NULL;
   1736 	isc_timermgr_t *timermgr = NULL;
   1737 	dns_master_style_t *style = NULL;
   1738 	struct sigaction sa;
   1739 
   1740 	progname = argv[0];
   1741 	preparse_args(argc, argv);
   1742 
   1743 	argc--;
   1744 	argv++;
   1745 
   1746 	isc_mem_create(&mctx);
   1747 
   1748 	result = dst_lib_init(mctx, NULL);
   1749 	if (result != ISC_R_SUCCESS) {
   1750 		fatal("dst_lib_init failed: %d", result);
   1751 	}
   1752 
   1753 	CHECK(isc_appctx_create(mctx, &actx));
   1754 
   1755 	isc_managers_create(mctx, 1, 0, &netmgr, &taskmgr, &timermgr);
   1756 
   1757 	parse_args(argc, argv);
   1758 
   1759 	CHECK(setup_style(&style));
   1760 
   1761 	setup_logging(stderr);
   1762 
   1763 	CHECK(isc_app_ctxstart(actx));
   1764 
   1765 	/* Unblock SIGINT if it's been blocked by isc_app_ctxstart() */
   1766 	memset(&sa, 0, sizeof(sa));
   1767 	sa.sa_handler = SIG_DFL;
   1768 	if (sigfillset(&sa.sa_mask) != 0 || sigaction(SIGINT, &sa, NULL) < 0) {
   1769 		fatal("Couldn't set up signal handler");
   1770 	}
   1771 
   1772 	/* Create client */
   1773 	result = dns_client_create(mctx, actx, taskmgr, netmgr, timermgr, 0,
   1774 				   &client, srcaddr4, srcaddr6);
   1775 	if (result != ISC_R_SUCCESS) {
   1776 		delv_log(ISC_LOG_ERROR, "dns_client_create: %s",
   1777 			 isc_result_totext(result));
   1778 		goto cleanup;
   1779 	}
   1780 
   1781 	/* Set the nameserver */
   1782 	if (server != NULL) {
   1783 		addserver(client);
   1784 	} else {
   1785 		findserver(client);
   1786 	}
   1787 
   1788 	CHECK(setup_dnsseckeys(client));
   1789 
   1790 	/* Construct QNAME */
   1791 	CHECK(convert_name(&qfn, &query_name, qname));
   1792 
   1793 	/* Set up resolution options */
   1794 	resopt = DNS_CLIENTRESOPT_NOCDFLAG;
   1795 	if (no_sigs) {
   1796 		resopt |= DNS_CLIENTRESOPT_NODNSSEC;
   1797 	}
   1798 	if (!root_validation) {
   1799 		resopt |= DNS_CLIENTRESOPT_NOVALIDATE;
   1800 	}
   1801 	if (cdflag) {
   1802 		resopt &= ~DNS_CLIENTRESOPT_NOCDFLAG;
   1803 	}
   1804 	if (use_tcp) {
   1805 		resopt |= DNS_CLIENTRESOPT_TCP;
   1806 	}
   1807 
   1808 	/* Perform resolution */
   1809 	ISC_LIST_INIT(namelist);
   1810 	result = dns_client_resolve(client, query_name, dns_rdataclass_in,
   1811 				    qtype, resopt, &namelist);
   1812 	if (result != ISC_R_SUCCESS && !yaml) {
   1813 		delv_log(ISC_LOG_ERROR, "resolution failed: %s",
   1814 			 isc_result_totext(result));
   1815 	}
   1816 
   1817 	if (yaml) {
   1818 		printf("type: DELV_RESULT\n");
   1819 		dns_name_format(query_name, namestr, sizeof(namestr));
   1820 		printf("query_name: %s\n", namestr);
   1821 		printf("status: %s\n", isc_result_totext(result));
   1822 		printf("records:\n");
   1823 	}
   1824 
   1825 	for (response_name = ISC_LIST_HEAD(namelist); response_name != NULL;
   1826 	     response_name = ISC_LIST_NEXT(response_name, link))
   1827 	{
   1828 		for (rdataset = ISC_LIST_HEAD(response_name->list);
   1829 		     rdataset != NULL; rdataset = ISC_LIST_NEXT(rdataset, link))
   1830 		{
   1831 			result = printdata(rdataset, response_name, style);
   1832 			if (result != ISC_R_SUCCESS) {
   1833 				delv_log(ISC_LOG_ERROR, "print data failed");
   1834 			}
   1835 		}
   1836 	}
   1837 
   1838 	dns_client_freeresanswer(client, &namelist);
   1839 
   1840 cleanup:
   1841 	if (trust_anchor != NULL) {
   1842 		isc_mem_free(mctx, trust_anchor);
   1843 	}
   1844 	if (anchorfile != NULL) {
   1845 		isc_mem_free(mctx, anchorfile);
   1846 	}
   1847 	if (qname != NULL) {
   1848 		isc_mem_free(mctx, qname);
   1849 	}
   1850 	if (style != NULL) {
   1851 		dns_master_styledestroy(&style, mctx);
   1852 	}
   1853 	if (client != NULL) {
   1854 		dns_client_detach(&client);
   1855 	}
   1856 
   1857 	isc_managers_destroy(&netmgr, &taskmgr, &timermgr);
   1858 
   1859 	if (actx != NULL) {
   1860 		isc_appctx_destroy(&actx);
   1861 	}
   1862 	if (lctx != NULL) {
   1863 		isc_log_destroy(&lctx);
   1864 	}
   1865 	isc_mem_detach(&mctx);
   1866 
   1867 	dst_lib_destroy();
   1868 
   1869 	return (0);
   1870 }
   1871