delv.c 42.3 KB
Newer Older
Evan Hunt's avatar
Evan Hunt committed
1
/*
2
 * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
Evan Hunt's avatar
Evan Hunt 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.
Evan Hunt's avatar
Evan Hunt committed
10
11
12
13
14
 */

#include <config.h>
#include <bind.keys.h>

15
#ifndef WIN32
Evan Hunt's avatar
Evan Hunt committed
16
17
#include <sys/types.h>
#include <sys/socket.h>
18
#include <signal.h>
Evan Hunt's avatar
Evan Hunt committed
19
20
21
22
23

#include <netinet/in.h>

#include <arpa/inet.h>

24
25
26
#include <netdb.h>
#endif

27
#include <stdbool.h>
Evan Hunt's avatar
Evan Hunt committed
28
#include <stdio.h>
29
#include <inttypes.h>
Evan Hunt's avatar
Evan Hunt committed
30
31
#include <stdlib.h>
#include <string.h>
32
#include <unistd.h>
Evan Hunt's avatar
Evan Hunt committed
33
34
35
36
37
38
39

#include <isc/app.h>
#include <isc/base64.h>
#include <isc/buffer.h>
#include <isc/lib.h>
#include <isc/log.h>
#include <isc/mem.h>
40
41
42
#ifdef WIN32
#include <isc/ntpaths.h>
#endif
Evan Hunt's avatar
Evan Hunt committed
43
#include <isc/parseint.h>
Mark Andrews's avatar
Mark Andrews committed
44
#include <isc/print.h>
Evan Hunt's avatar
Evan Hunt committed
45
46
#include <isc/sockaddr.h>
#include <isc/socket.h>
Evan Hunt's avatar
Evan Hunt committed
47
#include <isc/string.h>
Evan Hunt's avatar
Evan Hunt committed
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
87
#include <isc/task.h>
#include <isc/timer.h>
#include <isc/util.h>

#include <irs/resconf.h>
#include <irs/netdb.h>

#include <isccfg/log.h>
#include <isccfg/namedconf.h>

#include <dns/byaddr.h>
#include <dns/client.h>
#include <dns/fixedname.h>
#include <dns/keytable.h>
#include <dns/keyvalues.h>
#include <dns/lib.h>
#include <dns/log.h>
#include <dns/masterdump.h>
#include <dns/name.h>
#include <dns/rdata.h>
#include <dns/rdataclass.h>
#include <dns/rdataset.h>
#include <dns/rdatastruct.h>
#include <dns/rdatatype.h>
#include <dns/result.h>
#include <dns/secalg.h>
#include <dns/view.h>

#include <dst/dst.h>
#include <dst/result.h>

#define CHECK(r) \
	do { \
		result = (r); \
		if (result != ISC_R_SUCCESS) \
			goto cleanup; \
	} while (0)

#define MAXNAME (DNS_NAME_MAXTEXT+1)

88
/* Variables used internally by delv. */
Evan Hunt's avatar
Evan Hunt committed
89
90
91
92
93
94
95
96
char *progname;
static isc_mem_t *mctx = NULL;
static isc_log_t *lctx = NULL;

/* Configurables */
static char *server = NULL;
static const char *port = "53";
static isc_sockaddr_t *srcaddr4 = NULL, *srcaddr6 = NULL;
97
static isc_sockaddr_t a4, a6;
Evan Hunt's avatar
Evan Hunt committed
98
static char *curqname = NULL, *qname = NULL;
99
static bool classset = false;
Evan Hunt's avatar
Evan Hunt committed
100
static dns_rdatatype_t qtype = dns_rdatatype_none;
101
static bool typeset = false;
Evan Hunt's avatar
Evan Hunt committed
102
103

static unsigned int styleflags = 0;
104
static uint32_t splitwidth = 0xffffffff;
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
static bool
	showcomments = true,
	showdnssec = true,
	showtrust = true,
	rrcomments = true,
	noclass = false,
	nocrypto = false,
	nottl = false,
	multiline = false,
	short_form = false,
	print_unknown_format = false;

static bool
	resolve_trace = false,
	validator_trace = false,
	message_trace = false;

static bool
	use_ipv4 = true,
	use_ipv6 = true;

static bool
	cdflag = false,
	no_sigs = false,
	root_validation = true,
	dlv_validation = true;

static bool use_tcp = false;
Evan Hunt's avatar
Evan Hunt committed
133

Evan Hunt's avatar
Evan Hunt committed
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
static char *anchorfile = NULL;
static char *trust_anchor = NULL;
static char *dlv_anchor = NULL;
static int trusted_keys = 0;

static dns_fixedname_t afn, dfn;
static dns_name_t *anchor_name = NULL, *dlv_name = NULL;

/* Default bind.keys contents */
static char anchortext[] = MANAGED_KEYS;

/*
 * Static function prototypes
 */
static isc_result_t
149
get_reverse(char *reverse, size_t len, char *value, bool strict);
Evan Hunt's avatar
Evan Hunt committed
150
151

static isc_result_t
152
parse_uint(uint32_t *uip, const char *value, uint32_t max,
Evan Hunt's avatar
Evan Hunt committed
153
154
155
156
157
	   const char *desc);

static void
usage(void) {
	fputs(
158
"Usage:  delv [@server] {q-opt} {d-opt} [domain] [q-type] [q-class]\n"
Evan Hunt's avatar
Evan Hunt committed
159
160
161
162
163
164
165
166
167
168
169
"Where:  domain	  is in the Domain Name System\n"
"        q-class  is one of (in,hs,ch,...) [default: in]\n"
"        q-type   is one of (a,any,mx,ns,soa,hinfo,axfr,txt,...) [default:a]\n"
"        q-opt    is one of:\n"
"                 -x dot-notation     (shortcut for reverse lookups)\n"
"                 -d level            (set debugging level)\n"
"                 -a anchor-file      (specify root and dlv trust anchors)\n"
"                 -b address[#port]   (bind to source address/port)\n"
"                 -p port             (specify port number)\n"
"                 -q name             (specify query name)\n"
"                 -t type             (specify query type)\n"
170
171
"                 -c class            (option included for compatibility;\n"
"                                      only IN is supported)\n"
Evan Hunt's avatar
Evan Hunt committed
172
173
174
175
176
177
178
179
180
181
182
183
184
"                 -4                  (use IPv4 query transport only)\n"
"                 -6                  (use IPv6 query transport only)\n"
"                 -i                  (disable DNSSEC validation)\n"
"                 -m                  (enable memory usage debugging)\n"
"        d-opt    is of the form +keyword[=value], where keyword is:\n"
"                 +[no]all            (Set or clear all display flags)\n"
"                 +[no]class          (Control display of class)\n"
"                 +[no]crypto         (Control display of cryptographic\n"
"                                      fields in records)\n"
"                 +[no]multiline      (Print records in an expanded format)\n"
"                 +[no]comments       (Control display of comment lines)\n"
"                 +[no]rrcomments     (Control display of per-record "
				       "comments)\n"
185
"                 +[no]unknownformat  (Print RDATA in RFC 3597 \"unknown\" format)\n"
Evan Hunt's avatar
Evan Hunt committed
186
187
"                 +[no]short          (Short form answer)\n"
"                 +[no]split=##       (Split hex/base64 fields into chunks)\n"
Evan Hunt's avatar
Evan Hunt committed
188
"                 +[no]tcp            (TCP mode)\n"
Evan Hunt's avatar
Evan Hunt committed
189
190
191
192
193
194
195
196
197
198
199
200
201
202
"                 +[no]ttl            (Control display of ttls in records)\n"
"                 +[no]trust          (Control display of trust level)\n"
"                 +[no]rtrace         (Trace resolver fetches)\n"
"                 +[no]mtrace         (Trace messages received)\n"
"                 +[no]vtrace         (Trace validation process)\n"
"                 +[no]dlv            (DNSSEC lookaside validation anchor)\n"
"                 +[no]root           (DNSSEC validation trust anchor)\n"
"                 +[no]dnssec         (Display DNSSEC records)\n"
"        -h                           (print help and exit)\n"
"        -v                           (print version and exit)\n",
	stderr);
	exit(1);
}

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

