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