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