Evan Hunt's avatar
Evan Hunt committed
207
208
209
210
211
212
213
214
215
216
217
218
219
static void
fatal(const char *format, ...) {
	va_list args;

	fflush(stdout);
	fprintf(stderr, "%s: ", progname);
	va_start(args, format);
	vfprintf(stderr, format, args);
	va_end(args);
	fprintf(stderr, "\n");
	exit(1);
}

220
221
222
static void
warn(const char *format, ...) ISC_FORMAT_PRINTF(1, 2);

Evan Hunt's avatar
Evan Hunt committed
223
224
225
226
227
228
229
230
231
232
233
234
235
static void
warn(const char *format, ...) {
	va_list args;

	fflush(stdout);
	fprintf(stderr, "%s: warning: ", progname);
	va_start(args, format);
	vfprintf(stderr, format, args);
	va_end(args);
	fprintf(stderr, "\n");
}

static isc_logcategory_t categories[] = {
236
	{ "delv",	     0 },
Evan Hunt's avatar
Evan Hunt committed
237
238
239
240
241
242
	{ NULL,		     0 }
};
#define LOGCATEGORY_DEFAULT		(&categories[0])
#define LOGMODULE_DEFAULT		(&modules[0])

static isc_logmodule_t modules[] = {
243
	{ "delv",	 		0 },
Evan Hunt's avatar
Evan Hunt committed
244
245
246
	{ NULL, 			0 }
};

247
static void
248
delv_log(int level, const char *fmt, ...) ISC_FORMAT_PRINTF(2, 3);
249

Evan Hunt's avatar
Evan Hunt committed
250
static void
251
delv_log(int level, const char *fmt, ...) {
Evan Hunt's avatar
Evan Hunt committed
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
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
368
369
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
	va_list ap;
	char msgbuf[2048];

	if (! isc_log_wouldlog(lctx, level))
		return;

	va_start(ap, fmt);

	vsnprintf(msgbuf, sizeof(msgbuf), fmt, ap);
	isc_log_write(lctx, LOGCATEGORY_DEFAULT, LOGMODULE_DEFAULT,
		      level, "%s", msgbuf);
	va_end(ap);
}

static int loglevel = 0;

static void
setup_logging(FILE *errout) {
	isc_result_t result;
	isc_logdestination_t destination;
	isc_logconfig_t *logconfig = NULL;

	result = isc_log_create(mctx, &lctx, &logconfig);
	if (result != ISC_R_SUCCESS)
		fatal("Couldn't set up logging");

	isc_log_registercategories(lctx, categories);
	isc_log_registermodules(lctx, modules);
	isc_log_setcontext(lctx);
	dns_log_init(lctx);
	dns_log_setcontext(lctx);
	cfg_log_init(lctx);

	destination.file.stream = errout;
	destination.file.name = NULL;
	destination.file.versions = ISC_LOG_ROLLNEVER;
	destination.file.maximum_size = 0;

	result = isc_log_createchannel(logconfig, "stderr",
				       ISC_LOG_TOFILEDESC, ISC_LOG_DYNAMIC,
				       &destination, ISC_LOG_PRINTPREFIX);
	if (result != ISC_R_SUCCESS)
		fatal("Couldn't set up log channel 'stderr'");

	isc_log_setdebuglevel(lctx, loglevel);

	result = isc_log_settag(logconfig, ";; ");
	if (result != ISC_R_SUCCESS)
		fatal("Couldn't set log tag");

	result = isc_log_usechannel(logconfig, "stderr",
				    ISC_LOGCATEGORY_DEFAULT, NULL);
	if (result != ISC_R_SUCCESS)
		fatal("Couldn't attach to log channel 'stderr'");

	if (resolve_trace && loglevel < 1) {
		result = isc_log_createchannel(logconfig, "resolver",
					       ISC_LOG_TOFILEDESC,
					       ISC_LOG_DEBUG(1),
					       &destination,
					       ISC_LOG_PRINTPREFIX);
		if (result != ISC_R_SUCCESS)
			fatal("Couldn't set up log channel 'resolver'");

		result = isc_log_usechannel(logconfig, "resolver",
					    DNS_LOGCATEGORY_RESOLVER,
					    DNS_LOGMODULE_RESOLVER);
		if (result != ISC_R_SUCCESS)
			fatal("Couldn't attach to log channel 'resolver'");
	}

	if (validator_trace && loglevel < 3) {
		result = isc_log_createchannel(logconfig, "validator",
					       ISC_LOG_TOFILEDESC,
					       ISC_LOG_DEBUG(3),
					       &destination,
					       ISC_LOG_PRINTPREFIX);
		if (result != ISC_R_SUCCESS)
			fatal("Couldn't set up log channel 'validator'");

		result = isc_log_usechannel(logconfig, "validator",
					    DNS_LOGCATEGORY_DNSSEC,
					    DNS_LOGMODULE_VALIDATOR);
		if (result != ISC_R_SUCCESS)
			fatal("Couldn't attach to log channel 'validator'");
	}

	if (message_trace && loglevel < 10) {
		result = isc_log_createchannel(logconfig, "messages",
					       ISC_LOG_TOFILEDESC,
					       ISC_LOG_DEBUG(10),
					       &destination,
					       ISC_LOG_PRINTPREFIX);
		if (result != ISC_R_SUCCESS)
			fatal("Couldn't set up log channel 'messages'");

		result = isc_log_usechannel(logconfig, "messages",
					    DNS_LOGCATEGORY_RESOLVER,
					    DNS_LOGMODULE_PACKETS);
		if (result != ISC_R_SUCCESS)
			fatal("Couldn't attach to log channel 'messagse'");
	}
}

static void
print_status(dns_rdataset_t *rdataset) {
	const char *astr = "", *tstr = "";

	REQUIRE(rdataset != NULL);

	if (!showtrust || !dns_rdataset_isassociated(rdataset))
		return;

	if ((rdataset->attributes & DNS_RDATASETATTR_NEGATIVE) != 0)
		astr = "negative response, ";

	switch (rdataset->trust) {
	case dns_trust_none:
		tstr = "untrusted";
		break;
	case dns_trust_pending_additional:
		tstr = "signed additional data, pending validation";
		break;
	case dns_trust_pending_answer:
		tstr = "signed answer, pending validation";
		break;
	case dns_trust_additional:
		tstr = "unsigned additional data";
		break;
	case dns_trust_glue:
		tstr = "glue data";
		break;
	case dns_trust_answer:
		if (root_validation || dlv_validation)
			tstr = "unsigned answer";
		else
			tstr = "answer not validated";
		break;
	case dns_trust_authauthority:
		tstr = "authority data";
		break;
	case dns_trust_authanswer:
		tstr = "authoritative";
		break;
	case dns_trust_secure:
		tstr = "fully validated";
		break;
	case dns_trust_ultimate:
		tstr = "ultimate trust";
		break;
	}

	printf("; %s%s\n", astr, tstr);
}

