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