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