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