static isc_result_t
printdata(dns_rdataset_t *rdataset, dns_name_t *owner,
	  dns_master_style_t *style)
{
	isc_result_t result = ISC_R_SUCCESS;
	static dns_trust_t trust;
413
	static bool first = true;
Evan Hunt's avatar
Evan Hunt committed
414
415
416
417
418
419
420
421
	isc_buffer_t target;
	isc_region_t r;
	char *t = NULL;
	int len = 2048;

	if (!dns_rdataset_isassociated(rdataset)) {
		char namebuf[DNS_NAME_FORMATSIZE];
		dns_name_format(owner, namebuf, sizeof(namebuf));
422
		delv_log(ISC_LOG_DEBUG(4),
Evan Hunt's avatar
Evan Hunt committed
423
424
425
426
427
428
429
430
431
432
433
434
			  "WARN: empty rdataset %s", namebuf);
		return (ISC_R_SUCCESS);
	}

	if (!showdnssec && rdataset->type == dns_rdatatype_rrsig)
		return (ISC_R_SUCCESS);

	if (first || rdataset->trust != trust) {
		if (!first && showtrust && !short_form)
			putchar('\n');
		print_status(rdataset);
		trust = rdataset->trust;
435
		first = false;
Evan Hunt's avatar
Evan Hunt committed
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
	}

	do {
		t = isc_mem_get(mctx, len);
		if (t == NULL)
			return (ISC_R_NOMEMORY);

		isc_buffer_init(&target, t, len);
		if (short_form) {
			dns_rdata_t rdata = DNS_RDATA_INIT;
			for (result = dns_rdataset_first(rdataset);
			     result == ISC_R_SUCCESS;
			     result = dns_rdataset_next(rdataset))
			{
				if ((rdataset->attributes &
				     DNS_RDATASETATTR_NEGATIVE) != 0)
					continue;

				dns_rdataset_current(rdataset, &rdata);
				result = dns_rdata_tofmttext(&rdata,
							     dns_rootname,
457
458
							     styleflags, 0,
							     splitwidth, " ",
Evan Hunt's avatar
Evan Hunt committed
459
460
461
462
							     &target);
				if (result != ISC_R_SUCCESS)
					break;

463
				if (isc_buffer_availablelength(&target) < 1) {
Evan Hunt's avatar
Evan Hunt committed
464
465
466
467
					result = ISC_R_NOSPACE;
					break;
				}

468
				isc_buffer_putstr(&target, "\n");
Evan Hunt's avatar
Evan Hunt committed
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483

				dns_rdata_reset(&rdata);
			}
		} else {
			if ((rdataset->attributes &
			     DNS_RDATASETATTR_NEGATIVE) != 0)
				isc_buffer_putstr(&target, "; ");

			result = dns_master_rdatasettotext(owner, rdataset,
							   style, &target);
		}

		if (result == ISC_R_NOSPACE) {
			isc_mem_put(mctx, t, len);
			len += 1024;
484
485
486
		} else if (result == ISC_R_NOMORE)
			result = ISC_R_SUCCESS;
		else
Evan Hunt's avatar
Evan Hunt committed
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
			CHECK(result);
	} while (result == ISC_R_NOSPACE);

	isc_buffer_usedregion(&target, &r);
	printf("%.*s", (int)r.length, (char *)r.base);

 cleanup:
	if (t != NULL)
		isc_mem_put(mctx, t, len);

	return (ISC_R_SUCCESS);
}

static isc_result_t
setup_style(dns_master_style_t **stylep) {
	isc_result_t result;
	dns_master_style_t *style = NULL;

	REQUIRE(stylep != NULL || *stylep == NULL);

	styleflags |= DNS_STYLEFLAG_REL_OWNER;
	if (showcomments)
		styleflags |= DNS_STYLEFLAG_COMMENT;
510
511
	if (print_unknown_format)
		styleflags |= DNS_STYLEFLAG_UNKNOWNFORMAT;
Evan Hunt's avatar
Evan Hunt committed
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
537
538
539
540
541
542
543
544
545
546
547
	if (rrcomments)
		styleflags |= DNS_STYLEFLAG_RRCOMMENT;
	if (nottl)
		styleflags |= DNS_STYLEFLAG_NO_TTL;
	if (noclass)
		styleflags |= DNS_STYLEFLAG_NO_CLASS;
	if (nocrypto)
		styleflags |= DNS_STYLEFLAG_NOCRYPTO;
	if (multiline) {
		styleflags |= DNS_STYLEFLAG_MULTILINE;
		styleflags |= DNS_STYLEFLAG_COMMENT;
	}

	if (multiline || (nottl && noclass))
		result = dns_master_stylecreate2(&style, styleflags,
						 24, 24, 24, 32, 80, 8,
						 splitwidth, mctx);
	else if (nottl || noclass)
		result = dns_master_stylecreate2(&style, styleflags,
						 24, 24, 32, 40, 80, 8,
						 splitwidth, mctx);
	else
		result = dns_master_stylecreate2(&style, styleflags,
						 24, 32, 40, 48, 80, 8,
						 splitwidth, mctx);

	if (result == ISC_R_SUCCESS)
		*stylep = style;
	return (result);
}

static isc_result_t
convert_name(dns_fixedname_t *fn, dns_name_t **name, const char *text) {
	isc_result_t result;
	isc_buffer_t b;
	dns_name_t *n;
548
	unsigned int len;
Evan Hunt's avatar
Evan Hunt committed
549
550
551
552
553
554

	REQUIRE(fn != NULL && name != NULL && text != NULL);
	len = strlen(text);

	isc_buffer_constinit(&b, text, len);
	isc_buffer_add(&b, len);
555
	n = dns_fixedname_initname(fn);
Evan Hunt's avatar
Evan Hunt committed
556
557
558

	result = dns_name_fromtext(n, &b, dns_rootname, 0, NULL);
	if (result != ISC_R_SUCCESS) {
559
		delv_log(ISC_LOG_ERROR, "failed to convert QNAME %s: %s",
Evan Hunt's avatar
Evan Hunt committed
560
561
562
563
564
565
566
567
568
569
570
			  text, isc_result_totext(result));
		return (result);
	}

	*name = n;
	return (ISC_R_SUCCESS);
}

static isc_result_t
key_fromconfig(const cfg_obj_t *key, dns_client_t *client) {
	dns_rdata_dnskey_t keystruct;
571
	uint32_t flags, proto, alg;
Evan Hunt's avatar
Evan Hunt committed
572
573
574
575
576
577
578
579
580
	const char *keystr, *keynamestr;
	unsigned char keydata[4096];
	isc_buffer_t keydatabuf;
	unsigned char rrdata[4096];
	isc_buffer_t rrdatabuf;
	isc_region_t r;
	dns_fixedname_t fkeyname;
	dns_name_t *keyname;
	isc_result_t result;
581
	bool match_root = false, match_dlv = false;
Evan Hunt's avatar
Evan Hunt committed
582
583
584
585
586
587
588

	keynamestr = cfg_obj_asstring(cfg_tuple_get(key, "name"));
	CHECK(convert_name(&fkeyname, &keyname, keynamestr));

	if (!root_validation && !dlv_validation)
		return (ISC_R_SUCCESS);

Evan Hunt's avatar
Evan Hunt committed
589
590
591
592
	if (anchor_name)
		match_root = dns_name_equal(keyname, anchor_name);
	if (dlv_name)
		match_dlv = dns_name_equal(keyname, dlv_name);
Evan Hunt's avatar
Evan Hunt committed
593
594
595
596
597
598
599

	if (!match_root && !match_dlv)
		return (ISC_R_SUCCESS);
	if ((!root_validation && match_root) || (!dlv_validation && match_dlv))
		return (ISC_R_SUCCESS);

	if (match_root)
600
		delv_log(ISC_LOG_DEBUG(3), "adding trust anchor %s",
Evan Hunt's avatar
Evan Hunt committed
601
602
			  trust_anchor);
	if (match_dlv)
603
		delv_log(ISC_LOG_DEBUG(3), "adding DLV trust anchor %s",
Evan Hunt's avatar
Evan Hunt committed
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
			  dlv_anchor);

	flags = cfg_obj_asuint32(cfg_tuple_get(key, "flags"));
	proto = cfg_obj_asuint32(cfg_tuple_get(key, "protocol"));
	alg = cfg_obj_asuint32(cfg_tuple_get(key, "algorithm"));

	keystruct.common.rdclass = dns_rdataclass_in;
	keystruct.common.rdtype = dns_rdatatype_dnskey;
	/*
	 * The key data in keystruct is not dynamically allocated.
	 */
	keystruct.mctx = NULL;

	ISC_LINK_INIT(&keystruct.common, link);

	if (flags > 0xffff)
		CHECK(ISC_R_RANGE);
	if (proto > 0xff)
		CHECK(ISC_R_RANGE);
	if (alg > 0xff)
		CHECK(ISC_R_RANGE);

626
627
628
	keystruct.flags = (uint16_t)flags;
	keystruct.protocol = (uint8_t)proto;
	keystruct.algorithm = (uint8_t)alg;
Evan Hunt's avatar
Evan Hunt committed
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682

	isc_buffer_init(&keydatabuf, keydata, sizeof(keydata));
	isc_buffer_init(&rrdatabuf, rrdata, sizeof(rrdata));

	keystr = cfg_obj_asstring(cfg_tuple_get(key, "key"));
	CHECK(isc_base64_decodestring(keystr, &keydatabuf));
	isc_buffer_usedregion(&keydatabuf, &r);
	keystruct.datalen = r.length;
	keystruct.data = r.base;

	CHECK(dns_rdata_fromstruct(NULL,
				   keystruct.common.rdclass,
				   keystruct.common.rdtype,
				   &keystruct, &rrdatabuf));

	CHECK(dns_client_addtrustedkey(client, dns_rdataclass_in,
				       keyname, &rrdatabuf));
	trusted_keys++;

 cleanup:
	if (result == DST_R_NOCRYPTO)
		cfg_obj_log(key, lctx, ISC_LOG_ERROR, "no crypto support");
	else if (result == DST_R_UNSUPPORTEDALG) {
		cfg_obj_log(key, lctx, ISC_LOG_WARNING,
			    "skipping trusted key '%s': %s",
			    keynamestr, isc_result_totext(result));
		result = ISC_R_SUCCESS;
	} else if (result != ISC_R_SUCCESS) {
		cfg_obj_log(key, lctx, ISC_LOG_ERROR,
			    "failed to add trusted key '%s': %s",
			    keynamestr, isc_result_totext(result));
		result = ISC_R_FAILURE;
	}

	return (result);
}

