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