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