static isc_result_t
load_keys(const cfg_obj_t *keys, dns_client_t *client) {
	const cfg_listelt_t *elt, *elt2;
	const cfg_obj_t *key, *keylist;
	isc_result_t result = ISC_R_SUCCESS;

	for (elt = cfg_list_first(keys);
	     elt != NULL;
	     elt = cfg_list_next(elt))
	{
		keylist = cfg_listelt_value(elt);

		for (elt2 = cfg_list_first(keylist);
		     elt2 != NULL;
		     elt2 = cfg_list_next(elt2))
		{
			key = cfg_listelt_value(elt2);
Tinderbox User's avatar
Tinderbox User committed
683
			CHECK(key_fromconfig(key, client));
Evan Hunt's avatar
Evan Hunt committed
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
		}
	}

 cleanup:
	if (result == DST_R_NOCRYPTO)
		result = ISC_R_SUCCESS;
	return (result);
}

static isc_result_t
setup_dnsseckeys(dns_client_t *client) {
	isc_result_t result;
	cfg_parser_t *parser = NULL;
	const cfg_obj_t *keys = NULL;
	const cfg_obj_t *managed_keys = NULL;
	cfg_obj_t *bindkeys = NULL;
	const char *filename = anchorfile;

	if (!root_validation && !dlv_validation)
		return (ISC_R_SUCCESS);

705
706
	if (filename == NULL) {
#ifndef WIN32
Evan Hunt's avatar
Evan Hunt committed
707
		filename = SYSCONFDIR "/bind.keys";
708
709
710
711
712
713
714
#else
		static char buf[MAX_PATH];
		strlcpy(buf, isc_ntpaths_get(SYS_CONF_DIR), sizeof(buf));
		strlcat(buf, "\\bind.keys", sizeof(buf));
		filename = buf;
#endif
	}
Evan Hunt's avatar
Evan Hunt committed
715

Evan Hunt's avatar
Evan Hunt committed
716
	if (trust_anchor == NULL) {
Evan Hunt's avatar
Evan Hunt committed
717
		trust_anchor = isc_mem_strdup(mctx, ".");
Evan Hunt's avatar
Evan Hunt committed
718
719
720
721
		if (trust_anchor == NULL)
			fatal("out of memory");
	}

Evan Hunt's avatar
Evan Hunt committed
722
723
724
725
	if (trust_anchor != NULL)
		CHECK(convert_name(&afn, &anchor_name, trust_anchor));
	if (dlv_anchor != NULL)
		CHECK(convert_name(&dfn, &dlv_name, dlv_anchor));
Evan Hunt's avatar
Evan Hunt committed
726
727
728
729
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
761
762
763
764
765
766
767

	CHECK(cfg_parser_create(mctx, dns_lctx, &parser));

	if (access(filename, R_OK) != 0) {
		if (anchorfile != NULL)
			fatal("Unable to read key file '%s'", anchorfile);
	} else {
		result = cfg_parse_file(parser, filename,
					&cfg_type_bindkeys, &bindkeys);
		if (result != ISC_R_SUCCESS)
			if (anchorfile != NULL)
				fatal("Unable to load keys from '%s'",
				      anchorfile);
	}

	if (bindkeys == NULL) {
		isc_buffer_t b;

		isc_buffer_init(&b, anchortext, sizeof(anchortext) - 1);
		isc_buffer_add(&b, sizeof(anchortext) - 1);
		result = cfg_parse_buffer(parser, &b, &cfg_type_bindkeys,
					  &bindkeys);
		if (result != ISC_R_SUCCESS)
			fatal("Unable to parse built-in keys");
	}

	INSIST(bindkeys != NULL);
	cfg_map_get(bindkeys, "trusted-keys", &keys);
	cfg_map_get(bindkeys, "managed-keys", &managed_keys);

	if (keys != NULL)
		CHECK(load_keys(keys, client));
	if (managed_keys != NULL)
		CHECK(load_keys(managed_keys, client));
	result = ISC_R_SUCCESS;

	if (trusted_keys == 0)
		fatal("No trusted keys were loaded");

	if (dlv_validation)
		dns_client_setdlv(client, dns_rdataclass_in, dlv_anchor);

Witold Krecicki's avatar
Witold Krecicki committed
768

Evan Hunt's avatar
Evan Hunt committed
769
 cleanup:
Witold Krecicki's avatar
Witold Krecicki committed
770
771
772
773
774
775
	if (bindkeys != NULL) {
		cfg_obj_destroy(parser, &bindkeys);
	}
	if (parser != NULL) {
		cfg_parser_destroy(&parser);
	}
Evan Hunt's avatar
Evan Hunt committed
776
	if (result != ISC_R_SUCCESS)
777
		delv_log(ISC_LOG_ERROR, "setup_dnsseckeys: %s",
Evan Hunt's avatar
Evan Hunt committed
778
779
780
781
782
783
784
			  isc_result_totext(result));
	return (result);
}

