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