Import bind 9.5.2 vendor sources.
[dragonfly.git] / contrib / bind-9.5.2 / bin / dig / dighost.c
1 /*
2  * Copyright (C) 2004-2009  Internet Systems Consortium, Inc. ("ISC")
3  * Copyright (C) 2000-2003  Internet Software Consortium.
4  *
5  * Permission to use, copy, modify, and/or distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
10  * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11  * AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
12  * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13  * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
14  * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15  * PERFORMANCE OF THIS SOFTWARE.
16  */
17
18 /* $Id: dighost.c,v 1.304.12.16 2009/06/24 03:42:32 marka Exp $ */
19
20 /*! \file
21  *  \note
22  * Notice to programmers:  Do not use this code as an example of how to
23  * use the ISC library to perform DNS lookups.  Dig and Host both operate
24  * on the request level, since they allow fine-tuning of output and are
25  * intended as debugging tools.  As a result, they perform many of the
26  * functions which could be better handled using the dns_resolver
27  * functions in most applications.
28  */
29
30 #include <config.h>
31 #include <stdlib.h>
32 #include <unistd.h>
33 #include <string.h>
34 #include <limits.h>
35
36 #ifdef HAVE_LOCALE_H
37 #include <locale.h>
38 #endif
39
40 #ifdef WITH_IDN
41 #include <idn/result.h>
42 #include <idn/log.h>
43 #include <idn/resconf.h>
44 #include <idn/api.h>
45 #endif
46
47 #include <dns/byaddr.h>
48 #ifdef DIG_SIGCHASE
49 #include <dns/dnssec.h>
50 #include <dns/ds.h>
51 #include <dns/nsec.h>
52 #include <isc/random.h>
53 #include <ctype.h>
54 #endif
55 #include <dns/fixedname.h>
56 #include <dns/message.h>
57 #include <dns/name.h>
58 #include <dns/rdata.h>
59 #include <dns/rdataclass.h>
60 #include <dns/rdatalist.h>
61 #include <dns/rdataset.h>
62 #include <dns/rdatastruct.h>
63 #include <dns/rdatatype.h>
64 #include <dns/result.h>
65 #include <dns/tsig.h>
66
67 #include <dst/dst.h>
68
69 #include <isc/app.h>
70 #include <isc/base64.h>
71 #include <isc/entropy.h>
72 #include <isc/file.h>
73 #include <isc/lang.h>
74 #include <isc/netaddr.h>
75 #ifdef DIG_SIGCHASE
76 #include <isc/netdb.h>
77 #endif
78 #include <isc/print.h>
79 #include <isc/random.h>
80 #include <isc/result.h>
81 #include <isc/string.h>
82 #include <isc/task.h>
83 #include <isc/timer.h>
84 #include <isc/types.h>
85 #include <isc/util.h>
86
87 #include <lwres/lwres.h>
88 #include <lwres/net.h>
89
90 #include <bind9/getaddresses.h>
91
92 #include <dig/dig.h>
93
94 #if ! defined(NS_INADDRSZ)
95 #define NS_INADDRSZ      4
96 #endif
97
98 #if ! defined(NS_IN6ADDRSZ)
99 #define NS_IN6ADDRSZ    16
100 #endif
101
102 static lwres_context_t *lwctx = NULL;
103 static lwres_conf_t *lwconf;
104
105 dig_lookuplist_t lookup_list;
106 dig_serverlist_t server_list;
107 dig_searchlistlist_t search_list;
108
109 isc_boolean_t
110         check_ra = ISC_FALSE,
111         have_ipv4 = ISC_FALSE,
112         have_ipv6 = ISC_FALSE,
113         specified_source = ISC_FALSE,
114         free_now = ISC_FALSE,
115         cancel_now = ISC_FALSE,
116         usesearch = ISC_FALSE,
117         showsearch = ISC_FALSE,
118         qr = ISC_FALSE,
119         is_dst_up = ISC_FALSE;
120 in_port_t port = 53;
121 unsigned int timeout = 0;
122 unsigned int extrabytes;
123 isc_mem_t *mctx = NULL;
124 isc_taskmgr_t *taskmgr = NULL;
125 isc_task_t *global_task = NULL;
126 isc_timermgr_t *timermgr = NULL;
127 isc_socketmgr_t *socketmgr = NULL;
128 isc_sockaddr_t bind_address;
129 isc_sockaddr_t bind_any;
130 int sendcount = 0;
131 int recvcount = 0;
132 int sockcount = 0;
133 int ndots = -1;
134 int tries = 3;
135 int lookup_counter = 0;
136
137 #ifdef WITH_IDN
138 static void             initialize_idn(void);
139 static isc_result_t     output_filter(isc_buffer_t *buffer,
140                                       unsigned int used_org,
141                                       isc_boolean_t absolute);
142 static idn_result_t     append_textname(char *name, const char *origin,
143                                         size_t namesize);
144 static void             idn_check_result(idn_result_t r, const char *msg);
145
146 #define MAXDLEN         256
147 int  idnoptions = 0;
148 #endif
149
150 /*%
151  * Exit Codes:
152  *
153  *\li   0   Everything went well, including things like NXDOMAIN
154  *\li   1   Usage error
155  *\li   7   Got too many RR's or Names
156  *\li   8   Couldn't open batch file
157  *\li   9   No reply from server
158  *\li   10  Internal error
159  */
160 int exitcode = 0;
161 int fatalexit = 0;
162 char keynametext[MXNAME];
163 char keyfile[MXNAME] = "";
164 char keysecret[MXNAME] = "";
165 dns_name_t *hmacname = NULL;
166 unsigned int digestbits = 0;
167 isc_buffer_t *namebuf = NULL;
168 dns_tsigkey_t *key = NULL;
169 isc_boolean_t validated = ISC_TRUE;
170 isc_entropy_t *entp = NULL;
171 isc_mempool_t *commctx = NULL;
172 isc_boolean_t debugging = ISC_FALSE;
173 isc_boolean_t memdebugging = ISC_FALSE;
174 char *progname = NULL;
175 isc_mutex_t lookup_lock;
176 dig_lookup_t *current_lookup = NULL;
177
178 #ifdef DIG_SIGCHASE
179
180 isc_result_t      get_trusted_key(isc_mem_t *mctx);
181 dns_rdataset_t *  sigchase_scanname(dns_rdatatype_t type,
182                                     dns_rdatatype_t covers,
183                                     isc_boolean_t *lookedup,
184                                     dns_name_t *rdata_name);
185 dns_rdataset_t *  chase_scanname_section(dns_message_t *msg,
186                                          dns_name_t *name,
187                                          dns_rdatatype_t type,
188                                          dns_rdatatype_t covers,
189                                          int section);
190 isc_result_t      advanced_rrsearch(dns_rdataset_t **rdataset,
191                                     dns_name_t *name,
192                                     dns_rdatatype_t type,
193                                     dns_rdatatype_t covers,
194                                     isc_boolean_t *lookedup);
195 isc_result_t      sigchase_verify_sig_key(dns_name_t *name,
196                                           dns_rdataset_t *rdataset,
197                                           dst_key_t* dnsseckey,
198                                           dns_rdataset_t *sigrdataset,
199                                           isc_mem_t *mctx);
200 isc_result_t      sigchase_verify_sig(dns_name_t *name,
201                                       dns_rdataset_t *rdataset,
202                                       dns_rdataset_t *keyrdataset,
203                                       dns_rdataset_t *sigrdataset,
204                                       isc_mem_t *mctx);
205 isc_result_t      sigchase_verify_ds(dns_name_t *name,
206                                      dns_rdataset_t *keyrdataset,
207                                      dns_rdataset_t *dsrdataset,
208                                      isc_mem_t *mctx);
209 void              sigchase(dns_message_t *msg);
210 void              print_rdata(dns_rdata_t *rdata, isc_mem_t *mctx);
211 void              print_rdataset(dns_name_t *name,
212                                  dns_rdataset_t *rdataset, isc_mem_t *mctx);
213 void              dup_name(dns_name_t *source, dns_name_t* target,
214                            isc_mem_t *mctx);
215 void              free_name(dns_name_t *name, isc_mem_t *mctx);
216 void              dump_database(void);
217 void              dump_database_section(dns_message_t *msg, int section);
218 dns_rdataset_t *  search_type(dns_name_t *name, dns_rdatatype_t type,
219                               dns_rdatatype_t covers);
220 isc_result_t      contains_trusted_key(dns_name_t *name,
221                                        dns_rdataset_t *rdataset,
222                                        dns_rdataset_t *sigrdataset,
223                                        isc_mem_t *mctx);
224 void              print_type(dns_rdatatype_t type);
225 isc_result_t      prove_nx_domain(dns_message_t * msg,
226                                   dns_name_t * name,
227                                   dns_name_t * rdata_name,
228                                   dns_rdataset_t ** rdataset,
229                                   dns_rdataset_t ** sigrdataset);
230 isc_result_t      prove_nx_type(dns_message_t * msg, dns_name_t *name,
231                                 dns_rdataset_t *nsec,
232                                 dns_rdataclass_t class,
233                                 dns_rdatatype_t type,
234                                 dns_name_t * rdata_name,
235                                 dns_rdataset_t ** rdataset,
236                                 dns_rdataset_t ** sigrdataset);
237 isc_result_t      prove_nx(dns_message_t * msg, dns_name_t * name,
238                            dns_rdataclass_t class,
239                            dns_rdatatype_t type,
240                            dns_name_t * rdata_name,
241                            dns_rdataset_t ** rdataset,
242                            dns_rdataset_t ** sigrdataset);
243 static void       nameFromString(const char *str, dns_name_t *p_ret);
244 int               inf_name(dns_name_t * name1, dns_name_t * name2);
245 isc_result_t      opentmpkey(isc_mem_t *mctx, const char *file,
246                              char **tempp, FILE **fp);
247 isc_result_t      removetmpkey(isc_mem_t *mctx, const char *file);
248 void              clean_trustedkey(void);
249 void              insert_trustedkey(dst_key_t  * key);
250 #if DIG_SIGCHASE_BU
251 isc_result_t      getneededrr(dns_message_t *msg);
252 void              sigchase_bottom_up(dns_message_t *msg);
253 void              sigchase_bu(dns_message_t *msg);
254 #endif
255 #if DIG_SIGCHASE_TD
256 isc_result_t      initialization(dns_name_t *name);
257 isc_result_t      prepare_lookup(dns_name_t *name);
258 isc_result_t      grandfather_pb_test(dns_name_t * zone_name,
259                                       dns_rdataset_t *sigrdataset);
260 isc_result_t      child_of_zone(dns_name_t *name,
261                                 dns_name_t *zone_name,
262                                 dns_name_t *child_name);
263 void              sigchase_td(dns_message_t *msg);
264 #endif
265 char trustedkey[MXNAME] = "";
266
267 dns_rdataset_t *chase_rdataset = NULL;
268 dns_rdataset_t *chase_sigrdataset = NULL;
269 dns_rdataset_t *chase_dsrdataset = NULL;
270 dns_rdataset_t *chase_sigdsrdataset = NULL;
271 dns_rdataset_t *chase_keyrdataset = NULL;
272 dns_rdataset_t *chase_sigkeyrdataset = NULL;
273 dns_rdataset_t *chase_nsrdataset = NULL;
274
275 dns_name_t chase_name; /* the query name */
276 #if DIG_SIGCHASE_TD
277 /*
278  * the current name is the parent name when we follow delegation
279  */
280 dns_name_t chase_current_name;
281 /*
282  * the child name is used for delegation (NS DS responses in AUTHORITY section)
283  */
284 dns_name_t chase_authority_name;
285 #endif
286 #if DIG_SIGCHASE_BU
287 dns_name_t chase_signame;
288 #endif
289
290
291 isc_boolean_t chase_siglookedup = ISC_FALSE;
292 isc_boolean_t chase_keylookedup = ISC_FALSE;
293 isc_boolean_t chase_sigkeylookedup = ISC_FALSE;
294 isc_boolean_t chase_dslookedup = ISC_FALSE;
295 isc_boolean_t chase_sigdslookedup = ISC_FALSE;
296 #if DIG_SIGCHASE_TD
297 isc_boolean_t chase_nslookedup = ISC_FALSE;
298 isc_boolean_t chase_lookedup = ISC_FALSE;
299
300
301 isc_boolean_t delegation_follow = ISC_FALSE;
302 isc_boolean_t grandfather_pb = ISC_FALSE;
303 isc_boolean_t have_response = ISC_FALSE;
304 isc_boolean_t have_delegation_ns = ISC_FALSE;
305 dns_message_t * error_message = NULL;
306 #endif
307
308 isc_boolean_t dsvalidating = ISC_FALSE;
309 isc_boolean_t chase_name_dup = ISC_FALSE;
310
311 ISC_LIST(dig_message_t) chase_message_list;
312 ISC_LIST(dig_message_t) chase_message_list2;
313
314
315 #define MAX_TRUSTED_KEY 5
316 typedef struct struct_trusted_key_list {
317         dst_key_t * key[MAX_TRUSTED_KEY];
318         int nb_tk;
319 } struct_tk_list;
320
321 struct_tk_list tk_list = { {NULL, NULL, NULL, NULL, NULL}, 0};
322
323 #endif
324
325 #define DIG_MAX_ADDRESSES 20
326
327 /*%
328  * Apply and clear locks at the event level in global task.
329  * Can I get rid of these using shutdown events?  XXX
330  */
331 #define LOCK_LOOKUP {\
332         debug("lock_lookup %s:%d", __FILE__, __LINE__);\
333         check_result(isc_mutex_lock((&lookup_lock)), "isc_mutex_lock");\
334         debug("success");\
335 }
336 #define UNLOCK_LOOKUP {\
337         debug("unlock_lookup %s:%d", __FILE__, __LINE__);\
338         check_result(isc_mutex_unlock((&lookup_lock)),\
339                      "isc_mutex_unlock");\
340 }
341
342 static void
343 cancel_lookup(dig_lookup_t *lookup);
344
345 static void
346 recv_done(isc_task_t *task, isc_event_t *event);
347
348 static void
349 send_udp(dig_query_t *query);
350
351 static void
352 connect_timeout(isc_task_t *task, isc_event_t *event);
353
354 static void
355 launch_next_query(dig_query_t *query, isc_boolean_t include_question);
356
357
358 static void *
359 mem_alloc(void *arg, size_t size) {
360         return (isc_mem_get(arg, size));
361 }
362
363 static void
364 mem_free(void *arg, void *mem, size_t size) {
365         isc_mem_put(arg, mem, size);
366 }
367
368 char *
369 next_token(char **stringp, const char *delim) {
370         char *res;
371
372         do {
373                 res = strsep(stringp, delim);
374                 if (res == NULL)
375                         break;
376         } while (*res == '\0');
377         return (res);
378 }
379
380 static int
381 count_dots(char *string) {
382         char *s;
383         int i = 0;
384
385         s = string;
386         while (*s != '\0') {
387                 if (*s == '.')
388                         i++;
389                 s++;
390         }
391         return (i);
392 }
393
394 static void
395 hex_dump(isc_buffer_t *b) {
396         unsigned int len;
397         isc_region_t r;
398
399         isc_buffer_usedregion(b, &r);
400
401         printf("%d bytes\n", r.length);
402         for (len = 0; len < r.length; len++) {
403                 printf("%02x ", r.base[len]);
404                 if (len % 16 == 15)
405                         printf("\n");
406         }
407         if (len % 16 != 0)
408                 printf("\n");
409 }
410
411 /*%
412  * Append 'len' bytes of 'text' at '*p', failing with
413  * ISC_R_NOSPACE if that would advance p past 'end'.
414  */
415 static isc_result_t
416 append(const char *text, int len, char **p, char *end) {
417         if (len > end - *p)
418                 return (ISC_R_NOSPACE);
419         memcpy(*p, text, len);
420         *p += len;
421         return (ISC_R_SUCCESS);
422 }
423
424 static isc_result_t
425 reverse_octets(const char *in, char **p, char *end) {
426         char *dot = strchr(in, '.');
427         int len;
428         if (dot != NULL) {
429                 isc_result_t result;
430                 result = reverse_octets(dot + 1, p, end);
431                 if (result != ISC_R_SUCCESS)
432                         return (result);
433                 result = append(".", 1, p, end);
434                 if (result != ISC_R_SUCCESS)
435                         return (result);
436                 len = dot - in;
437         } else {
438                 len = strlen(in);
439         }
440         return (append(in, len, p, end));
441 }
442
443 isc_result_t
444 get_reverse(char *reverse, size_t len, char *value, isc_boolean_t ip6_int,
445             isc_boolean_t strict)
446 {
447         int r;
448         isc_result_t result;
449         isc_netaddr_t addr;
450
451         addr.family = AF_INET6;
452         r = inet_pton(AF_INET6, value, &addr.type.in6);
453         if (r > 0) {
454                 /* This is a valid IPv6 address. */
455                 dns_fixedname_t fname;
456                 dns_name_t *name;
457                 unsigned int options = 0;
458
459                 if (ip6_int)
460                         options |= DNS_BYADDROPT_IPV6INT;
461                 dns_fixedname_init(&fname);
462                 name = dns_fixedname_name(&fname);
463                 result = dns_byaddr_createptrname2(&addr, options, name);
464                 if (result != ISC_R_SUCCESS)
465                         return (result);
466                 dns_name_format(name, reverse, len);
467                 return (ISC_R_SUCCESS);
468         } else {
469                 /*
470                  * Not a valid IPv6 address.  Assume IPv4.
471                  * If 'strict' is not set, construct the
472                  * in-addr.arpa name by blindly reversing
473                  * octets whether or not they look like integers,
474                  * so that this can be used for RFC2317 names
475                  * and such.
476                  */
477                 char *p = reverse;
478                 char *end = reverse + len;
479                 if (strict && inet_pton(AF_INET, value, &addr.type.in) != 1)
480                         return (DNS_R_BADDOTTEDQUAD);
481                 result = reverse_octets(value, &p, end);
482                 if (result != ISC_R_SUCCESS)
483                         return (result);
484                 /* Append .in-addr.arpa. and a terminating NUL. */
485                 result = append(".in-addr.arpa.", 15, &p, end);
486                 if (result != ISC_R_SUCCESS)
487                         return (result);
488                 return (ISC_R_SUCCESS);
489         }
490 }
491
492 void
493 fatal(const char *format, ...) {
494         va_list args;
495
496         fflush(stdout);
497         fprintf(stderr, "%s: ", progname);
498         va_start(args, format);
499         vfprintf(stderr, format, args);
500         va_end(args);
501         fprintf(stderr, "\n");
502         if (exitcode < 10)
503                 exitcode = 10;
504         if (fatalexit != 0)
505                 exitcode = fatalexit;
506         exit(exitcode);
507 }
508
509 void
510 debug(const char *format, ...) {
511         va_list args;
512
513         if (debugging) {
514                 fflush(stdout);
515                 va_start(args, format);
516                 vfprintf(stderr, format, args);
517                 va_end(args);
518                 fprintf(stderr, "\n");
519         }
520 }
521
522 void
523 check_result(isc_result_t result, const char *msg) {
524         if (result != ISC_R_SUCCESS) {
525                 fatal("%s: %s", msg, isc_result_totext(result));
526         }
527 }
528
529 /*%
530  * Create a server structure, which is part of the lookup structure.
531  * This is little more than a linked list of servers to query in hopes
532  * of finding the answer the user is looking for
533  */
534 dig_server_t *
535 make_server(const char *servname, const char *userarg) {
536         dig_server_t *srv;
537
538         REQUIRE(servname != NULL);
539
540         debug("make_server(%s)", servname);
541         srv = isc_mem_allocate(mctx, sizeof(struct dig_server));
542         if (srv == NULL)
543                 fatal("memory allocation failure in %s:%d",
544                       __FILE__, __LINE__);
545         strncpy(srv->servername, servname, MXNAME);
546         strncpy(srv->userarg, userarg, MXNAME);
547         srv->servername[MXNAME-1] = 0;
548         srv->userarg[MXNAME-1] = 0;
549         ISC_LINK_INIT(srv, link);
550         return (srv);
551 }
552
553 static int
554 addr2af(int lwresaddrtype)
555 {
556         int af = 0;
557
558         switch (lwresaddrtype) {
559         case LWRES_ADDRTYPE_V4:
560                 af = AF_INET;
561                 break;
562
563         case LWRES_ADDRTYPE_V6:
564                 af = AF_INET6;
565                 break;
566         }
567
568         return (af);
569 }
570
571 /*%
572  * Create a copy of the server list from the lwres configuration structure.
573  * The dest list must have already had ISC_LIST_INIT applied.
574  */
575 static void
576 copy_server_list(lwres_conf_t *confdata, dig_serverlist_t *dest) {
577         dig_server_t *newsrv;
578         char tmp[sizeof("ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255")];
579         int af;
580         int i;
581
582         debug("copy_server_list()");
583         for (i = 0; i < confdata->nsnext; i++) {
584                 af = addr2af(confdata->nameservers[i].family);
585
586                 if (af == AF_INET && !have_ipv4)
587                         continue;
588                 if (af == AF_INET6 && !have_ipv6)
589                         continue;
590
591                 lwres_net_ntop(af, confdata->nameservers[i].address,
592                                    tmp, sizeof(tmp));
593                 newsrv = make_server(tmp, tmp);
594                 ISC_LINK_INIT(newsrv, link);
595                 ISC_LIST_ENQUEUE(*dest, newsrv, link);
596         }
597 }
598
599 void
600 flush_server_list(void) {
601         dig_server_t *s, *ps;
602
603         debug("flush_server_list()");
604         s = ISC_LIST_HEAD(server_list);
605         while (s != NULL) {
606                 ps = s;
607                 s = ISC_LIST_NEXT(s, link);
608                 ISC_LIST_DEQUEUE(server_list, ps, link);
609                 isc_mem_free(mctx, ps);
610         }
611 }
612
613 void
614 set_nameserver(char *opt) {
615         isc_result_t result;
616         isc_sockaddr_t sockaddrs[DIG_MAX_ADDRESSES];
617         isc_netaddr_t netaddr;
618         int count, i;
619         dig_server_t *srv;
620         char tmp[ISC_NETADDR_FORMATSIZE];
621
622         if (opt == NULL)
623                 return;
624
625         result = bind9_getaddresses(opt, 0, sockaddrs,
626                                     DIG_MAX_ADDRESSES, &count);
627         if (result != ISC_R_SUCCESS)
628                 fatal("couldn't get address for '%s': %s",
629                       opt, isc_result_totext(result));
630
631         flush_server_list();
632
633         for (i = 0; i < count; i++) {
634                 isc_netaddr_fromsockaddr(&netaddr, &sockaddrs[i]);
635                 isc_netaddr_format(&netaddr, tmp, sizeof(tmp));
636                 srv = make_server(tmp, opt);
637                 if (srv == NULL)
638                         fatal("memory allocation failure");
639                 ISC_LIST_APPEND(server_list, srv, link);
640         }
641 }
642
643 static isc_result_t
644 add_nameserver(lwres_conf_t *confdata, const char *addr, int af) {
645
646         int i = confdata->nsnext;
647
648         if (confdata->nsnext >= LWRES_CONFMAXNAMESERVERS)
649                 return (ISC_R_FAILURE);
650
651         switch (af) {
652         case AF_INET:
653                 confdata->nameservers[i].family = LWRES_ADDRTYPE_V4;
654                 confdata->nameservers[i].length = NS_INADDRSZ;
655                 break;
656         case AF_INET6:
657                 confdata->nameservers[i].family = LWRES_ADDRTYPE_V6;
658                 confdata->nameservers[i].length = NS_IN6ADDRSZ;
659                 break;
660         default:
661                 return (ISC_R_FAILURE);
662         }
663
664         if (lwres_net_pton(af, addr, &confdata->nameservers[i].address) == 1) {
665                 confdata->nsnext++;
666                 return (ISC_R_SUCCESS);
667         }
668         return (ISC_R_FAILURE);
669 }
670
671 /*%
672  * Produce a cloned server list.  The dest list must have already had
673  * ISC_LIST_INIT applied.
674  */
675 void
676 clone_server_list(dig_serverlist_t src, dig_serverlist_t *dest) {
677         dig_server_t *srv, *newsrv;
678
679         debug("clone_server_list()");
680         srv = ISC_LIST_HEAD(src);
681         while (srv != NULL) {
682                 newsrv = make_server(srv->servername, srv->userarg);
683                 ISC_LINK_INIT(newsrv, link);
684                 ISC_LIST_ENQUEUE(*dest, newsrv, link);
685                 srv = ISC_LIST_NEXT(srv, link);
686         }
687 }
688
689 /*%
690  * Create an empty lookup structure, which holds all the information needed
691  * to get an answer to a user's question.  This structure contains two
692  * linked lists: the server list (servers to query) and the query list
693  * (outstanding queries which have been made to the listed servers).
694  */
695 dig_lookup_t *
696 make_empty_lookup(void) {
697         dig_lookup_t *looknew;
698
699         debug("make_empty_lookup()");
700
701         INSIST(!free_now);
702
703         looknew = isc_mem_allocate(mctx, sizeof(struct dig_lookup));
704         if (looknew == NULL)
705                 fatal("memory allocation failure in %s:%d",
706                        __FILE__, __LINE__);
707         looknew->pending = ISC_TRUE;
708         looknew->textname[0] = 0;
709         looknew->cmdline[0] = 0;
710         looknew->rdtype = dns_rdatatype_a;
711         looknew->qrdtype = dns_rdatatype_a;
712         looknew->rdclass = dns_rdataclass_in;
713         looknew->rdtypeset = ISC_FALSE;
714         looknew->rdclassset = ISC_FALSE;
715         looknew->sendspace = NULL;
716         looknew->sendmsg = NULL;
717         looknew->name = NULL;
718         looknew->oname = NULL;
719         looknew->timer = NULL;
720         looknew->xfr_q = NULL;
721         looknew->current_query = NULL;
722         looknew->doing_xfr = ISC_FALSE;
723         looknew->ixfr_serial = ISC_FALSE;
724         looknew->trace = ISC_FALSE;
725         looknew->trace_root = ISC_FALSE;
726         looknew->identify = ISC_FALSE;
727         looknew->identify_previous_line = ISC_FALSE;
728         looknew->ignore = ISC_FALSE;
729         looknew->servfail_stops = ISC_TRUE;
730         looknew->besteffort = ISC_TRUE;
731         looknew->dnssec = ISC_FALSE;
732         looknew->nsid = ISC_FALSE;
733 #ifdef DIG_SIGCHASE
734         looknew->sigchase = ISC_FALSE;
735 #if DIG_SIGCHASE_TD
736         looknew->do_topdown = ISC_FALSE;
737         looknew->trace_root_sigchase = ISC_FALSE;
738         looknew->rdtype_sigchaseset = ISC_FALSE;
739         looknew->rdtype_sigchase = dns_rdatatype_any;
740         looknew->qrdtype_sigchase = dns_rdatatype_any;
741         looknew->rdclass_sigchase = dns_rdataclass_in;
742         looknew->rdclass_sigchaseset = ISC_FALSE;
743 #endif
744 #endif
745         looknew->udpsize = 0;
746         looknew->edns = -1;
747         looknew->recurse = ISC_TRUE;
748         looknew->aaonly = ISC_FALSE;
749         looknew->adflag = ISC_FALSE;
750         looknew->cdflag = ISC_FALSE;
751         looknew->ns_search_only = ISC_FALSE;
752         looknew->origin = NULL;
753         looknew->tsigctx = NULL;
754         looknew->querysig = NULL;
755         looknew->retries = tries;
756         looknew->nsfound = 0;
757         looknew->tcp_mode = ISC_FALSE;
758         looknew->ip6_int = ISC_FALSE;
759         looknew->comments = ISC_TRUE;
760         looknew->stats = ISC_TRUE;
761         looknew->section_question = ISC_TRUE;
762         looknew->section_answer = ISC_TRUE;
763         looknew->section_authority = ISC_TRUE;
764         looknew->section_additional = ISC_TRUE;
765         looknew->new_search = ISC_FALSE;
766         looknew->done_as_is = ISC_FALSE;
767         looknew->need_search = ISC_FALSE;
768         ISC_LINK_INIT(looknew, link);
769         ISC_LIST_INIT(looknew->q);
770         ISC_LIST_INIT(looknew->my_server_list);
771         return (looknew);
772 }
773
774 /*%
775  * Clone a lookup, perhaps copying the server list.  This does not clone
776  * the query list, since it will be regenerated by the setup_lookup()
777  * function, nor does it queue up the new lookup for processing.
778  * Caution: If you don't clone the servers, you MUST clone the server
779  * list separately from somewhere else, or construct it by hand.
780  */
781 dig_lookup_t *
782 clone_lookup(dig_lookup_t *lookold, isc_boolean_t servers) {
783         dig_lookup_t *looknew;
784
785         debug("clone_lookup()");
786
787         INSIST(!free_now);
788
789         looknew = make_empty_lookup();
790         INSIST(looknew != NULL);
791         strncpy(looknew->textname, lookold->textname, MXNAME);
792 #if DIG_SIGCHASE_TD
793         strncpy(looknew->textnamesigchase, lookold->textnamesigchase, MXNAME);
794 #endif
795         strncpy(looknew->cmdline, lookold->cmdline, MXNAME);
796         looknew->textname[MXNAME-1] = 0;
797         looknew->rdtype = lookold->rdtype;
798         looknew->qrdtype = lookold->qrdtype;
799         looknew->rdclass = lookold->rdclass;
800         looknew->rdtypeset = lookold->rdtypeset;
801         looknew->rdclassset = lookold->rdclassset;
802         looknew->doing_xfr = lookold->doing_xfr;
803         looknew->ixfr_serial = lookold->ixfr_serial;
804         looknew->trace = lookold->trace;
805         looknew->trace_root = lookold->trace_root;
806         looknew->identify = lookold->identify;
807         looknew->identify_previous_line = lookold->identify_previous_line;
808         looknew->ignore = lookold->ignore;
809         looknew->servfail_stops = lookold->servfail_stops;
810         looknew->besteffort = lookold->besteffort;
811         looknew->dnssec = lookold->dnssec;
812         looknew->nsid = lookold->nsid;
813 #ifdef DIG_SIGCHASE
814         looknew->sigchase = lookold->sigchase;
815 #if DIG_SIGCHASE_TD
816         looknew->do_topdown = lookold->do_topdown;
817         looknew->trace_root_sigchase = lookold->trace_root_sigchase;
818         looknew->rdtype_sigchaseset = lookold->rdtype_sigchaseset;
819         looknew->rdtype_sigchase = lookold->rdtype_sigchase;
820         looknew->qrdtype_sigchase = lookold->qrdtype_sigchase;
821         looknew->rdclass_sigchase = lookold->rdclass_sigchase;
822         looknew->rdclass_sigchaseset = lookold->rdclass_sigchaseset;
823 #endif
824 #endif
825         looknew->udpsize = lookold->udpsize;
826         looknew->edns = lookold->edns;
827         looknew->recurse = lookold->recurse;
828         looknew->aaonly = lookold->aaonly;
829         looknew->adflag = lookold->adflag;
830         looknew->cdflag = lookold->cdflag;
831         looknew->ns_search_only = lookold->ns_search_only;
832         looknew->tcp_mode = lookold->tcp_mode;
833         looknew->comments = lookold->comments;
834         looknew->stats = lookold->stats;
835         looknew->section_question = lookold->section_question;
836         looknew->section_answer = lookold->section_answer;
837         looknew->section_authority = lookold->section_authority;
838         looknew->section_additional = lookold->section_additional;
839         looknew->retries = lookold->retries;
840         looknew->tsigctx = NULL;
841         looknew->need_search = lookold->need_search;
842         looknew->done_as_is = lookold->done_as_is;
843
844         if (servers)
845                 clone_server_list(lookold->my_server_list,
846                                   &looknew->my_server_list);
847         return (looknew);
848 }
849
850 /*%
851  * Requeue a lookup for further processing, perhaps copying the server
852  * list.  The new lookup structure is returned to the caller, and is
853  * queued for processing.  If servers are not cloned in the requeue, they
854  * must be added before allowing the current event to complete, since the
855  * completion of the event may result in the next entry on the lookup
856  * queue getting run.
857  */
858 dig_lookup_t *
859 requeue_lookup(dig_lookup_t *lookold, isc_boolean_t servers) {
860         dig_lookup_t *looknew;
861
862         debug("requeue_lookup()");
863
864         lookup_counter++;
865         if (lookup_counter > LOOKUP_LIMIT)
866                 fatal("too many lookups");
867
868         looknew = clone_lookup(lookold, servers);
869         INSIST(looknew != NULL);
870
871         debug("before insertion, init@%p -> %p, new@%p -> %p",
872               lookold, lookold->link.next, looknew, looknew->link.next);
873         ISC_LIST_PREPEND(lookup_list, looknew, link);
874         debug("after insertion, init -> %p, new = %p, new -> %p",
875               lookold, looknew, looknew->link.next);
876         return (looknew);
877 }
878
879
880 static void
881 setup_text_key(void) {
882         isc_result_t result;
883         dns_name_t keyname;
884         isc_buffer_t secretbuf;
885         int secretsize;
886         unsigned char *secretstore;
887
888         debug("setup_text_key()");
889         result = isc_buffer_allocate(mctx, &namebuf, MXNAME);
890         check_result(result, "isc_buffer_allocate");
891         dns_name_init(&keyname, NULL);
892         check_result(result, "dns_name_init");
893         isc_buffer_putstr(namebuf, keynametext);
894         secretsize = strlen(keysecret) * 3 / 4;
895         secretstore = isc_mem_allocate(mctx, secretsize);
896         if (secretstore == NULL)
897                 fatal("memory allocation failure in %s:%d",
898                       __FILE__, __LINE__);
899         isc_buffer_init(&secretbuf, secretstore, secretsize);
900         result = isc_base64_decodestring(keysecret, &secretbuf);
901         if (result != ISC_R_SUCCESS)
902                 goto failure;
903
904         secretsize = isc_buffer_usedlength(&secretbuf);
905
906         result = dns_name_fromtext(&keyname, namebuf,
907                                    dns_rootname, ISC_FALSE,
908                                    namebuf);
909         if (result != ISC_R_SUCCESS)
910                 goto failure;
911
912         result = dns_tsigkey_create(&keyname, hmacname, secretstore,
913                                     secretsize, ISC_FALSE, NULL, 0, 0, mctx,
914                                     NULL, &key);
915  failure:
916         if (result != ISC_R_SUCCESS)
917                 printf(";; Couldn't create key %s: %s\n",
918                        keynametext, isc_result_totext(result));
919         else
920                 dst_key_setbits(key->key, digestbits);
921
922         isc_mem_free(mctx, secretstore);
923         dns_name_invalidate(&keyname);
924         isc_buffer_free(&namebuf);
925 }
926
927 static void
928 setup_file_key(void) {
929         isc_result_t result;
930         dst_key_t *dstkey = NULL;
931
932         debug("setup_file_key()");
933         result = dst_key_fromnamedfile(keyfile, DST_TYPE_PRIVATE | DST_TYPE_KEY,
934                                        mctx, &dstkey);
935         if (result != ISC_R_SUCCESS) {
936                 fprintf(stderr, "Couldn't read key from %s: %s\n",
937                         keyfile, isc_result_totext(result));
938                 goto failure;
939         }
940
941         switch (dst_key_alg(dstkey)) {
942         case DST_ALG_HMACMD5:
943                 hmacname = DNS_TSIG_HMACMD5_NAME;
944                 break;
945         case DST_ALG_HMACSHA1:
946                 hmacname = DNS_TSIG_HMACSHA1_NAME;
947                 break;
948         case DST_ALG_HMACSHA224:
949                 hmacname = DNS_TSIG_HMACSHA224_NAME;
950                 break;
951         case DST_ALG_HMACSHA256:
952                 hmacname = DNS_TSIG_HMACSHA256_NAME;
953                 break;
954         case DST_ALG_HMACSHA384:
955                 hmacname = DNS_TSIG_HMACSHA384_NAME;
956                 break;
957         case DST_ALG_HMACSHA512:
958                 hmacname = DNS_TSIG_HMACSHA512_NAME;
959                 break;
960         default:
961                 printf(";; Couldn't create key %s: bad algorithm\n",
962                        keynametext);
963                 goto failure;
964         }
965         result = dns_tsigkey_createfromkey(dst_key_name(dstkey), hmacname,
966                                            dstkey, ISC_FALSE, NULL, 0, 0,
967                                            mctx, NULL, &key);
968         if (result != ISC_R_SUCCESS) {
969                 printf(";; Couldn't create key %s: %s\n",
970                        keynametext, isc_result_totext(result));
971                 goto failure;
972         }
973         dstkey = NULL;
974  failure:
975         if (dstkey != NULL)
976                 dst_key_free(&dstkey);
977 }
978
979 static dig_searchlist_t *
980 make_searchlist_entry(char *domain) {
981         dig_searchlist_t *search;
982         search = isc_mem_allocate(mctx, sizeof(*search));
983         if (search == NULL)
984                 fatal("memory allocation failure in %s:%d",
985                       __FILE__, __LINE__);
986         strncpy(search->origin, domain, MXNAME);
987         search->origin[MXNAME-1] = 0;
988         ISC_LINK_INIT(search, link);
989         return (search);
990 }
991
992 static void
993 create_search_list(lwres_conf_t *confdata) {
994         int i;
995         dig_searchlist_t *search;
996
997         debug("create_search_list()");
998         ISC_LIST_INIT(search_list);
999
1000         for (i = 0; i < confdata->searchnxt; i++) {
1001                 search = make_searchlist_entry(confdata->search[i]);
1002                 ISC_LIST_APPEND(search_list, search, link);
1003         }
1004 }
1005
1006 /*%
1007  * Setup the system as a whole, reading key information and resolv.conf
1008  * settings.
1009  */
1010 void
1011 setup_system(void) {
1012         dig_searchlist_t *domain = NULL;
1013         lwres_result_t lwresult;
1014         unsigned int lwresflags;
1015
1016         debug("setup_system()");
1017
1018         lwresflags = LWRES_CONTEXT_SERVERMODE;
1019         if (have_ipv4)
1020                 lwresflags |= LWRES_CONTEXT_USEIPV4;
1021         if (have_ipv6)
1022                 lwresflags |= LWRES_CONTEXT_USEIPV6;
1023
1024         lwresult = lwres_context_create(&lwctx, mctx, mem_alloc, mem_free,
1025                                         lwresflags);
1026         if (lwresult != LWRES_R_SUCCESS)
1027                 fatal("lwres_context_create failed");
1028
1029         lwresult = lwres_conf_parse(lwctx, RESOLV_CONF);
1030         if (lwresult != LWRES_R_SUCCESS && lwresult != LWRES_R_NOTFOUND)
1031                 fatal("parse of %s failed", RESOLV_CONF);
1032
1033         lwconf = lwres_conf_get(lwctx);
1034
1035         /* Make the search list */
1036         if (lwconf->searchnxt > 0)
1037                 create_search_list(lwconf);
1038         else { /* No search list. Use the domain name if any */
1039                 if (lwconf->domainname != NULL) {
1040                         domain = make_searchlist_entry(lwconf->domainname);
1041                         ISC_LIST_INITANDAPPEND(search_list, domain, link);
1042                         domain  = NULL;
1043                 }
1044         }
1045
1046         if (ndots == -1) {
1047                 ndots = lwconf->ndots;
1048                 debug("ndots is %d.", ndots);
1049         }
1050
1051         /* If user doesn't specify server use nameservers from resolv.conf. */
1052         if (ISC_LIST_EMPTY(server_list))
1053                 copy_server_list(lwconf, &server_list);
1054
1055         /* If we don't find a nameserver fall back to localhost */
1056         if (ISC_LIST_EMPTY(server_list)) {
1057                 if (have_ipv4) {
1058                         lwresult = add_nameserver(lwconf, "127.0.0.1", AF_INET);
1059                         if (lwresult != ISC_R_SUCCESS)
1060                                 fatal("add_nameserver failed");
1061                 }
1062                 if (have_ipv6) {
1063                         lwresult = add_nameserver(lwconf, "::1", AF_INET6);
1064                         if (lwresult != ISC_R_SUCCESS)
1065                                 fatal("add_nameserver failed");
1066                 }
1067
1068                 copy_server_list(lwconf, &server_list);
1069         }
1070
1071 #ifdef WITH_IDN
1072         initialize_idn();
1073 #endif
1074
1075         if (keyfile[0] != 0)
1076                 setup_file_key();
1077         else if (keysecret[0] != 0)
1078                 setup_text_key();
1079 #ifdef DIG_SIGCHASE
1080         /* Setup the list of messages for +sigchase */
1081         ISC_LIST_INIT(chase_message_list);
1082         ISC_LIST_INIT(chase_message_list2);
1083         dns_name_init(&chase_name, NULL);
1084 #if DIG_SIGCHASE_TD
1085         dns_name_init(&chase_current_name, NULL);
1086         dns_name_init(&chase_authority_name, NULL);
1087 #endif
1088 #if DIG_SIGCHASE_BU
1089         dns_name_init(&chase_signame, NULL);
1090 #endif
1091
1092 #endif
1093
1094 }
1095
1096 static void
1097 clear_searchlist(void) {
1098         dig_searchlist_t *search;
1099         while ((search = ISC_LIST_HEAD(search_list)) != NULL) {
1100                 ISC_LIST_UNLINK(search_list, search, link);
1101                 isc_mem_free(mctx, search);
1102         }
1103 }
1104
1105 /*%
1106  * Override the search list derived from resolv.conf by 'domain'.
1107  */
1108 void
1109 set_search_domain(char *domain) {
1110         dig_searchlist_t *search;
1111
1112         clear_searchlist();
1113         search = make_searchlist_entry(domain);
1114         ISC_LIST_APPEND(search_list, search, link);
1115 }
1116
1117 /*%
1118  * Setup the ISC and DNS libraries for use by the system.
1119  */
1120 void
1121 setup_libs(void) {
1122         isc_result_t result;
1123
1124         debug("setup_libs()");
1125
1126         result = isc_net_probeipv4();
1127         if (result == ISC_R_SUCCESS)
1128                 have_ipv4 = ISC_TRUE;
1129
1130         result = isc_net_probeipv6();
1131         if (result == ISC_R_SUCCESS)
1132                 have_ipv6 = ISC_TRUE;
1133         if (!have_ipv6 && !have_ipv4)
1134                 fatal("can't find either v4 or v6 networking");
1135
1136         result = isc_mem_create(0, 0, &mctx);
1137         check_result(result, "isc_mem_create");
1138
1139         result = isc_taskmgr_create(mctx, 1, 0, &taskmgr);
1140         check_result(result, "isc_taskmgr_create");
1141
1142         result = isc_task_create(taskmgr, 0, &global_task);
1143         check_result(result, "isc_task_create");
1144
1145         result = isc_timermgr_create(mctx, &timermgr);
1146         check_result(result, "isc_timermgr_create");
1147
1148         result = isc_socketmgr_create(mctx, &socketmgr);
1149         check_result(result, "isc_socketmgr_create");
1150
1151         result = isc_entropy_create(mctx, &entp);
1152         check_result(result, "isc_entropy_create");
1153
1154         result = dst_lib_init(mctx, entp, 0);
1155         check_result(result, "dst_lib_init");
1156         is_dst_up = ISC_TRUE;
1157
1158         result = isc_mempool_create(mctx, COMMSIZE, &commctx);
1159         check_result(result, "isc_mempool_create");
1160         isc_mempool_setname(commctx, "COMMPOOL");
1161         /*
1162          * 6 and 2 set as reasonable parameters for 3 or 4 nameserver
1163          * systems.
1164          */
1165         isc_mempool_setfreemax(commctx, 6);
1166         isc_mempool_setfillcount(commctx, 2);
1167
1168         result = isc_mutex_init(&lookup_lock);
1169         check_result(result, "isc_mutex_init");
1170
1171         dns_result_register();
1172 }
1173
1174 /*%
1175  * Add EDNS0 option record to a message.  Currently, the only supported
1176  * options are UDP buffer size, the DO bit, and NSID request.
1177  */
1178 static void
1179 add_opt(dns_message_t *msg, isc_uint16_t udpsize, isc_uint16_t edns,
1180         isc_boolean_t dnssec, isc_boolean_t nsid)
1181 {
1182         dns_rdataset_t *rdataset = NULL;
1183         dns_rdatalist_t *rdatalist = NULL;
1184         dns_rdata_t *rdata = NULL;
1185         isc_result_t result;
1186
1187         debug("add_opt()");
1188         result = dns_message_gettemprdataset(msg, &rdataset);
1189         check_result(result, "dns_message_gettemprdataset");
1190         dns_rdataset_init(rdataset);
1191         result = dns_message_gettemprdatalist(msg, &rdatalist);
1192         check_result(result, "dns_message_gettemprdatalist");
1193         result = dns_message_gettemprdata(msg, &rdata);
1194         check_result(result, "dns_message_gettemprdata");
1195
1196         debug("setting udp size of %d", udpsize);
1197         rdatalist->type = dns_rdatatype_opt;
1198         rdatalist->covers = 0;
1199         rdatalist->rdclass = udpsize;
1200         rdatalist->ttl = edns << 16;
1201         if (dnssec)
1202                 rdatalist->ttl |= DNS_MESSAGEEXTFLAG_DO;
1203         if (nsid) {
1204                 unsigned char data[4];
1205                 isc_buffer_t buf;
1206
1207                 isc_buffer_init(&buf, data, sizeof(data));
1208                 isc_buffer_putuint16(&buf, DNS_OPT_NSID);
1209                 isc_buffer_putuint16(&buf, 0);
1210                 rdata->data = data;
1211                 rdata->length = sizeof(data);
1212         } else {
1213                 rdata->data = NULL;
1214                 rdata->length = 0;
1215         }
1216         ISC_LIST_INIT(rdatalist->rdata);
1217         ISC_LIST_APPEND(rdatalist->rdata, rdata, link);
1218         dns_rdatalist_tordataset(rdatalist, rdataset);
1219         result = dns_message_setopt(msg, rdataset);
1220         check_result(result, "dns_message_setopt");
1221 }
1222
1223 /*%
1224  * Add a question section to a message, asking for the specified name,
1225  * type, and class.
1226  */
1227 static void
1228 add_question(dns_message_t *message, dns_name_t *name,
1229              dns_rdataclass_t rdclass, dns_rdatatype_t rdtype)
1230 {
1231         dns_rdataset_t *rdataset;
1232         isc_result_t result;
1233
1234         debug("add_question()");
1235         rdataset = NULL;
1236         result = dns_message_gettemprdataset(message, &rdataset);
1237         check_result(result, "dns_message_gettemprdataset()");
1238         dns_rdataset_init(rdataset);
1239         dns_rdataset_makequestion(rdataset, rdclass, rdtype);
1240         ISC_LIST_APPEND(name->list, rdataset, link);
1241 }
1242
1243 /*%
1244  * Check if we're done with all the queued lookups, which is true iff
1245  * all sockets, sends, and recvs are accounted for (counters == 0),
1246  * and the lookup list is empty.
1247  * If we are done, pass control back out to dighost_shutdown() (which is
1248  * part of dig.c, host.c, or nslookup.c) to either shutdown the system as
1249  * a whole or reseed the lookup list.
1250  */
1251 static void
1252 check_if_done(void) {
1253         debug("check_if_done()");
1254         debug("list %s", ISC_LIST_EMPTY(lookup_list) ? "empty" : "full");
1255         if (ISC_LIST_EMPTY(lookup_list) && current_lookup == NULL &&
1256             sendcount == 0) {
1257                 INSIST(sockcount == 0);
1258                 INSIST(recvcount == 0);
1259                 debug("shutting down");
1260                 dighost_shutdown();
1261         }
1262 }
1263
1264 /*%
1265  * Clear out a query when we're done with it.  WARNING: This routine
1266  * WILL invalidate the query pointer.
1267  */
1268 static void
1269 clear_query(dig_query_t *query) {
1270         dig_lookup_t *lookup;
1271
1272         REQUIRE(query != NULL);
1273
1274         debug("clear_query(%p)", query);
1275
1276         lookup = query->lookup;
1277
1278         if (lookup->current_query == query)
1279                 lookup->current_query = NULL;
1280
1281         ISC_LIST_UNLINK(lookup->q, query, link);
1282         if (ISC_LINK_LINKED(&query->recvbuf, link))
1283                 ISC_LIST_DEQUEUE(query->recvlist, &query->recvbuf,
1284                                  link);
1285         if (ISC_LINK_LINKED(&query->lengthbuf, link))
1286                 ISC_LIST_DEQUEUE(query->lengthlist, &query->lengthbuf,
1287                                  link);
1288         INSIST(query->recvspace != NULL);
1289         if (query->sock != NULL) {
1290                 isc_socket_detach(&query->sock);
1291                 sockcount--;
1292                 debug("sockcount=%d", sockcount);
1293         }
1294         isc_mempool_put(commctx, query->recvspace);
1295         isc_buffer_invalidate(&query->recvbuf);
1296         isc_buffer_invalidate(&query->lengthbuf);
1297         if (query->waiting_senddone)
1298                 query->pending_free = ISC_TRUE;
1299         else
1300                 isc_mem_free(mctx, query);
1301 }
1302
1303 /*%
1304  * Try and clear out a lookup if we're done with it.  Return ISC_TRUE if
1305  * the lookup was successfully cleared.  If ISC_TRUE is returned, the
1306  * lookup pointer has been invalidated.
1307  */
1308 static isc_boolean_t
1309 try_clear_lookup(dig_lookup_t *lookup) {
1310         dig_query_t *q;
1311
1312         REQUIRE(lookup != NULL);
1313
1314         debug("try_clear_lookup(%p)", lookup);
1315
1316         if (ISC_LIST_HEAD(lookup->q) != NULL) {
1317                 if (debugging) {
1318                         q = ISC_LIST_HEAD(lookup->q);
1319                         while (q != NULL) {
1320                                 debug("query to %s still pending", q->servname);
1321                                 q = ISC_LIST_NEXT(q, link);
1322                         }
1323                 }
1324                 return (ISC_FALSE);
1325         }
1326
1327         /*
1328          * At this point, we know there are no queries on the lookup,
1329          * so can make it go away also.
1330          */
1331         destroy_lookup(lookup);
1332         return (ISC_TRUE);
1333 }
1334
1335 void
1336 destroy_lookup(dig_lookup_t *lookup) {
1337         dig_server_t *s;
1338         void *ptr;
1339
1340         debug("destroy");
1341         s = ISC_LIST_HEAD(lookup->my_server_list);
1342         while (s != NULL) {
1343                 debug("freeing server %p belonging to %p", s, lookup);
1344                 ptr = s;
1345                 s = ISC_LIST_NEXT(s, link);
1346                 ISC_LIST_DEQUEUE(lookup->my_server_list,
1347                                  (dig_server_t *)ptr, link);
1348                 isc_mem_free(mctx, ptr);
1349         }
1350         if (lookup->sendmsg != NULL)
1351                 dns_message_destroy(&lookup->sendmsg);
1352         if (lookup->querysig != NULL) {
1353                 debug("freeing buffer %p", lookup->querysig);
1354                 isc_buffer_free(&lookup->querysig);
1355         }
1356         if (lookup->timer != NULL)
1357                 isc_timer_detach(&lookup->timer);
1358         if (lookup->sendspace != NULL)
1359                 isc_mempool_put(commctx, lookup->sendspace);
1360
1361         if (lookup->tsigctx != NULL)
1362                 dst_context_destroy(&lookup->tsigctx);
1363
1364         isc_mem_free(mctx, lookup);
1365 }
1366
1367 /*%
1368  * If we can, start the next lookup in the queue running.
1369  * This assumes that the lookup on the head of the queue hasn't been
1370  * started yet.  It also removes the lookup from the head of the queue,
1371  * setting the current_lookup pointer pointing to it.
1372  */
1373 void
1374 start_lookup(void) {
1375         debug("start_lookup()");
1376         if (cancel_now)
1377                 return;
1378
1379         /*
1380          * If there's a current lookup running, we really shouldn't get
1381          * here.
1382          */
1383         INSIST(current_lookup == NULL);
1384
1385         current_lookup = ISC_LIST_HEAD(lookup_list);
1386         /*
1387          * Put the current lookup somewhere so cancel_all can find it
1388          */
1389         if (current_lookup != NULL) {
1390                 ISC_LIST_DEQUEUE(lookup_list, current_lookup, link);
1391 #if DIG_SIGCHASE_TD
1392                 if (current_lookup->do_topdown &&
1393                     !current_lookup->rdtype_sigchaseset) {
1394                         dst_key_t *trustedkey = NULL;
1395                         isc_buffer_t *b = NULL;
1396                         isc_region_t r;
1397                         isc_result_t result;
1398                         dns_name_t query_name;
1399                         dns_name_t *key_name;
1400                         int i;
1401
1402                         result = get_trusted_key(mctx);
1403                         if (result != ISC_R_SUCCESS) {
1404                                 printf("\n;; No trusted key, "
1405                                        "+sigchase option is disabled\n");
1406                                 current_lookup->sigchase = ISC_FALSE;
1407                                 goto novalidation;
1408                         }
1409                         dns_name_init(&query_name, NULL);
1410                         nameFromString(current_lookup->textname, &query_name);
1411
1412                         for (i = 0; i < tk_list.nb_tk; i++) {
1413                                 key_name = dst_key_name(tk_list.key[i]);
1414
1415                                 if (dns_name_issubdomain(&query_name,
1416                                                          key_name) == ISC_TRUE)
1417                                         trustedkey = tk_list.key[i];
1418                                 /*
1419                                  * Verify temp is really the lowest
1420                                  * WARNING
1421                                  */
1422                         }
1423                         if (trustedkey == NULL) {
1424                                 printf("\n;; The queried zone: ");
1425                                 dns_name_print(&query_name, stdout);
1426                                 printf(" isn't a subdomain of any Trusted Keys"
1427                                        ": +sigchase option is disable\n");
1428                                 current_lookup->sigchase = ISC_FALSE;
1429                                 free_name(&query_name, mctx);
1430                                 goto novalidation;
1431                         }
1432                         free_name(&query_name, mctx);
1433
1434                         current_lookup->rdtype_sigchase
1435                                 = current_lookup->rdtype;
1436                         current_lookup->rdtype_sigchaseset
1437                                 = current_lookup->rdtypeset;
1438                         current_lookup->rdtype = dns_rdatatype_ns;
1439
1440                         current_lookup->qrdtype_sigchase
1441                                 = current_lookup->qrdtype;
1442                         current_lookup->qrdtype = dns_rdatatype_ns;
1443
1444                         current_lookup->rdclass_sigchase
1445                                 = current_lookup->rdclass;
1446                         current_lookup->rdclass_sigchaseset
1447                                 = current_lookup->rdclassset;
1448                         current_lookup->rdclass = dns_rdataclass_in;
1449
1450                         strncpy(current_lookup->textnamesigchase,
1451                                 current_lookup->textname, MXNAME);
1452
1453                         current_lookup->trace_root_sigchase = ISC_TRUE;
1454
1455                         result = isc_buffer_allocate(mctx, &b, BUFSIZE);
1456                         check_result(result, "isc_buffer_allocate");
1457                         result = dns_name_totext(dst_key_name(trustedkey),
1458                                                  ISC_FALSE, b);
1459                         check_result(result, "dns_name_totext");
1460                         isc_buffer_usedregion(b, &r);
1461                         r.base[r.length] = '\0';
1462                         strncpy(current_lookup->textname, (char*)r.base,
1463                                 MXNAME);
1464                         isc_buffer_free(&b);
1465
1466                         nameFromString(current_lookup->textnamesigchase,
1467                                        &chase_name);
1468
1469                         dns_name_init(&chase_authority_name, NULL);
1470                 }
1471         novalidation:
1472 #endif
1473                 setup_lookup(current_lookup);
1474                 do_lookup(current_lookup);
1475         } else {
1476                 check_if_done();
1477         }
1478 }
1479
1480 /*%
1481  * If we can, clear the current lookup and start the next one running.
1482  * This calls try_clear_lookup, so may invalidate the lookup pointer.
1483  */
1484 static void
1485 check_next_lookup(dig_lookup_t *lookup) {
1486
1487         INSIST(!free_now);
1488
1489         debug("check_next_lookup(%p)", lookup);
1490
1491         if (ISC_LIST_HEAD(lookup->q) != NULL) {
1492                 debug("still have a worker");
1493                 return;
1494         }
1495         if (try_clear_lookup(lookup)) {
1496                 current_lookup = NULL;
1497                 start_lookup();
1498         }
1499 }
1500
1501 /*%
1502  * Create and queue a new lookup as a followup to the current lookup,
1503  * based on the supplied message and section.  This is used in trace and
1504  * name server search modes to start a new lookup using servers from
1505  * NS records in a reply. Returns the number of followup lookups made.
1506  */
1507 static int
1508 followup_lookup(dns_message_t *msg, dig_query_t *query, dns_section_t section)
1509 {
1510         dig_lookup_t *lookup = NULL;
1511         dig_server_t *srv = NULL;
1512         dns_rdataset_t *rdataset = NULL;
1513         dns_rdata_t rdata = DNS_RDATA_INIT;
1514         dns_name_t *name = NULL;
1515         isc_result_t result;
1516         isc_boolean_t success = ISC_FALSE;
1517         int numLookups = 0;
1518         dns_name_t *domain;
1519         isc_boolean_t horizontal = ISC_FALSE, bad = ISC_FALSE;
1520
1521         INSIST(!free_now);
1522
1523         debug("following up %s", query->lookup->textname);
1524
1525         for (result = dns_message_firstname(msg, section);
1526              result == ISC_R_SUCCESS;
1527              result = dns_message_nextname(msg, section)) {
1528                 name = NULL;
1529                 dns_message_currentname(msg, section, &name);
1530
1531                 if (section == DNS_SECTION_AUTHORITY) {
1532                         rdataset = NULL;
1533                         result = dns_message_findtype(name, dns_rdatatype_soa,
1534                                                       0, &rdataset);
1535                         if (result == ISC_R_SUCCESS)
1536                                 return (0);
1537                 }
1538                 rdataset = NULL;
1539                 result = dns_message_findtype(name, dns_rdatatype_ns, 0,
1540                                               &rdataset);
1541                 if (result != ISC_R_SUCCESS)
1542                         continue;
1543
1544                 debug("found NS set");
1545
1546                 if (query->lookup->trace && !query->lookup->trace_root) {
1547                         dns_namereln_t namereln;
1548                         unsigned int nlabels;
1549                         int order;
1550
1551                         domain = dns_fixedname_name(&query->lookup->fdomain);
1552                         namereln = dns_name_fullcompare(name, domain,
1553                                                         &order, &nlabels);
1554                         if (namereln == dns_namereln_equal) {
1555                                 if (!horizontal)
1556                                         printf(";; BAD (HORIZONTAL) REFERRAL\n");
1557                                 horizontal = ISC_TRUE;
1558                         } else if (namereln != dns_namereln_subdomain) {
1559                                 if (!bad)
1560                                         printf(";; BAD REFERRAL\n");
1561                                 bad = ISC_TRUE;
1562                                 continue;
1563                         }
1564                 }
1565
1566                 for (result = dns_rdataset_first(rdataset);
1567                      result == ISC_R_SUCCESS;
1568                      result = dns_rdataset_next(rdataset)) {
1569                         char namestr[DNS_NAME_FORMATSIZE];
1570                         dns_rdata_ns_t ns;
1571
1572                         if (query->lookup->trace_root &&
1573                             query->lookup->nsfound >= MXSERV)
1574                                 break;
1575
1576                         dns_rdataset_current(rdataset, &rdata);
1577
1578                         query->lookup->nsfound++;
1579                         result = dns_rdata_tostruct(&rdata, &ns, NULL);
1580                         check_result(result, "dns_rdata_tostruct");
1581                         dns_name_format(&ns.name, namestr, sizeof(namestr));
1582                         dns_rdata_freestruct(&ns);
1583
1584                         /* Initialize lookup if we've not yet */
1585                         debug("found NS %d %s", numLookups, namestr);
1586                         numLookups++;
1587                         if (!success) {
1588                                 success = ISC_TRUE;
1589                                 lookup_counter++;
1590                                 lookup = requeue_lookup(query->lookup,
1591                                                         ISC_FALSE);
1592                                 cancel_lookup(query->lookup);
1593                                 lookup->doing_xfr = ISC_FALSE;
1594                                 if (!lookup->trace_root &&
1595                                     section == DNS_SECTION_ANSWER)
1596                                         lookup->trace = ISC_FALSE;
1597                                 else
1598                                         lookup->trace = query->lookup->trace;
1599                                 lookup->ns_search_only =
1600                                         query->lookup->ns_search_only;
1601                                 lookup->trace_root = ISC_FALSE;
1602                                 if (lookup->ns_search_only)
1603                                         lookup->recurse = ISC_FALSE;
1604                                 dns_fixedname_init(&lookup->fdomain);
1605                                 domain = dns_fixedname_name(&lookup->fdomain);
1606                                 dns_name_copy(name, domain, NULL);
1607                         }
1608                         srv = make_server(namestr, namestr);
1609                         debug("adding server %s", srv->servername);
1610                         ISC_LIST_APPEND(lookup->my_server_list, srv, link);
1611                         dns_rdata_reset(&rdata);
1612                 }
1613         }
1614
1615         if (lookup == NULL &&
1616             section == DNS_SECTION_ANSWER &&
1617             (query->lookup->trace || query->lookup->ns_search_only))
1618                 return (followup_lookup(msg, query, DNS_SECTION_AUTHORITY));
1619
1620         /*
1621          * Randomize the order the nameserver will be tried.
1622          */
1623         if (numLookups > 1) {
1624                 isc_uint32_t i, j;
1625                 dig_serverlist_t my_server_list;
1626
1627                 ISC_LIST_INIT(my_server_list);
1628
1629                 for (i = numLookups; i > 0; i--) {
1630                         isc_random_get(&j);
1631                         j %= i;
1632                         srv = ISC_LIST_HEAD(lookup->my_server_list);
1633                         while (j-- > 0)
1634                                 srv = ISC_LIST_NEXT(srv, link);
1635                         ISC_LIST_DEQUEUE(lookup->my_server_list, srv, link);
1636                         ISC_LIST_APPEND(my_server_list, srv, link);
1637                 }
1638                 ISC_LIST_APPENDLIST(lookup->my_server_list,
1639                                     my_server_list, link);
1640         }
1641
1642         return (numLookups);
1643 }
1644
1645 /*%
1646  * Create and queue a new lookup using the next origin from the search
1647  * list, read in setup_system().
1648  *
1649  * Return ISC_TRUE iff there was another searchlist entry.
1650  */
1651 static isc_boolean_t
1652 next_origin(dns_message_t *msg, dig_query_t *query) {
1653         dig_lookup_t *lookup;
1654         dig_searchlist_t *search;
1655
1656         UNUSED(msg);
1657
1658         INSIST(!free_now);
1659
1660         debug("next_origin()");
1661         debug("following up %s", query->lookup->textname);
1662
1663         if (!usesearch)
1664                 /*
1665                  * We're not using a search list, so don't even think
1666                  * about finding the next entry.
1667                  */
1668                 return (ISC_FALSE);
1669         if (query->lookup->origin == NULL && !query->lookup->need_search)
1670                 /*
1671                  * Then we just did rootorg; there's nothing left.
1672                  */
1673                 return (ISC_FALSE);
1674         if (query->lookup->origin == NULL && query->lookup->need_search) {
1675                 lookup = requeue_lookup(query->lookup, ISC_TRUE);
1676                 lookup->origin = ISC_LIST_HEAD(search_list);
1677                 lookup->need_search = ISC_FALSE;
1678         } else {
1679                 search = ISC_LIST_NEXT(query->lookup->origin, link);
1680                 if (search == NULL && query->lookup->done_as_is)
1681                         return (ISC_FALSE);
1682                 lookup = requeue_lookup(query->lookup, ISC_TRUE);
1683                 lookup->origin = search;
1684         }
1685         cancel_lookup(query->lookup);
1686         return (ISC_TRUE);
1687 }
1688
1689 /*%
1690  * Insert an SOA record into the sendmessage in a lookup.  Used for
1691  * creating IXFR queries.
1692  */
1693 static void
1694 insert_soa(dig_lookup_t *lookup) {
1695         isc_result_t result;
1696         dns_rdata_soa_t soa;
1697         dns_rdata_t *rdata = NULL;
1698         dns_rdatalist_t *rdatalist = NULL;
1699         dns_rdataset_t *rdataset = NULL;
1700         dns_name_t *soaname = NULL;
1701
1702         debug("insert_soa()");
1703         soa.mctx = mctx;
1704         soa.serial = lookup->ixfr_serial;
1705         soa.refresh = 0;
1706         soa.retry = 0;
1707         soa.expire = 0;
1708         soa.minimum = 0;
1709         soa.common.rdclass = lookup->rdclass;
1710         soa.common.rdtype = dns_rdatatype_soa;
1711
1712         dns_name_init(&soa.origin, NULL);
1713         dns_name_init(&soa.contact, NULL);
1714
1715         dns_name_clone(dns_rootname, &soa.origin);
1716         dns_name_clone(dns_rootname, &soa.contact);
1717
1718         isc_buffer_init(&lookup->rdatabuf, lookup->rdatastore,
1719                         sizeof(lookup->rdatastore));
1720
1721         result = dns_message_gettemprdata(lookup->sendmsg, &rdata);
1722         check_result(result, "dns_message_gettemprdata");
1723
1724         result = dns_rdata_fromstruct(rdata, lookup->rdclass,
1725                                       dns_rdatatype_soa, &soa,
1726                                       &lookup->rdatabuf);
1727         check_result(result, "isc_rdata_fromstruct");
1728
1729         result = dns_message_gettemprdatalist(lookup->sendmsg, &rdatalist);
1730         check_result(result, "dns_message_gettemprdatalist");
1731
1732         result = dns_message_gettemprdataset(lookup->sendmsg, &rdataset);
1733         check_result(result, "dns_message_gettemprdataset");
1734
1735         dns_rdatalist_init(rdatalist);
1736         rdatalist->type = dns_rdatatype_soa;
1737         rdatalist->rdclass = lookup->rdclass;
1738         rdatalist->covers = 0;
1739         rdatalist->ttl = 0;
1740         ISC_LIST_INIT(rdatalist->rdata);
1741         ISC_LIST_APPEND(rdatalist->rdata, rdata, link);
1742
1743         dns_rdataset_init(rdataset);
1744         dns_rdatalist_tordataset(rdatalist, rdataset);
1745
1746         result = dns_message_gettempname(lookup->sendmsg, &soaname);
1747         check_result(result, "dns_message_gettempname");
1748         dns_name_init(soaname, NULL);
1749         dns_name_clone(lookup->name, soaname);
1750         ISC_LIST_INIT(soaname->list);
1751         ISC_LIST_APPEND(soaname->list, rdataset, link);
1752         dns_message_addname(lookup->sendmsg, soaname, DNS_SECTION_AUTHORITY);
1753 }
1754
1755 /*%
1756  * Setup the supplied lookup structure, making it ready to start sending
1757  * queries to servers.  Create and initialize the message to be sent as
1758  * well as the query structures and buffer space for the replies.  If the
1759  * server list is empty, clone it from the system default list.
1760  */
1761 void
1762 setup_lookup(dig_lookup_t *lookup) {
1763         isc_result_t result;
1764         isc_uint32_t id;
1765         int len;
1766         dig_server_t *serv;
1767         dig_query_t *query;
1768         isc_buffer_t b;
1769         dns_compress_t cctx;
1770         char store[MXNAME];
1771 #ifdef WITH_IDN
1772         idn_result_t mr;
1773         char utf8_textname[MXNAME], utf8_origin[MXNAME], idn_textname[MXNAME];
1774 #endif
1775
1776 #ifdef WITH_IDN
1777         result = dns_name_settotextfilter(output_filter);
1778         check_result(result, "dns_name_settotextfilter");
1779 #endif
1780
1781         REQUIRE(lookup != NULL);
1782         INSIST(!free_now);
1783
1784         debug("setup_lookup(%p)", lookup);
1785
1786         result = dns_message_create(mctx, DNS_MESSAGE_INTENTRENDER,
1787                                     &lookup->sendmsg);
1788         check_result(result, "dns_message_create");
1789
1790         if (lookup->new_search) {
1791                 debug("resetting lookup counter.");
1792                 lookup_counter = 0;
1793         }
1794
1795         if (ISC_LIST_EMPTY(lookup->my_server_list)) {
1796                 debug("cloning server list");
1797                 clone_server_list(server_list, &lookup->my_server_list);
1798         }
1799         result = dns_message_gettempname(lookup->sendmsg, &lookup->name);
1800         check_result(result, "dns_message_gettempname");
1801         dns_name_init(lookup->name, NULL);
1802
1803         isc_buffer_init(&lookup->namebuf, lookup->namespace,
1804                         sizeof(lookup->namespace));
1805         isc_buffer_init(&lookup->onamebuf, lookup->onamespace,
1806                         sizeof(lookup->onamespace));
1807
1808 #ifdef WITH_IDN
1809         /*
1810          * We cannot convert `textname' and `origin' separately.
1811          * `textname' doesn't contain TLD, but local mapping needs
1812          * TLD.
1813          */
1814         mr = idn_encodename(IDN_LOCALCONV | IDN_DELIMMAP, lookup->textname,
1815                             utf8_textname, sizeof(utf8_textname));
1816         idn_check_result(mr, "convert textname to UTF-8");
1817 #endif
1818
1819         /*
1820          * If the name has too many dots, force the origin to be NULL
1821          * (which produces an absolute lookup).  Otherwise, take the origin
1822          * we have if there's one in the struct already.  If it's NULL,
1823          * take the first entry in the searchlist iff either usesearch
1824          * is TRUE or we got a domain line in the resolv.conf file.
1825          */
1826         if (lookup->new_search) {
1827 #ifdef WITH_IDN
1828                 if ((count_dots(utf8_textname) >= ndots) || !usesearch) {
1829                         lookup->origin = NULL; /* Force abs lookup */
1830                         lookup->done_as_is = ISC_TRUE;
1831                         lookup->need_search = usesearch;
1832                 } else if (lookup->origin == NULL && usesearch) {
1833                         lookup->origin = ISC_LIST_HEAD(search_list);
1834                         lookup->need_search = ISC_FALSE;
1835                 }
1836 #else
1837                 if ((count_dots(lookup->textname) >= ndots) || !usesearch) {
1838                         lookup->origin = NULL; /* Force abs lookup */
1839                         lookup->done_as_is = ISC_TRUE;
1840                         lookup->need_search = usesearch;
1841                 } else if (lookup->origin == NULL && usesearch) {
1842                         lookup->origin = ISC_LIST_HEAD(search_list);
1843                         lookup->need_search = ISC_FALSE;
1844                 }
1845 #endif
1846         }
1847
1848 #ifdef WITH_IDN
1849         if (lookup->origin != NULL) {
1850                 mr = idn_encodename(IDN_LOCALCONV | IDN_DELIMMAP,
1851                                     lookup->origin->origin, utf8_origin,
1852                                     sizeof(utf8_origin));
1853                 idn_check_result(mr, "convert origin to UTF-8");
1854                 mr = append_textname(utf8_textname, utf8_origin,
1855                                      sizeof(utf8_textname));
1856                 idn_check_result(mr, "append origin to textname");
1857         }
1858         mr = idn_encodename(idnoptions | IDN_LOCALMAP | IDN_NAMEPREP |
1859                             IDN_IDNCONV | IDN_LENCHECK, utf8_textname,
1860                             idn_textname, sizeof(idn_textname));
1861         idn_check_result(mr, "convert UTF-8 textname to IDN encoding");
1862 #else
1863         if (lookup->origin != NULL) {
1864                 debug("trying origin %s", lookup->origin->origin);
1865                 result = dns_message_gettempname(lookup->sendmsg,
1866                                                  &lookup->oname);
1867                 check_result(result, "dns_message_gettempname");
1868                 dns_name_init(lookup->oname, NULL);
1869                 /* XXX Helper funct to conv char* to name? */
1870                 len = strlen(lookup->origin->origin);
1871                 isc_buffer_init(&b, lookup->origin->origin, len);
1872                 isc_buffer_add(&b, len);
1873                 result = dns_name_fromtext(lookup->oname, &b, dns_rootname,
1874                                            ISC_FALSE, &lookup->onamebuf);
1875                 if (result != ISC_R_SUCCESS) {
1876                         dns_message_puttempname(lookup->sendmsg,
1877                                                 &lookup->name);
1878                         dns_message_puttempname(lookup->sendmsg,
1879                                                 &lookup->oname);
1880                         fatal("'%s' is not in legal name syntax (%s)",
1881                               lookup->origin->origin,
1882                               isc_result_totext(result));
1883                 }
1884                 if (lookup->trace && lookup->trace_root) {
1885                         dns_name_clone(dns_rootname, lookup->name);
1886                 } else {
1887                         len = strlen(lookup->textname);
1888                         isc_buffer_init(&b, lookup->textname, len);
1889                         isc_buffer_add(&b, len);
1890                         result = dns_name_fromtext(lookup->name, &b,
1891                                                    lookup->oname, ISC_FALSE,
1892                                                    &lookup->namebuf);
1893                 }
1894                 if (result != ISC_R_SUCCESS) {
1895                         dns_message_puttempname(lookup->sendmsg,
1896                                                 &lookup->name);
1897                         dns_message_puttempname(lookup->sendmsg,
1898                                                 &lookup->oname);
1899                         fatal("'%s' is not in legal name syntax (%s)",
1900                               lookup->textname, isc_result_totext(result));
1901                 }
1902                 dns_message_puttempname(lookup->sendmsg, &lookup->oname);
1903         } else
1904 #endif
1905         {
1906                 debug("using root origin");
1907                 if (lookup->trace && lookup->trace_root)
1908                         dns_name_clone(dns_rootname, lookup->name);
1909                 else {
1910 #ifdef WITH_IDN
1911                         len = strlen(idn_textname);
1912                         isc_buffer_init(&b, idn_textname, len);
1913                         isc_buffer_add(&b, len);
1914                         result = dns_name_fromtext(lookup->name, &b,
1915                                                    dns_rootname,
1916                                                    ISC_FALSE,
1917                                                    &lookup->namebuf);
1918 #else
1919                         len = strlen(lookup->textname);
1920                         isc_buffer_init(&b, lookup->textname, len);
1921                         isc_buffer_add(&b, len);
1922                         result = dns_name_fromtext(lookup->name, &b,
1923                                                    dns_rootname,
1924                                                    ISC_FALSE,
1925                                                    &lookup->namebuf);
1926 #endif
1927                 }
1928                 if (result != ISC_R_SUCCESS) {
1929                         dns_message_puttempname(lookup->sendmsg,
1930                                                 &lookup->name);
1931                         isc_buffer_init(&b, store, MXNAME);
1932                         fatal("'%s' is not a legal name "
1933                               "(%s)", lookup->textname,
1934                               isc_result_totext(result));
1935                 }
1936         }
1937         dns_name_format(lookup->name, store, sizeof(store));
1938         trying(store, lookup);
1939         INSIST(dns_name_isabsolute(lookup->name));
1940
1941         isc_random_get(&id);
1942         lookup->sendmsg->id = (unsigned short)id & 0xFFFF;
1943         lookup->sendmsg->opcode = dns_opcode_query;
1944         lookup->msgcounter = 0;
1945         /*
1946          * If this is a trace request, completely disallow recursion, since
1947          * it's meaningless for traces.
1948          */
1949         if (lookup->trace || (lookup->ns_search_only && !lookup->trace_root))
1950                 lookup->recurse = ISC_FALSE;
1951
1952         if (lookup->recurse &&
1953             lookup->rdtype != dns_rdatatype_axfr &&
1954             lookup->rdtype != dns_rdatatype_ixfr) {
1955                 debug("recursive query");
1956                 lookup->sendmsg->flags |= DNS_MESSAGEFLAG_RD;
1957         }
1958
1959         /* XXX aaflag */
1960         if (lookup->aaonly) {
1961                 debug("AA query");
1962                 lookup->sendmsg->flags |= DNS_MESSAGEFLAG_AA;
1963         }
1964
1965         if (lookup->adflag) {
1966                 debug("AD query");
1967                 lookup->sendmsg->flags |= DNS_MESSAGEFLAG_AD;
1968         }
1969
1970         if (lookup->cdflag) {
1971                 debug("CD query");
1972                 lookup->sendmsg->flags |= DNS_MESSAGEFLAG_CD;
1973         }
1974
1975         dns_message_addname(lookup->sendmsg, lookup->name,
1976                             DNS_SECTION_QUESTION);
1977
1978         if (lookup->trace && lookup->trace_root) {
1979                 lookup->qrdtype = lookup->rdtype;
1980                 lookup->rdtype = dns_rdatatype_ns;
1981         }
1982
1983         if ((lookup->rdtype == dns_rdatatype_axfr) ||
1984             (lookup->rdtype == dns_rdatatype_ixfr)) {
1985                 /*
1986                  * Force TCP mode if we're doing an axfr.
1987                  */
1988                 if (lookup->rdtype == dns_rdatatype_axfr) {
1989                         lookup->doing_xfr = ISC_TRUE;
1990                         lookup->tcp_mode = ISC_TRUE;
1991                 } else if (lookup->tcp_mode) {
1992                         lookup->doing_xfr = ISC_TRUE;
1993                 }
1994         }
1995
1996         add_question(lookup->sendmsg, lookup->name, lookup->rdclass,
1997                      lookup->rdtype);
1998
1999         /* add_soa */
2000         if (lookup->rdtype == dns_rdatatype_ixfr)
2001                 insert_soa(lookup);
2002
2003         /* XXX Insist this? */
2004         lookup->tsigctx = NULL;
2005         lookup->querysig = NULL;
2006         if (key != NULL) {
2007                 debug("initializing keys");
2008                 result = dns_message_settsigkey(lookup->sendmsg, key);
2009                 check_result(result, "dns_message_settsigkey");
2010         }
2011
2012         lookup->sendspace = isc_mempool_get(commctx);
2013         if (lookup->sendspace == NULL)
2014                 fatal("memory allocation failure");
2015
2016         result = dns_compress_init(&cctx, -1, mctx);
2017         check_result(result, "dns_compress_init");
2018
2019         debug("starting to render the message");
2020         isc_buffer_init(&lookup->renderbuf, lookup->sendspace, COMMSIZE);
2021         result = dns_message_renderbegin(lookup->sendmsg, &cctx,
2022                                          &lookup->renderbuf);
2023         check_result(result, "dns_message_renderbegin");
2024         if (lookup->udpsize > 0 || lookup->dnssec || lookup->edns > -1) {
2025                 if (lookup->udpsize == 0)
2026                         lookup->udpsize = 4096;
2027                 if (lookup->edns < 0)
2028                         lookup->edns = 0;
2029                 add_opt(lookup->sendmsg, lookup->udpsize,
2030                         lookup->edns, lookup->dnssec, lookup->nsid);
2031         }
2032
2033         result = dns_message_rendersection(lookup->sendmsg,
2034                                            DNS_SECTION_QUESTION, 0);
2035         check_result(result, "dns_message_rendersection");
2036         result = dns_message_rendersection(lookup->sendmsg,
2037                                            DNS_SECTION_AUTHORITY, 0);
2038         check_result(result, "dns_message_rendersection");
2039         result = dns_message_renderend(lookup->sendmsg);
2040         check_result(result, "dns_message_renderend");
2041         debug("done rendering");
2042
2043         dns_compress_invalidate(&cctx);
2044
2045         /*
2046          * Force TCP mode if the request is larger than 512 bytes.
2047          */
2048         if (isc_buffer_usedlength(&lookup->renderbuf) > 512)
2049                 lookup->tcp_mode = ISC_TRUE;
2050
2051         lookup->pending = ISC_FALSE;
2052
2053         for (serv = ISC_LIST_HEAD(lookup->my_server_list);
2054              serv != NULL;
2055              serv = ISC_LIST_NEXT(serv, link)) {
2056                 query = isc_mem_allocate(mctx, sizeof(dig_query_t));
2057                 if (query == NULL)
2058                         fatal("memory allocation failure in %s:%d",
2059                               __FILE__, __LINE__);
2060                 debug("create query %p linked to lookup %p",
2061                        query, lookup);
2062                 query->lookup = lookup;
2063                 query->waiting_connect = ISC_FALSE;
2064                 query->waiting_senddone = ISC_FALSE;
2065                 query->pending_free = ISC_FALSE;
2066                 query->recv_made = ISC_FALSE;
2067                 query->first_pass = ISC_TRUE;
2068                 query->first_soa_rcvd = ISC_FALSE;
2069                 query->second_rr_rcvd = ISC_FALSE;
2070                 query->first_repeat_rcvd = ISC_FALSE;
2071                 query->warn_id = ISC_TRUE;
2072                 query->first_rr_serial = 0;
2073                 query->second_rr_serial = 0;
2074                 query->servname = serv->servername;
2075                 query->userarg = serv->userarg;
2076                 query->rr_count = 0;
2077                 query->msg_count = 0;
2078                 query->byte_count = 0;
2079                 ISC_LINK_INIT(query, link);
2080                 ISC_LIST_INIT(query->recvlist);
2081                 ISC_LIST_INIT(query->lengthlist);
2082                 query->sock = NULL;
2083                 query->recvspace = isc_mempool_get(commctx);
2084                 if (query->recvspace == NULL)
2085                         fatal("memory allocation failure");
2086
2087                 isc_buffer_init(&query->recvbuf, query->recvspace, COMMSIZE);
2088                 isc_buffer_init(&query->lengthbuf, query->lengthspace, 2);
2089                 isc_buffer_init(&query->slbuf, query->slspace, 2);
2090                 query->sendbuf = lookup->renderbuf;
2091
2092                 ISC_LINK_INIT(query, link);
2093                 ISC_LIST_ENQUEUE(lookup->q, query, link);
2094         }
2095         /* XXX qrflag, print_query, etc... */
2096         if (!ISC_LIST_EMPTY(lookup->q) && qr) {
2097                 extrabytes = 0;
2098                 printmessage(ISC_LIST_HEAD(lookup->q), lookup->sendmsg,
2099                              ISC_TRUE);
2100         }
2101 }
2102
2103 /*%
2104  * Event handler for send completion.  Track send counter, and clear out
2105  * the query if the send was canceled.
2106  */
2107 static void
2108 send_done(isc_task_t *_task, isc_event_t *event) {
2109         isc_socketevent_t *sevent = (isc_socketevent_t *)event;
2110         isc_buffer_t *b = NULL;
2111         dig_query_t *query, *next;
2112         dig_lookup_t *l;
2113
2114         REQUIRE(event->ev_type == ISC_SOCKEVENT_SENDDONE);
2115
2116         UNUSED(_task);
2117
2118         LOCK_LOOKUP;
2119
2120         debug("send_done()");
2121         sendcount--;
2122         debug("sendcount=%d", sendcount);
2123         INSIST(sendcount >= 0);
2124
2125         for  (b = ISC_LIST_HEAD(sevent->bufferlist);
2126               b != NULL;
2127               b = ISC_LIST_HEAD(sevent->bufferlist))
2128                 ISC_LIST_DEQUEUE(sevent->bufferlist, b, link);
2129
2130         query = event->ev_arg;
2131         query->waiting_senddone = ISC_FALSE;
2132         l = query->lookup;
2133
2134         if (l->ns_search_only && !l->trace_root) {
2135                 debug("sending next, since searching");
2136                 next = ISC_LIST_NEXT(query, link);
2137                 if (next != NULL)
2138                         send_udp(next);
2139         }
2140
2141         isc_event_free(&event);
2142
2143         if (query->pending_free)
2144                 isc_mem_free(mctx, query);
2145
2146         check_if_done();
2147         UNLOCK_LOOKUP;
2148 }
2149
2150 /*%
2151  * Cancel a lookup, sending isc_socket_cancel() requests to all outstanding
2152  * IO sockets.  The cancel handlers should take care of cleaning up the
2153  * query and lookup structures
2154  */
2155 static void
2156 cancel_lookup(dig_lookup_t *lookup) {
2157         dig_query_t *query, *next;
2158
2159         debug("cancel_lookup()");
2160         query = ISC_LIST_HEAD(lookup->q);
2161         while (query != NULL) {
2162                 next = ISC_LIST_NEXT(query, link);
2163                 if (query->sock != NULL) {
2164                         isc_socket_cancel(query->sock, global_task,
2165                                           ISC_SOCKCANCEL_ALL);
2166                         check_if_done();
2167                 } else {
2168                         clear_query(query);
2169                 }
2170                 query = next;
2171         }
2172         if (lookup->timer != NULL)
2173                 isc_timer_detach(&lookup->timer);
2174         lookup->pending = ISC_FALSE;
2175         lookup->retries = 0;
2176 }
2177
2178 static void
2179 bringup_timer(dig_query_t *query, unsigned int default_timeout) {
2180         dig_lookup_t *l;
2181         unsigned int local_timeout;
2182         isc_result_t result;
2183
2184         debug("bringup_timer()");
2185         /*
2186          * If the timer already exists, that means we're calling this
2187          * a second time (for a retry).  Don't need to recreate it,
2188          * just reset it.
2189          */
2190         l = query->lookup;
2191         if (ISC_LIST_NEXT(query, link) != NULL)
2192                 local_timeout = SERVER_TIMEOUT;
2193         else {
2194                 if (timeout == 0)
2195                         local_timeout = default_timeout;
2196                 else
2197                         local_timeout = timeout;
2198         }
2199         debug("have local timeout of %d", local_timeout);
2200         isc_interval_set(&l->interval, local_timeout, 0);
2201         if (l->timer != NULL)
2202                 isc_timer_detach(&l->timer);
2203         result = isc_timer_create(timermgr, isc_timertype_once, NULL,
2204                                   &l->interval, global_task, connect_timeout,
2205                                   l, &l->timer);
2206         check_result(result, "isc_timer_create");
2207 }
2208
2209 static void
2210 force_timeout(dig_lookup_t *l, dig_query_t *query) {
2211         isc_event_t *event;
2212
2213         event = isc_event_allocate(mctx, query, ISC_TIMEREVENT_IDLE,
2214                                    connect_timeout, l,
2215                                    sizeof(isc_event_t));
2216         if (event == NULL) {
2217                 fatal("isc_event_allocate: %s",
2218                       isc_result_totext(ISC_R_NOMEMORY));
2219         }
2220         isc_task_send(global_task, &event);
2221 }
2222
2223
2224 static void
2225 connect_done(isc_task_t *task, isc_event_t *event);
2226
2227 /*%
2228  * Unlike send_udp, this can't be called multiple times with the same
2229  * query.  When we retry TCP, we requeue the whole lookup, which should
2230  * start anew.
2231  */
2232 static void
2233 send_tcp_connect(dig_query_t *query) {
2234         isc_result_t result;
2235         dig_query_t *next;
2236         dig_lookup_t *l;
2237
2238         debug("send_tcp_connect(%p)", query);
2239
2240         l = query->lookup;
2241         query->waiting_connect = ISC_TRUE;
2242         query->lookup->current_query = query;
2243         result = get_address(query->servname, port, &query->sockaddr);
2244         if (result == ISC_R_NOTFOUND) {
2245                 /*
2246                  * This servname doesn't have an address.  Try the next server
2247                  * by triggering an immediate 'timeout' (we lie, but the effect
2248                  * is the same).
2249                  */
2250                 force_timeout(l, query);
2251                 return;
2252         }
2253
2254         if (specified_source &&
2255             (isc_sockaddr_pf(&query->sockaddr) !=
2256              isc_sockaddr_pf(&bind_address))) {
2257                 printf(";; Skipping server %s, incompatible "
2258                        "address family\n", query->servname);
2259                 query->waiting_connect = ISC_FALSE;
2260                 next = ISC_LIST_NEXT(query, link);
2261                 l = query->lookup;
2262                 clear_query(query);
2263                 if (next == NULL) {
2264                         printf(";; No acceptable nameservers\n");
2265                         check_next_lookup(l);
2266                         return;
2267                 }
2268                 send_tcp_connect(next);
2269                 return;
2270         }
2271         INSIST(query->sock == NULL);
2272         result = isc_socket_create(socketmgr,
2273                                    isc_sockaddr_pf(&query->sockaddr),
2274                                    isc_sockettype_tcp, &query->sock);
2275         check_result(result, "isc_socket_create");
2276         sockcount++;
2277         debug("sockcount=%d", sockcount);
2278         if (specified_source)
2279                 result = isc_socket_bind(query->sock, &bind_address,
2280                                          ISC_SOCKET_REUSEADDRESS);
2281         else {
2282                 if ((isc_sockaddr_pf(&query->sockaddr) == AF_INET) &&
2283                     have_ipv4)
2284                         isc_sockaddr_any(&bind_any);
2285                 else
2286                         isc_sockaddr_any6(&bind_any);
2287                 result = isc_socket_bind(query->sock, &bind_any, 0);
2288         }
2289         check_result(result, "isc_socket_bind");
2290         bringup_timer(query, TCP_TIMEOUT);
2291         result = isc_socket_connect(query->sock, &query->sockaddr,
2292                                     global_task, connect_done, query);
2293         check_result(result, "isc_socket_connect");
2294         /*
2295          * If we're at the endgame of a nameserver search, we need to
2296          * immediately bring up all the queries.  Do it here.
2297          */
2298         if (l->ns_search_only && !l->trace_root) {
2299                 debug("sending next, since searching");
2300                 next = ISC_LIST_NEXT(query, link);
2301                 if (next != NULL)
2302                         send_tcp_connect(next);
2303         }
2304 }
2305
2306 /*%
2307  * Send a UDP packet to the remote nameserver, possible starting the
2308  * recv action as well.  Also make sure that the timer is running and
2309  * is properly reset.
2310  */
2311 static void
2312 send_udp(dig_query_t *query) {
2313         dig_lookup_t *l = NULL;
2314         isc_result_t result;
2315
2316         debug("send_udp(%p)", query);
2317
2318         l = query->lookup;
2319         bringup_timer(query, UDP_TIMEOUT);
2320         l->current_query = query;
2321         debug("working on lookup %p, query %p", query->lookup, query);
2322         if (!query->recv_made) {
2323                 /* XXX Check the sense of this, need assertion? */
2324                 query->waiting_connect = ISC_FALSE;
2325                 result = get_address(query->servname, port, &query->sockaddr);
2326                 if (result == ISC_R_NOTFOUND) {
2327                         /* This servname doesn't have an address. */
2328                         force_timeout(l, query);
2329                         return;
2330                 }
2331
2332                 result = isc_socket_create(socketmgr,
2333                                            isc_sockaddr_pf(&query->sockaddr),
2334                                            isc_sockettype_udp, &query->sock);
2335                 check_result(result, "isc_socket_create");
2336                 sockcount++;
2337                 debug("sockcount=%d", sockcount);
2338                 if (specified_source) {
2339                         result = isc_socket_bind(query->sock, &bind_address,
2340                                                  ISC_SOCKET_REUSEADDRESS);
2341                 } else {
2342                         isc_sockaddr_anyofpf(&bind_any,
2343                                         isc_sockaddr_pf(&query->sockaddr));
2344                         result = isc_socket_bind(query->sock, &bind_any, 0);
2345                 }
2346                 check_result(result, "isc_socket_bind");
2347
2348                 query->recv_made = ISC_TRUE;
2349                 ISC_LINK_INIT(&query->recvbuf, link);
2350                 ISC_LIST_ENQUEUE(query->recvlist, &query->recvbuf,
2351                                  link);
2352                 debug("recving with lookup=%p, query=%p, sock=%p",
2353                       query->lookup, query, query->sock);
2354                 result = isc_socket_recvv(query->sock, &query->recvlist, 1,
2355                                           global_task, recv_done, query);
2356                 check_result(result, "isc_socket_recvv");
2357                 recvcount++;
2358                 debug("recvcount=%d", recvcount);
2359         }
2360         ISC_LIST_INIT(query->sendlist);
2361         ISC_LIST_ENQUEUE(query->sendlist, &query->sendbuf, link);
2362         debug("sending a request");
2363         TIME_NOW(&query->time_sent);
2364         INSIST(query->sock != NULL);
2365         query->waiting_senddone = ISC_TRUE;
2366         result = isc_socket_sendtov(query->sock, &query->sendlist,
2367                                     global_task, send_done, query,
2368                                     &query->sockaddr, NULL);
2369         check_result(result, "isc_socket_sendtov");
2370         sendcount++;
2371 }
2372
2373 /*%
2374  * IO timeout handler, used for both connect and recv timeouts.  If
2375  * retries are still allowed, either resend the UDP packet or queue a
2376  * new TCP lookup.  Otherwise, cancel the lookup.
2377  */
2378 static void
2379 connect_timeout(isc_task_t *task, isc_event_t *event) {
2380         dig_lookup_t *l = NULL;
2381         dig_query_t *query = NULL, *cq;
2382
2383         UNUSED(task);
2384         REQUIRE(event->ev_type == ISC_TIMEREVENT_IDLE);
2385
2386         debug("connect_timeout()");
2387
2388         LOCK_LOOKUP;
2389         l = event->ev_arg;
2390         query = l->current_query;
2391         isc_event_free(&event);
2392
2393         INSIST(!free_now);
2394
2395         if ((query != NULL) && (query->lookup->current_query != NULL) &&
2396             (ISC_LIST_NEXT(query->lookup->current_query, link) != NULL)) {
2397                 debug("trying next server...");
2398                 cq = query->lookup->current_query;
2399                 if (!l->tcp_mode)
2400                         send_udp(ISC_LIST_NEXT(cq, link));
2401                 else {
2402                         isc_socket_cancel(query->sock, NULL,
2403                                           ISC_SOCKCANCEL_ALL);
2404                         isc_socket_detach(&query->sock);
2405                         sockcount--;
2406                         debug("sockcount=%d", sockcount);
2407                         send_tcp_connect(ISC_LIST_NEXT(cq, link));
2408                 }
2409                 UNLOCK_LOOKUP;
2410                 return;
2411         }
2412
2413         if (l->retries > 1) {
2414                 if (!l->tcp_mode) {
2415                         l->retries--;
2416                         debug("resending UDP request to first server");
2417                         send_udp(ISC_LIST_HEAD(l->q));
2418                 } else {
2419                         debug("making new TCP request, %d tries left",
2420                               l->retries);
2421                         l->retries--;
2422                         requeue_lookup(l, ISC_TRUE);
2423                         cancel_lookup(l);
2424                         check_next_lookup(l);
2425                 }
2426         } else {
2427                 fputs(l->cmdline, stdout);
2428                 printf(";; connection timed out; no servers could be "
2429                        "reached\n");
2430                 cancel_lookup(l);
2431                 check_next_lookup(l);
2432                 if (exitcode < 9)
2433                         exitcode = 9;
2434         }
2435         UNLOCK_LOOKUP;
2436 }
2437
2438 /*%
2439  * Event handler for the TCP recv which gets the length header of TCP
2440  * packets.  Start the next recv of length bytes.
2441  */
2442 static void
2443 tcp_length_done(isc_task_t *task, isc_event_t *event) {
2444         isc_socketevent_t *sevent;
2445         isc_buffer_t *b = NULL;
2446         isc_result_t result;
2447         dig_query_t *query = NULL;
2448         dig_lookup_t *l;
2449         isc_uint16_t length;
2450
2451         REQUIRE(event->ev_type == ISC_SOCKEVENT_RECVDONE);
2452         INSIST(!free_now);
2453
2454         UNUSED(task);
2455
2456         debug("tcp_length_done()");
2457
2458         LOCK_LOOKUP;
2459         sevent = (isc_socketevent_t *)event;
2460         query = event->ev_arg;
2461
2462         recvcount--;
2463         INSIST(recvcount >= 0);
2464
2465         b = ISC_LIST_HEAD(sevent->bufferlist);
2466         INSIST(b ==  &query->lengthbuf);
2467         ISC_LIST_DEQUEUE(sevent->bufferlist, b, link);
2468
2469         if (sevent->result == ISC_R_CANCELED) {
2470                 isc_event_free(&event);
2471                 l = query->lookup;
2472                 clear_query(query);
2473                 check_next_lookup(l);
2474                 UNLOCK_LOOKUP;
2475                 return;
2476         }
2477         if (sevent->result != ISC_R_SUCCESS) {
2478                 char sockstr[ISC_SOCKADDR_FORMATSIZE];
2479                 isc_sockaddr_format(&query->sockaddr, sockstr,
2480                                     sizeof(sockstr));
2481                 printf(";; communications error to %s: %s\n",
2482                        sockstr, isc_result_totext(sevent->result));
2483                 l = query->lookup;
2484                 isc_socket_detach(&query->sock);
2485                 sockcount--;
2486                 debug("sockcount=%d", sockcount);
2487                 INSIST(sockcount >= 0);
2488                 isc_event_free(&event);
2489                 clear_query(query);
2490                 check_next_lookup(l);
2491                 UNLOCK_LOOKUP;
2492                 return;
2493         }
2494         length = isc_buffer_getuint16(b);
2495         if (length == 0) {
2496                 isc_event_free(&event);
2497                 launch_next_query(query, ISC_FALSE);
2498                 UNLOCK_LOOKUP;
2499                 return;
2500         }
2501
2502         /*
2503          * Even though the buffer was already init'ed, we need
2504          * to redo it now, to force the length we want.
2505          */
2506         isc_buffer_invalidate(&query->recvbuf);
2507         isc_buffer_init(&query->recvbuf, query->recvspace, length);
2508         ENSURE(ISC_LIST_EMPTY(query->recvlist));
2509         ISC_LINK_INIT(&query->recvbuf, link);
2510         ISC_LIST_ENQUEUE(query->recvlist, &query->recvbuf, link);
2511         debug("recving with lookup=%p, query=%p", query->lookup, query);
2512         result = isc_socket_recvv(query->sock, &query->recvlist, length, task,
2513                                   recv_done, query);
2514         check_result(result, "isc_socket_recvv");
2515         recvcount++;
2516         debug("resubmitted recv request with length %d, recvcount=%d",
2517               length, recvcount);
2518         isc_event_free(&event);
2519         UNLOCK_LOOKUP;
2520 }
2521
2522 /*%
2523  * For transfers that involve multiple recvs (XFR's in particular),
2524  * launch the next recv.
2525  */
2526 static void
2527 launch_next_query(dig_query_t *query, isc_boolean_t include_question) {
2528         isc_result_t result;
2529         dig_lookup_t *l;
2530
2531         INSIST(!free_now);
2532
2533         debug("launch_next_query()");
2534
2535         if (!query->lookup->pending) {
2536                 debug("ignoring launch_next_query because !pending");
2537                 isc_socket_detach(&query->sock);
2538                 sockcount--;
2539                 debug("sockcount=%d", sockcount);
2540                 INSIST(sockcount >= 0);
2541                 query->waiting_connect = ISC_FALSE;
2542                 l = query->lookup;
2543                 clear_query(query);
2544                 check_next_lookup(l);
2545                 return;
2546         }
2547
2548         isc_buffer_clear(&query->slbuf);
2549         isc_buffer_clear(&query->lengthbuf);
2550         isc_buffer_putuint16(&query->slbuf, (isc_uint16_t) query->sendbuf.used);
2551         ISC_LIST_INIT(query->sendlist);
2552         ISC_LINK_INIT(&query->slbuf, link);
2553         ISC_LIST_ENQUEUE(query->sendlist, &query->slbuf, link);
2554         if (include_question)
2555                 ISC_LIST_ENQUEUE(query->sendlist, &query->sendbuf, link);
2556         ISC_LINK_INIT(&query->lengthbuf, link);
2557         ISC_LIST_ENQUEUE(query->lengthlist, &query->lengthbuf, link);
2558
2559         result = isc_socket_recvv(query->sock, &query->lengthlist, 0,
2560                                   global_task, tcp_length_done, query);
2561         check_result(result, "isc_socket_recvv");
2562         recvcount++;
2563         debug("recvcount=%d", recvcount);
2564         if (!query->first_soa_rcvd) {
2565                 debug("sending a request in launch_next_query");
2566                 TIME_NOW(&query->time_sent);
2567                 query->waiting_senddone = ISC_TRUE;
2568                 result = isc_socket_sendv(query->sock, &query->sendlist,
2569                                           global_task, send_done, query);
2570                 check_result(result, "isc_socket_sendv");
2571                 sendcount++;
2572                 debug("sendcount=%d", sendcount);
2573         }
2574         query->waiting_connect = ISC_FALSE;
2575 #if 0
2576         check_next_lookup(query->lookup);
2577 #endif
2578         return;
2579 }
2580
2581 /*%
2582  * Event handler for TCP connect complete.  Make sure the connection was
2583  * successful, then pass into launch_next_query to actually send the
2584  * question.
2585  */
2586 static void
2587 connect_done(isc_task_t *task, isc_event_t *event) {
2588         isc_socketevent_t *sevent = NULL;
2589         dig_query_t *query = NULL, *next;
2590         dig_lookup_t *l;
2591
2592         UNUSED(task);
2593
2594         REQUIRE(event->ev_type == ISC_SOCKEVENT_CONNECT);
2595         INSIST(!free_now);
2596
2597         debug("connect_done()");
2598
2599         LOCK_LOOKUP;
2600         sevent = (isc_socketevent_t *)event;
2601         query = sevent->ev_arg;
2602
2603         INSIST(query->waiting_connect);
2604
2605         query->waiting_connect = ISC_FALSE;
2606
2607         if (sevent->result == ISC_R_CANCELED) {
2608                 debug("in cancel handler");
2609                 isc_socket_detach(&query->sock);
2610                 sockcount--;
2611                 INSIST(sockcount >= 0);
2612                 debug("sockcount=%d", sockcount);
2613                 query->waiting_connect = ISC_FALSE;
2614                 isc_event_free(&event);
2615                 l = query->lookup;
2616                 clear_query(query);
2617                 check_next_lookup(l);
2618                 UNLOCK_LOOKUP;
2619                 return;
2620         }
2621         if (sevent->result != ISC_R_SUCCESS) {
2622                 char sockstr[ISC_SOCKADDR_FORMATSIZE];
2623
2624                 debug("unsuccessful connection: %s",
2625                       isc_result_totext(sevent->result));
2626                 isc_sockaddr_format(&query->sockaddr, sockstr, sizeof(sockstr));
2627                 if (sevent->result != ISC_R_CANCELED)
2628                         printf(";; Connection to %s(%s) for %s failed: "
2629                                "%s.\n", sockstr,
2630                                query->servname, query->lookup->textname,
2631                                isc_result_totext(sevent->result));
2632                 isc_socket_detach(&query->sock);
2633                 sockcount--;
2634                 INSIST(sockcount >= 0);
2635                 /* XXX Clean up exitcodes */
2636                 if (exitcode < 9)
2637                         exitcode = 9;
2638                 debug("sockcount=%d", sockcount);
2639                 query->waiting_connect = ISC_FALSE;
2640                 isc_event_free(&event);
2641                 l = query->lookup;
2642                 if (l->current_query != NULL)
2643                         next = ISC_LIST_NEXT(l->current_query, link);
2644                 else
2645                         next = NULL;
2646                 clear_query(query);
2647                 if (next != NULL) {
2648                         bringup_timer(next, TCP_TIMEOUT);
2649                         send_tcp_connect(next);
2650                 } else {
2651                         check_next_lookup(l);
2652                 }
2653                 UNLOCK_LOOKUP;
2654                 return;
2655         }
2656         launch_next_query(query, ISC_TRUE);
2657         isc_event_free(&event);
2658         UNLOCK_LOOKUP;
2659 }
2660
2661 /*%
2662  * Check if the ongoing XFR needs more data before it's complete, using
2663  * the semantics of IXFR and AXFR protocols.  Much of the complexity of
2664  * this routine comes from determining when an IXFR is complete.
2665  * ISC_FALSE means more data is on the way, and the recv has been issued.
2666  */
2667 static isc_boolean_t
2668 check_for_more_data(dig_query_t *query, dns_message_t *msg,
2669                     isc_socketevent_t *sevent)
2670 {
2671         dns_rdataset_t *rdataset = NULL;
2672         dns_rdata_t rdata = DNS_RDATA_INIT;
2673         dns_rdata_soa_t soa;
2674         isc_uint32_t serial;
2675         isc_result_t result;
2676
2677         debug("check_for_more_data()");
2678
2679         /*
2680          * By the time we're in this routine, we know we're doing
2681          * either an AXFR or IXFR.  If there's no second_rr_type,
2682          * then we don't yet know which kind of answer we got back
2683          * from the server.  Here, we're going to walk through the
2684          * rr's in the message, acting as necessary whenever we hit
2685          * an SOA rr.
2686          */
2687
2688         query->msg_count++;
2689         query->byte_count += sevent->n;
2690         result = dns_message_firstname(msg, DNS_SECTION_ANSWER);
2691         if (result != ISC_R_SUCCESS) {
2692                 puts("; Transfer failed.");
2693                 return (ISC_TRUE);
2694         }
2695         do {
2696                 dns_name_t *name;
2697                 name = NULL;
2698                 dns_message_currentname(msg, DNS_SECTION_ANSWER,
2699                                         &name);
2700                 for (rdataset = ISC_LIST_HEAD(name->list);
2701                      rdataset != NULL;
2702                      rdataset = ISC_LIST_NEXT(rdataset, link)) {
2703                         result = dns_rdataset_first(rdataset);
2704                         if (result != ISC_R_SUCCESS)
2705                                 continue;
2706                         do {
2707                                 query->rr_count++;
2708                                 dns_rdata_reset(&rdata);
2709                                 dns_rdataset_current(rdataset, &rdata);
2710                                 /*
2711                                  * If this is the first rr, make sure
2712                                  * it's an SOA
2713                                  */
2714                                 if ((!query->first_soa_rcvd) &&
2715                                     (rdata.type != dns_rdatatype_soa)) {
2716                                         puts("; Transfer failed.  "
2717                                              "Didn't start with SOA answer.");
2718                                         return (ISC_TRUE);
2719                                 }
2720                                 if ((!query->second_rr_rcvd) &&
2721                                     (rdata.type != dns_rdatatype_soa)) {
2722                                         query->second_rr_rcvd = ISC_TRUE;
2723                                         query->second_rr_serial = 0;
2724                                         debug("got the second rr as nonsoa");
2725                                         goto next_rdata;
2726                                 }
2727
2728                                 /*
2729                                  * If the record is anything except an SOA
2730                                  * now, just continue on...
2731                                  */
2732                                 if (rdata.type != dns_rdatatype_soa)
2733                                         goto next_rdata;
2734                                 /* Now we have an SOA.  Work with it. */
2735                                 debug("got an SOA");
2736                                 result = dns_rdata_tostruct(&rdata, &soa, NULL);
2737                                 check_result(result, "dns_rdata_tostruct");
2738                                 serial = soa.serial;
2739                                 dns_rdata_freestruct(&soa);
2740                                 if (!query->first_soa_rcvd) {
2741                                         query->first_soa_rcvd = ISC_TRUE;
2742                                         query->first_rr_serial = serial;
2743                                         debug("this is the first %d",
2744                                                query->lookup->ixfr_serial);
2745                                         if (query->lookup->ixfr_serial >=
2746                                             serial)
2747                                                 goto doexit;
2748                                         goto next_rdata;
2749                                 }
2750                                 if (query->lookup->rdtype ==
2751                                     dns_rdatatype_axfr) {
2752                                         debug("doing axfr, got second SOA");
2753                                         goto doexit;
2754                                 }
2755                                 if (!query->second_rr_rcvd) {
2756                                         if (query->first_rr_serial == serial) {
2757                                                 debug("doing ixfr, got "
2758                                                       "empty zone");
2759                                                 goto doexit;
2760                                         }
2761                                         debug("this is the second %d",
2762                                                query->lookup->ixfr_serial);
2763                                         query->second_rr_rcvd = ISC_TRUE;
2764                                         query->second_rr_serial = serial;
2765                                         goto next_rdata;
2766                                 }
2767                                 if (query->second_rr_serial == 0) {
2768                                         /*
2769                                          * If the second RR was a non-SOA
2770                                          * record, and we're getting any
2771                                          * other SOA, then this is an
2772                                          * AXFR, and we're done.
2773                                          */
2774                                         debug("done, since axfr");
2775                                         goto doexit;
2776                                 }
2777                                 /*
2778                                  * If we get to this point, we're doing an
2779                                  * IXFR and have to start really looking
2780                                  * at serial numbers.
2781                                  */
2782                                 if (query->first_rr_serial == serial) {
2783                                         debug("got a match for ixfr");
2784                                         if (!query->first_repeat_rcvd) {
2785                                                 query->first_repeat_rcvd =
2786                                                         ISC_TRUE;
2787                                                 goto next_rdata;
2788                                         }
2789                                         debug("done with ixfr");
2790                                         goto doexit;
2791                                 }
2792                                 debug("meaningless soa %d", serial);
2793                         next_rdata:
2794                                 result = dns_rdataset_next(rdataset);
2795                         } while (result == ISC_R_SUCCESS);
2796                 }
2797                 result = dns_message_nextname(msg, DNS_SECTION_ANSWER);
2798         } while (result == ISC_R_SUCCESS);
2799         launch_next_query(query, ISC_FALSE);
2800         return (ISC_FALSE);
2801  doexit:
2802         received(sevent->n, &sevent->address, query);
2803         return (ISC_TRUE);
2804 }
2805
2806 /*%
2807  * Event handler for recv complete.  Perform whatever actions are necessary,
2808  * based on the specifics of the user's request.
2809  */
2810 static void
2811 recv_done(isc_task_t *task, isc_event_t *event) {
2812         isc_socketevent_t *sevent = NULL;
2813         dig_query_t *query = NULL;
2814         isc_buffer_t *b = NULL;
2815         dns_message_t *msg = NULL;
2816 #ifdef DIG_SIGCHASE
2817         dig_message_t *chase_msg = NULL;
2818         dig_message_t *chase_msg2 = NULL;
2819 #endif
2820         isc_result_t result;
2821         dig_lookup_t *n, *l;
2822         isc_boolean_t docancel = ISC_FALSE;
2823         isc_boolean_t match = ISC_TRUE;
2824         unsigned int parseflags;
2825         dns_messageid_t id;
2826         unsigned int msgflags;
2827 #ifdef DIG_SIGCHASE
2828         isc_result_t do_sigchase = ISC_FALSE;
2829
2830         dns_message_t *msg_temp = NULL;
2831         isc_region_t r;
2832         isc_buffer_t *buf = NULL;
2833 #endif
2834
2835         UNUSED(task);
2836         INSIST(!free_now);
2837
2838         debug("recv_done()");
2839
2840         LOCK_LOOKUP;
2841         recvcount--;
2842         debug("recvcount=%d", recvcount);
2843         INSIST(recvcount >= 0);
2844
2845         query = event->ev_arg;
2846         debug("lookup=%p, query=%p", query->lookup, query);
2847
2848         l = query->lookup;
2849
2850         REQUIRE(event->ev_type == ISC_SOCKEVENT_RECVDONE);
2851         sevent = (isc_socketevent_t *)event;
2852
2853         b = ISC_LIST_HEAD(sevent->bufferlist);
2854         INSIST(b == &query->recvbuf);
2855         ISC_LIST_DEQUEUE(sevent->bufferlist, &query->recvbuf, link);
2856
2857         if ((l->tcp_mode) && (l->timer != NULL))
2858                 isc_timer_touch(l->timer);
2859         if ((!l->pending && !l->ns_search_only) || cancel_now) {
2860                 debug("no longer pending.  Got %s",
2861                         isc_result_totext(sevent->result));
2862                 query->waiting_connect = ISC_FALSE;
2863
2864                 isc_event_free(&event);
2865                 clear_query(query);
2866                 check_next_lookup(l);
2867                 UNLOCK_LOOKUP;
2868                 return;
2869         }
2870
2871         if (sevent->result != ISC_R_SUCCESS) {
2872                 if (sevent->result == ISC_R_CANCELED) {
2873                         debug("in recv cancel handler");
2874                         query->waiting_connect = ISC_FALSE;
2875                 } else {
2876                         printf(";; communications error: %s\n",
2877                                isc_result_totext(sevent->result));
2878                         isc_socket_detach(&query->sock);
2879                         sockcount--;
2880                         debug("sockcount=%d", sockcount);
2881                         INSIST(sockcount >= 0);
2882                 }
2883                 isc_event_free(&event);
2884                 clear_query(query);
2885                 check_next_lookup(l);
2886                 UNLOCK_LOOKUP;
2887                 return;
2888         }
2889
2890         if (!l->tcp_mode &&
2891             !isc_sockaddr_compare(&sevent->address, &query->sockaddr,
2892                                   ISC_SOCKADDR_CMPADDR|
2893                                   ISC_SOCKADDR_CMPPORT|
2894                                   ISC_SOCKADDR_CMPSCOPE|
2895                                   ISC_SOCKADDR_CMPSCOPEZERO)) {
2896                 char buf1[ISC_SOCKADDR_FORMATSIZE];
2897                 char buf2[ISC_SOCKADDR_FORMATSIZE];
2898                 isc_sockaddr_t any;
2899
2900                 if (isc_sockaddr_pf(&query->sockaddr) == AF_INET)
2901                         isc_sockaddr_any(&any);
2902                 else
2903                         isc_sockaddr_any6(&any);
2904
2905                 /*
2906                 * We don't expect a match when the packet is
2907                 * sent to 0.0.0.0, :: or to a multicast addresses.
2908                 * XXXMPA broadcast needs to be handled here as well.
2909                 */
2910                 if ((!isc_sockaddr_eqaddr(&query->sockaddr, &any) &&
2911                      !isc_sockaddr_ismulticast(&query->sockaddr)) ||
2912                     isc_sockaddr_getport(&query->sockaddr) !=
2913                     isc_sockaddr_getport(&sevent->address)) {
2914                         isc_sockaddr_format(&sevent->address, buf1,
2915                         sizeof(buf1));
2916                         isc_sockaddr_format(&query->sockaddr, buf2,
2917                         sizeof(buf2));
2918                         printf(";; reply from unexpected source: %s,"
2919                         " expected %s\n", buf1, buf2);
2920                         match = ISC_FALSE;
2921                 }
2922         }
2923
2924         result = dns_message_peekheader(b, &id, &msgflags);
2925         if (result != ISC_R_SUCCESS || l->sendmsg->id != id) {
2926                 match = ISC_FALSE;
2927                 if (l->tcp_mode) {
2928                         isc_boolean_t fail = ISC_TRUE;
2929                         if (result == ISC_R_SUCCESS) {
2930                                 if (!query->first_soa_rcvd ||
2931                                      query->warn_id)
2932                                         printf(";; %s: ID mismatch: "
2933                                                "expected ID %u, got %u\n",
2934                                                query->first_soa_rcvd ?
2935                                                "WARNING" : "ERROR",
2936                                                l->sendmsg->id, id);
2937                                 if (query->first_soa_rcvd)
2938                                         fail = ISC_FALSE;
2939                                 query->warn_id = ISC_FALSE;
2940                         } else
2941                                 printf(";; ERROR: short "
2942                                        "(< header size) message\n");
2943                         if (fail) {
2944                                 isc_event_free(&event);
2945                                 clear_query(query);
2946                                 check_next_lookup(l);
2947                                 UNLOCK_LOOKUP;
2948                                 return;
2949                         }
2950                         match = ISC_TRUE;
2951                 } else if (result == ISC_R_SUCCESS)
2952                         printf(";; Warning: ID mismatch: "
2953                                "expected ID %u, got %u\n", l->sendmsg->id, id);
2954                 else
2955                         printf(";; Warning: short "
2956                                "(< header size) message received\n");
2957         }
2958
2959         if (result == ISC_R_SUCCESS && (msgflags & DNS_MESSAGEFLAG_QR) == 0)
2960                 printf(";; Warning: query response not set\n");
2961
2962         if (!match)
2963                 goto udp_mismatch;
2964
2965         result = dns_message_create(mctx, DNS_MESSAGE_INTENTPARSE, &msg);
2966         check_result(result, "dns_message_create");
2967
2968         if (key != NULL) {
2969                 if (l->querysig == NULL) {
2970                         debug("getting initial querysig");
2971                         result = dns_message_getquerytsig(l->sendmsg, mctx,
2972                                                           &l->querysig);
2973                         check_result(result, "dns_message_getquerytsig");
2974                 }
2975                 result = dns_message_setquerytsig(msg, l->querysig);
2976                 check_result(result, "dns_message_setquerytsig");
2977                 result = dns_message_settsigkey(msg, key);
2978                 check_result(result, "dns_message_settsigkey");
2979                 msg->tsigctx = l->tsigctx;
2980                 l->tsigctx = NULL;
2981                 if (l->msgcounter != 0)
2982                         msg->tcp_continuation = 1;
2983                 l->msgcounter++;
2984         }
2985
2986         debug("before parse starts");
2987         parseflags = DNS_MESSAGEPARSE_PRESERVEORDER;
2988 #ifdef DIG_SIGCHASE
2989         if (!l->sigchase) {
2990                 do_sigchase = ISC_FALSE;
2991         } else {
2992                 parseflags = 0;
2993                 do_sigchase = ISC_TRUE;
2994         }
2995 #endif
2996         if (l->besteffort) {
2997                 parseflags |= DNS_MESSAGEPARSE_BESTEFFORT;
2998                 parseflags |= DNS_MESSAGEPARSE_IGNORETRUNCATION;
2999         }
3000         result = dns_message_parse(msg, b, parseflags);
3001         if (result == DNS_R_RECOVERABLE) {
3002                 printf(";; Warning: Message parser reports malformed "
3003                        "message packet.\n");
3004                 result = ISC_R_SUCCESS;
3005         }
3006         if (result != ISC_R_SUCCESS) {
3007                 printf(";; Got bad packet: %s\n", isc_result_totext(result));
3008                 hex_dump(b);
3009                 query->waiting_connect = ISC_FALSE;
3010                 dns_message_destroy(&msg);
3011                 isc_event_free(&event);
3012                 clear_query(query);
3013                 cancel_lookup(l);
3014                 check_next_lookup(l);
3015                 UNLOCK_LOOKUP;
3016                 return;
3017         }
3018         if (msg->counts[DNS_SECTION_QUESTION] != 0) {
3019                 match = ISC_TRUE;
3020                 for (result = dns_message_firstname(msg, DNS_SECTION_QUESTION);
3021                      result == ISC_R_SUCCESS && match;
3022                      result = dns_message_nextname(msg, DNS_SECTION_QUESTION)) {
3023                         dns_name_t *name = NULL;
3024                         dns_rdataset_t *rdataset;
3025
3026                         dns_message_currentname(msg, DNS_SECTION_QUESTION,
3027                                                 &name);
3028                         for (rdataset = ISC_LIST_HEAD(name->list);
3029                              rdataset != NULL;
3030                              rdataset = ISC_LIST_NEXT(rdataset, link)) {
3031                                 if (l->rdtype != rdataset->type ||
3032                                     l->rdclass != rdataset->rdclass ||
3033                                     !dns_name_equal(l->name, name)) {
3034                                         char namestr[DNS_NAME_FORMATSIZE];
3035                                         char typebuf[DNS_RDATATYPE_FORMATSIZE];
3036                                         char classbuf[DNS_RDATACLASS_FORMATSIZE];
3037                                         dns_name_format(name, namestr,
3038                                                         sizeof(namestr));
3039                                         dns_rdatatype_format(rdataset->type,
3040                                                              typebuf,
3041                                                              sizeof(typebuf));
3042                                         dns_rdataclass_format(rdataset->rdclass,
3043                                                               classbuf,
3044                                                               sizeof(classbuf));
3045                                         printf(";; Question section mismatch: "
3046                                                "got %s/%s/%s\n",
3047                                                namestr, typebuf, classbuf);
3048                                         match = ISC_FALSE;
3049                                 }
3050                         }
3051                 }
3052                 if (!match) {
3053                         dns_message_destroy(&msg);
3054                         if (l->tcp_mode) {
3055                                 isc_event_free(&event);
3056                                 clear_query(query);
3057                                 check_next_lookup(l);
3058                                 UNLOCK_LOOKUP;
3059                                 return;
3060                         } else
3061                                 goto udp_mismatch;
3062                 }
3063         }
3064         if ((msg->flags & DNS_MESSAGEFLAG_TC) != 0 &&
3065             !l->ignore && !l->tcp_mode) {
3066                 printf(";; Truncated, retrying in TCP mode.\n");
3067                 n = requeue_lookup(l, ISC_TRUE);
3068                 n->tcp_mode = ISC_TRUE;
3069                 n->origin = query->lookup->origin;
3070                 dns_message_destroy(&msg);
3071                 isc_event_free(&event);
3072                 clear_query(query);
3073                 cancel_lookup(l);
3074                 check_next_lookup(l);
3075                 UNLOCK_LOOKUP;
3076                 return;
3077         }
3078         if ((msg->rcode == dns_rcode_servfail && !l->servfail_stops) ||
3079             (check_ra && (msg->flags & DNS_MESSAGEFLAG_RA) == 0 && l->recurse))
3080         {
3081                 dig_query_t *next = ISC_LIST_NEXT(query, link);
3082                 if (l->current_query == query)
3083                         l->current_query = NULL;
3084                 if (next != NULL) {
3085                         debug("sending query %p\n", next);
3086                         if (l->tcp_mode)
3087                                 send_tcp_connect(next);
3088                         else
3089                                 send_udp(next);
3090                 }
3091                 /*
3092                  * If our query is at the head of the list and there
3093                  * is no next, we're the only one left, so fall
3094                  * through to print the message.
3095                  */
3096                 if ((ISC_LIST_HEAD(l->q) != query) ||
3097                     (ISC_LIST_NEXT(query, link) != NULL)) {
3098                         if( l->comments == ISC_TRUE )
3099                                 printf(";; Got %s from %s, "
3100                                        "trying next server\n",
3101                                        msg->rcode == dns_rcode_servfail ?
3102                                        "SERVFAIL reply" :
3103                                        "recursion not available",
3104                                        query->servname);
3105                         clear_query(query);
3106                         check_next_lookup(l);
3107                         dns_message_destroy(&msg);
3108                         isc_event_free(&event);
3109                         UNLOCK_LOOKUP;
3110                         return;
3111                 }
3112         }
3113
3114         if (key != NULL) {
3115                 result = dns_tsig_verify(&query->recvbuf, msg, NULL, NULL);
3116                 if (result != ISC_R_SUCCESS) {
3117                         printf(";; Couldn't verify signature: %s\n",
3118                                isc_result_totext(result));
3119                         validated = ISC_FALSE;
3120                 }
3121                 l->tsigctx = msg->tsigctx;
3122                 msg->tsigctx = NULL;
3123                 if (l->querysig != NULL) {
3124                         debug("freeing querysig buffer %p", l->querysig);
3125                         isc_buffer_free(&l->querysig);
3126                 }
3127                 result = dns_message_getquerytsig(msg, mctx, &l->querysig);
3128                 check_result(result,"dns_message_getquerytsig");
3129         }
3130
3131         extrabytes = isc_buffer_remaininglength(b);
3132
3133         debug("after parse");
3134         if (l->doing_xfr && l->xfr_q == NULL) {
3135                 l->xfr_q = query;
3136                 /*
3137                  * Once we are in the XFR message, increase
3138                  * the timeout to much longer, so brief network
3139                  * outages won't cause the XFR to abort
3140                  */
3141                 if (timeout != INT_MAX && l->timer != NULL) {
3142                         unsigned int local_timeout;
3143
3144                         if (timeout == 0) {
3145                                 if (l->tcp_mode)
3146                                         local_timeout = TCP_TIMEOUT * 4;
3147                                 else
3148                                         local_timeout = UDP_TIMEOUT * 4;
3149                         } else {
3150                                 if (timeout < (INT_MAX / 4))
3151                                         local_timeout = timeout * 4;
3152                                 else
3153                                         local_timeout = INT_MAX;
3154                         }
3155                         debug("have local timeout of %d", local_timeout);
3156                         isc_interval_set(&l->interval, local_timeout, 0);
3157                         result = isc_timer_reset(l->timer,
3158                                                  isc_timertype_once,
3159                                                  NULL,
3160                                                  &l->interval,
3161                                                  ISC_FALSE);
3162                         check_result(result, "isc_timer_reset");
3163                 }
3164         }
3165
3166         if (!l->doing_xfr || l->xfr_q == query) {
3167                 if (msg->rcode != dns_rcode_noerror &&
3168                     (l->origin != NULL || l->need_search)) {
3169                         if (!next_origin(msg, query) || showsearch) {
3170                                 printmessage(query, msg, ISC_TRUE);
3171                                 received(b->used, &sevent->address, query);
3172                         }
3173                 } else if (!l->trace && !l->ns_search_only) {
3174 #ifdef DIG_SIGCHASE
3175                         if (!do_sigchase)
3176 #endif
3177                                 printmessage(query, msg, ISC_TRUE);
3178                 } else if (l->trace) {
3179                         int n = 0;
3180                         int count = msg->counts[DNS_SECTION_ANSWER];
3181
3182                         debug("in TRACE code");
3183                         if (!l->ns_search_only)
3184                                 printmessage(query, msg, ISC_TRUE);
3185
3186                         l->rdtype = l->qrdtype;
3187                         if (l->trace_root || (l->ns_search_only && count > 0)) {
3188                                 if (!l->trace_root)
3189                                         l->rdtype = dns_rdatatype_soa;
3190                                 n = followup_lookup(msg, query,
3191                                                     DNS_SECTION_ANSWER);
3192                                 l->trace_root = ISC_FALSE;
3193                         } else if (count == 0)
3194                                 n = followup_lookup(msg, query,
3195                                                     DNS_SECTION_AUTHORITY);
3196                         if (n == 0)
3197                                 docancel = ISC_TRUE;
3198                 } else {
3199                         debug("in NSSEARCH code");
3200
3201                         if (l->trace_root) {
3202                                 /*
3203                                  * This is the initial NS query.
3204                                  */
3205                                 int n;
3206
3207                                 l->rdtype = dns_rdatatype_soa;
3208                                 n = followup_lookup(msg, query,
3209                                                     DNS_SECTION_ANSWER);
3210                                 if (n == 0)
3211                                         docancel = ISC_TRUE;
3212                                 l->trace_root = ISC_FALSE;
3213                         } else
3214 #ifdef DIG_SIGCHASE
3215                                 if (!do_sigchase)
3216 #endif
3217                                 printmessage(query, msg, ISC_TRUE);
3218                 }
3219 #ifdef DIG_SIGCHASE
3220                 if (do_sigchase) {
3221                         chase_msg = isc_mem_allocate(mctx,
3222                                                      sizeof(dig_message_t));
3223                         if (chase_msg == NULL) {
3224                                 fatal("Memory allocation failure in %s:%d",
3225                                       __FILE__, __LINE__);
3226                         }
3227                         ISC_LIST_INITANDAPPEND(chase_message_list, chase_msg,
3228                                                link);
3229                         if (dns_message_create(mctx, DNS_MESSAGE_INTENTPARSE,
3230                                                &msg_temp) != ISC_R_SUCCESS) {
3231                                 fatal("dns_message_create in %s:%d",
3232                                       __FILE__, __LINE__);
3233                         }
3234
3235                         isc_buffer_usedregion(b, &r);
3236                         result = isc_buffer_allocate(mctx, &buf, r.length);
3237
3238                         check_result(result, "isc_buffer_allocate");
3239                         result =  isc_buffer_copyregion(buf, &r);
3240                         check_result(result, "isc_buffer_copyregion");
3241
3242                         result =  dns_message_parse(msg_temp, buf, 0);
3243
3244                         isc_buffer_free(&buf);
3245                         chase_msg->msg = msg_temp;
3246
3247                         chase_msg2 = isc_mem_allocate(mctx,
3248                                                       sizeof(dig_message_t));
3249                         if (chase_msg2 == NULL) {
3250                                 fatal("Memory allocation failure in %s:%d",
3251                                       __FILE__, __LINE__);
3252                         }
3253                         ISC_LIST_INITANDAPPEND(chase_message_list2, chase_msg2,
3254                                                link);
3255                         chase_msg2->msg = msg;
3256                 }
3257 #endif
3258         }
3259
3260 #ifdef DIG_SIGCHASE
3261         if (l->sigchase && ISC_LIST_EMPTY(lookup_list)) {
3262                 sigchase(msg_temp);
3263         }
3264 #endif
3265
3266         if (l->pending)
3267                 debug("still pending.");
3268         if (l->doing_xfr) {
3269                 if (query != l->xfr_q) {
3270                         dns_message_destroy(&msg);
3271                         isc_event_free(&event);
3272                         query->waiting_connect = ISC_FALSE;
3273                         UNLOCK_LOOKUP;
3274                         return;
3275                 }
3276                 if (!docancel)
3277                         docancel = check_for_more_data(query, msg, sevent);
3278                 if (docancel) {
3279                         dns_message_destroy(&msg);
3280                         clear_query(query);
3281                         cancel_lookup(l);
3282                         check_next_lookup(l);
3283                 }
3284         } else {
3285
3286                 if (msg->rcode == dns_rcode_noerror || l->origin == NULL) {
3287
3288 #ifdef DIG_SIGCHASE
3289                         if (!l->sigchase)
3290 #endif
3291                                 received(b->used, &sevent->address, query);
3292                 }
3293
3294                 if (!query->lookup->ns_search_only)
3295                         query->lookup->pending = ISC_FALSE;
3296                 if (!query->lookup->ns_search_only ||
3297                     query->lookup->trace_root || docancel) {
3298 #ifdef DIG_SIGCHASE
3299                         if (!do_sigchase)
3300 #endif
3301                                 dns_message_destroy(&msg);
3302
3303                         cancel_lookup(l);
3304                 }
3305                 clear_query(query);
3306                 check_next_lookup(l);
3307         }
3308         if (msg != NULL) {
3309 #ifdef DIG_SIGCHASE
3310                 if (do_sigchase)
3311                         msg = NULL;
3312                 else
3313 #endif
3314                         dns_message_destroy(&msg);
3315         }
3316         isc_event_free(&event);
3317         UNLOCK_LOOKUP;
3318         return;
3319
3320  udp_mismatch:
3321         isc_buffer_invalidate(&query->recvbuf);
3322         isc_buffer_init(&query->recvbuf, query->recvspace, COMMSIZE);
3323         ISC_LIST_ENQUEUE(query->recvlist, &query->recvbuf, link);
3324         result = isc_socket_recvv(query->sock, &query->recvlist, 1,
3325                                   global_task, recv_done, query);
3326         check_result(result, "isc_socket_recvv");
3327         recvcount++;
3328         isc_event_free(&event);
3329         UNLOCK_LOOKUP;
3330         return;
3331 }
3332
3333 /*%
3334  * Turn a name into an address, using system-supplied routines.  This is
3335  * used in looking up server names, etc... and needs to use system-supplied
3336  * routines, since they may be using a non-DNS system for these lookups.
3337  */
3338 isc_result_t
3339 get_address(char *host, in_port_t port, isc_sockaddr_t *sockaddr) {
3340         int count;
3341         isc_result_t result;
3342
3343         isc_app_block();
3344         result = bind9_getaddresses(host, port, sockaddr, 1, &count);
3345         isc_app_unblock();
3346         if (result != ISC_R_SUCCESS)
3347                 return (result);
3348
3349         INSIST(count == 1);
3350
3351         return (ISC_R_SUCCESS);
3352 }
3353
3354 /*%
3355  * Initiate either a TCP or UDP lookup
3356  */
3357 void
3358 do_lookup(dig_lookup_t *lookup) {
3359
3360         REQUIRE(lookup != NULL);
3361
3362         debug("do_lookup()");
3363         lookup->pending = ISC_TRUE;
3364         if (lookup->tcp_mode)
3365                 send_tcp_connect(ISC_LIST_HEAD(lookup->q));
3366         else
3367                 send_udp(ISC_LIST_HEAD(lookup->q));
3368 }
3369
3370 /*%
3371  * Start everything in action upon task startup.
3372  */
3373 void
3374 onrun_callback(isc_task_t *task, isc_event_t *event) {
3375         UNUSED(task);
3376
3377         isc_event_free(&event);
3378         LOCK_LOOKUP;
3379         start_lookup();
3380         UNLOCK_LOOKUP;
3381 }
3382
3383 /*%
3384  * Make everything on the lookup queue go away.  Mainly used by the
3385  * SIGINT handler.
3386  */
3387 void
3388 cancel_all(void) {
3389         dig_lookup_t *l, *n;
3390         dig_query_t *q, *nq;
3391
3392         debug("cancel_all()");
3393
3394         LOCK_LOOKUP;
3395         if (free_now) {
3396                 UNLOCK_LOOKUP;
3397                 return;
3398         }
3399         cancel_now = ISC_TRUE;
3400         if (current_lookup != NULL) {
3401                 if (current_lookup->timer != NULL)
3402                         isc_timer_detach(&current_lookup->timer);
3403                 q = ISC_LIST_HEAD(current_lookup->q);
3404                 while (q != NULL) {
3405                         debug("canceling query %p, belonging to %p",
3406                               q, current_lookup);
3407                         nq = ISC_LIST_NEXT(q, link);
3408                         if (q->sock != NULL) {
3409                                 isc_socket_cancel(q->sock, NULL,
3410                                                   ISC_SOCKCANCEL_ALL);
3411                         } else {
3412                                 clear_query(q);
3413                         }
3414                         q = nq;
3415                 }
3416         }
3417         l = ISC_LIST_HEAD(lookup_list);
3418         while (l != NULL) {
3419                 n = ISC_LIST_NEXT(l, link);
3420                 ISC_LIST_DEQUEUE(lookup_list, l, link);
3421                 try_clear_lookup(l);
3422                 l = n;
3423         }
3424         UNLOCK_LOOKUP;
3425 }
3426
3427 /*%
3428  * Destroy all of the libs we are using, and get everything ready for a
3429  * clean shutdown.
3430  */
3431 void
3432 destroy_libs(void) {
3433 #ifdef DIG_SIGCHASE
3434         void * ptr;
3435         dig_message_t *chase_msg;
3436 #endif
3437 #ifdef WITH_IDN
3438         isc_result_t result;
3439 #endif
3440
3441         debug("destroy_libs()");
3442         if (global_task != NULL) {
3443                 debug("freeing task");
3444                 isc_task_detach(&global_task);
3445         }
3446         /*
3447          * The taskmgr_destroy() call blocks until all events are cleared
3448          * from the task.
3449          */
3450         if (taskmgr != NULL) {
3451                 debug("freeing taskmgr");
3452                 isc_taskmgr_destroy(&taskmgr);
3453         }
3454         LOCK_LOOKUP;
3455         REQUIRE(sockcount == 0);
3456         REQUIRE(recvcount == 0);
3457         REQUIRE(sendcount == 0);
3458
3459         INSIST(ISC_LIST_HEAD(lookup_list) == NULL);
3460         INSIST(current_lookup == NULL);
3461         INSIST(!free_now);
3462
3463         free_now = ISC_TRUE;
3464
3465         lwres_conf_clear(lwctx);
3466         lwres_context_destroy(&lwctx);
3467
3468         flush_server_list();
3469
3470         clear_searchlist();
3471
3472 #ifdef WITH_IDN
3473         result = dns_name_settotextfilter(NULL);
3474         check_result(result, "dns_name_settotextfilter");
3475 #endif
3476         dns_name_destroy();
3477
3478         if (commctx != NULL) {
3479                 debug("freeing commctx");
3480                 isc_mempool_destroy(&commctx);
3481         }
3482         if (socketmgr != NULL) {
3483                 debug("freeing socketmgr");
3484                 isc_socketmgr_destroy(&socketmgr);
3485         }
3486         if (timermgr != NULL) {
3487                 debug("freeing timermgr");
3488                 isc_timermgr_destroy(&timermgr);
3489         }
3490         if (key != NULL) {
3491                 debug("freeing key %p", key);
3492                 dns_tsigkey_detach(&key);
3493         }
3494         if (namebuf != NULL)
3495                 isc_buffer_free(&namebuf);
3496
3497         if (is_dst_up) {
3498                 debug("destroy DST lib");
3499                 dst_lib_destroy();
3500                 is_dst_up = ISC_FALSE;
3501         }
3502         if (entp != NULL) {
3503                 debug("detach from entropy");
3504                 isc_entropy_detach(&entp);
3505         }
3506
3507         UNLOCK_LOOKUP;
3508         DESTROYLOCK(&lookup_lock);
3509 #ifdef DIG_SIGCHASE
3510
3511         debug("Destroy the messages kept for sigchase");
3512         /* Destroy the messages kept for sigchase */
3513         chase_msg = ISC_LIST_HEAD(chase_message_list);
3514
3515         while (chase_msg != NULL) {
3516                 INSIST(chase_msg->msg != NULL);
3517                 dns_message_destroy(&(chase_msg->msg));
3518                 ptr = chase_msg;
3519                 chase_msg = ISC_LIST_NEXT(chase_msg, link);
3520                 isc_mem_free(mctx, ptr);
3521         }
3522
3523         chase_msg = ISC_LIST_HEAD(chase_message_list2);
3524
3525         while (chase_msg != NULL) {
3526                 INSIST(chase_msg->msg != NULL);
3527                 dns_message_destroy(&(chase_msg->msg));
3528                 ptr = chase_msg;
3529                 chase_msg = ISC_LIST_NEXT(chase_msg, link);
3530                 isc_mem_free(mctx, ptr);
3531         }
3532         if (dns_name_dynamic(&chase_name))
3533                 free_name(&chase_name, mctx);
3534 #if DIG_SIGCHASE_TD
3535         if (dns_name_dynamic(&chase_current_name))
3536                 free_name(&chase_current_name, mctx);
3537         if (dns_name_dynamic(&chase_authority_name))
3538                 free_name(&chase_authority_name, mctx);
3539 #endif
3540 #if DIG_SIGCHASE_BU
3541         if (dns_name_dynamic(&chase_signame))
3542                 free_name(&chase_signame, mctx);
3543 #endif
3544
3545         debug("Destroy memory");
3546
3547 #endif
3548         if (memdebugging != 0)
3549                 isc_mem_stats(mctx, stderr);
3550         if (mctx != NULL)
3551                 isc_mem_destroy(&mctx);
3552 }
3553
3554 #ifdef WITH_IDN
3555 static void
3556 initialize_idn(void) {
3557         idn_result_t r;
3558         isc_result_t result;
3559
3560 #ifdef HAVE_SETLOCALE
3561         /* Set locale */
3562         (void)setlocale(LC_ALL, "");
3563 #endif
3564         /* Create configuration context. */
3565         r = idn_nameinit(1);
3566         if (r != idn_success)
3567                 fatal("idn api initialization failed: %s",
3568                       idn_result_tostring(r));
3569
3570         /* Set domain name -> text post-conversion filter. */
3571         result = dns_name_settotextfilter(output_filter);
3572         check_result(result, "dns_name_settotextfilter");
3573 }
3574
3575 static isc_result_t
3576 output_filter(isc_buffer_t *buffer, unsigned int used_org,
3577               isc_boolean_t absolute)
3578 {
3579         char tmp1[MAXDLEN], tmp2[MAXDLEN];
3580         size_t fromlen, tolen;
3581         isc_boolean_t end_with_dot;
3582
3583         /*
3584          * Copy contents of 'buffer' to 'tmp1', supply trailing dot
3585          * if 'absolute' is true, and terminate with NUL.
3586          */
3587         fromlen = isc_buffer_usedlength(buffer) - used_org;
3588         if (fromlen >= MAXDLEN)
3589                 return (ISC_R_SUCCESS);
3590         memcpy(tmp1, (char *)isc_buffer_base(buffer) + used_org, fromlen);
3591         end_with_dot = (tmp1[fromlen - 1] == '.') ? ISC_TRUE : ISC_FALSE;
3592         if (absolute && !end_with_dot) {
3593                 fromlen++;
3594                 if (fromlen >= MAXDLEN)
3595                         return (ISC_R_SUCCESS);
3596                 tmp1[fromlen - 1] = '.';
3597         }
3598         tmp1[fromlen] = '\0';
3599
3600         /*
3601          * Convert contents of 'tmp1' to local encoding.
3602          */
3603         if (idn_decodename(IDN_DECODE_APP, tmp1, tmp2, MAXDLEN) != idn_success)
3604                 return (ISC_R_SUCCESS);
3605         strcpy(tmp1, tmp2);
3606
3607         /*
3608          * Copy the converted contents in 'tmp1' back to 'buffer'.
3609          * If we have appended trailing dot, remove it.
3610          */
3611         tolen = strlen(tmp1);
3612         if (absolute && !end_with_dot && tmp1[tolen - 1] == '.')
3613                 tolen--;
3614
3615         if (isc_buffer_length(buffer) < used_org + tolen)
3616                 return (ISC_R_NOSPACE);
3617
3618         isc_buffer_subtract(buffer, isc_buffer_usedlength(buffer) - used_org);
3619         memcpy(isc_buffer_used(buffer), tmp1, tolen);
3620         isc_buffer_add(buffer, tolen);
3621
3622         return (ISC_R_SUCCESS);
3623 }
3624
3625 static idn_result_t
3626 append_textname(char *name, const char *origin, size_t namesize) {
3627         size_t namelen = strlen(name);
3628         size_t originlen = strlen(origin);
3629
3630         /* Already absolute? */
3631         if (namelen > 0 && name[namelen - 1] == '.')
3632                 return idn_success;
3633
3634         /* Append dot and origin */
3635
3636         if (namelen + 1 + originlen >= namesize)
3637                 return idn_buffer_overflow;
3638
3639         name[namelen++] = '.';
3640         (void)strcpy(name + namelen, origin);
3641         return idn_success;
3642 }
3643
3644 static void
3645 idn_check_result(idn_result_t r, const char *msg) {
3646         if (r != idn_success) {
3647                 exitcode = 1;
3648                 fatal("%s: %s", msg, idn_result_tostring(r));
3649         }
3650 }
3651 #endif /* WITH_IDN */
3652
3653 #ifdef DIG_SIGCHASE
3654 void
3655 print_type(dns_rdatatype_t type)
3656 {
3657         isc_buffer_t * b = NULL;
3658         isc_result_t result;
3659         isc_region_t r;
3660
3661         result = isc_buffer_allocate(mctx, &b, 4000);
3662         check_result(result, "isc_buffer_allocate");
3663
3664         result = dns_rdatatype_totext(type, b);
3665         check_result(result, "print_type");
3666
3667         isc_buffer_usedregion(b, &r);
3668         r.base[r.length] = '\0';
3669
3670         printf("%s", r.base);
3671
3672         isc_buffer_free(&b);
3673 }
3674
3675 void
3676 dump_database_section(dns_message_t *msg, int section)
3677 {
3678         dns_name_t *msg_name=NULL;
3679
3680         dns_rdataset_t *rdataset;
3681
3682         do {
3683                 dns_message_currentname(msg, section, &msg_name);
3684
3685                 for (rdataset = ISC_LIST_HEAD(msg_name->list); rdataset != NULL;
3686                      rdataset = ISC_LIST_NEXT(rdataset, link)) {
3687                         dns_name_print(msg_name, stdout);
3688                         printf("\n");
3689                         print_rdataset(msg_name, rdataset, mctx);
3690                         printf("end\n");
3691                 }
3692                 msg_name = NULL;
3693         } while (dns_message_nextname(msg, section) == ISC_R_SUCCESS);
3694 }
3695
3696 void
3697 dump_database(void) {
3698         dig_message_t * msg;
3699
3700         for (msg = ISC_LIST_HEAD(chase_message_list);  msg != NULL;
3701              msg = ISC_LIST_NEXT(msg, link)) {
3702                 if (dns_message_firstname(msg->msg, DNS_SECTION_ANSWER)
3703                     == ISC_R_SUCCESS)
3704                         dump_database_section(msg->msg, DNS_SECTION_ANSWER);
3705
3706                 if (dns_message_firstname(msg->msg, DNS_SECTION_AUTHORITY)
3707                     == ISC_R_SUCCESS)
3708                         dump_database_section(msg->msg, DNS_SECTION_AUTHORITY);
3709
3710                 if (dns_message_firstname(msg->msg, DNS_SECTION_ADDITIONAL)
3711                     == ISC_R_SUCCESS)
3712                         dump_database_section(msg->msg, DNS_SECTION_ADDITIONAL);
3713         }
3714 }
3715
3716
3717 dns_rdataset_t *
3718 search_type(dns_name_t *name, dns_rdatatype_t type, dns_rdatatype_t covers) {
3719         dns_rdataset_t *rdataset;
3720         dns_rdata_sig_t siginfo;
3721         dns_rdata_t sigrdata = DNS_RDATA_INIT;
3722         isc_result_t result;
3723
3724         for (rdataset = ISC_LIST_HEAD(name->list); rdataset != NULL;
3725              rdataset = ISC_LIST_NEXT(rdataset, link)) {
3726                 if (type == dns_rdatatype_any) {
3727                         if (rdataset->type != dns_rdatatype_rrsig)
3728                                 return (rdataset);
3729                 } else if ((type == dns_rdatatype_rrsig) &&
3730                            (rdataset->type == dns_rdatatype_rrsig)) {
3731                         result = dns_rdataset_first(rdataset);
3732                         check_result(result, "empty rdataset");
3733                         dns_rdataset_current(rdataset, &sigrdata);
3734                         result = dns_rdata_tostruct(&sigrdata, &siginfo, NULL);
3735                         check_result(result, "sigrdata tostruct siginfo");
3736
3737                         if ((siginfo.covered == covers) ||
3738                             (covers == dns_rdatatype_any)) {
3739                                 dns_rdata_reset(&sigrdata);
3740                                 dns_rdata_freestruct(&siginfo);
3741                                 return (rdataset);
3742                         }
3743                         dns_rdata_reset(&sigrdata);
3744                         dns_rdata_freestruct(&siginfo);
3745                 } else if (rdataset->type == type)
3746                         return (rdataset);
3747         }
3748         return (NULL);
3749 }
3750
3751 dns_rdataset_t *
3752 chase_scanname_section(dns_message_t *msg, dns_name_t *name,
3753                        dns_rdatatype_t type, dns_rdatatype_t covers,
3754                        int section)
3755 {
3756         dns_rdataset_t *rdataset;
3757         dns_name_t *msg_name = NULL;
3758
3759         do {
3760                 dns_message_currentname(msg, section, &msg_name);
3761                 if (dns_name_compare(msg_name, name) == 0) {
3762                         rdataset = search_type(msg_name, type, covers);
3763                         if (rdataset != NULL)
3764                                 return (rdataset);
3765                 }
3766                 msg_name = NULL;
3767         } while (dns_message_nextname(msg, section) == ISC_R_SUCCESS);
3768
3769         return (NULL);
3770 }
3771
3772
3773 dns_rdataset_t *
3774 chase_scanname(dns_name_t *name, dns_rdatatype_t type, dns_rdatatype_t covers)
3775 {
3776         dns_rdataset_t *rdataset = NULL;
3777         dig_message_t * msg;
3778
3779         for (msg = ISC_LIST_HEAD(chase_message_list2);  msg != NULL;
3780              msg = ISC_LIST_NEXT(msg, link)) {
3781                 if (dns_message_firstname(msg->msg, DNS_SECTION_ANSWER)
3782                     == ISC_R_SUCCESS)
3783                         rdataset = chase_scanname_section(msg->msg, name,
3784                                                           type, covers,
3785                                                           DNS_SECTION_ANSWER);
3786                         if (rdataset != NULL)
3787                                 return (rdataset);
3788                 if (dns_message_firstname(msg->msg, DNS_SECTION_AUTHORITY)
3789                     == ISC_R_SUCCESS)
3790                         rdataset =
3791                                 chase_scanname_section(msg->msg, name,
3792                                                        type, covers,
3793                                                        DNS_SECTION_AUTHORITY);
3794                         if (rdataset != NULL)
3795                                 return (rdataset);
3796                 if (dns_message_firstname(msg->msg, DNS_SECTION_ADDITIONAL)
3797                     == ISC_R_SUCCESS)
3798                         rdataset =
3799                                 chase_scanname_section(msg->msg, name, type,
3800                                                        covers,
3801                                                        DNS_SECTION_ADDITIONAL);
3802                         if (rdataset != NULL)
3803                                 return (rdataset);
3804         }
3805
3806         return (NULL);
3807 }
3808
3809 dns_rdataset_t *
3810 sigchase_scanname(dns_rdatatype_t type, dns_rdatatype_t covers,
3811                   isc_boolean_t * lookedup, dns_name_t *rdata_name)
3812 {
3813         dig_lookup_t *lookup;
3814         isc_buffer_t *b = NULL;
3815         isc_region_t r;
3816         isc_result_t result;
3817         dns_rdataset_t * temp;
3818         dns_rdatatype_t querytype;
3819
3820         temp = chase_scanname(rdata_name, type, covers);
3821         if (temp != NULL)
3822                 return (temp);
3823
3824         if (*lookedup == ISC_TRUE)
3825                 return (NULL);
3826
3827         lookup = clone_lookup(current_lookup, ISC_TRUE);
3828         lookup->trace_root = ISC_FALSE;
3829         lookup->new_search = ISC_TRUE;
3830
3831         result = isc_buffer_allocate(mctx, &b, BUFSIZE);
3832         check_result(result, "isc_buffer_allocate");
3833         result = dns_name_totext(rdata_name, ISC_FALSE, b);
3834         check_result(result, "dns_name_totext");
3835         isc_buffer_usedregion(b, &r);
3836         r.base[r.length] = '\0';
3837         strcpy(lookup->textname, (char*)r.base);
3838         isc_buffer_free(&b);
3839
3840         if (type ==  dns_rdatatype_rrsig)
3841                 querytype = covers;
3842         else
3843                 querytype = type;
3844
3845         if (querytype == 0 || querytype == 255) {
3846                 printf("Error in the queried type: %d\n", querytype);
3847                 return (NULL);
3848         }
3849
3850         lookup->rdtype = querytype;
3851         lookup->rdtypeset = ISC_TRUE;
3852         lookup->qrdtype = querytype;
3853         *lookedup = ISC_TRUE;
3854
3855         ISC_LIST_APPEND(lookup_list, lookup, link);
3856         printf("\n\nLaunch a query to find a RRset of type ");
3857         print_type(type);
3858         printf(" for zone: %s\n", lookup->textname);
3859         return (NULL);
3860 }
3861
3862 void
3863 insert_trustedkey(dst_key_t * key)
3864 {
3865         if (key == NULL)
3866                 return;
3867         if (tk_list.nb_tk >= MAX_TRUSTED_KEY)
3868                 return;
3869
3870         tk_list.key[tk_list.nb_tk++] = key;
3871         return;
3872 }
3873
3874 void
3875 clean_trustedkey()
3876 {
3877         int i = 0;
3878
3879         for (i= 0; i < MAX_TRUSTED_KEY; i++) {
3880                 if (tk_list.key[i] != NULL) {
3881                         dst_key_free(&tk_list.key[i]);
3882                         tk_list.key[i] = NULL;
3883                 } else
3884                         break;
3885         }
3886         tk_list.nb_tk = 0;
3887         return;
3888 }
3889
3890 char alphnum[] =
3891         "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
3892
3893 isc_result_t
3894 removetmpkey(isc_mem_t *mctx, const char *file)
3895 {
3896         char *tempnamekey = NULL;
3897         int tempnamekeylen;
3898         isc_result_t result;
3899
3900         tempnamekeylen = strlen(file)+10;
3901
3902         tempnamekey = isc_mem_allocate(mctx, tempnamekeylen);
3903         if (tempnamekey == NULL)
3904                 return (ISC_R_NOMEMORY);
3905
3906         memset(tempnamekey, 0, tempnamekeylen);
3907
3908         strcat(tempnamekey, file);
3909         strcat(tempnamekey,".key");
3910         isc_file_remove(tempnamekey);
3911
3912         result = isc_file_remove(tempnamekey);
3913         isc_mem_free(mctx, tempnamekey);
3914         return (result);
3915 }
3916
3917 isc_result_t
3918 opentmpkey(isc_mem_t *mctx, const char *file, char **tempp, FILE **fp) {
3919         FILE *f = NULL;
3920         isc_result_t result;
3921         char *tempname = NULL;
3922         char *tempnamekey = NULL;
3923         int tempnamelen;
3924         int tempnamekeylen;
3925         char *x;
3926         char *cp;
3927         isc_uint32_t which;
3928
3929         while (1) {
3930                 tempnamelen = strlen(file) + 20;
3931                 tempname = isc_mem_allocate(mctx, tempnamelen);
3932                 if (tempname == NULL)
3933                         return (ISC_R_NOMEMORY);
3934                 memset(tempname, 0, tempnamelen);
3935
3936                 result = isc_file_mktemplate(file, tempname, tempnamelen);
3937                 if (result != ISC_R_SUCCESS)
3938                         goto cleanup;
3939
3940                 cp = tempname;
3941                 while (*cp != '\0')
3942                         cp++;
3943                 if (cp == tempname) {
3944                         isc_mem_free(mctx, tempname);
3945                         return (ISC_R_FAILURE);
3946                 }
3947
3948                 x = cp--;
3949                 while (cp >= tempname && *cp == 'X') {
3950                         isc_random_get(&which);
3951                         *cp = alphnum[which % (sizeof(alphnum) - 1)];
3952                         x = cp--;
3953                 }
3954
3955                 tempnamekeylen = tempnamelen+5;
3956                 tempnamekey = isc_mem_allocate(mctx, tempnamekeylen);
3957                 if (tempnamekey == NULL)
3958                         return (ISC_R_NOMEMORY);
3959
3960                 memset(tempnamekey, 0, tempnamekeylen);
3961                 strncpy(tempnamekey, tempname, tempnamelen);
3962                 strcat(tempnamekey ,".key");
3963
3964
3965                 if (isc_file_exists(tempnamekey)) {
3966                         isc_mem_free(mctx, tempnamekey);
3967                         isc_mem_free(mctx, tempname);
3968                         continue;
3969                 }
3970
3971                 if ((f = fopen(tempnamekey, "w")) == NULL) {
3972                         printf("get_trusted_key(): trusted key not found %s\n",
3973                                tempnamekey);
3974                         return (ISC_R_FAILURE);
3975                 }
3976                 break;
3977         }
3978         isc_mem_free(mctx, tempnamekey);
3979         *tempp = tempname;
3980         *fp = f;
3981         return (ISC_R_SUCCESS);
3982
3983  cleanup:
3984         isc_mem_free(mctx, tempname);
3985
3986         return (result);
3987 }
3988
3989
3990 isc_result_t
3991 get_trusted_key(isc_mem_t *mctx)
3992 {
3993         isc_result_t result;
3994         const char *filename = NULL;
3995         char *filetemp = NULL;
3996         char buf[1500];
3997         FILE *fp, *fptemp;
3998         dst_key_t *key = NULL;
3999
4000         result = isc_file_exists(trustedkey);
4001         if (result !=  ISC_TRUE) {
4002                 result = isc_file_exists("/etc/trusted-key.key");
4003                 if (result !=  ISC_TRUE) {
4004                         result = isc_file_exists("./trusted-key.key");
4005                         if (result !=  ISC_TRUE)
4006                                 return (ISC_R_FAILURE);
4007                         else
4008                                 filename = "./trusted-key.key";
4009                 } else
4010                         filename = "/etc/trusted-key.key";
4011         } else
4012                 filename = trustedkey;
4013
4014         if (filename == NULL) {
4015                 printf("No trusted key\n");
4016                 return (ISC_R_FAILURE);
4017         }
4018
4019         if ((fp = fopen(filename, "r")) == NULL) {
4020                 printf("get_trusted_key(): trusted key not found %s\n",
4021                        filename);
4022                 return (ISC_R_FAILURE);
4023         }
4024         while (fgets(buf, sizeof(buf), fp) != NULL) {
4025                 result = opentmpkey(mctx,"tmp_file", &filetemp, &fptemp);
4026                 if (result != ISC_R_SUCCESS) {
4027                         fclose(fp);
4028                         return (ISC_R_FAILURE);
4029                 }
4030                 if (fputs(buf, fptemp) < 0) {
4031                         fclose(fp);
4032                         fclose(fptemp);
4033                         return (ISC_R_FAILURE);
4034                 }
4035                 fclose(fptemp);
4036                 result = dst_key_fromnamedfile(filetemp, DST_TYPE_PUBLIC,
4037                                                mctx, &key);
4038                 removetmpkey(mctx, filetemp);
4039                 isc_mem_free(mctx, filetemp);
4040                 if (result !=  ISC_R_SUCCESS) {
4041                         fclose(fp);
4042                         return (ISC_R_FAILURE);
4043                 }
4044                 insert_trustedkey(key);
4045 #if 0
4046                 dst_key_tofile(key, DST_TYPE_PUBLIC,"/tmp");
4047 #endif
4048                 key = NULL;
4049         }
4050         return (ISC_R_SUCCESS);
4051 }
4052
4053
4054 static void
4055 nameFromString(const char *str, dns_name_t *p_ret) {
4056         size_t len = strlen(str);
4057         isc_result_t result;
4058         isc_buffer_t buffer;
4059         dns_fixedname_t fixedname;
4060
4061         REQUIRE(p_ret != NULL);
4062         REQUIRE(str != NULL);
4063
4064         isc_buffer_init(&buffer, str, len);
4065         isc_buffer_add(&buffer, len);
4066
4067         dns_fixedname_init(&fixedname);
4068         result = dns_name_fromtext(dns_fixedname_name(&fixedname), &buffer,
4069                                    dns_rootname, ISC_TRUE, NULL);
4070         check_result(result, "nameFromString");
4071
4072         if (dns_name_dynamic(p_ret))
4073                 free_name(p_ret, mctx);
4074
4075         result = dns_name_dup(dns_fixedname_name(&fixedname), mctx, p_ret);
4076         check_result(result, "nameFromString");
4077 }
4078
4079
4080 #if DIG_SIGCHASE_TD
4081 isc_result_t
4082 prepare_lookup(dns_name_t *name)
4083 {
4084         isc_result_t result;
4085         dig_lookup_t *lookup = NULL;
4086         dig_server_t *s;
4087         void *ptr;
4088
4089         lookup = clone_lookup(current_lookup, ISC_TRUE);
4090         lookup->trace_root = ISC_FALSE;
4091         lookup->new_search = ISC_TRUE;
4092         lookup->trace_root_sigchase = ISC_FALSE;
4093
4094         strncpy(lookup->textname, lookup->textnamesigchase, MXNAME);
4095
4096         lookup->rdtype = lookup->rdtype_sigchase;
4097         lookup->rdtypeset = ISC_TRUE;
4098         lookup->qrdtype = lookup->qrdtype_sigchase;
4099
4100         s = ISC_LIST_HEAD(lookup->my_server_list);
4101         while (s != NULL) {
4102                 debug("freeing server %p belonging to %p",
4103                       s, lookup);
4104                 ptr = s;
4105                 s = ISC_LIST_NEXT(s, link);
4106                 ISC_LIST_DEQUEUE(lookup->my_server_list,
4107                                  (dig_server_t *)ptr, link);
4108                 isc_mem_free(mctx, ptr);
4109         }
4110
4111
4112         for (result = dns_rdataset_first(chase_nsrdataset);
4113              result == ISC_R_SUCCESS;
4114              result = dns_rdataset_next(chase_nsrdataset)) {
4115                 char namestr[DNS_NAME_FORMATSIZE];
4116                 dns_rdata_ns_t ns;
4117                 dns_rdata_t rdata = DNS_RDATA_INIT;
4118                 dig_server_t * srv = NULL;
4119 #define __FOLLOW_GLUE__
4120 #ifdef __FOLLOW_GLUE__
4121                 isc_buffer_t *b = NULL;
4122                 isc_result_t result;
4123                 isc_region_t r;
4124                 dns_rdataset_t *rdataset = NULL;
4125                 isc_boolean_t true = ISC_TRUE;
4126 #endif
4127
4128                 memset(namestr, 0, DNS_NAME_FORMATSIZE);
4129
4130                 dns_rdataset_current(chase_nsrdataset, &rdata);
4131
4132                 result = dns_rdata_tostruct(&rdata, &ns, NULL);
4133                 check_result(result, "dns_rdata_tostruct");
4134
4135 #ifdef __FOLLOW_GLUE__
4136
4137                 result = advanced_rrsearch(&rdataset, &ns.name,
4138                                            dns_rdatatype_aaaa,
4139                                            dns_rdatatype_any, &true);
4140                 if (result == ISC_R_SUCCESS) {
4141                         for (result = dns_rdataset_first(rdataset);
4142                              result == ISC_R_SUCCESS;
4143                              result = dns_rdataset_next(rdataset)) {
4144                                 dns_rdata_t aaaa = DNS_RDATA_INIT;
4145                                 dns_rdataset_current(rdataset, &aaaa);
4146
4147                                 result = isc_buffer_allocate(mctx, &b, 80);
4148                                 check_result(result, "isc_buffer_allocate");
4149
4150                                 dns_rdata_totext(&aaaa, &ns.name, b);
4151                                 isc_buffer_usedregion(b, &r);
4152                                 r.base[r.length] = '\0';
4153                                 strncpy(namestr, (char*)r.base,
4154                                         DNS_NAME_FORMATSIZE);
4155                                 isc_buffer_free(&b);
4156                                 dns_rdata_reset(&aaaa);
4157
4158
4159                                 srv = make_server(namestr, namestr);
4160
4161                                 ISC_LIST_APPEND(lookup->my_server_list,
4162                                                 srv, link);
4163                         }
4164                 }
4165
4166                 rdataset = NULL;
4167                 result = advanced_rrsearch(&rdataset, &ns.name, dns_rdatatype_a,
4168                                            dns_rdatatype_any, &true);
4169                 if (result == ISC_R_SUCCESS) {
4170                         for (result = dns_rdataset_first(rdataset);
4171                              result == ISC_R_SUCCESS;
4172                              result = dns_rdataset_next(rdataset)) {
4173                                 dns_rdata_t a = DNS_RDATA_INIT;
4174                                 dns_rdataset_current(rdataset, &a);
4175
4176                                 result = isc_buffer_allocate(mctx, &b, 80);
4177                                 check_result(result, "isc_buffer_allocate");
4178
4179                                 dns_rdata_totext(&a, &ns.name, b);
4180                                 isc_buffer_usedregion(b, &r);
4181                                 r.base[r.length] = '\0';
4182                                 strncpy(namestr, (char*)r.base,
4183                                         DNS_NAME_FORMATSIZE);
4184                                 isc_buffer_free(&b);
4185                                 dns_rdata_reset(&a);
4186                                 printf("ns name: %s\n", namestr);
4187
4188
4189                                 srv = make_server(namestr, namestr);
4190
4191                                 ISC_LIST_APPEND(lookup->my_server_list,
4192                                                 srv, link);
4193                         }
4194                 }
4195 #else
4196
4197                 dns_name_format(&ns.name, namestr, sizeof(namestr));
4198                 printf("ns name: ");
4199                 dns_name_print(&ns.name, stdout);
4200                 printf("\n");
4201                 srv = make_server(namestr, namestr);
4202
4203                 ISC_LIST_APPEND(lookup->my_server_list, srv, link);
4204
4205 #endif
4206                 dns_rdata_freestruct(&ns);
4207                 dns_rdata_reset(&rdata);
4208
4209         }
4210
4211         ISC_LIST_APPEND(lookup_list, lookup, link);
4212         printf("\nLaunch a query to find a RRset of type ");
4213         print_type(lookup->rdtype);
4214         printf(" for zone: %s", lookup->textname);
4215         printf(" with nameservers:");
4216         printf("\n");
4217         print_rdataset(name, chase_nsrdataset, mctx);
4218         return (ISC_R_SUCCESS);
4219 }
4220
4221
4222 isc_result_t
4223 child_of_zone(dns_name_t * name, dns_name_t * zone_name,
4224               dns_name_t * child_name)
4225 {
4226         dns_namereln_t name_reln;
4227         int orderp;
4228         unsigned int nlabelsp;
4229
4230         name_reln = dns_name_fullcompare(name, zone_name, &orderp, &nlabelsp);
4231         if (name_reln != dns_namereln_subdomain ||
4232             dns_name_countlabels(name) <= dns_name_countlabels(zone_name) + 1) {
4233                 printf("\n;; ERROR : ");
4234                 dns_name_print(name, stdout);
4235                 printf(" is not a subdomain of: ");
4236                 dns_name_print(zone_name, stdout);
4237                 printf(" FAILED\n\n");
4238                 return (ISC_R_FAILURE);
4239         }
4240
4241         dns_name_getlabelsequence(name,
4242                                   dns_name_countlabels(name) -
4243                                   dns_name_countlabels(zone_name) -1,
4244                                   dns_name_countlabels(zone_name) +1,
4245                                   child_name);
4246         return (ISC_R_SUCCESS);
4247 }
4248
4249 isc_result_t
4250 grandfather_pb_test(dns_name_t *zone_name, dns_rdataset_t  *sigrdataset)
4251 {
4252         isc_result_t result;
4253         dns_rdata_t sigrdata = DNS_RDATA_INIT;
4254         dns_rdata_sig_t siginfo;
4255
4256         result = dns_rdataset_first(sigrdataset);
4257         check_result(result, "empty RRSIG dataset");
4258         dns_rdata_init(&sigrdata);
4259
4260         do {
4261                 dns_rdataset_current(sigrdataset, &sigrdata);
4262
4263                 result = dns_rdata_tostruct(&sigrdata, &siginfo, NULL);
4264                 check_result(result, "sigrdata tostruct siginfo");
4265
4266                 if (dns_name_compare(&siginfo.signer, zone_name) == 0) {
4267                         dns_rdata_freestruct(&siginfo);
4268                         dns_rdata_reset(&sigrdata);
4269                         return (ISC_R_SUCCESS);
4270                 }
4271
4272                 dns_rdata_freestruct(&siginfo);
4273                 dns_rdata_reset(&sigrdata);
4274
4275         } while (dns_rdataset_next(chase_sigkeyrdataset) == ISC_R_SUCCESS);
4276
4277         dns_rdata_reset(&sigrdata);
4278
4279         return (ISC_R_FAILURE);
4280 }
4281
4282
4283 isc_result_t
4284 initialization(dns_name_t *name)
4285 {
4286         isc_result_t   result;
4287         isc_boolean_t  true = ISC_TRUE;
4288
4289         chase_nsrdataset = NULL;
4290         result = advanced_rrsearch(&chase_nsrdataset, name, dns_rdatatype_ns,
4291                                    dns_rdatatype_any, &true);
4292         if (result != ISC_R_SUCCESS) {
4293                 printf("\n;; NS RRset is missing to continue validation:"
4294                        " FAILED\n\n");
4295                 return (ISC_R_FAILURE);
4296         }
4297         INSIST(chase_nsrdataset != NULL);
4298         prepare_lookup(name);
4299
4300         dup_name(name, &chase_current_name, mctx);
4301
4302         return (ISC_R_SUCCESS);
4303 }
4304 #endif
4305
4306 void
4307 print_rdataset(dns_name_t *name, dns_rdataset_t *rdataset, isc_mem_t *mctx)
4308 {
4309         isc_buffer_t *b = NULL;
4310         isc_result_t result;
4311         isc_region_t r;
4312
4313         result = isc_buffer_allocate(mctx, &b, 9000);
4314         check_result(result, "isc_buffer_allocate");
4315
4316         printrdataset(name, rdataset, b);
4317
4318         isc_buffer_usedregion(b, &r);
4319         r.base[r.length] = '\0';
4320
4321
4322         printf("%s\n", r.base);
4323
4324         isc_buffer_free(&b);
4325 }
4326
4327
4328 void
4329 dup_name(dns_name_t *source, dns_name_t *target, isc_mem_t *mctx) {
4330         isc_result_t result;
4331
4332         if (dns_name_dynamic(target))
4333                 free_name(target, mctx);
4334         result = dns_name_dup(source, mctx, target);
4335         check_result(result, "dns_name_dup");
4336 }
4337
4338 void
4339 free_name(dns_name_t *name, isc_mem_t *mctx) {
4340         dns_name_free(name, mctx);
4341         dns_name_init(name, NULL);
4342 }
4343
4344 /*
4345  *
4346  * take a DNSKEY RRset and the RRSIG RRset corresponding in parameter
4347  * return ISC_R_SUCCESS if the DNSKEY RRset contains a trusted_key
4348  *                      and the RRset is valid
4349  * return ISC_R_NOTFOUND if not contains trusted key
4350                         or if the RRset isn't valid
4351  * return ISC_R_FAILURE if problem
4352  *
4353  */
4354 isc_result_t
4355 contains_trusted_key(dns_name_t *name, dns_rdataset_t *rdataset,
4356                      dns_rdataset_t *sigrdataset,
4357                      isc_mem_t *mctx)
4358 {
4359         isc_result_t result;
4360         dns_rdata_t rdata = DNS_RDATA_INIT;
4361         dst_key_t *trustedKey = NULL;
4362         dst_key_t *dnsseckey = NULL;
4363         int i;
4364
4365         if (name == NULL || rdataset == NULL)
4366                 return (ISC_R_FAILURE);
4367
4368         result = dns_rdataset_first(rdataset);
4369         check_result(result, "empty rdataset");
4370
4371         do {
4372                 dns_rdataset_current(rdataset, &rdata);
4373                 INSIST(rdata.type == dns_rdatatype_dnskey);
4374
4375                 result = dns_dnssec_keyfromrdata(name, &rdata,
4376                                                  mctx, &dnsseckey);
4377                 check_result(result, "dns_dnssec_keyfromrdata");
4378
4379
4380                 for (i = 0; i < tk_list.nb_tk; i++) {
4381                         if (dst_key_compare(tk_list.key[i], dnsseckey)
4382                             == ISC_TRUE) {
4383                                 dns_rdata_reset(&rdata);
4384
4385                                 printf(";; Ok, find a Trusted Key in the "
4386                                        "DNSKEY RRset: %d\n",
4387                                        dst_key_id(dnsseckey));
4388                                 if (sigchase_verify_sig_key(name, rdataset,
4389                                                             dnsseckey,
4390                                                             sigrdataset,
4391                                                             mctx)
4392                                     == ISC_R_SUCCESS) {
4393                                         dst_key_free(&dnsseckey);
4394                                         dnsseckey = NULL;
4395                                         return (ISC_R_SUCCESS);
4396                                 }
4397                         }
4398                 }
4399
4400                 dns_rdata_reset(&rdata);
4401                 if (dnsseckey != NULL)
4402                         dst_key_free(&dnsseckey);
4403         } while (dns_rdataset_next(rdataset) == ISC_R_SUCCESS);
4404
4405         if (trustedKey != NULL)
4406                 dst_key_free(&trustedKey);
4407         trustedKey = NULL;
4408
4409         return (ISC_R_NOTFOUND);
4410 }
4411
4412 isc_result_t
4413 sigchase_verify_sig(dns_name_t *name, dns_rdataset_t *rdataset,
4414                     dns_rdataset_t *keyrdataset,
4415                     dns_rdataset_t *sigrdataset,
4416                     isc_mem_t *mctx)
4417 {
4418         isc_result_t result;
4419         dns_rdata_t keyrdata = DNS_RDATA_INIT;
4420         dst_key_t *dnsseckey = NULL;
4421
4422         result = dns_rdataset_first(keyrdataset);
4423         check_result(result, "empty DNSKEY dataset");
4424         dns_rdata_init(&keyrdata);
4425
4426         do {
4427                 dns_rdataset_current(keyrdataset, &keyrdata);
4428                 INSIST(keyrdata.type == dns_rdatatype_dnskey);
4429
4430                 result = dns_dnssec_keyfromrdata(name, &keyrdata,
4431                                                  mctx, &dnsseckey);
4432                 check_result(result, "dns_dnssec_keyfromrdata");
4433
4434                 result = sigchase_verify_sig_key(name, rdataset, dnsseckey,
4435                                                  sigrdataset, mctx);
4436                 if (result == ISC_R_SUCCESS) {
4437                         dns_rdata_reset(&keyrdata);
4438                         dst_key_free(&dnsseckey);
4439                         return (ISC_R_SUCCESS);
4440                 }
4441                 dst_key_free(&dnsseckey);
4442                 dns_rdata_reset(&keyrdata);
4443         } while (dns_rdataset_next(chase_keyrdataset) == ISC_R_SUCCESS);
4444
4445         dns_rdata_reset(&keyrdata);
4446
4447         return (ISC_R_NOTFOUND);
4448 }
4449
4450 isc_result_t
4451 sigchase_verify_sig_key(dns_name_t *name, dns_rdataset_t *rdataset,
4452                         dst_key_t *dnsseckey, dns_rdataset_t *sigrdataset,
4453                         isc_mem_t *mctx)
4454 {
4455         isc_result_t result;
4456         dns_rdata_t sigrdata = DNS_RDATA_INIT;
4457         dns_rdata_sig_t siginfo;
4458
4459         result = dns_rdataset_first(sigrdataset);
4460         check_result(result, "empty RRSIG dataset");
4461         dns_rdata_init(&sigrdata);
4462
4463         do {
4464                 dns_rdataset_current(sigrdataset, &sigrdata);
4465
4466                 result = dns_rdata_tostruct(&sigrdata, &siginfo, NULL);
4467                 check_result(result, "sigrdata tostruct siginfo");
4468
4469                 /*
4470                  * Test if the id of the DNSKEY is
4471                  * the id of the DNSKEY signer's
4472                  */
4473                 if (siginfo.keyid == dst_key_id(dnsseckey)) {
4474
4475                         result = dns_rdataset_first(rdataset);
4476                         check_result(result, "empty DS dataset");
4477
4478                         result = dns_dnssec_verify(name, rdataset, dnsseckey,
4479                                                    ISC_FALSE, mctx, &sigrdata);
4480
4481                         printf(";; VERIFYING ");
4482                         print_type(rdataset->type);
4483                         printf(" RRset for ");
4484                         dns_name_print(name, stdout);
4485                         printf(" with DNSKEY:%d: %s\n", dst_key_id(dnsseckey),
4486                                isc_result_totext(result));
4487
4488                         if (result == ISC_R_SUCCESS) {
4489                                 dns_rdata_reset(&sigrdata);
4490                                 return (result);
4491                         }
4492                 }
4493                 dns_rdata_freestruct(&siginfo);
4494                 dns_rdata_reset(&sigrdata);
4495
4496         } while (dns_rdataset_next(chase_sigkeyrdataset) == ISC_R_SUCCESS);
4497
4498         dns_rdata_reset(&sigrdata);
4499
4500         return (ISC_R_NOTFOUND);
4501 }
4502
4503
4504 isc_result_t
4505 sigchase_verify_ds(dns_name_t *name, dns_rdataset_t *keyrdataset,
4506                    dns_rdataset_t *dsrdataset, isc_mem_t *mctx)
4507 {
4508         isc_result_t result;
4509         dns_rdata_t keyrdata = DNS_RDATA_INIT;
4510         dns_rdata_t newdsrdata = DNS_RDATA_INIT;
4511         dns_rdata_t dsrdata = DNS_RDATA_INIT;
4512         dns_rdata_ds_t dsinfo;
4513         dst_key_t *dnsseckey = NULL;
4514         unsigned char dsbuf[DNS_DS_BUFFERSIZE];
4515
4516         result = dns_rdataset_first(dsrdataset);
4517         check_result(result, "empty DSset dataset");
4518         do {
4519                 dns_rdataset_current(dsrdataset, &dsrdata);
4520
4521                 result = dns_rdata_tostruct(&dsrdata, &dsinfo, NULL);
4522                 check_result(result, "dns_rdata_tostruct for DS");
4523
4524                 result = dns_rdataset_first(keyrdataset);
4525                 check_result(result, "empty KEY dataset");
4526
4527                 do {
4528                         dns_rdataset_current(keyrdataset, &keyrdata);
4529                         INSIST(keyrdata.type == dns_rdatatype_dnskey);
4530
4531                         result = dns_dnssec_keyfromrdata(name, &keyrdata,
4532                                                          mctx, &dnsseckey);
4533                         check_result(result, "dns_dnssec_keyfromrdata");
4534
4535                         /*
4536                          * Test if the id of the DNSKEY is the
4537                          * id of DNSKEY referenced by the DS
4538                          */
4539                         if (dsinfo.key_tag == dst_key_id(dnsseckey)) {
4540
4541                                 result = dns_ds_buildrdata(name, &keyrdata,
4542                                                            dsinfo.digest_type,
4543                                                            dsbuf, &newdsrdata);
4544                                 dns_rdata_freestruct(&dsinfo);
4545
4546                                 if (result != ISC_R_SUCCESS) {
4547                                         dns_rdata_reset(&keyrdata);
4548                                         dns_rdata_reset(&newdsrdata);
4549                                         dns_rdata_reset(&dsrdata);
4550                                         dst_key_free(&dnsseckey);
4551                                         dns_rdata_freestruct(&dsinfo);
4552                                         printf("Oops: impossible to build"
4553                                                " new DS rdata\n");
4554                                         return (result);
4555                                 }
4556
4557
4558                                 if (dns_rdata_compare(&dsrdata,
4559                                                       &newdsrdata) == 0) {
4560                                         printf(";; OK a DS valids a DNSKEY"
4561                                                " in the RRset\n");
4562                                         printf(";; Now verify that this"
4563                                                " DNSKEY validates the "
4564                                                "DNSKEY RRset\n");
4565
4566                                         result = sigchase_verify_sig_key(name,
4567                                                          keyrdataset,
4568                                                          dnsseckey,
4569                                                          chase_sigkeyrdataset,
4570                                                          mctx);
4571                                         if (result ==  ISC_R_SUCCESS) {
4572                                                 dns_rdata_reset(&keyrdata);
4573                                                 dns_rdata_reset(&newdsrdata);
4574                                                 dns_rdata_reset(&dsrdata);
4575                                                 dst_key_free(&dnsseckey);
4576
4577                                                 return (result);
4578                                         }
4579                                 } else {
4580                                         printf(";; This DS is NOT the DS for"
4581                                                " the chasing KEY: FAILED\n");
4582                                 }
4583
4584                                 dns_rdata_reset(&newdsrdata);
4585                         }
4586                         dst_key_free(&dnsseckey);
4587                         dns_rdata_reset(&keyrdata);
4588                         dnsseckey = NULL;
4589                 } while (dns_rdataset_next(chase_keyrdataset) == ISC_R_SUCCESS);
4590                 dns_rdata_reset(&dsrdata);
4591
4592         } while (dns_rdataset_next(chase_dsrdataset) == ISC_R_SUCCESS);
4593
4594         dns_rdata_reset(&keyrdata);
4595         dns_rdata_reset(&newdsrdata);
4596         dns_rdata_reset(&dsrdata);
4597
4598         return (ISC_R_NOTFOUND);
4599 }
4600
4601 /*
4602  *
4603  * take a pointer on a rdataset in parameter and try to resolv it.
4604  * the searched rrset is a rrset on 'name' with type 'type'
4605  * (and if the type is a rrsig the signature cover 'covers').
4606  * the lookedup is to known if you have already done the query on the net.
4607  * ISC_R_SUCCESS: if we found the rrset
4608  * ISC_R_NOTFOUND: we do not found the rrset in cache
4609  * and we do a query on the net
4610  * ISC_R_FAILURE: rrset not found
4611  */
4612 isc_result_t
4613 advanced_rrsearch(dns_rdataset_t **rdataset, dns_name_t *name,
4614                   dns_rdatatype_t type, dns_rdatatype_t covers,
4615                   isc_boolean_t *lookedup)
4616 {
4617         isc_boolean_t  tmplookedup;
4618
4619         INSIST(rdataset != NULL);
4620
4621         if (*rdataset != NULL)
4622                 return (ISC_R_SUCCESS);
4623
4624         tmplookedup = *lookedup;
4625         if ((*rdataset = sigchase_scanname(type, covers,
4626                                            lookedup, name)) == NULL) {
4627                 if (tmplookedup)
4628                         return (ISC_R_FAILURE);
4629                 return (ISC_R_NOTFOUND);
4630         }
4631         *lookedup = ISC_FALSE;
4632         return (ISC_R_SUCCESS);
4633 }
4634
4635
4636
4637 #if DIG_SIGCHASE_TD
4638 void
4639 sigchase_td(dns_message_t *msg)
4640 {
4641         isc_result_t result;
4642         dns_name_t *name = NULL;
4643         isc_boolean_t have_answer = ISC_FALSE;
4644         isc_boolean_t true = ISC_TRUE;
4645
4646         if ((result = dns_message_firstname(msg, DNS_SECTION_ANSWER))
4647             == ISC_R_SUCCESS) {
4648                 dns_message_currentname(msg, DNS_SECTION_ANSWER, &name);
4649                 if (current_lookup->trace_root_sigchase) {
4650                         initialization(name);
4651                         return;
4652                 }
4653                 have_answer = true;
4654         } else {
4655                 if (!current_lookup->trace_root_sigchase) {
4656                         result = dns_message_firstname(msg,
4657                                                        DNS_SECTION_AUTHORITY);
4658                         if (result == ISC_R_SUCCESS)
4659                                 dns_message_currentname(msg,
4660                                                         DNS_SECTION_AUTHORITY,
4661                                                         &name);
4662                         chase_nsrdataset
4663                                 = chase_scanname_section(msg, name,
4664                                                          dns_rdatatype_ns,
4665                                                          dns_rdatatype_any,
4666                                                          DNS_SECTION_AUTHORITY);
4667                         dup_name(name, &chase_authority_name, mctx);
4668                         if (chase_nsrdataset != NULL) {
4669                                 have_delegation_ns = ISC_TRUE;
4670                                 printf("no response but there is a delegation"
4671                                        " in authority section:");
4672                                 dns_name_print(name, stdout);
4673                                 printf("\n");
4674                         } else {
4675                                 printf("no response and no delegation in "
4676                                        "authority section but a reference"
4677                                        " to: ");
4678                                 dns_name_print(name, stdout);
4679                                 printf("\n");
4680                                 error_message = msg;
4681                         }
4682                 } else {
4683                         printf(";; NO ANSWERS: %s\n",
4684                                isc_result_totext(result));
4685                         free_name(&chase_name, mctx);
4686                         clean_trustedkey();
4687                         return;
4688                 }
4689         }
4690
4691
4692         if (have_answer) {
4693                 chase_rdataset
4694                         = chase_scanname_section(msg, &chase_name,
4695                                                  current_lookup
4696                                                  ->rdtype_sigchase,
4697                                                  dns_rdatatype_any,
4698                                                  DNS_SECTION_ANSWER);
4699                 if (chase_rdataset != NULL)
4700                         have_response = ISC_TRUE;
4701         }
4702
4703         result = advanced_rrsearch(&chase_keyrdataset,
4704                                    &chase_current_name,
4705                                    dns_rdatatype_dnskey,
4706                                    dns_rdatatype_any,
4707                                    &chase_keylookedup);
4708         if (result == ISC_R_FAILURE) {
4709                 printf("\n;; DNSKEY is missing to continue validation:"
4710                        " FAILED\n\n");
4711                 goto cleanandgo;
4712         }
4713         if (result == ISC_R_NOTFOUND)
4714                 return;
4715         INSIST(chase_keyrdataset != NULL);
4716         printf("\n;; DNSKEYset:\n");
4717         print_rdataset(&chase_current_name , chase_keyrdataset, mctx);
4718
4719
4720         result = advanced_rrsearch(&chase_sigkeyrdataset,
4721                                    &chase_current_name,
4722                                    dns_rdatatype_rrsig,
4723                                    dns_rdatatype_dnskey,
4724                                    &chase_sigkeylookedup);
4725         if (result == ISC_R_FAILURE) {
4726                 printf("\n;; RRSIG of DNSKEY is missing to continue validation:"
4727                        " FAILED\n\n");
4728                 goto cleanandgo;
4729         }
4730         if (result == ISC_R_NOTFOUND)
4731                 return;
4732         INSIST(chase_sigkeyrdataset != NULL);
4733         printf("\n;; RRSIG of the DNSKEYset:\n");
4734         print_rdataset(&chase_current_name , chase_sigkeyrdataset, mctx);
4735
4736
4737         if (!chase_dslookedup && !chase_nslookedup) {
4738                 if (!delegation_follow) {
4739                         result = contains_trusted_key(&chase_current_name,
4740                                                       chase_keyrdataset,
4741                                                       chase_sigkeyrdataset,
4742                                                       mctx);
4743                 } else {
4744                         INSIST(chase_dsrdataset != NULL);
4745                         INSIST(chase_sigdsrdataset != NULL);
4746                         result = sigchase_verify_ds(&chase_current_name,
4747                                                     chase_keyrdataset,
4748                                                     chase_dsrdataset,
4749                                                     mctx);
4750                 }
4751
4752                 if (result != ISC_R_SUCCESS) {
4753                         printf("\n;; chain of trust can't be validated:"
4754                                " FAILED\n\n");
4755                         goto cleanandgo;
4756                 } else {
4757                         chase_dsrdataset = NULL;
4758                         chase_sigdsrdataset = NULL;
4759                 }
4760         }
4761
4762         if (have_response || (!have_delegation_ns && !have_response)) {
4763                 /* test if it's a grand father case */
4764
4765                 if (have_response) {
4766                         result = advanced_rrsearch(&chase_sigrdataset,
4767                                                    &chase_name,
4768                                                    dns_rdatatype_rrsig,
4769                                                    current_lookup
4770                                                    ->rdtype_sigchase,
4771                                                    &true);
4772                         if (result == ISC_R_FAILURE) {
4773                                 printf("\n;; RRset is missing to continue"
4774                                        " validation SHOULD NOT APPEND:"
4775                                        " FAILED\n\n");
4776                                 goto cleanandgo;
4777                         }
4778
4779                 } else {
4780                         result = advanced_rrsearch(&chase_sigrdataset,
4781                                                    &chase_authority_name,
4782                                                    dns_rdatatype_rrsig,
4783                                                    dns_rdatatype_any,
4784                                                    &true);
4785                         if (result == ISC_R_FAILURE) {
4786                                 printf("\n;; RRSIG is missing  to continue"
4787                                        " validation SHOULD NOT APPEND:"
4788                                        " FAILED\n\n");
4789                                 goto cleanandgo;
4790                         }
4791                 }
4792                 result =  grandfather_pb_test(&chase_current_name,
4793                                               chase_sigrdataset);
4794                 if (result != ISC_R_SUCCESS) {
4795                         dns_name_t tmp_name;
4796
4797                         printf("\n;; We are in a Grand Father Problem:"
4798                                " See 2.2.1 in RFC 3568\n");
4799                         chase_rdataset = NULL;
4800                         chase_sigrdataset = NULL;
4801                         have_response = ISC_FALSE;
4802                         have_delegation_ns = ISC_FALSE;
4803
4804                         dns_name_init(&tmp_name, NULL);
4805                         result = child_of_zone(&chase_name, &chase_current_name,
4806                                                &tmp_name);
4807                         if (dns_name_dynamic(&chase_authority_name))
4808                                 free_name(&chase_authority_name, mctx);
4809                         dup_name(&tmp_name, &chase_authority_name, mctx);
4810                         printf(";; and we try to continue chain of trust"
4811                                " validation of the zone: ");
4812                         dns_name_print(&chase_authority_name, stdout);
4813                         printf("\n");
4814                         have_delegation_ns = ISC_TRUE;
4815                 } else {
4816                         if (have_response)
4817                                 goto finalstep;
4818                         else
4819                                 chase_sigrdataset = NULL;
4820                 }
4821         }
4822
4823         if (have_delegation_ns) {
4824                 chase_nsrdataset = NULL;
4825                 result = advanced_rrsearch(&chase_nsrdataset,
4826                                            &chase_authority_name,
4827                                            dns_rdatatype_ns,
4828                                            dns_rdatatype_any,
4829                                            &chase_nslookedup);
4830                 if (result == ISC_R_FAILURE) {
4831                         printf("\n;;NSset is missing to continue validation:"
4832                                " FAILED\n\n");
4833                         goto cleanandgo;
4834                 }
4835                 if (result == ISC_R_NOTFOUND) {
4836                         return;
4837                 }
4838                 INSIST(chase_nsrdataset != NULL);
4839
4840                 result = advanced_rrsearch(&chase_dsrdataset,
4841                                            &chase_authority_name,
4842                                            dns_rdatatype_ds,
4843                                            dns_rdatatype_any,
4844                                            &chase_dslookedup);
4845                 if (result == ISC_R_FAILURE) {
4846                         printf("\n;; DSset is missing to continue validation:"
4847                                " FAILED\n\n");
4848                         goto cleanandgo;
4849                 }
4850                 if (result == ISC_R_NOTFOUND)
4851                         return;
4852                 INSIST(chase_dsrdataset != NULL);
4853                 printf("\n;; DSset:\n");
4854                 print_rdataset(&chase_authority_name , chase_dsrdataset, mctx);
4855
4856                 result = advanced_rrsearch(&chase_sigdsrdataset,
4857                                            &chase_authority_name,
4858                                            dns_rdatatype_rrsig,
4859                                            dns_rdatatype_ds,
4860                                            &true);
4861                 if (result != ISC_R_SUCCESS) {
4862                         printf("\n;; DSset is missing to continue validation:"
4863                                " FAILED\n\n");
4864                         goto cleanandgo;
4865                 }
4866                 printf("\n;; RRSIGset of DSset\n");
4867                 print_rdataset(&chase_authority_name,
4868                                chase_sigdsrdataset, mctx);
4869                 INSIST(chase_sigdsrdataset != NULL);
4870
4871                 result = sigchase_verify_sig(&chase_authority_name,
4872                                              chase_dsrdataset,
4873                                              chase_keyrdataset,
4874                                              chase_sigdsrdataset, mctx);
4875                 if (result != ISC_R_SUCCESS) {
4876                         printf("\n;; Impossible to verify the DSset:"
4877                                " FAILED\n\n");
4878                         goto cleanandgo;
4879                 }
4880                 chase_keyrdataset = NULL;
4881                 chase_sigkeyrdataset = NULL;
4882
4883
4884                 prepare_lookup(&chase_authority_name);
4885
4886                 have_response = ISC_FALSE;
4887                 have_delegation_ns = ISC_FALSE;
4888                 delegation_follow = ISC_TRUE;
4889                 error_message = NULL;
4890                 dup_name(&chase_authority_name, &chase_current_name, mctx);
4891                 free_name(&chase_authority_name, mctx);
4892                 return;
4893         }
4894
4895
4896         if (error_message != NULL) {
4897                 dns_rdataset_t *rdataset;
4898                 dns_rdataset_t *sigrdataset;
4899                 dns_name_t rdata_name;
4900                 isc_result_t ret = ISC_R_FAILURE;
4901
4902                 dns_name_init(&rdata_name, NULL);
4903                 result = prove_nx(error_message, &chase_name,
4904                                   current_lookup->rdclass_sigchase,
4905                                   current_lookup->rdtype_sigchase, &rdata_name,
4906                                   &rdataset, &sigrdataset);
4907                 if (rdataset == NULL || sigrdataset == NULL ||
4908                     dns_name_countlabels(&rdata_name) == 0) {
4909                         printf("\n;; Impossible to verify the non-existence,"
4910                                " the NSEC RRset can't be validated:"
4911                                " FAILED\n\n");
4912                         goto cleanandgo;
4913                 }
4914                 ret = sigchase_verify_sig(&rdata_name, rdataset,
4915                                           chase_keyrdataset,
4916                                           sigrdataset, mctx);
4917                 if (ret != ISC_R_SUCCESS) {
4918                         free_name(&rdata_name, mctx);
4919                         printf("\n;; Impossible to verify the NSEC RR to prove"
4920                                " the non-existence : FAILED\n\n");
4921                         goto cleanandgo;
4922                 }
4923                 free_name(&rdata_name, mctx);
4924                 if (result != ISC_R_SUCCESS) {
4925                         printf("\n;; Impossible to verify the non-existence:"
4926                                " FAILED\n\n");
4927                         goto cleanandgo;
4928                 } else {
4929                         printf("\n;; OK the query doesn't have response but"
4930                                " we have validate this fact : SUCCESS\n\n");
4931                         goto cleanandgo;
4932                 }
4933         }
4934
4935  cleanandgo:
4936         printf(";; cleanandgo \n");
4937         if (dns_name_dynamic(&chase_current_name))
4938                 free_name(&chase_current_name, mctx);
4939         if (dns_name_dynamic(&chase_authority_name))
4940                 free_name(&chase_authority_name, mctx);
4941         clean_trustedkey();
4942         return;
4943
4944         finalstep :
4945                 result = advanced_rrsearch(&chase_rdataset, &chase_name,
4946                                            current_lookup->rdtype_sigchase,
4947                                            dns_rdatatype_any ,
4948                                            &true);
4949         if (result == ISC_R_FAILURE) {
4950                 printf("\n;; RRsig of RRset is missing to continue validation"
4951                        " SHOULD NOT APPEND: FAILED\n\n");
4952                 goto cleanandgo;
4953         }
4954         result = sigchase_verify_sig(&chase_name, chase_rdataset,
4955                                      chase_keyrdataset,
4956                                      chase_sigrdataset, mctx);
4957         if (result != ISC_R_SUCCESS) {
4958                 printf("\n;; Impossible to verify the RRset : FAILED\n\n");
4959                 /*
4960                   printf("RRset:\n");
4961                   print_rdataset(&chase_name , chase_rdataset, mctx);
4962                   printf("DNSKEYset:\n");
4963                   print_rdataset(&chase_name , chase_keyrdataset, mctx);
4964                   printf("RRSIG of RRset:\n");
4965                   print_rdataset(&chase_name , chase_sigrdataset, mctx);
4966                   printf("\n");
4967                 */
4968                 goto cleanandgo;
4969         } else {
4970                 printf("\n;; The Answer:\n");
4971                 print_rdataset(&chase_name , chase_rdataset, mctx);
4972
4973                 printf("\n;; FINISH : we have validate the DNSSEC chain"
4974                        " of trust: SUCCESS\n\n");
4975                 goto cleanandgo;
4976         }
4977 }
4978
4979 #endif
4980
4981
4982 #if DIG_SIGCHASE_BU
4983
4984 isc_result_t
4985 getneededrr(dns_message_t *msg)
4986 {
4987         isc_result_t result;
4988         dns_name_t *name = NULL;
4989         dns_rdata_t sigrdata = DNS_RDATA_INIT;
4990         dns_rdata_sig_t siginfo;
4991         isc_boolean_t   true = ISC_TRUE;
4992
4993         if ((result = dns_message_firstname(msg, DNS_SECTION_ANSWER))
4994             != ISC_R_SUCCESS) {
4995                 printf(";; NO ANSWERS: %s\n", isc_result_totext(result));
4996
4997                 if (chase_name.ndata == NULL)
4998                         return (ISC_R_ADDRNOTAVAIL);
4999         } else {
5000                 dns_message_currentname(msg, DNS_SECTION_ANSWER, &name);
5001         }
5002
5003         /* What do we chase? */
5004         if (chase_rdataset == NULL) {
5005                 result = advanced_rrsearch(&chase_rdataset, name,
5006                                            dns_rdatatype_any,
5007                                            dns_rdatatype_any, &true);
5008                 if (result != ISC_R_SUCCESS) {
5009                         printf("\n;; No Answers: Validation FAILED\n\n");
5010                         return (ISC_R_NOTFOUND);
5011                 }
5012                 dup_name(name, &chase_name, mctx);
5013                 printf(";; RRset to chase:\n");
5014                 print_rdataset(&chase_name, chase_rdataset, mctx);
5015         }
5016         INSIST(chase_rdataset != NULL);
5017
5018
5019         if (chase_sigrdataset == NULL) {
5020                 result = advanced_rrsearch(&chase_sigrdataset, name,
5021                                            dns_rdatatype_rrsig,
5022                                            chase_rdataset->type,
5023                                            &chase_siglookedup);
5024                 if (result == ISC_R_FAILURE) {
5025                         printf("\n;; RRSIG is missing for continue validation:"
5026                                " FAILED\n\n");
5027                         if (dns_name_dynamic(&chase_name))
5028                                 free_name(&chase_name, mctx);
5029                         return (ISC_R_NOTFOUND);
5030                 }
5031                 if (result == ISC_R_NOTFOUND) {
5032                         return (ISC_R_NOTFOUND);
5033                 }
5034                 printf("\n;; RRSIG of the RRset to chase:\n");
5035                 print_rdataset(&chase_name, chase_sigrdataset, mctx);
5036         }
5037         INSIST(chase_sigrdataset != NULL);
5038
5039
5040         /* first find the DNSKEY name */
5041         result = dns_rdataset_first(chase_sigrdataset);
5042         check_result(result, "empty RRSIG dataset");
5043         dns_rdataset_current(chase_sigrdataset, &sigrdata);
5044         result = dns_rdata_tostruct(&sigrdata, &siginfo, NULL);
5045         check_result(result, "sigrdata tostruct siginfo");
5046         dup_name(&siginfo.signer, &chase_signame, mctx);
5047         dns_rdata_freestruct(&siginfo);
5048         dns_rdata_reset(&sigrdata);
5049
5050         /* Do we have a key?  */
5051         if (chase_keyrdataset == NULL) {
5052                 result = advanced_rrsearch(&chase_keyrdataset,
5053                                            &chase_signame,
5054                                            dns_rdatatype_dnskey,
5055                                            dns_rdatatype_any,
5056                                            &chase_keylookedup);
5057                 if (result == ISC_R_FAILURE) {
5058                         printf("\n;; DNSKEY is missing to continue validation:"
5059                                " FAILED\n\n");
5060                         free_name(&chase_signame, mctx);
5061                         if (dns_name_dynamic(&chase_name))
5062                                 free_name(&chase_name, mctx);
5063                         return (ISC_R_NOTFOUND);
5064                 }
5065                 if (result == ISC_R_NOTFOUND) {
5066                         free_name(&chase_signame, mctx);
5067                         return (ISC_R_NOTFOUND);
5068                 }
5069                 printf("\n;; DNSKEYset that signs the RRset to chase:\n");
5070                 print_rdataset(&chase_signame, chase_keyrdataset, mctx);
5071         }
5072         INSIST(chase_keyrdataset != NULL);
5073
5074         if (chase_sigkeyrdataset == NULL) {
5075                 result = advanced_rrsearch(&chase_sigkeyrdataset,
5076                                            &chase_signame,
5077                                            dns_rdatatype_rrsig,
5078                                            dns_rdatatype_dnskey,
5079                                            &chase_sigkeylookedup);
5080                 if (result == ISC_R_FAILURE) {
5081                         printf("\n;; RRSIG for DNSKEY  is missing  to continue"
5082                                " validation : FAILED\n\n");
5083                         free_name(&chase_signame, mctx);
5084                         if (dns_name_dynamic(&chase_name))
5085                                 free_name(&chase_name, mctx);
5086                         return (ISC_R_NOTFOUND);
5087                 }
5088                 if (result == ISC_R_NOTFOUND) {
5089                         free_name(&chase_signame, mctx);
5090                         return (ISC_R_NOTFOUND);
5091                 }
5092                 printf("\n;; RRSIG of the DNSKEYset that signs the "
5093                        "RRset to chase:\n");
5094                 print_rdataset(&chase_signame, chase_sigkeyrdataset, mctx);
5095         }
5096         INSIST(chase_sigkeyrdataset != NULL);
5097
5098
5099         if (chase_dsrdataset == NULL) {
5100                 result = advanced_rrsearch(&chase_dsrdataset, &chase_signame,
5101                                            dns_rdatatype_ds,
5102                                            dns_rdatatype_any,
5103                 &chase_dslookedup);
5104                 if (result == ISC_R_FAILURE) {
5105                         printf("\n;; WARNING There is no DS for the zone: ");
5106                         dns_name_print(&chase_signame, stdout);
5107                         printf("\n");
5108                 }
5109                 if (result == ISC_R_NOTFOUND) {
5110                         free_name(&chase_signame, mctx);
5111                         return (ISC_R_NOTFOUND);
5112                 }
5113                 if (chase_dsrdataset != NULL) {
5114                         printf("\n;; DSset of the DNSKEYset\n");
5115                         print_rdataset(&chase_signame, chase_dsrdataset, mctx);
5116                 }
5117         }
5118
5119         if (chase_dsrdataset != NULL) {
5120                 /*
5121                  * if there is no RRSIG of DS,
5122                  * we don't want to search on the network
5123                  */
5124                 result = advanced_rrsearch(&chase_sigdsrdataset,
5125                                            &chase_signame,
5126                                            dns_rdatatype_rrsig,
5127                                            dns_rdatatype_ds, &true);
5128                 if (result == ISC_R_FAILURE) {
5129                         printf(";; WARNING : NO RRSIG DS : RRSIG DS"
5130                                " should come with DS\n");
5131                         /*
5132                          * We continue even the DS couldn't be validated,
5133                          * because the DNSKEY could be a Trusted Key.
5134                          */
5135                         chase_dsrdataset = NULL;
5136                 } else {
5137                         printf("\n;; RRSIG of the DSset of the DNSKEYset\n");
5138                         print_rdataset(&chase_signame, chase_sigdsrdataset,
5139                                        mctx);
5140                 }
5141         }
5142         return (1);
5143 }
5144
5145
5146
5147 void
5148 sigchase_bu(dns_message_t *msg)
5149 {
5150         isc_result_t result;
5151         int ret;
5152
5153         if (tk_list.nb_tk == 0) {
5154                 result = get_trusted_key(mctx);
5155                 if (result != ISC_R_SUCCESS) {
5156                         printf("No trusted keys present\n");
5157                         return;
5158                 }
5159         }
5160
5161
5162         ret = getneededrr(msg);
5163         if (ret == ISC_R_NOTFOUND)
5164                 return;
5165
5166         if (ret == ISC_R_ADDRNOTAVAIL) {
5167                 /* We have no response */
5168                 dns_rdataset_t *rdataset;
5169                 dns_rdataset_t *sigrdataset;
5170                 dns_name_t rdata_name;
5171                 dns_name_t query_name;
5172
5173
5174                 dns_name_init(&query_name, NULL);
5175                 dns_name_init(&rdata_name, NULL);
5176                 nameFromString(current_lookup->textname, &query_name);
5177
5178                 result = prove_nx(msg, &query_name, current_lookup->rdclass,
5179                                   current_lookup->rdtype, &rdata_name,
5180                                   &rdataset, &sigrdataset);
5181                 free_name(&query_name, mctx);
5182                 if (rdataset == NULL || sigrdataset == NULL ||
5183                     dns_name_countlabels(&rdata_name) == 0) {
5184                         printf("\n;; Impossible to verify the Non-existence,"
5185                                " the NSEC RRset can't be validated: "
5186                                "FAILED\n\n");
5187                         clean_trustedkey();
5188                         return;
5189                 }
5190
5191                 if (result != ISC_R_SUCCESS) {
5192                         printf("\n No Answers and impossible to prove the"
5193                                " unsecurity : Validation FAILED\n\n");
5194                         clean_trustedkey();
5195                         return;
5196                 }
5197                 printf(";; An NSEC prove the non-existence of a answers,"
5198                        " Now we want validate this NSEC\n");
5199
5200                 dup_name(&rdata_name, &chase_name, mctx);
5201                 free_name(&rdata_name, mctx);
5202                 chase_rdataset =  rdataset;
5203                 chase_sigrdataset = sigrdataset;
5204                 chase_keyrdataset = NULL;
5205                 chase_sigkeyrdataset = NULL;
5206                 chase_dsrdataset = NULL;
5207                 chase_sigdsrdataset = NULL;
5208                 chase_siglookedup = ISC_FALSE;
5209                 chase_keylookedup = ISC_FALSE;
5210                 chase_dslookedup = ISC_FALSE;
5211                 chase_sigdslookedup = ISC_FALSE;
5212                 sigchase(msg);
5213                 clean_trustedkey();
5214                 return;
5215         }
5216
5217
5218         printf("\n\n\n;; WE HAVE MATERIAL, WE NOW DO VALIDATION\n");
5219
5220         result = sigchase_verify_sig(&chase_name, chase_rdataset,
5221                                      chase_keyrdataset,
5222                                      chase_sigrdataset, mctx);
5223         if (result != ISC_R_SUCCESS) {
5224                 free_name(&chase_name, mctx);
5225                 free_name(&chase_signame, mctx);
5226                 printf(";; No DNSKEY is valid to check the RRSIG"
5227                        " of the RRset: FAILED\n");
5228                 clean_trustedkey();
5229                 return;
5230         }
5231         printf(";; OK We found DNSKEY (or more) to validate the RRset\n");
5232
5233         result = contains_trusted_key(&chase_signame, chase_keyrdataset,
5234                                       chase_sigkeyrdataset, mctx);
5235         if (result ==  ISC_R_SUCCESS) {
5236                 free_name(&chase_name, mctx);
5237                 free_name(&chase_signame, mctx);
5238                 printf("\n;; Ok this DNSKEY is a Trusted Key,"
5239                        " DNSSEC validation is ok: SUCCESS\n\n");
5240                 clean_trustedkey();
5241                 return;
5242         }
5243
5244         printf(";; Now, we are going to validate this DNSKEY by the DS\n");
5245
5246         if (chase_dsrdataset == NULL) {
5247                 free_name(&chase_name, mctx);
5248                 free_name(&chase_signame, mctx);
5249                 printf(";; the DNSKEY isn't trusted-key and there isn't"
5250                        " DS to validate the DNSKEY: FAILED\n");
5251                 clean_trustedkey();
5252                 return;
5253         }
5254
5255         result =  sigchase_verify_ds(&chase_signame, chase_keyrdataset,
5256                                      chase_dsrdataset, mctx);
5257         if (result !=  ISC_R_SUCCESS) {
5258                 free_name(&chase_signame, mctx);
5259                 free_name(&chase_name, mctx);
5260                 printf(";; ERROR no DS validates a DNSKEY in the"
5261                        " DNSKEY RRset: FAILED\n");
5262                 clean_trustedkey();
5263                 return;
5264         } else
5265                 printf(";; OK this DNSKEY (validated by the DS) validates"
5266                        " the RRset of the DNSKEYs, thus the DNSKEY validates"
5267                        " the RRset\n");
5268         INSIST(chase_sigdsrdataset != NULL);
5269
5270         dup_name(&chase_signame, &chase_name, mctx);
5271         free_name(&chase_signame, mctx);
5272         chase_rdataset = chase_dsrdataset;
5273         chase_sigrdataset = chase_sigdsrdataset;
5274         chase_keyrdataset = NULL;
5275         chase_sigkeyrdataset = NULL;
5276         chase_dsrdataset = NULL;
5277         chase_sigdsrdataset = NULL;
5278         chase_siglookedup = chase_keylookedup = ISC_FALSE;
5279         chase_dslookedup = chase_sigdslookedup = ISC_FALSE;
5280
5281         printf(";; Now, we want to validate the DS :  recursive call\n");
5282         sigchase(msg);
5283         return;
5284 }
5285 #endif
5286
5287 void
5288 sigchase(dns_message_t *msg) {
5289 #if DIG_SIGCHASE_TD
5290         if (current_lookup->do_topdown) {
5291                 sigchase_td(msg);
5292                 return;
5293         }
5294 #endif
5295 #if DIG_SIGCHASE_BU
5296         sigchase_bu(msg);
5297         return;
5298 #endif
5299 }
5300
5301
5302 /*
5303  * return 1  if name1  <  name2
5304  *        0  if name1  == name2
5305  *        -1 if name1  >  name2
5306  *    and -2 if problem
5307  */
5308 int
5309 inf_name(dns_name_t *name1, dns_name_t *name2)
5310 {
5311         dns_label_t  label1;
5312         dns_label_t  label2;
5313         unsigned int nblabel1;
5314         unsigned int nblabel2;
5315         int min_lum_label;
5316         int i;
5317         int ret = -2;
5318
5319         nblabel1 = dns_name_countlabels(name1);
5320         nblabel2 = dns_name_countlabels(name2);
5321
5322         if (nblabel1 >= nblabel2)
5323                 min_lum_label = nblabel2;
5324         else
5325                 min_lum_label = nblabel1;
5326
5327
5328         for (i=1 ; i < min_lum_label; i++) {
5329                 dns_name_getlabel(name1, nblabel1 -1  - i, &label1);
5330                 dns_name_getlabel(name2, nblabel2 -1  - i, &label2);
5331                 if ((ret = isc_region_compare(&label1, &label2)) != 0) {
5332                         if (ret < 0)
5333                                 return (-1);
5334                         else if (ret > 0)
5335                                 return (1);
5336                 }
5337         }
5338         if (nblabel1 == nblabel2)
5339                 return (0);
5340
5341         if (nblabel1 < nblabel2)
5342                 return (-1);
5343         else
5344                 return (1);
5345 }
5346
5347 /**
5348  *
5349  *
5350  *
5351  */
5352 isc_result_t
5353 prove_nx_domain(dns_message_t *msg,
5354                 dns_name_t *name,
5355                 dns_name_t *rdata_name,
5356                 dns_rdataset_t **rdataset,
5357                 dns_rdataset_t **sigrdataset)
5358 {
5359         isc_result_t ret = ISC_R_FAILURE;
5360         isc_result_t result = ISC_R_NOTFOUND;
5361         dns_rdataset_t *nsecset = NULL;
5362         dns_rdataset_t *signsecset = NULL ;
5363         dns_rdata_t nsec = DNS_RDATA_INIT;
5364         dns_name_t *nsecname;
5365         dns_rdata_nsec_t nsecstruct;
5366
5367         if ((result = dns_message_firstname(msg, DNS_SECTION_AUTHORITY))
5368             != ISC_R_SUCCESS) {
5369                 printf(";; nothing in authority section : impossible to"
5370                        " validate the non-existence : FAILED\n");
5371                 return (ISC_R_FAILURE);
5372         }
5373
5374         do {
5375                 nsecname = NULL;
5376                 dns_message_currentname(msg, DNS_SECTION_AUTHORITY, &nsecname);
5377                 nsecset = search_type(nsecname, dns_rdatatype_nsec,
5378                                       dns_rdatatype_any);
5379                 if (nsecset == NULL)
5380                         continue;
5381
5382                 printf("There is a NSEC for this zone in the"
5383                        " AUTHORITY section:\n");
5384                 print_rdataset(nsecname, nsecset, mctx);
5385
5386                 for (result = dns_rdataset_first(nsecset);
5387                      result == ISC_R_SUCCESS;
5388                      result = dns_rdataset_next(nsecset)) {
5389                         dns_rdataset_current(nsecset, &nsec);
5390
5391
5392                         signsecset
5393                                 = chase_scanname_section(msg, nsecname,
5394                                                  dns_rdatatype_rrsig,
5395                                                  dns_rdatatype_nsec,
5396                                                  DNS_SECTION_AUTHORITY);
5397                         if (signsecset == NULL) {
5398                                 printf(";; no RRSIG NSEC in authority section:"
5399                                        " impossible to validate the "
5400                                        "non-existence: FAILED\n");
5401                                 return (ISC_R_FAILURE);
5402                         }
5403
5404                         ret = dns_rdata_tostruct(&nsec, &nsecstruct, NULL);
5405                         check_result(ret,"dns_rdata_tostruct");
5406
5407                         if ((inf_name(nsecname, &nsecstruct.next) == 1 &&
5408                              inf_name(name, &nsecstruct.next) == 1) ||
5409                             (inf_name(name, nsecname) == 1 &&
5410                              inf_name(&nsecstruct.next, name) == 1)) {
5411                                 dns_rdata_freestruct(&nsecstruct);
5412                                 *rdataset = nsecset;
5413                                 *sigrdataset = signsecset;
5414                                 dup_name(nsecname, rdata_name, mctx);
5415
5416                                 return (ISC_R_SUCCESS);
5417                         }
5418
5419                         dns_rdata_freestruct(&nsecstruct);
5420                         dns_rdata_reset(&nsec);
5421                 }
5422         } while (dns_message_nextname(msg, DNS_SECTION_AUTHORITY)
5423                  == ISC_R_SUCCESS);
5424
5425         *rdataset = NULL;
5426         *sigrdataset =  NULL;
5427         rdata_name = NULL;
5428         return (ISC_R_FAILURE);
5429 }
5430
5431 /**
5432  *
5433  *
5434  *
5435  *
5436  *
5437  */
5438 isc_result_t
5439 prove_nx_type(dns_message_t *msg, dns_name_t *name, dns_rdataset_t *nsecset,
5440               dns_rdataclass_t class, dns_rdatatype_t type,
5441               dns_name_t *rdata_name, dns_rdataset_t **rdataset,
5442               dns_rdataset_t **sigrdataset)
5443 {
5444         isc_result_t ret;
5445         dns_rdataset_t *signsecset;
5446         dns_rdata_t nsec = DNS_RDATA_INIT;
5447
5448         UNUSED(class);
5449
5450         ret = dns_rdataset_first(nsecset);
5451         check_result(ret,"dns_rdataset_first");
5452
5453         dns_rdataset_current(nsecset, &nsec);
5454
5455         ret = dns_nsec_typepresent(&nsec, type);
5456         if (ret == ISC_R_SUCCESS)
5457                 printf("OK the NSEC said that the type doesn't exist \n");
5458
5459         signsecset = chase_scanname_section(msg, name,
5460                                             dns_rdatatype_rrsig,
5461                                             dns_rdatatype_nsec,
5462                                             DNS_SECTION_AUTHORITY);
5463         if (signsecset == NULL) {
5464                 printf("There isn't RRSIG NSEC for the zone \n");
5465                 return (ISC_R_FAILURE);
5466         }
5467         dup_name(name, rdata_name, mctx);
5468         *rdataset = nsecset;
5469         *sigrdataset = signsecset;
5470
5471         return (ret);
5472 }
5473
5474 /**
5475  *
5476  *
5477  *
5478  *
5479  */
5480 isc_result_t
5481 prove_nx(dns_message_t *msg, dns_name_t *name, dns_rdataclass_t class,
5482          dns_rdatatype_t type, dns_name_t *rdata_name,
5483          dns_rdataset_t **rdataset, dns_rdataset_t **sigrdataset)
5484 {
5485         isc_result_t ret;
5486         dns_rdataset_t *nsecset = NULL;
5487
5488         printf("We want to prove the non-existence of a type of rdata %d"
5489                " or of the zone: \n", type);
5490
5491         if ((ret = dns_message_firstname(msg, DNS_SECTION_AUTHORITY))
5492             != ISC_R_SUCCESS) {
5493                 printf(";; nothing in authority section : impossible to"
5494                        " validate the non-existence : FAILED\n");
5495                 return (ISC_R_FAILURE);
5496         }
5497
5498         nsecset = chase_scanname_section(msg, name, dns_rdatatype_nsec,
5499                                          dns_rdatatype_any,
5500                                          DNS_SECTION_AUTHORITY);
5501         if (nsecset != NULL) {
5502                 printf("We have a NSEC for this zone :OK\n");
5503                 ret = prove_nx_type(msg, name, nsecset, class,
5504                                     type, rdata_name, rdataset,
5505                                     sigrdataset);
5506                 if (ret != ISC_R_SUCCESS) {
5507                         printf("prove_nx: ERROR type exist\n");
5508                         return (ret);
5509                 } else {
5510                         printf("prove_nx: OK type does not exist\n");
5511                         return (ISC_R_SUCCESS);
5512                 }
5513         } else {
5514                 printf("there is no NSEC for this zone: validating "
5515                        "that the zone doesn't exist\n");
5516                 ret = prove_nx_domain(msg, name, rdata_name,
5517                                       rdataset, sigrdataset);
5518                 return (ret);
5519         }
5520         /* Never get here */
5521 }
5522 #endif