static isc_result_t
addserver(dns_client_t *client) {
	struct addrinfo hints, *res, *cur;
785
	int gaierror;
Evan Hunt's avatar
Evan Hunt committed
786
787
788
789
	struct in_addr in4;
	struct in6_addr in6;
	isc_sockaddr_t *sa;
	isc_sockaddrlist_t servers;
790
	uint32_t destport;
Evan Hunt's avatar
Evan Hunt committed
791
792
793
794
795
796
797
798
799
	isc_result_t result;
	dns_name_t *name = NULL;

	result = parse_uint(&destport, port, 0xffff, "port");
	if (result != ISC_R_SUCCESS)
		fatal("Couldn't parse port number");

	ISC_LIST_INIT(servers);

800
801
802
803
	if (inet_pton(AF_INET, server, &in4) == 1) {
		if (!use_ipv4) {
			fatal("Use of IPv4 disabled by -6");
		}
Evan Hunt's avatar
Evan Hunt committed
804
		sa = isc_mem_get(mctx, sizeof(*sa));
805
806
		if (sa == NULL)
			return (ISC_R_NOMEMORY);
Evan Hunt's avatar
Evan Hunt committed
807
808
809
		ISC_LINK_INIT(sa, link);
		isc_sockaddr_fromin(sa, &in4, destport);
		ISC_LIST_APPEND(servers, sa, link);
810
811
812
813
	} else if (inet_pton(AF_INET6, server, &in6) == 1) {
		if (!use_ipv6) {
			fatal("Use of IPv6 disabled by -4");
		}
Evan Hunt's avatar
Evan Hunt committed
814
		sa = isc_mem_get(mctx, sizeof(*sa));
815
816
		if (sa == NULL)
			return (ISC_R_NOMEMORY);
Evan Hunt's avatar
Evan Hunt committed
817
818
819
820
821
822
823
824
825
826
827
828
829
		ISC_LINK_INIT(sa, link);
		isc_sockaddr_fromin6(sa, &in6, destport);
		ISC_LIST_APPEND(servers, sa, link);
	} else {
		memset(&hints, 0, sizeof(hints));
		if (!use_ipv6)
			hints.ai_family = AF_INET;
		else if (!use_ipv4)
			hints.ai_family = AF_INET6;
		else
			hints.ai_family = AF_UNSPEC;
		hints.ai_socktype = SOCK_DGRAM;
		hints.ai_protocol = IPPROTO_UDP;
830
831
		gaierror = getaddrinfo(server, port, &hints, &res);
		if (gaierror != 0) {
832
			delv_log(ISC_LOG_ERROR,
Evan Hunt's avatar
Evan Hunt committed
833
				  "getaddrinfo failed: %s",
834
				  gai_strerror(gaierror));
Evan Hunt's avatar
Evan Hunt committed
835
836
837
			return (ISC_R_FAILURE);
		}

838
839
840
841
842
		result = ISC_R_SUCCESS;
		for (cur = res; cur != NULL; cur = cur->ai_next) {
			if (cur->ai_family != AF_INET &&
			    cur->ai_family != AF_INET6)
				continue;
Evan Hunt's avatar
Evan Hunt committed
843
			sa = isc_mem_get(mctx, sizeof(*sa));
844
845
846
847
			if (sa == NULL) {
				result = ISC_R_NOMEMORY;
				break;
			}
Evan Hunt's avatar
Evan Hunt committed
848
849
			memset(sa, 0, sizeof(*sa));
			ISC_LINK_INIT(sa, link);
850
			memmove(&sa->type, cur->ai_addr, cur->ai_addrlen);
851
			sa->length = (unsigned int)cur->ai_addrlen;
Evan Hunt's avatar
Evan Hunt committed
852
853
			ISC_LIST_APPEND(servers, sa, link);
		}
854
855
		freeaddrinfo(res);
		CHECK(result);
Evan Hunt's avatar
Evan Hunt committed
856
857
858
859
860
861
862
863
864
865
866
867
868
	}


	CHECK(dns_client_setservers(client, dns_rdataclass_in, name, &servers));

 cleanup:
	while (!ISC_LIST_EMPTY(servers)) {
		sa = ISC_LIST_HEAD(servers);
		ISC_LIST_UNLINK(servers, sa, link);
		isc_mem_put(mctx, sa, sizeof(*sa));
	}

	if (result != ISC_R_SUCCESS)
869
		delv_log(ISC_LOG_ERROR, "addserver: %s",
Evan Hunt's avatar
Evan Hunt committed
870
871
872
873
874
875
876
877
878
879
880
			  isc_result_totext(result));

	return (result);
}

static isc_result_t
findserver(dns_client_t *client) {
	isc_result_t result;
	irs_resconf_t *resconf = NULL;
	isc_sockaddrlist_t *nameservers;
	isc_sockaddr_t *sa, *next;
881
	uint32_t destport;
882
883
884
885

	result = parse_uint(&destport, port, 0xffff, "port");
	if (result != ISC_R_SUCCESS)
		fatal("Couldn't parse port number");
Evan Hunt's avatar
Evan Hunt committed
886
887
888

	result = irs_resconf_load(mctx, "/etc/resolv.conf", &resconf);
	if (result != ISC_R_SUCCESS && result != ISC_R_FILENOTFOUND) {
889
		delv_log(ISC_LOG_ERROR, "irs_resconf_load: %s",
Evan Hunt's avatar
Evan Hunt committed
890
891
892
893
894
895
896
897
			  isc_result_totext(result));
		goto cleanup;
	}

	/* Get nameservers from resolv.conf */
	nameservers = irs_resconf_getnameservers(resconf);
	for (sa = ISC_LIST_HEAD(*nameservers); sa != NULL; sa = next) {
		next = ISC_LIST_NEXT(sa, link);
898
899
900
901
902

		/* Set destination port */
		if (sa->type.sa.sa_family == AF_INET && use_ipv4) {
			sa->type.sin.sin_port = htons(destport);
			continue;
Evan Hunt's avatar
Evan Hunt committed
903
		}
904
905
906
		if (sa->type.sa.sa_family == AF_INET6 && use_ipv6) {
			sa->type.sin6.sin6_port = htons(destport);
			continue;
Evan Hunt's avatar
Evan Hunt committed
907
		}
908
909
910
911

		/* Incompatible protocol family */
		ISC_LIST_UNLINK(*nameservers, sa, link);
		isc_mem_put(mctx, sa, sizeof(*sa));
Evan Hunt's avatar
Evan Hunt committed
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
	}

	/* None found, use localhost */
	if (ISC_LIST_EMPTY(*nameservers)) {
		if (use_ipv4) {
			struct in_addr localhost;
			localhost.s_addr = htonl(INADDR_LOOPBACK);
			sa = isc_mem_get(mctx, sizeof(*sa));
			if (sa == NULL) {
				result = ISC_R_NOMEMORY;
				goto cleanup;
			}
			isc_sockaddr_fromin(sa, &localhost, destport);

			ISC_LINK_INIT(sa, link);
			ISC_LIST_APPEND(*nameservers, sa, link);
		}

		if (use_ipv6) {
			sa = isc_mem_get(mctx, sizeof(*sa));
			if (sa == NULL) {
				result = ISC_R_NOMEMORY;
				goto cleanup;
			}
936
			isc_sockaddr_fromin6(sa, &in6addr_loopback, destport);
Evan Hunt's avatar
Evan Hunt committed
937
938
939
940
941
942
943
944
945

			ISC_LINK_INIT(sa, link);
			ISC_LIST_APPEND(*nameservers, sa, link);
		}
	}

	result = dns_client_setservers(client, dns_rdataclass_in, NULL,
				       nameservers);
	if (result != ISC_R_SUCCESS)
946
		delv_log(ISC_LOG_ERROR, "dns_client_setservers: %s",
Evan Hunt's avatar
Evan Hunt committed
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
			  isc_result_totext(result));

cleanup:
	if (resconf != NULL)
		irs_resconf_destroy(&resconf);
	return (result);
}

static char *
next_token(char **stringp, const char *delim) {
	char *res;

	do {
		res = strsep(stringp, delim);
		if (res == NULL)
			break;
	} while (*res == '\0');
	return (res);
}

static isc_result_t
968
parse_uint(uint32_t *uip, const char *value, uint32_t max,
Evan Hunt's avatar
Evan Hunt committed
969
	   const char *desc) {
970
	uint32_t n;
Evan Hunt's avatar
Evan Hunt committed
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
	isc_result_t result = isc_parse_uint32(&n, value, 10);
	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 void
plus_option(char *option) {
	isc_result_t result;
	char option_store[256];
	char *cmd, *value, *ptr;
988
	bool state = true;
Evan Hunt's avatar
Evan Hunt committed
989

990
	strlcpy(option_store, option, sizeof(option_store));
Evan Hunt's avatar
Evan Hunt committed
991
992
993
994
995
996
997
998
999
	ptr = option_store;
	cmd = next_token(&ptr,"=");
	if (cmd == NULL) {
		printf(";; Invalid option %s\n", option_store);
		return;
	}
	value = ptr;
	if (strncasecmp(cmd, "no", 2)==0) {
		cmd += 2;
1000
		state = false;
Evan Hunt's avatar
Evan Hunt committed
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
	}

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

	switch (cmd[0]) {
	case 'a': /* all */
		FULLCHECK("all");
		showcomments = state;
		rrcomments = state;
		showtrust = state;
		break;
	case 'c':
		switch (cmd[1]) {
		case 'd': /* cdflag */
			FULLCHECK("cdflag");
			cdflag = state;
			break;
		case 'l': /* class */
			FULLCHECK("class");
1025
			noclass = !state;
Evan Hunt's avatar
Evan Hunt committed
1026
1027
1028
1029
1030
1031
1032
			break;
		case 'o': /* comments */
			FULLCHECK("comments");
			showcomments = state;
			break;
		case 'r': /* crypto */
			FULLCHECK("crypto");
1033
			nocrypto = !state;
Evan Hunt's avatar
Evan Hunt committed
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
			break;
		default:
			goto invalid_option;
		}
		break;
	case 'd':
		switch (cmd[1]) {
		case 'l': /* dlv */
			FULLCHECK("dlv");
			if (state && no_sigs)
				break;
			dlv_validation = state;
Evan Hunt's avatar
Evan Hunt committed
1046
			if (value != NULL) {
Evan Hunt's avatar
Evan Hunt committed
1047
				dlv_anchor = isc_mem_strdup(mctx, value);
Evan Hunt's avatar
Evan Hunt committed
1048
1049
1050
				if (dlv_anchor == NULL)
					fatal("out of memory");
			}
Evan Hunt's avatar
Evan Hunt committed
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
			break;
		case 'n': /* dnssec */
			FULLCHECK("dnssec");
			showdnssec = state;
			break;
		default:
			goto invalid_option;
		}
		break;
	case 'm':
		switch (cmd[1]) {
		case 't': /* mtrace */
			message_trace = state;
			if (state)
				resolve_trace = state;
			break;
		case 'u': /* multiline */
			FULLCHECK("multiline");
			multiline = state;
			break;
		default:
			goto invalid_option;
		}
		break;
	case 'r':
		switch (cmd[1]) {
		case 'o': /* root */
			FULLCHECK("root");
			if (state && no_sigs)
				break;
			root_validation = state;
Evan Hunt's avatar
Evan Hunt committed
1082
			if (value != NULL) {
Evan Hunt's avatar
Evan Hunt committed
1083
				trust_anchor = isc_mem_strdup(mctx, value);
Evan Hunt's avatar
Evan Hunt committed
1084
1085
1086
				if (trust_anchor == NULL)
					fatal("out of memory");
			}
Evan Hunt's avatar
Evan Hunt committed
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
			break;
		case 'r': /* rrcomments */
			FULLCHECK("rrcomments");
			rrcomments = state;
			break;
		case 't': /* rtrace */
			FULLCHECK("rtrace");
			resolve_trace = state;
			break;
		default:
			goto invalid_option;
		}
		break;
	case 's':
		switch (cmd[1]) {
		case 'h': /* short */
			FULLCHECK("short");
			short_form = state;
			if (short_form) {
1106
1107
1108
1109
				multiline = false;
				showcomments = false;
				showtrust = false;
				showdnssec = false;
Evan Hunt's avatar
Evan Hunt committed
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
			}
			break;
		case 'p': /* split */
			FULLCHECK("split");
			if (value != NULL && !state)
				goto invalid_option;
			if (!state) {
				splitwidth = 0;
				break;
			} else if (value == NULL)
				break;

			result = parse_uint(&splitwidth, value,
					    1023, "split");
			if (splitwidth % 4 != 0) {
				splitwidth = ((splitwidth + 3) / 4) * 4;
				warn("split must be a multiple of 4; "
				     "adjusting to %d", splitwidth);
			}
			/*
			 * There is an adjustment done in the
			 * totext_<rrtype>() functions which causes
			 * splitwidth to shrink.  This is okay when we're
			 * using the default width but incorrect in this
			 * case, so we correct for it
			 */
			if (splitwidth)
				splitwidth += 3;
			if (result != ISC_R_SUCCESS)
				fatal("Couldn't parse split");
			break;
		default:
			goto invalid_option;
		}
		break;
1145
1146
1147
1148
	case 'u':
		FULLCHECK("unknownformat");
		print_unknown_format = state;
		break;
Evan Hunt's avatar
Evan Hunt committed
1149
1150
	case 't':
		switch (cmd[1]) {
Evan Hunt's avatar
Evan Hunt committed
1151
1152
1153
1154
		case 'c': /* tcp */
			FULLCHECK("tcp");
			use_tcp = state;
			break;
Evan Hunt's avatar
Evan Hunt committed
1155
1156
1157
1158
1159
1160
		case 'r': /* trust */
			FULLCHECK("trust");
			showtrust = state;
			break;
		case 't': /* ttl */
			FULLCHECK("ttl");
1161
			nottl = !state;
Evan Hunt's avatar
Evan Hunt committed
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
			break;
		default:
			goto invalid_option;
		}
		break;
	case 'v': /* vtrace */
		FULLCHECK("vtrace");
		validator_trace = state;
		if (state)
			resolve_trace = state;
		break;
	default:
	invalid_option:
		/*
		 * We can also add a "need_value:" case here if we ever
		 * add a plus-option that requires a specified value
		 */
		fprintf(stderr, "Invalid option: +%s\n", option);
		usage();
	}
	return;
}

/*
 * options: "46a:b:c:d:himp:q:t:vx:";
 */
static const char *single_dash_opts = "46himv";
Mark Andrews's avatar
Mark Andrews committed
1189
1190
static const char *dash_opts = "46abcdhimpqtvx";

1191
1192
static bool
dash_option(char *option, char *next, bool *open_type_class) {
Evan Hunt's avatar
Evan Hunt committed
1193
1194
	char opt, *value;
	isc_result_t result;
1195
	bool value_from_next;
Evan Hunt's avatar
Evan Hunt committed
1196
1197
1198
1199
1200
1201
1202
	isc_textregion_t tr;
	dns_rdatatype_t rdtype;
	dns_rdataclass_t rdclass;
	char textname[MAXNAME];
	struct in_addr in4;
	struct in6_addr in6;
	in_port_t srcport;
1203
	uint32_t num;
Evan Hunt's avatar
Evan Hunt committed
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
	char *hash;

	while (strpbrk(option, single_dash_opts) == &option[0]) {
		/*
		 * Since the -[46himv] options do not take an argument,
		 * account for them (in any number and/or combination)
		 * if they appear as the first character(s) of a q-opt.
		 */
		opt = option[0];
		switch (opt) {
		case '4':
			if (isc_net_probeipv4() != ISC_R_SUCCESS)
				fatal("IPv4 networking not available");
			if (use_ipv6) {
				isc_net_disableipv6();
1219
				use_ipv6 = false;
Evan Hunt's avatar
Evan Hunt committed
1220
1221
1222
1223
1224
1225
1226
			}
			break;
		case '6':
			if (isc_net_probeipv6() != ISC_R_SUCCESS)
				fatal("IPv6 networking not available");
			if (use_ipv4) {
				isc_net_disableipv4();
1227
				use_ipv4 = false;
Evan Hunt's avatar
Evan Hunt committed
1228
1229
1230
1231
1232
1233
1234
			}
			break;
		case 'h':
			usage();
			exit(0);
			/* NOTREACHED */
		case 'i':
1235
1236
1237
			no_sigs = true;
			dlv_validation = false;
			root_validation = false;
Evan Hunt's avatar
Evan Hunt committed
1238
1239
1240
1241
1242
			break;
		case 'm':
			/* handled in preparse_args() */
			break;
		case 'v':
1243
			fputs("delv " VERSION "\n", stderr);
Evan Hunt's avatar
Evan Hunt committed
1244
1245
1246
1247
			exit(0);
			/* NOTREACHED */
		default:
			INSIST(0);
1248
			ISC_UNREACHABLE();
Evan Hunt's avatar
Evan Hunt committed
1249
1250
1251
1252
		}
		if (strlen(option) > 1U)
			option = &option[1];
		else
1253
			return (false);
Evan Hunt's avatar
Evan Hunt committed
1254
1255
1256
	}
	opt = option[0];
	if (strlen(option) > 1U) {
1257
		value_from_next = false;
Evan Hunt's avatar
Evan Hunt committed
1258
1259
		value = &option[1];
	} else {
1260
		value_from_next = true;
Evan Hunt's avatar
Evan Hunt committed
1261
1262
1263
1264
1265
1266
1267
		value = next;
	}
	if (value == NULL)
		goto invalid_option;
	switch (opt) {
	case 'a':
		anchorfile = isc_mem_strdup(mctx, value);
Evan Hunt's avatar
Evan Hunt committed
1268
1269
		if (anchorfile == NULL)
			fatal("out of memory");
Evan Hunt's avatar
Evan Hunt committed
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
		return (value_from_next);
	case 'b':
		hash = strchr(value, '#');
		if (hash != NULL) {
			result = parse_uint(&num, hash + 1, 0xffff, "port");
			if (result != ISC_R_SUCCESS)
				fatal("Couldn't parse port number");
			srcport = num;
			*hash = '\0';
		} else
			srcport = 0;

		if (inet_pton(AF_INET, value, &in4) == 1) {
			if (srcaddr4 != NULL)
				fatal("Only one local address per family "
				      "can be specified\n");
			isc_sockaddr_fromin(&a4, &in4, srcport);
			srcaddr4 = &a4;
		} else if (inet_pton(AF_INET6, value, &in6) == 1) {
			if (srcaddr6 != NULL)
				fatal("Only one local address per family "
				      "can be specified\n");
			isc_sockaddr_fromin6(&a6, &in6, srcport);
			srcaddr6 = &a6;
		} else {
			if (hash != NULL)
				*hash = '#';
			fatal("Invalid address %s", value);
		}
		if (hash != NULL)
			*hash = '#';
		return (value_from_next);
	case 'c':
		if (classset)
			warn("extra query class");

1306
		*open_type_class = false;
Evan Hunt's avatar
Evan Hunt committed
1307
1308
1309
1310
1311
		tr.base = value;
		tr.length = strlen(value);
		result = dns_rdataclass_fromtext(&rdclass,
						 (isc_textregion_t *)&tr);
		if (result == ISC_R_SUCCESS)
1312
			classset = true;
Evan Hunt's avatar
Evan Hunt committed
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
		else if (rdclass != dns_rdataclass_in)
			warn("ignoring non-IN query class");
		else
			warn("ignoring invalid class");
		return (value_from_next);
	case 'd':
		result = parse_uint(&num, value, 99, "debug level");
		if (result != ISC_R_SUCCESS)
			fatal("Couldn't parse debug level");
		loglevel = num;
		return (value_from_next);
	case 'p':
		port = value;
		return (value_from_next);
	case 'q':
Evan Hunt's avatar
Evan Hunt committed
1328
		if (curqname != NULL) {
Evan Hunt's avatar
Evan Hunt committed
1329
			warn("extra query name");
Evan Hunt's avatar
Evan Hunt committed
1330
			isc_mem_free(mctx, curqname);
Evan Hunt's avatar
Evan Hunt committed
1331
		}
Evan Hunt's avatar
Evan Hunt committed
1332
1333
1334
		curqname = isc_mem_strdup(mctx, value);
		if (curqname == NULL)
			fatal("out of memory");
Evan Hunt's avatar
Evan Hunt committed
1335
1336
		return (value_from_next);
	case 't':
1337
		*open_type_class = false;
Evan Hunt's avatar
Evan Hunt committed
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
		tr.base = value;
		tr.length = strlen(value);
		result = dns_rdatatype_fromtext(&rdtype,
					(isc_textregion_t *)&tr);
		if (result == ISC_R_SUCCESS) {
			if (typeset)
				warn("extra query type");
			if (rdtype == dns_rdatatype_ixfr ||
			    rdtype == dns_rdatatype_axfr)
				fatal("Transfer not supported");
			qtype = rdtype;
1349
			typeset = true;
Evan Hunt's avatar
Evan Hunt committed
1350
1351
1352
1353
1354
		} else
			warn("ignoring invalid type");
		return (value_from_next);
	case 'x':
		result = get_reverse(textname, sizeof(textname), value,
1355
				     false);
Evan Hunt's avatar
Evan Hunt committed
1356
		if (result == ISC_R_SUCCESS) {
Evan Hunt's avatar
Evan Hunt committed
1357
1358
			if (curqname != NULL) {
				isc_mem_free(mctx, curqname);
Evan Hunt's avatar
Evan Hunt committed
1359
				warn("extra query name");
Evan Hunt's avatar
Evan Hunt committed
1360
			}
Evan Hunt's avatar
Evan Hunt committed
1361
			curqname = isc_mem_strdup(mctx, textname);
Evan Hunt's avatar
Evan Hunt committed
1362
1363
			if (curqname == NULL)
				fatal("out of memory");
Evan Hunt's avatar
Evan Hunt committed
1364
1365
1366
			if (typeset)
				warn("extra query type");
			qtype = dns_rdatatype_ptr;
1367
			typeset = true;
Evan Hunt's avatar
Evan Hunt committed
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
		} else {
			fprintf(stderr, "Invalid IP address %s\n", value);
			exit(1);
		}
		return (value_from_next);
	invalid_option:
	default:
		fprintf(stderr, "Invalid option: -%s\n", option);
		usage();
	}
	/* NOTREACHED */
1379
	return (false);
Evan Hunt's avatar
Evan Hunt committed
1380
1381
1382
1383
1384
1385
1386
1387
}

/*
 * Check for -m first to determine whether to enable
 * memory debugging when setting up the memory context.
 */
static void
preparse_args(int argc, char **argv) {
1388
	bool ipv4only = false, ipv6only = false;
Evan Hunt's avatar
Evan Hunt committed
1389
1390
1391
	char *option;

	for (argc--, argv++; argc > 0; argc--, argv++) {
Evan Hunt's avatar
style    
Evan Hunt committed
1392
		if (argv[0][0] != '-') {
Evan Hunt's avatar
Evan Hunt committed
1393
			continue;
Evan Hunt's avatar
style    
Evan Hunt committed
1394
1395
		}

Evan Hunt's avatar
Evan Hunt committed
1396
1397
		option = &argv[0][1];
		while (strpbrk(option, single_dash_opts) == &option[0]) {
1398
1399
			switch (option[0]) {
			case 'm':
Evan Hunt's avatar
Evan Hunt committed
1400
1401
				isc_mem_debugging = ISC_MEM_DEBUGTRACE |
					ISC_MEM_DEBUGRECORD;
1402
1403
1404
1405
1406
				break;
			case '4':
				if (ipv6only) {
					fatal("only one of -4 and -6 allowed");
				}
1407
				ipv4only = true;
1408
1409
1410
1411
1412
				break;
			case '6':
				if (ipv4only) {
					fatal("only one of -4 and -6 allowed");
				}
1413
				ipv6only = true;
1414
				break;
Evan Hunt's avatar
Evan Hunt committed
1415
1416
1417
			}
			option = &option[1];
		}
Evan Hunt's avatar
style    
Evan Hunt committed
1418

Mark Andrews's avatar
Mark Andrews committed
1419
1420
1421
		if (strlen(option) == 0U) {
			continue;
		}
Evan Hunt's avatar
style    
Evan Hunt committed
1422

Mark Andrews's avatar
Mark Andrews committed
1423
1424
		/* Look for dash value option. */
		if (strpbrk(option, dash_opts) != &option[0] ||
Evan Hunt's avatar
style    
Evan Hunt committed
1425
1426
		    strlen(option) > 1U)
		{
Mark Andrews's avatar
Mark Andrews committed
1427
1428
1429
			/* Error or value in option. */
			continue;
		}
Evan Hunt's avatar
style    
Evan Hunt committed
1430

Mark Andrews's avatar
Mark Andrews committed
1431
		/* Dash value is next argument so we need to skip it. */
Evan Hunt's avatar
style    
Evan Hunt committed
1432
1433
1434
		argc--;
		argv++;

Mark Andrews's avatar
Mark Andrews committed
1435
		/* Handle missing argument */
Evan Hunt's avatar
style    
Evan Hunt committed
1436
		if (argc == 0) {
Mark Andrews's avatar
Mark Andrews committed
1437
			break;
Evan Hunt's avatar
style    
Evan Hunt committed
1438
		}
Evan Hunt's avatar
Evan Hunt committed
1439
1440
1441
1442
1443
1444
	}
}

/*
 * Argument parsing is based on dig, but simplified: only one
 * QNAME/QCLASS/QTYPE tuple can be specified, and options have
1445
 * been removed that aren't applicable to delv. The interface
Evan Hunt's avatar
Evan Hunt committed
1446
1447
1448
1449
1450
1451
1452
1453
 * should be familiar to dig users, however.
 */
static void
parse_args(int argc, char **argv) {
	isc_result_t result;
	isc_textregion_t tr;
	dns_rdatatype_t rdtype;
	dns_rdataclass_t rdclass;
1454
	bool open_type_class = true;
Evan Hunt's avatar
Evan Hunt committed
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492

	for (; argc > 0; argc--, argv++) {
		if (argv[0][0] == '@') {
			server = &argv[0][1];
		} else if (argv[0][0] == '+') {
			plus_option(&argv[0][1]);
		} else if (argv[0][0] == '-') {
			if (argc <= 1) {
				if (dash_option(&argv[0][1], NULL,
						&open_type_class))
				{
					argc--;
					argv++;
				}
			} else {
				if (dash_option(&argv[0][1], argv[1],
						&open_type_class))
				{
					argc--;
					argv++;
				}
			}
		} else {
			/*
			 * Anything which isn't an option
			 */
			if (open_type_class) {
				tr.base = argv[0];
				tr.length = strlen(argv[0]);
				result = dns_rdatatype_fromtext(&rdtype,
					(isc_textregion_t *)&tr);
				if (result == ISC_R_SUCCESS) {
					if (typeset)
						warn("extra query type");
					if (rdtype == dns_rdatatype_ixfr ||
					    rdtype == dns_rdatatype_axfr)
						fatal("Transfer not supported");
					qtype = rdtype;
1493
					typeset = true;
Evan Hunt's avatar
Evan Hunt committed
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
					continue;
				}
				result = dns_rdataclass_fromtext(&rdclass,
						     (isc_textregion_t *)&tr);
				if (result == ISC_R_SUCCESS) {
					if (classset)
						warn("extra query class");
					else if (rdclass != dns_rdataclass_in)
						warn("ignoring non-IN "
						     "query class");
					continue;
				}
			}

Evan Hunt's avatar
Evan Hunt committed
1508
1509
1510
1511
1512
			if (curqname == NULL) {
				curqname = isc_mem_strdup(mctx, argv[0]);
				if (curqname == NULL)
					fatal("out of memory");
			}
Evan Hunt's avatar
Evan Hunt committed
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
		}
	}

	/*
	 * If no qname or qtype specified, search for root/NS
	 * If no qtype specified, use A
	 */
	if (!typeset)
		qtype = dns_rdatatype_a;

	if (curqname == NULL) {
		qname = isc_mem_strdup(mctx, ".");
Evan Hunt's avatar
Evan Hunt committed
1525
1526
1527
		if (qname == NULL)
			fatal("out of memory");

Evan Hunt's avatar
Evan Hunt committed
1528
1529
1530
		if (!typeset)
			qtype = dns_rdatatype_ns;
	} else
Evan Hunt's avatar
Evan Hunt committed
1531
		qname = curqname;
Evan Hunt's avatar
Evan Hunt committed
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
}

static isc_result_t
append_str(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) {
	char *dot = strchr(in, '.');
	int len;
	if (dot != NULL) {
		isc_result_t result;
		result = reverse_octets(dot + 1, p, end);
		if (result != ISC_R_SUCCESS)
			return (result);
		result = append_str(".", 1, p, end);
		if (result != ISC_R_SUCCESS)
			return (result);
		len = (int)(dot - in);
	} else
		len = strlen(in);
	return (append_str(in, len, p, end));
}

static isc_result_t
1562
get_reverse(char *reverse, size_t len, char *value, bool strict) {
Evan Hunt's avatar
Evan Hunt committed
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
	int r;
	isc_result_t result;
	isc_netaddr_t addr;

	addr.family = AF_INET6;
	r = inet_pton(AF_INET6, value, &addr.type.in6);
	if (r > 0) {
		/* This is a valid IPv6 address. */
		dns_fixedname_t fname;
		dns_name_t *name;
		unsigned int options = 0;

1575
		name = dns_fixedname_initname(&fname);
Evan Hunt's avatar
Evan Hunt committed
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
		result = dns_byaddr_createptrname2(&addr, options, name);
		if (result != ISC_R_SUCCESS)
			return (result);
		dns_name_format(name, reverse, (unsigned int)len);
		return (ISC_R_SUCCESS);
	} else {
		/*
		 * Not a valid IPv6 address.  Assume IPv4.
		 * If 'strict' is not set, 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;
		if (strict && inet_pton(AF_INET, value, &addr.type.in) != 1)
			return (DNS_R_BADDOTTEDQUAD);
		result = reverse_octets(value, &p, end);
		if (result != ISC_R_SUCCESS)
			return (result);
		result = append_str(".in-addr.arpa.", 15, &p, end);
		if (result != ISC_R_SUCCESS)
			return (result);
		return (ISC_R_SUCCESS);
	}
}

int
main(int argc, char *argv[]) {
	dns_client_t *client = NULL;
	isc_result_t result;
	dns_fixedname_t qfn;
	dns_name_t *query_name, *response_name;
	dns_rdataset_t *rdataset;
	dns_namelist_t namelist;
Evan Hunt's avatar
Evan Hunt committed
1612
	unsigned int resopt, clopt;
Evan Hunt's avatar
Evan Hunt committed
1613
1614
1615
1616
1617
	isc_appctx_t *actx = NULL;
	isc_taskmgr_t *taskmgr = NULL;
	isc_socketmgr_t *socketmgr = NULL;
	isc_timermgr_t *timermgr = NULL;
	dns_master_style_t *style = NULL;
1618
#ifndef WIN32
Evan Hunt's avatar
Evan Hunt committed
1619
	struct sigaction sa;
1620
#endif
Evan Hunt's avatar
Evan Hunt committed
1621
1622

	progname = argv[0];
1623
	preparse_args(argc, argv);
Evan Hunt's avatar
Evan Hunt committed
1624

1625
1626
	argc--;
	argv++;
Evan Hunt's avatar
Evan Hunt committed
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649

	isc_lib_register();
	result = dns_lib_init();
	if (result != ISC_R_SUCCESS)
		fatal("dns_lib_init failed: %d", result);

	result = isc_mem_create(0, 0, &mctx);
	if (result != ISC_R_SUCCESS)
		fatal("failed to create mctx");

	CHECK(isc_appctx_create(mctx, &actx));
	CHECK(isc_taskmgr_createinctx(mctx, actx, 1, 0, &taskmgr));
	CHECK(isc_socketmgr_createinctx(mctx, actx, &socketmgr));
	CHECK(isc_timermgr_createinctx(mctx, actx, &timermgr));

	parse_args(argc, argv);

	CHECK(setup_style(&style));

	setup_logging(stderr);

	CHECK(isc_app_ctxstart(actx));

1650
#ifndef WIN32
Evan Hunt's avatar
Evan Hunt committed
1651
1652
1653
1654
1655
	/* Unblock SIGINT if it's been blocked by isc_app_ctxstart() */
	memset(&sa, 0, sizeof(sa));
	sa.sa_handler = SIG_DFL;
	if (sigfillset(&sa.sa_mask) != 0 || sigaction(SIGINT, &sa, NULL) < 0)
		fatal("Couldn't set up signal handler");
1656
#endif
Evan Hunt's avatar
Evan Hunt committed
1657
1658

	/* Create client */
Evan Hunt's avatar
Evan Hunt committed
1659
	clopt = DNS_CLIENTCREATEOPT_USECACHE;
Evan Hunt's avatar
Evan Hunt committed
1660
	result = dns_client_createx2(mctx, actx, taskmgr, socketmgr, timermgr,
Evan Hunt's avatar
Evan Hunt committed
1661
				     clopt, &client, srcaddr4, srcaddr6);
Evan Hunt's avatar
Evan Hunt committed
1662
	if (result != ISC_R_SUCCESS) {
1663
		delv_log(ISC_LOG_ERROR, "dns_client_create: %s",
Evan Hunt's avatar
Evan Hunt committed
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
			  isc_result_totext(result));
		goto cleanup;
	}

	/* Set the nameserver */
	if (server != NULL)
		addserver(client);
	else
		findserver(client);

	CHECK(setup_dnsseckeys(client));

	/* Construct QNAME */