]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/bind9/bin/dig/dighost.c
Update to BIND 9.6.3, the latest from ISC on the 9.6 branch.
[FreeBSD/FreeBSD.git] / contrib / bind9 / bin / dig / dighost.c
1 /*
2  * Copyright (C) 2004-2010  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.17 2010-12-09 01:12:54 marka Exp $ */
19
20 /*! \file
21  *  \note
22  * Notice to programmers:  Do not use this code as an example of how to
23  * use the ISC library to perform DNS lookups.  Dig and Host both operate
24  * on the request level, since they allow fine-tuning of output and are
25  * intended as debugging tools.  As a result, they perform many of the
26  * functions which could be better handled using the dns_resolver
27  * functions in most applications.
28  */
29
30 #include <config.h>
31 #include <stdlib.h>
32 #include <unistd.h>
33 #include <string.h>
34 #include <limits.h>
35
36 #ifdef HAVE_LOCALE_H
37 #include <locale.h>
38 #endif
39
40 #ifdef WITH_IDN
41 #include <idn/result.h>
42 #include <idn/log.h>
43 #include <idn/resconf.h>
44 #include <idn/api.h>
45 #endif
46
47 #include <dns/byaddr.h>
48 #ifdef DIG_SIGCHASE
49 #include <dns/dnssec.h>
50 #include <dns/ds.h>
51 #include <dns/nsec.h>
52 #include <isc/random.h>
53 #include <ctype.h>
54 #endif
55 #include <dns/fixedname.h>
56 #include <dns/message.h>
57 #include <dns/name.h>
58 #include <dns/rdata.h>
59 #include <dns/rdataclass.h>
60 #include <dns/rdatalist.h>
61 #include <dns/rdataset.h>
62 #include <dns/rdatastruct.h>
63 #include <dns/rdatatype.h>
64 #include <dns/result.h>
65 #include <dns/tsig.h>
66
67 #include <dst/dst.h>
68
69 #include <isc/app.h>
70 #include <isc/base64.h>
71 #include <isc/entropy.h>
72 #include <isc/file.h>
73 #include <isc/lang.h>
74 #include <isc/netaddr.h>
75 #ifdef DIG_SIGCHASE
76 #include <isc/netdb.h>
77 #endif
78 #include <isc/print.h>
79 #include <isc/random.h>
80 #include <isc/result.h>
81 #include <isc/string.h>
82 #include <isc/task.h>
83 #include <isc/timer.h>
84 #include <isc/types.h>
85 #include <isc/util.h>
86
87 #include <lwres/lwres.h>
88 #include <lwres/net.h>
89
90 #include <bind9/getaddresses.h>
91
92 #include <dig/dig.h>
93
94 #if ! defined(NS_INADDRSZ)
95 #define NS_INADDRSZ      4
96 #endif
97
98 #if ! defined(NS_IN6ADDRSZ)
99 #define NS_IN6ADDRSZ    16
100 #endif
101
102 static lwres_context_t *lwctx = NULL;
103 static lwres_conf_t *lwconf;
104
105 dig_lookuplist_t lookup_list;
106 dig_serverlist_t server_list;
107 dig_searchlistlist_t search_list;
108
109 isc_boolean_t
110         check_ra = ISC_FALSE,
111         have_ipv4 = ISC_FALSE,
112         have_ipv6 = ISC_FALSE,
113         specified_source = ISC_FALSE,
114         free_now = ISC_FALSE,
115         cancel_now = ISC_FALSE,
116         usesearch = ISC_FALSE,
117         showsearch = ISC_FALSE,
118         qr = ISC_FALSE,
119         is_dst_up = ISC_FALSE;
120 in_port_t port = 53;
121 unsigned int timeout = 0;
122 unsigned int extrabytes;
123 isc_mem_t *mctx = NULL;
124 isc_taskmgr_t *taskmgr = NULL;
125 isc_task_t *global_task = NULL;
126 isc_timermgr_t *timermgr = NULL;
127 isc_socketmgr_t *socketmgr = NULL;
128 isc_sockaddr_t bind_address;
129 isc_sockaddr_t bind_any;
130 int sendcount = 0;
131 int recvcount = 0;
132 int sockcount = 0;
133 int ndots = -1;
134 int tries = 3;
135 int lookup_counter = 0;
136
137 #ifdef WITH_IDN
138 static void             initialize_idn(void);
139 static isc_result_t     output_filter(isc_buffer_t *buffer,
140                                       unsigned int used_org,
141                                       isc_boolean_t absolute);
142 static idn_result_t     append_textname(char *name, const char *origin,
143                                         size_t namesize);
144 static void             idn_check_result(idn_result_t r, const char *msg);
145
146 #define MAXDLEN         256
147 int  idnoptions = 0;
148 #endif
149
150 /*%
151  * Exit Codes:
152  *
153  *\li   0   Everything went well, including things like NXDOMAIN
154  *\li   1   Usage error
155  *\li   7   Got too many RR's or Names
156  *\li   8   Couldn't open batch file
157  *\li   9   No reply from server
158  *\li   10  Internal error
159  */
160 int exitcode = 0;
161 int fatalexit = 0;
162 char keynametext[MXNAME];
163 char keyfile[MXNAME] = "";
164 char keysecret[MXNAME] = "";
165 dns_name_t *hmacname = NULL;
166 unsigned int digestbits = 0;
167 isc_buffer_t *namebuf = NULL;
168 dns_tsigkey_t *key = NULL;
169 isc_boolean_t validated = ISC_TRUE;
170 isc_entropy_t *entp = NULL;
171 isc_mempool_t *commctx = NULL;
172 isc_boolean_t debugging = ISC_FALSE;
173 isc_boolean_t memdebugging = ISC_FALSE;
174 char *progname = NULL;
175 isc_mutex_t lookup_lock;
176 dig_lookup_t *current_lookup = NULL;
177
178 #ifdef DIG_SIGCHASE
179
180 isc_result_t      get_trusted_key(isc_mem_t *mctx);
181 dns_rdataset_t *  sigchase_scanname(dns_rdatatype_t type,
182                                     dns_rdatatype_t covers,
183                                     isc_boolean_t *lookedup,
184                                     dns_name_t *rdata_name);
185 dns_rdataset_t *  chase_scanname_section(dns_message_t *msg,
186                                          dns_name_t *name,
187                                          dns_rdatatype_t type,
188                                          dns_rdatatype_t covers,
189                                          int section);
190 isc_result_t      advanced_rrsearch(dns_rdataset_t **rdataset,
191                                     dns_name_t *name,
192                                     dns_rdatatype_t type,
193                                     dns_rdatatype_t covers,
194                                     isc_boolean_t *lookedup);
195 isc_result_t      sigchase_verify_sig_key(dns_name_t *name,
196                                           dns_rdataset_t *rdataset,
197                                           dst_key_t* dnsseckey,
198                                           dns_rdataset_t *sigrdataset,
199                                           isc_mem_t *mctx);
200 isc_result_t      sigchase_verify_sig(dns_name_t *name,
201                                       dns_rdataset_t *rdataset,
202                                       dns_rdataset_t *keyrdataset,
203                                       dns_rdataset_t *sigrdataset,
204                                       isc_mem_t *mctx);
205 isc_result_t      sigchase_verify_ds(dns_name_t *name,
206                                      dns_rdataset_t *keyrdataset,
207                                      dns_rdataset_t *dsrdataset,
208                                      isc_mem_t *mctx);
209 void              sigchase(dns_message_t *msg);
210 void              print_rdata(dns_rdata_t *rdata, isc_mem_t *mctx);
211 void              print_rdataset(dns_name_t *name,
212                                  dns_rdataset_t *rdataset, isc_mem_t *mctx);
213 void              dup_name(dns_name_t *source, dns_name_t* target,
214                            isc_mem_t *mctx);
215 void              free_name(dns_name_t *name, isc_mem_t *mctx);
216 void              dump_database(void);
217 void              dump_database_section(dns_message_t *msg, int section);
218 dns_rdataset_t *  search_type(dns_name_t *name, dns_rdatatype_t type,
219                               dns_rdatatype_t covers);
220 isc_result_t      contains_trusted_key(dns_name_t *name,
221                                        dns_rdataset_t *rdataset,
222                                        dns_rdataset_t *sigrdataset,
223                                        isc_mem_t *mctx);
224 void              print_type(dns_rdatatype_t type);
225 isc_result_t      prove_nx_domain(dns_message_t * msg,
226                                   dns_name_t * name,
227                                   dns_name_t * rdata_name,
228                                   dns_rdataset_t ** rdataset,
229                                   dns_rdataset_t ** sigrdataset);
230 isc_result_t      prove_nx_type(dns_message_t * msg, dns_name_t *name,
231                                 dns_rdataset_t *nsec,
232                                 dns_rdataclass_t class,
233                                 dns_rdatatype_t type,
234                                 dns_name_t * rdata_name,
235                                 dns_rdataset_t ** rdataset,
236                                 dns_rdataset_t ** sigrdataset);
237 isc_result_t      prove_nx(dns_message_t * msg, dns_name_t * name,
238                            dns_rdataclass_t class,
239                            dns_rdatatype_t type,
240                            dns_name_t * rdata_name,
241                            dns_rdataset_t ** rdataset,
242                            dns_rdataset_t ** sigrdataset);
243 static void       nameFromString(const char *str, dns_name_t *p_ret);
244 int               inf_name(dns_name_t * name1, dns_name_t * name2);
245 isc_result_t      opentmpkey(isc_mem_t *mctx, const char *file,
246                              char **tempp, FILE **fp);
247 isc_result_t      removetmpkey(isc_mem_t *mctx, const char *file);
248 void              clean_trustedkey(void);
249 void              insert_trustedkey(dst_key_t **key);
250 #if DIG_SIGCHASE_BU
251 isc_result_t      getneededrr(dns_message_t *msg);
252 void              sigchase_bottom_up(dns_message_t *msg);
253 void              sigchase_bu(dns_message_t *msg);
254 #endif
255 #if DIG_SIGCHASE_TD
256 isc_result_t      initialization(dns_name_t *name);
257 isc_result_t      prepare_lookup(dns_name_t *name);
258 isc_result_t      grandfather_pb_test(dns_name_t * zone_name,
259                                       dns_rdataset_t *sigrdataset);
260 isc_result_t      child_of_zone(dns_name_t *name,
261                                 dns_name_t *zone_name,
262                                 dns_name_t *child_name);
263 void              sigchase_td(dns_message_t *msg);
264 #endif
265 char trustedkey[MXNAME] = "";
266
267 dns_rdataset_t *chase_rdataset = NULL;
268 dns_rdataset_t *chase_sigrdataset = NULL;
269 dns_rdataset_t *chase_dsrdataset = NULL;
270 dns_rdataset_t *chase_sigdsrdataset = NULL;
271 dns_rdataset_t *chase_keyrdataset = NULL;
272 dns_rdataset_t *chase_sigkeyrdataset = NULL;
273 dns_rdataset_t *chase_nsrdataset = NULL;
274
275 dns_name_t chase_name; /* the query name */
276 #if DIG_SIGCHASE_TD
277 /*
278  * the current name is the parent name when we follow delegation
279  */
280 dns_name_t chase_current_name;
281 /*
282  * the child name is used for delegation (NS DS responses in AUTHORITY section)
283  */
284 dns_name_t chase_authority_name;
285 #endif
286 #if DIG_SIGCHASE_BU
287 dns_name_t chase_signame;
288 #endif
289
290
291 isc_boolean_t chase_siglookedup = ISC_FALSE;
292 isc_boolean_t chase_keylookedup = ISC_FALSE;
293 isc_boolean_t chase_sigkeylookedup = ISC_FALSE;
294 isc_boolean_t chase_dslookedup = ISC_FALSE;
295 isc_boolean_t chase_sigdslookedup = ISC_FALSE;
296 #if DIG_SIGCHASE_TD
297 isc_boolean_t chase_nslookedup = ISC_FALSE;
298 isc_boolean_t chase_lookedup = ISC_FALSE;
299
300
301 isc_boolean_t delegation_follow = ISC_FALSE;
302 isc_boolean_t grandfather_pb = ISC_FALSE;
303 isc_boolean_t have_response = ISC_FALSE;
304 isc_boolean_t have_delegation_ns = ISC_FALSE;
305 dns_message_t * error_message = NULL;
306 #endif
307
308 isc_boolean_t dsvalidating = ISC_FALSE;
309 isc_boolean_t chase_name_dup = ISC_FALSE;
310
311 ISC_LIST(dig_message_t) chase_message_list;
312 ISC_LIST(dig_message_t) chase_message_list2;
313
314
315 #define MAX_TRUSTED_KEY 5
316 typedef struct struct_trusted_key_list {
317         dst_key_t * key[MAX_TRUSTED_KEY];
318         int nb_tk;
319 } struct_tk_list;
320
321 struct_tk_list tk_list = { {NULL, NULL, NULL, NULL, NULL}, 0};
322
323 #endif
324
325 #define DIG_MAX_ADDRESSES 20
326
327 /*%
328  * Apply and clear locks at the event level in global task.
329  * Can I get rid of these using shutdown events?  XXX
330  */
331 #define LOCK_LOOKUP {\
332         debug("lock_lookup %s:%d", __FILE__, __LINE__);\
333         check_result(isc_mutex_lock((&lookup_lock)), "isc_mutex_lock");\
334         debug("success");\
335 }
336 #define UNLOCK_LOOKUP {\
337         debug("unlock_lookup %s:%d", __FILE__, __LINE__);\
338         check_result(isc_mutex_unlock((&lookup_lock)),\
339                      "isc_mutex_unlock");\
340 }
341
342 static void
343 cancel_lookup(dig_lookup_t *lookup);
344
345 static void
346 recv_done(isc_task_t *task, isc_event_t *event);
347
348 static void
349 send_udp(dig_query_t *query);
350
351 static void
352 connect_timeout(isc_task_t *task, isc_event_t *event);
353
354 static void
355 launch_next_query(dig_query_t *query, isc_boolean_t include_question);
356
357
358 static void *
359 mem_alloc(void *arg, size_t size) {
360         return (isc_mem_get(arg, size));
361 }
362
363 static void
364 mem_free(void *arg, void *mem, size_t size) {
365         isc_mem_put(arg, mem, size);
366 }
367
368 char *
369 next_token(char **stringp, const char *delim) {
370         char *res;
371
372         do {
373                 res = strsep(stringp, delim);
374                 if (res == NULL)
375                         break;
376         } while (*res == '\0');
377         return (res);
378 }
379
380 static int
381 count_dots(char *string) {
382         char *s;
383         int i = 0;
384
385         s = string;
386         while (*s != '\0') {
387                 if (*s == '.')
388                         i++;
389                 s++;
390         }
391         return (i);
392 }
393
394 static void
395 hex_dump(isc_buffer_t *b) {
396         unsigned int len;
397         isc_region_t r;
398
399         isc_buffer_usedregion(b, &r);
400
401         printf("%d bytes\n", r.length);
402         for (len = 0; len < r.length; len++) {
403                 printf("%02x ", r.base[len]);
404                 if (len % 16 == 15)
405                         printf("\n");
406         }
407         if (len % 16 != 0)
408                 printf("\n");
409 }
410
411 /*%
412  * Append 'len' bytes of 'text' at '*p', failing with
413  * ISC_R_NOSPACE if that would advance p past 'end'.
414  */
415 static isc_result_t
416 append(const char *text, int len, char **p, char *end) {
417         if (len > end - *p)
418                 return (ISC_R_NOSPACE);
419         memcpy(*p, text, len);
420         *p += len;
421         return (ISC_R_SUCCESS);
422 }
423
424 static isc_result_t
425 reverse_octets(const char *in, char **p, char *end) {
426         char *dot = strchr(in, '.');
427         int len;
428         if (dot != NULL) {
429                 isc_result_t result;
430                 result = reverse_octets(dot + 1, p, end);
431                 if (result != ISC_R_SUCCESS)
432                         return (result);
433                 result = append(".", 1, p, end);
434                 if (result != ISC_R_SUCCESS)
435                         return (result);
436                 len = dot - in;
437         } else {
438                 len = strlen(in);
439         }
440         return (append(in, len, p, end));
441 }
442
443 isc_result_t
444 get_reverse(char *reverse, size_t len, char *value, isc_boolean_t ip6_int,
445             isc_boolean_t strict)
446 {
447         int r;
448         isc_result_t result;
449         isc_netaddr_t addr;
450
451         addr.family = AF_INET6;
452         r = inet_pton(AF_INET6, value, &addr.type.in6);
453         if (r > 0) {
454                 /* This is a valid IPv6 address. */
455                 dns_fixedname_t fname;
456                 dns_name_t *name;
457                 unsigned int options = 0;
458
459                 if (ip6_int)
460                         options |= DNS_BYADDROPT_IPV6INT;
461                 dns_fixedname_init(&fname);
462                 name = dns_fixedname_name(&fname);
463                 result = dns_byaddr_createptrname2(&addr, options, name);
464                 if (result != ISC_R_SUCCESS)
465                         return (result);
466                 dns_name_format(name, reverse, len);
467                 return (ISC_R_SUCCESS);
468         } else {
469                 /*
470                  * Not a valid IPv6 address.  Assume IPv4.
471                  * If 'strict' is not set, construct the
472                  * in-addr.arpa name by blindly reversing
473                  * octets whether or not they look like integers,
474                  * so that this can be used for RFC2317 names
475                  * and such.
476                  */
477                 char *p = reverse;
478                 char *end = reverse + len;
479                 if (strict && inet_pton(AF_INET, value, &addr.type.in) != 1)
480                         return (DNS_R_BADDOTTEDQUAD);
481                 result = reverse_octets(value, &p, end);
482                 if (result != ISC_R_SUCCESS)
483                         return (result);
484                 /* Append .in-addr.arpa. and a terminating NUL. */
485                 result = append(".in-addr.arpa.", 15, &p, end);
486                 if (result != ISC_R_SUCCESS)
487                         return (result);
488                 return (ISC_R_SUCCESS);
489         }
490 }
491
492 void
493 fatal(const char *format, ...) {
494         va_list args;
495
496         fflush(stdout);
497         fprintf(stderr, "%s: ", progname);
498         va_start(args, format);
499         vfprintf(stderr, format, args);
500         va_end(args);
501         fprintf(stderr, "\n");
502         if (exitcode < 10)
503                 exitcode = 10;
504         if (fatalexit != 0)
505                 exitcode = fatalexit;
506         exit(exitcode);
507 }
508
509 void
510 debug(const char *format, ...) {
511         va_list args;
512
513         if (debugging) {
514                 fflush(stdout);
515                 va_start(args, format);
516                 vfprintf(stderr, format, args);
517                 va_end(args);
518                 fprintf(stderr, "\n");
519         }
520 }
521
522 void
523 check_result(isc_result_t result, const char *msg) {
524         if (result != ISC_R_SUCCESS) {
525                 fatal("%s: %s", msg, isc_result_totext(result));
526         }
527 }
528
529 /*%
530  * Create a server structure, which is part of the lookup structure.
531  * This is little more than a linked list of servers to query in hopes
532  * of finding the answer the user is looking for
533  */
534 dig_server_t *
535 make_server(const char *servname, const char *userarg) {
536         dig_server_t *srv;
537
538         REQUIRE(servname != NULL);
539
540         debug("make_server(%s)", servname);
541         srv = isc_mem_allocate(mctx, sizeof(struct dig_server));
542         if (srv == NULL)
543                 fatal("memory allocation failure in %s:%d",
544                       __FILE__, __LINE__);
545         strncpy(srv->servername, servname, MXNAME);
546         strncpy(srv->userarg, userarg, MXNAME);
547         srv->servername[MXNAME-1] = 0;
548         srv->userarg[MXNAME-1] = 0;
549         ISC_LINK_INIT(srv, link);
550         return (srv);
551 }
552
553 static int
554 addr2af(int lwresaddrtype)
555 {
556         int af = 0;
557
558         switch (lwresaddrtype) {
559         case LWRES_ADDRTYPE_V4:
560                 af = AF_INET;
561                 break;
562
563         case LWRES_ADDRTYPE_V6:
564                 af = AF_INET6;
565                 break;
566         }
567
568         return (af);
569 }
570
571 /*%
572  * Create a copy of the server list from the lwres configuration structure.
573  * The dest list must have already had ISC_LIST_INIT applied.
574  */
575 static void
576 copy_server_list(lwres_conf_t *confdata, dig_serverlist_t *dest) {
577         dig_server_t *newsrv;
578         char tmp[sizeof("ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255")];
579         int af;
580         int i;
581
582         debug("copy_server_list()");
583         for (i = 0; i < confdata->nsnext; i++) {
584                 af = addr2af(confdata->nameservers[i].family);
585
586                 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  failure:
974         if (dstkey != NULL)
975                 dst_key_free(&dstkey);
976 }
977
978 static dig_searchlist_t *
979 make_searchlist_entry(char *domain) {
980         dig_searchlist_t *search;
981         search = isc_mem_allocate(mctx, sizeof(*search));
982         if (search == NULL)
983                 fatal("memory allocation failure in %s:%d",
984                       __FILE__, __LINE__);
985         strncpy(search->origin, domain, MXNAME);
986         search->origin[MXNAME-1] = 0;
987         ISC_LINK_INIT(search, link);
988         return (search);
989 }
990
991 static void
992 clear_searchlist(void) {
993         dig_searchlist_t *search;
994         while ((search = ISC_LIST_HEAD(search_list)) != NULL) {
995                 ISC_LIST_UNLINK(search_list, search, link);
996                 isc_mem_free(mctx, search);
997         }
998 }
999
1000 static void
1001 create_search_list(lwres_conf_t *confdata) {
1002         int i;
1003         dig_searchlist_t *search;
1004
1005         debug("create_search_list()");
1006         clear_searchlist();
1007
1008         for (i = 0; i < confdata->searchnxt; i++) {
1009                 search = make_searchlist_entry(confdata->search[i]);
1010                 ISC_LIST_APPEND(search_list, search, link);
1011         }
1012 }
1013
1014 /*%
1015  * Setup the system as a whole, reading key information and resolv.conf
1016  * settings.
1017  */
1018 void
1019 setup_system(void) {
1020         dig_searchlist_t *domain = NULL;
1021         lwres_result_t lwresult;
1022         unsigned int lwresflags;
1023
1024         debug("setup_system()");
1025
1026         lwresflags = LWRES_CONTEXT_SERVERMODE;
1027         if (have_ipv4)
1028                 lwresflags |= LWRES_CONTEXT_USEIPV4;
1029         if (have_ipv6)
1030                 lwresflags |= LWRES_CONTEXT_USEIPV6;
1031
1032         lwresult = lwres_context_create(&lwctx, mctx, mem_alloc, mem_free,
1033                                         lwresflags);
1034         if (lwresult != LWRES_R_SUCCESS)
1035                 fatal("lwres_context_create failed");
1036
1037         lwresult = lwres_conf_parse(lwctx, RESOLV_CONF);
1038         if (lwresult != LWRES_R_SUCCESS && lwresult != LWRES_R_NOTFOUND)
1039                 fatal("parse of %s failed", RESOLV_CONF);
1040
1041         lwconf = lwres_conf_get(lwctx);
1042
1043         /* Make the search list */
1044         if (lwconf->searchnxt > 0)
1045                 create_search_list(lwconf);
1046         else { /* No search list. Use the domain name if any */
1047                 if (lwconf->domainname != NULL) {
1048                         domain = make_searchlist_entry(lwconf->domainname);
1049                         ISC_LIST_APPEND(search_list, domain, link);
1050                         domain  = NULL;
1051                 }
1052         }
1053
1054         if (ndots == -1) {
1055                 ndots = lwconf->ndots;
1056                 debug("ndots is %d.", ndots);
1057         }
1058
1059         /* If user doesn't specify server use nameservers from resolv.conf. */
1060         if (ISC_LIST_EMPTY(server_list))
1061                 copy_server_list(lwconf, &server_list);
1062
1063         /* If we don't find a nameserver fall back to localhost */
1064         if (ISC_LIST_EMPTY(server_list)) {
1065                 if (have_ipv4) {
1066                         lwresult = add_nameserver(lwconf, "127.0.0.1", AF_INET);
1067                         if (lwresult != ISC_R_SUCCESS)
1068                                 fatal("add_nameserver failed");
1069                 }
1070                 if (have_ipv6) {
1071                         lwresult = add_nameserver(lwconf, "::1", AF_INET6);
1072                         if (lwresult != ISC_R_SUCCESS)
1073                                 fatal("add_nameserver failed");
1074                 }
1075
1076                 copy_server_list(lwconf, &server_list);
1077         }
1078
1079 #ifdef WITH_IDN
1080         initialize_idn();
1081 #endif
1082
1083         if (keyfile[0] != 0)
1084                 setup_file_key();
1085         else if (keysecret[0] != 0)
1086                 setup_text_key();
1087 #ifdef DIG_SIGCHASE
1088         /* Setup the list of messages for +sigchase */
1089         ISC_LIST_INIT(chase_message_list);
1090         ISC_LIST_INIT(chase_message_list2);
1091         dns_name_init(&chase_name, NULL);
1092 #if DIG_SIGCHASE_TD
1093         dns_name_init(&chase_current_name, NULL);
1094         dns_name_init(&chase_authority_name, NULL);
1095 #endif
1096 #if DIG_SIGCHASE_BU
1097         dns_name_init(&chase_signame, NULL);
1098 #endif
1099
1100 #endif
1101
1102 }
1103
1104 /*%
1105  * Override the search list derived from resolv.conf by 'domain'.
1106  */
1107 void
1108 set_search_domain(char *domain) {
1109         dig_searchlist_t *search;
1110
1111         clear_searchlist();
1112         search = make_searchlist_entry(domain);
1113         ISC_LIST_APPEND(search_list, search, link);
1114 }
1115
1116 /*%
1117  * Setup the ISC and DNS libraries for use by the system.
1118  */
1119 void
1120 setup_libs(void) {
1121         isc_result_t result;
1122
1123         debug("setup_libs()");
1124
1125         result = isc_net_probeipv4();
1126         if (result == ISC_R_SUCCESS)
1127                 have_ipv4 = ISC_TRUE;
1128
1129         result = isc_net_probeipv6();
1130         if (result == ISC_R_SUCCESS)
1131                 have_ipv6 = ISC_TRUE;
1132         if (!have_ipv6 && !have_ipv4)
1133                 fatal("can't find either v4 or v6 networking");
1134
1135         result = isc_mem_create(0, 0, &mctx);
1136         check_result(result, "isc_mem_create");
1137
1138         result = isc_taskmgr_create(mctx, 1, 0, &taskmgr);
1139         check_result(result, "isc_taskmgr_create");
1140
1141         result = isc_task_create(taskmgr, 0, &global_task);
1142         check_result(result, "isc_task_create");
1143
1144         result = isc_timermgr_create(mctx, &timermgr);
1145         check_result(result, "isc_timermgr_create");
1146
1147         result = isc_socketmgr_create(mctx, &socketmgr);
1148         check_result(result, "isc_socketmgr_create");
1149
1150         result = isc_entropy_create(mctx, &entp);
1151         check_result(result, "isc_entropy_create");
1152
1153         result = dst_lib_init(mctx, entp, 0);
1154         check_result(result, "dst_lib_init");
1155         is_dst_up = ISC_TRUE;
1156
1157         result = isc_mempool_create(mctx, COMMSIZE, &commctx);
1158         check_result(result, "isc_mempool_create");
1159         isc_mempool_setname(commctx, "COMMPOOL");
1160         /*
1161          * 6 and 2 set as reasonable parameters for 3 or 4 nameserver
1162          * systems.
1163          */
1164         isc_mempool_setfreemax(commctx, 6);
1165         isc_mempool_setfillcount(commctx, 2);
1166
1167         result = isc_mutex_init(&lookup_lock);
1168         check_result(result, "isc_mutex_init");
1169
1170         dns_result_register();
1171 }
1172
1173 /*%
1174  * Add EDNS0 option record to a message.  Currently, the only supported
1175  * options are UDP buffer size, the DO bit, and NSID request.
1176  */
1177 static void
1178 add_opt(dns_message_t *msg, isc_uint16_t udpsize, isc_uint16_t edns,
1179         isc_boolean_t dnssec, isc_boolean_t nsid)
1180 {
1181         dns_rdataset_t *rdataset = NULL;
1182         dns_rdatalist_t *rdatalist = NULL;
1183         dns_rdata_t *rdata = NULL;
1184         isc_result_t result;
1185
1186         debug("add_opt()");
1187         result = dns_message_gettemprdataset(msg, &rdataset);
1188         check_result(result, "dns_message_gettemprdataset");
1189         dns_rdataset_init(rdataset);
1190         result = dns_message_gettemprdatalist(msg, &rdatalist);
1191         check_result(result, "dns_message_gettemprdatalist");
1192         result = dns_message_gettemprdata(msg, &rdata);
1193         check_result(result, "dns_message_gettemprdata");
1194
1195         debug("setting udp size of %d", udpsize);
1196         rdatalist->type = dns_rdatatype_opt;
1197         rdatalist->covers = 0;
1198         rdatalist->rdclass = udpsize;
1199         rdatalist->ttl = edns << 16;
1200         if (dnssec)
1201                 rdatalist->ttl |= DNS_MESSAGEEXTFLAG_DO;
1202         if (nsid) {
1203                 isc_buffer_t *b = NULL;
1204
1205                 result = isc_buffer_allocate(mctx, &b, 4);
1206                 check_result(result, "isc_buffer_allocate");
1207                 isc_buffer_putuint16(b, DNS_OPT_NSID);
1208                 isc_buffer_putuint16(b, 0);
1209                 rdata->data = isc_buffer_base(b);
1210                 rdata->length = isc_buffer_usedlength(b);
1211                 dns_message_takebuffer(msg, &b);
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          * The timer may have expired if, for example, get_address() takes
2224          * long time and the timer was running on a different thread.
2225          * We need to cancel the possible timeout event not to confuse
2226          * ourselves due to the duplicate events.
2227          */
2228         if (l->timer != NULL)
2229                 isc_timer_detach(&l->timer);
2230 }
2231
2232
2233 static void
2234 connect_done(isc_task_t *task, isc_event_t *event);
2235
2236 /*%
2237  * Unlike send_udp, this can't be called multiple times with the same
2238  * query.  When we retry TCP, we requeue the whole lookup, which should
2239  * start anew.
2240  */
2241 static void
2242 send_tcp_connect(dig_query_t *query) {
2243         isc_result_t result;
2244         dig_query_t *next;
2245         dig_lookup_t *l;
2246
2247         debug("send_tcp_connect(%p)", query);
2248
2249         l = query->lookup;
2250         query->waiting_connect = ISC_TRUE;
2251         query->lookup->current_query = query;
2252         result = get_address(query->servname, port, &query->sockaddr);
2253         if (result != ISC_R_SUCCESS) {
2254                 /*
2255                  * This servname doesn't have an address.  Try the next server
2256                  * by triggering an immediate 'timeout' (we lie, but the effect
2257                  * is the same).
2258                  */
2259                 force_timeout(l, query);
2260                 return;
2261         }
2262
2263         if (specified_source &&
2264             (isc_sockaddr_pf(&query->sockaddr) !=
2265              isc_sockaddr_pf(&bind_address))) {
2266                 printf(";; Skipping server %s, incompatible "
2267                        "address family\n", query->servname);
2268                 query->waiting_connect = ISC_FALSE;
2269                 next = ISC_LIST_NEXT(query, link);
2270                 l = query->lookup;
2271                 clear_query(query);
2272                 if (next == NULL) {
2273                         printf(";; No acceptable nameservers\n");
2274                         check_next_lookup(l);
2275                         return;
2276                 }
2277                 send_tcp_connect(next);
2278                 return;
2279         }
2280         INSIST(query->sock == NULL);
2281         result = isc_socket_create(socketmgr,
2282                                    isc_sockaddr_pf(&query->sockaddr),
2283                                    isc_sockettype_tcp, &query->sock);
2284         check_result(result, "isc_socket_create");
2285         sockcount++;
2286         debug("sockcount=%d", sockcount);
2287         if (specified_source)
2288                 result = isc_socket_bind(query->sock, &bind_address,
2289                                          ISC_SOCKET_REUSEADDRESS);
2290         else {
2291                 if ((isc_sockaddr_pf(&query->sockaddr) == AF_INET) &&
2292                     have_ipv4)
2293                         isc_sockaddr_any(&bind_any);
2294                 else
2295                         isc_sockaddr_any6(&bind_any);
2296                 result = isc_socket_bind(query->sock, &bind_any, 0);
2297         }
2298         check_result(result, "isc_socket_bind");
2299         bringup_timer(query, TCP_TIMEOUT);
2300         result = isc_socket_connect(query->sock, &query->sockaddr,
2301                                     global_task, connect_done, query);
2302         check_result(result, "isc_socket_connect");
2303         /*
2304          * If we're at the endgame of a nameserver search, we need to
2305          * immediately bring up all the queries.  Do it here.
2306          */
2307         if (l->ns_search_only && !l->trace_root) {
2308                 debug("sending next, since searching");
2309                 next = ISC_LIST_NEXT(query, link);
2310                 if (next != NULL)
2311                         send_tcp_connect(next);
2312         }
2313 }
2314
2315 /*%
2316  * Send a UDP packet to the remote nameserver, possible starting the
2317  * recv action as well.  Also make sure that the timer is running and
2318  * is properly reset.
2319  */
2320 static void
2321 send_udp(dig_query_t *query) {
2322         dig_lookup_t *l = NULL;
2323         isc_result_t result;
2324
2325         debug("send_udp(%p)", query);
2326
2327         l = query->lookup;
2328         bringup_timer(query, UDP_TIMEOUT);
2329         l->current_query = query;
2330         debug("working on lookup %p, query %p", query->lookup, query);
2331         if (!query->recv_made) {
2332                 /* XXX Check the sense of this, need assertion? */
2333                 query->waiting_connect = ISC_FALSE;
2334                 result = get_address(query->servname, port, &query->sockaddr);
2335                 if (result != ISC_R_SUCCESS) {
2336                         /* This servname doesn't have an address. */
2337                         force_timeout(l, query);
2338                         return;
2339                 }
2340
2341                 result = isc_socket_create(socketmgr,
2342                                            isc_sockaddr_pf(&query->sockaddr),
2343                                            isc_sockettype_udp, &query->sock);
2344                 check_result(result, "isc_socket_create");
2345                 sockcount++;
2346                 debug("sockcount=%d", sockcount);
2347                 if (specified_source) {
2348                         result = isc_socket_bind(query->sock, &bind_address,
2349                                                  ISC_SOCKET_REUSEADDRESS);
2350                 } else {
2351                         isc_sockaddr_anyofpf(&bind_any,
2352                                         isc_sockaddr_pf(&query->sockaddr));
2353                         result = isc_socket_bind(query->sock, &bind_any, 0);
2354                 }
2355                 check_result(result, "isc_socket_bind");
2356
2357                 query->recv_made = ISC_TRUE;
2358                 ISC_LINK_INIT(&query->recvbuf, link);
2359                 ISC_LIST_ENQUEUE(query->recvlist, &query->recvbuf,
2360                                  link);
2361                 debug("recving with lookup=%p, query=%p, sock=%p",
2362                       query->lookup, query, query->sock);
2363                 result = isc_socket_recvv(query->sock, &query->recvlist, 1,
2364                                           global_task, recv_done, query);
2365                 check_result(result, "isc_socket_recvv");
2366                 recvcount++;
2367                 debug("recvcount=%d", recvcount);
2368         }
2369         ISC_LIST_INIT(query->sendlist);
2370         ISC_LIST_ENQUEUE(query->sendlist, &query->sendbuf, link);
2371         debug("sending a request");
2372         TIME_NOW(&query->time_sent);
2373         INSIST(query->sock != NULL);
2374         query->waiting_senddone = ISC_TRUE;
2375         result = isc_socket_sendtov(query->sock, &query->sendlist,
2376                                     global_task, send_done, query,
2377                                     &query->sockaddr, NULL);
2378         check_result(result, "isc_socket_sendtov");
2379         sendcount++;
2380 }
2381
2382 /*%
2383  * IO timeout handler, used for both connect and recv timeouts.  If
2384  * retries are still allowed, either resend the UDP packet or queue a
2385  * new TCP lookup.  Otherwise, cancel the lookup.
2386  */
2387 static void
2388 connect_timeout(isc_task_t *task, isc_event_t *event) {
2389         dig_lookup_t *l = NULL;
2390         dig_query_t *query = NULL, *cq;
2391
2392         UNUSED(task);
2393         REQUIRE(event->ev_type == ISC_TIMEREVENT_IDLE);
2394
2395         debug("connect_timeout()");
2396
2397         LOCK_LOOKUP;
2398         l = event->ev_arg;
2399         query = l->current_query;
2400         isc_event_free(&event);
2401
2402         INSIST(!free_now);
2403
2404         if ((query != NULL) && (query->lookup->current_query != NULL) &&
2405             (ISC_LIST_NEXT(query->lookup->current_query, link) != NULL)) {
2406                 debug("trying next server...");
2407                 cq = query->lookup->current_query;
2408                 if (!l->tcp_mode)
2409                         send_udp(ISC_LIST_NEXT(cq, link));
2410                 else {
2411                         if (query->sock != NULL)
2412                                 isc_socket_cancel(query->sock, NULL,
2413                                                   ISC_SOCKCANCEL_ALL);
2414                         send_tcp_connect(ISC_LIST_NEXT(cq, link));
2415                 }
2416                 UNLOCK_LOOKUP;
2417                 return;
2418         }
2419
2420         if (l->retries > 1) {
2421                 if (!l->tcp_mode) {
2422                         l->retries--;
2423                         debug("resending UDP request to first server");
2424                         send_udp(ISC_LIST_HEAD(l->q));
2425                 } else {
2426                         debug("making new TCP request, %d tries left",
2427                               l->retries);
2428                         l->retries--;
2429                         requeue_lookup(l, ISC_TRUE);
2430                         cancel_lookup(l);
2431                         check_next_lookup(l);
2432                 }
2433         } else {
2434                 fputs(l->cmdline, stdout);
2435                 printf(";; connection timed out; no servers could be "
2436                        "reached\n");
2437                 cancel_lookup(l);
2438                 check_next_lookup(l);
2439                 if (exitcode < 9)
2440                         exitcode = 9;
2441         }
2442         UNLOCK_LOOKUP;
2443 }
2444
2445 /*%
2446  * Event handler for the TCP recv which gets the length header of TCP
2447  * packets.  Start the next recv of length bytes.
2448  */
2449 static void
2450 tcp_length_done(isc_task_t *task, isc_event_t *event) {
2451         isc_socketevent_t *sevent;
2452         isc_buffer_t *b = NULL;
2453         isc_result_t result;
2454         dig_query_t *query = NULL;
2455         dig_lookup_t *l;
2456         isc_uint16_t length;
2457
2458         REQUIRE(event->ev_type == ISC_SOCKEVENT_RECVDONE);
2459         INSIST(!free_now);
2460
2461         UNUSED(task);
2462
2463         debug("tcp_length_done()");
2464
2465         LOCK_LOOKUP;
2466         sevent = (isc_socketevent_t *)event;
2467         query = event->ev_arg;
2468
2469         recvcount--;
2470         INSIST(recvcount >= 0);
2471
2472         b = ISC_LIST_HEAD(sevent->bufferlist);
2473         INSIST(b ==  &query->lengthbuf);
2474         ISC_LIST_DEQUEUE(sevent->bufferlist, b, link);
2475
2476         if (sevent->result == ISC_R_CANCELED) {
2477                 isc_event_free(&event);
2478                 l = query->lookup;
2479                 clear_query(query);
2480                 check_next_lookup(l);
2481                 UNLOCK_LOOKUP;
2482                 return;
2483         }
2484         if (sevent->result != ISC_R_SUCCESS) {
2485                 char sockstr[ISC_SOCKADDR_FORMATSIZE];
2486                 isc_sockaddr_format(&query->sockaddr, sockstr,
2487                                     sizeof(sockstr));
2488                 printf(";; communications error to %s: %s\n",
2489                        sockstr, isc_result_totext(sevent->result));
2490                 l = query->lookup;
2491                 isc_socket_detach(&query->sock);
2492                 sockcount--;
2493                 debug("sockcount=%d", sockcount);
2494                 INSIST(sockcount >= 0);
2495                 isc_event_free(&event);
2496                 clear_query(query);
2497                 check_next_lookup(l);
2498                 UNLOCK_LOOKUP;
2499                 return;
2500         }
2501         length = isc_buffer_getuint16(b);
2502         if (length == 0) {
2503                 isc_event_free(&event);
2504                 launch_next_query(query, ISC_FALSE);
2505                 UNLOCK_LOOKUP;
2506                 return;
2507         }
2508
2509         /*
2510          * Even though the buffer was already init'ed, we need
2511          * to redo it now, to force the length we want.
2512          */
2513         isc_buffer_invalidate(&query->recvbuf);
2514         isc_buffer_init(&query->recvbuf, query->recvspace, length);
2515         ENSURE(ISC_LIST_EMPTY(query->recvlist));
2516         ISC_LINK_INIT(&query->recvbuf, link);
2517         ISC_LIST_ENQUEUE(query->recvlist, &query->recvbuf, link);
2518         debug("recving with lookup=%p, query=%p", query->lookup, query);
2519         result = isc_socket_recvv(query->sock, &query->recvlist, length, task,
2520                                   recv_done, query);
2521         check_result(result, "isc_socket_recvv");
2522         recvcount++;
2523         debug("resubmitted recv request with length %d, recvcount=%d",
2524               length, recvcount);
2525         isc_event_free(&event);
2526         UNLOCK_LOOKUP;
2527 }
2528
2529 /*%
2530  * For transfers that involve multiple recvs (XFR's in particular),
2531  * launch the next recv.
2532  */
2533 static void
2534 launch_next_query(dig_query_t *query, isc_boolean_t include_question) {
2535         isc_result_t result;
2536         dig_lookup_t *l;
2537
2538         INSIST(!free_now);
2539
2540         debug("launch_next_query()");
2541
2542         if (!query->lookup->pending) {
2543                 debug("ignoring launch_next_query because !pending");
2544                 isc_socket_detach(&query->sock);
2545                 sockcount--;
2546                 debug("sockcount=%d", sockcount);
2547                 INSIST(sockcount >= 0);
2548                 query->waiting_connect = ISC_FALSE;
2549                 l = query->lookup;
2550                 clear_query(query);
2551                 check_next_lookup(l);
2552                 return;
2553         }
2554
2555         isc_buffer_clear(&query->slbuf);
2556         isc_buffer_clear(&query->lengthbuf);
2557         isc_buffer_putuint16(&query->slbuf, (isc_uint16_t) query->sendbuf.used);
2558         ISC_LIST_INIT(query->sendlist);
2559         ISC_LINK_INIT(&query->slbuf, link);
2560         ISC_LIST_ENQUEUE(query->sendlist, &query->slbuf, link);
2561         if (include_question)
2562                 ISC_LIST_ENQUEUE(query->sendlist, &query->sendbuf, link);
2563         ISC_LINK_INIT(&query->lengthbuf, link);
2564         ISC_LIST_ENQUEUE(query->lengthlist, &query->lengthbuf, link);
2565
2566         result = isc_socket_recvv(query->sock, &query->lengthlist, 0,
2567                                   global_task, tcp_length_done, query);
2568         check_result(result, "isc_socket_recvv");
2569         recvcount++;
2570         debug("recvcount=%d", recvcount);
2571         if (!query->first_soa_rcvd) {
2572                 debug("sending a request in launch_next_query");
2573                 TIME_NOW(&query->time_sent);
2574                 query->waiting_senddone = ISC_TRUE;
2575                 result = isc_socket_sendv(query->sock, &query->sendlist,
2576                                           global_task, send_done, query);
2577                 check_result(result, "isc_socket_sendv");
2578                 sendcount++;
2579                 debug("sendcount=%d", sendcount);
2580         }
2581         query->waiting_connect = ISC_FALSE;
2582 #if 0
2583         check_next_lookup(query->lookup);
2584 #endif
2585         return;
2586 }
2587
2588 /*%
2589  * Event handler for TCP connect complete.  Make sure the connection was
2590  * successful, then pass into launch_next_query to actually send the
2591  * question.
2592  */
2593 static void
2594 connect_done(isc_task_t *task, isc_event_t *event) {
2595         isc_socketevent_t *sevent = NULL;
2596         dig_query_t *query = NULL, *next;
2597         dig_lookup_t *l;
2598
2599         UNUSED(task);
2600
2601         REQUIRE(event->ev_type == ISC_SOCKEVENT_CONNECT);
2602         INSIST(!free_now);
2603
2604         debug("connect_done()");
2605
2606         LOCK_LOOKUP;
2607         sevent = (isc_socketevent_t *)event;
2608         query = sevent->ev_arg;
2609
2610         INSIST(query->waiting_connect);
2611
2612         query->waiting_connect = ISC_FALSE;
2613
2614         if (sevent->result == ISC_R_CANCELED) {
2615                 debug("in cancel handler");
2616                 isc_socket_detach(&query->sock);
2617                 INSIST(sockcount > 0);
2618                 sockcount--;
2619                 debug("sockcount=%d", sockcount);
2620                 query->waiting_connect = ISC_FALSE;
2621                 isc_event_free(&event);
2622                 l = query->lookup;
2623                 clear_query(query);
2624                 check_next_lookup(l);
2625                 UNLOCK_LOOKUP;
2626                 return;
2627         }
2628         if (sevent->result != ISC_R_SUCCESS) {
2629                 char sockstr[ISC_SOCKADDR_FORMATSIZE];
2630
2631                 debug("unsuccessful connection: %s",
2632                       isc_result_totext(sevent->result));
2633                 isc_sockaddr_format(&query->sockaddr, sockstr, sizeof(sockstr));
2634                 if (sevent->result != ISC_R_CANCELED)
2635                         printf(";; Connection to %s(%s) for %s failed: "
2636                                "%s.\n", sockstr,
2637                                query->servname, query->lookup->textname,
2638                                isc_result_totext(sevent->result));
2639                 isc_socket_detach(&query->sock);
2640                 sockcount--;
2641                 INSIST(sockcount >= 0);
2642                 /* XXX Clean up exitcodes */
2643                 if (exitcode < 9)
2644                         exitcode = 9;
2645                 debug("sockcount=%d", sockcount);
2646                 query->waiting_connect = ISC_FALSE;
2647                 isc_event_free(&event);
2648                 l = query->lookup;
2649                 if (l->current_query != NULL)
2650                         next = ISC_LIST_NEXT(l->current_query, link);
2651                 else
2652                         next = NULL;
2653                 clear_query(query);
2654                 if (next != NULL) {
2655                         bringup_timer(next, TCP_TIMEOUT);
2656                         send_tcp_connect(next);
2657                 } else {
2658                         check_next_lookup(l);
2659                 }
2660                 UNLOCK_LOOKUP;
2661                 return;
2662         }
2663         launch_next_query(query, ISC_TRUE);
2664         isc_event_free(&event);
2665         UNLOCK_LOOKUP;
2666 }
2667
2668 /*%
2669  * Check if the ongoing XFR needs more data before it's complete, using
2670  * the semantics of IXFR and AXFR protocols.  Much of the complexity of
2671  * this routine comes from determining when an IXFR is complete.
2672  * ISC_FALSE means more data is on the way, and the recv has been issued.
2673  */
2674 static isc_boolean_t
2675 check_for_more_data(dig_query_t *query, dns_message_t *msg,
2676                     isc_socketevent_t *sevent)
2677 {
2678         dns_rdataset_t *rdataset = NULL;
2679         dns_rdata_t rdata = DNS_RDATA_INIT;
2680         dns_rdata_soa_t soa;
2681         isc_uint32_t serial;
2682         isc_result_t result;
2683
2684         debug("check_for_more_data()");
2685
2686         /*
2687          * By the time we're in this routine, we know we're doing
2688          * either an AXFR or IXFR.  If there's no second_rr_type,
2689          * then we don't yet know which kind of answer we got back
2690          * from the server.  Here, we're going to walk through the
2691          * rr's in the message, acting as necessary whenever we hit
2692          * an SOA rr.
2693          */
2694
2695         query->msg_count++;
2696         query->byte_count += sevent->n;
2697         result = dns_message_firstname(msg, DNS_SECTION_ANSWER);
2698         if (result != ISC_R_SUCCESS) {
2699                 puts("; Transfer failed.");
2700                 return (ISC_TRUE);
2701         }
2702         do {
2703                 dns_name_t *name;
2704                 name = NULL;
2705                 dns_message_currentname(msg, DNS_SECTION_ANSWER,
2706                                         &name);
2707                 for (rdataset = ISC_LIST_HEAD(name->list);
2708                      rdataset != NULL;
2709                      rdataset = ISC_LIST_NEXT(rdataset, link)) {
2710                         result = dns_rdataset_first(rdataset);
2711                         if (result != ISC_R_SUCCESS)
2712                                 continue;
2713                         do {
2714                                 query->rr_count++;
2715                                 dns_rdata_reset(&rdata);
2716                                 dns_rdataset_current(rdataset, &rdata);
2717                                 /*
2718                                  * If this is the first rr, make sure
2719                                  * it's an SOA
2720                                  */
2721                                 if ((!query->first_soa_rcvd) &&
2722                                     (rdata.type != dns_rdatatype_soa)) {
2723                                         puts("; Transfer failed.  "
2724                                              "Didn't start with SOA answer.");
2725                                         return (ISC_TRUE);
2726                                 }
2727                                 if ((!query->second_rr_rcvd) &&
2728                                     (rdata.type != dns_rdatatype_soa)) {
2729                                         query->second_rr_rcvd = ISC_TRUE;
2730                                         query->second_rr_serial = 0;
2731                                         debug("got the second rr as nonsoa");
2732                                         goto next_rdata;
2733                                 }
2734
2735                                 /*
2736                                  * If the record is anything except an SOA
2737                                  * now, just continue on...
2738                                  */
2739                                 if (rdata.type != dns_rdatatype_soa)
2740                                         goto next_rdata;
2741                                 /* Now we have an SOA.  Work with it. */
2742                                 debug("got an SOA");
2743                                 result = dns_rdata_tostruct(&rdata, &soa, NULL);
2744                                 check_result(result, "dns_rdata_tostruct");
2745                                 serial = soa.serial;
2746                                 dns_rdata_freestruct(&soa);
2747                                 if (!query->first_soa_rcvd) {
2748                                         query->first_soa_rcvd = ISC_TRUE;
2749                                         query->first_rr_serial = serial;
2750                                         debug("this is the first %d",
2751                                                query->lookup->ixfr_serial);
2752                                         if (query->lookup->ixfr_serial >=
2753                                             serial)
2754                                                 goto doexit;
2755                                         goto next_rdata;
2756                                 }
2757                                 if (query->lookup->rdtype ==
2758                                     dns_rdatatype_axfr) {
2759                                         debug("doing axfr, got second SOA");
2760                                         goto doexit;
2761                                 }
2762                                 if (!query->second_rr_rcvd) {
2763                                         if (query->first_rr_serial == serial) {
2764                                                 debug("doing ixfr, got "
2765                                                       "empty zone");
2766                                                 goto doexit;
2767                                         }
2768                                         debug("this is the second %d",
2769                                                query->lookup->ixfr_serial);
2770                                         query->second_rr_rcvd = ISC_TRUE;
2771                                         query->second_rr_serial = serial;
2772                                         goto next_rdata;
2773                                 }
2774                                 if (query->second_rr_serial == 0) {
2775                                         /*
2776                                          * If the second RR was a non-SOA
2777                                          * record, and we're getting any
2778                                          * other SOA, then this is an
2779                                          * AXFR, and we're done.
2780                                          */
2781                                         debug("done, since axfr");
2782                                         goto doexit;
2783                                 }
2784                                 /*
2785                                  * If we get to this point, we're doing an
2786                                  * IXFR and have to start really looking
2787                                  * at serial numbers.
2788                                  */
2789                                 if (query->first_rr_serial == serial) {
2790                                         debug("got a match for ixfr");
2791                                         if (!query->first_repeat_rcvd) {
2792                                                 query->first_repeat_rcvd =
2793                                                         ISC_TRUE;
2794                                                 goto next_rdata;
2795                                         }
2796                                         debug("done with ixfr");
2797                                         goto doexit;
2798                                 }
2799                                 debug("meaningless soa %d", serial);
2800                         next_rdata:
2801                                 result = dns_rdataset_next(rdataset);
2802                         } while (result == ISC_R_SUCCESS);
2803                 }
2804                 result = dns_message_nextname(msg, DNS_SECTION_ANSWER);
2805         } while (result == ISC_R_SUCCESS);
2806         launch_next_query(query, ISC_FALSE);
2807         return (ISC_FALSE);
2808  doexit:
2809         received(sevent->n, &sevent->address, query);
2810         return (ISC_TRUE);
2811 }
2812
2813 /*%
2814  * Event handler for recv complete.  Perform whatever actions are necessary,
2815  * based on the specifics of the user's request.
2816  */
2817 static void
2818 recv_done(isc_task_t *task, isc_event_t *event) {
2819         isc_socketevent_t *sevent = NULL;
2820         dig_query_t *query = NULL;
2821         isc_buffer_t *b = NULL;
2822         dns_message_t *msg = NULL;
2823 #ifdef DIG_SIGCHASE
2824         dig_message_t *chase_msg = NULL;
2825         dig_message_t *chase_msg2 = NULL;
2826 #endif
2827         isc_result_t result;
2828         dig_lookup_t *n, *l;
2829         isc_boolean_t docancel = ISC_FALSE;
2830         isc_boolean_t match = ISC_TRUE;
2831         unsigned int parseflags;
2832         dns_messageid_t id;
2833         unsigned int msgflags;
2834 #ifdef DIG_SIGCHASE
2835         isc_result_t do_sigchase = ISC_FALSE;
2836
2837         dns_message_t *msg_temp = NULL;
2838         isc_region_t r;
2839         isc_buffer_t *buf = NULL;
2840 #endif
2841
2842         UNUSED(task);
2843         INSIST(!free_now);
2844
2845         debug("recv_done()");
2846
2847         LOCK_LOOKUP;
2848         recvcount--;
2849         debug("recvcount=%d", recvcount);
2850         INSIST(recvcount >= 0);
2851
2852         query = event->ev_arg;
2853         debug("lookup=%p, query=%p", query->lookup, query);
2854
2855         l = query->lookup;
2856
2857         REQUIRE(event->ev_type == ISC_SOCKEVENT_RECVDONE);
2858         sevent = (isc_socketevent_t *)event;
2859
2860         b = ISC_LIST_HEAD(sevent->bufferlist);
2861         INSIST(b == &query->recvbuf);
2862         ISC_LIST_DEQUEUE(sevent->bufferlist, &query->recvbuf, link);
2863
2864         if ((l->tcp_mode) && (l->timer != NULL))
2865                 isc_timer_touch(l->timer);
2866         if ((!l->pending && !l->ns_search_only) || cancel_now) {
2867                 debug("no longer pending.  Got %s",
2868                         isc_result_totext(sevent->result));
2869                 query->waiting_connect = ISC_FALSE;
2870
2871                 isc_event_free(&event);
2872                 clear_query(query);
2873                 check_next_lookup(l);
2874                 UNLOCK_LOOKUP;
2875                 return;
2876         }
2877
2878         if (sevent->result != ISC_R_SUCCESS) {
2879                 if (sevent->result == ISC_R_CANCELED) {
2880                         debug("in recv cancel handler");
2881                         query->waiting_connect = ISC_FALSE;
2882                 } else {
2883                         printf(";; communications error: %s\n",
2884                                isc_result_totext(sevent->result));
2885                         isc_socket_detach(&query->sock);
2886                         sockcount--;
2887                         debug("sockcount=%d", sockcount);
2888                         INSIST(sockcount >= 0);
2889                 }
2890                 isc_event_free(&event);
2891                 clear_query(query);
2892                 check_next_lookup(l);
2893                 UNLOCK_LOOKUP;
2894                 return;
2895         }
2896
2897         if (!l->tcp_mode &&
2898             !isc_sockaddr_compare(&sevent->address, &query->sockaddr,
2899                                   ISC_SOCKADDR_CMPADDR|
2900                                   ISC_SOCKADDR_CMPPORT|
2901                                   ISC_SOCKADDR_CMPSCOPE|
2902                                   ISC_SOCKADDR_CMPSCOPEZERO)) {
2903                 char buf1[ISC_SOCKADDR_FORMATSIZE];
2904                 char buf2[ISC_SOCKADDR_FORMATSIZE];
2905                 isc_sockaddr_t any;
2906
2907                 if (isc_sockaddr_pf(&query->sockaddr) == AF_INET)
2908                         isc_sockaddr_any(&any);
2909                 else
2910                         isc_sockaddr_any6(&any);
2911
2912                 /*
2913                 * We don't expect a match when the packet is
2914                 * sent to 0.0.0.0, :: or to a multicast addresses.
2915                 * XXXMPA broadcast needs to be handled here as well.
2916                 */
2917                 if ((!isc_sockaddr_eqaddr(&query->sockaddr, &any) &&
2918                      !isc_sockaddr_ismulticast(&query->sockaddr)) ||
2919                     isc_sockaddr_getport(&query->sockaddr) !=
2920                     isc_sockaddr_getport(&sevent->address)) {
2921                         isc_sockaddr_format(&sevent->address, buf1,
2922                         sizeof(buf1));
2923                         isc_sockaddr_format(&query->sockaddr, buf2,
2924                         sizeof(buf2));
2925                         printf(";; reply from unexpected source: %s,"
2926                         " expected %s\n", buf1, buf2);
2927                         match = ISC_FALSE;
2928                 }
2929         }
2930
2931         result = dns_message_peekheader(b, &id, &msgflags);
2932         if (result != ISC_R_SUCCESS || l->sendmsg->id != id) {
2933                 match = ISC_FALSE;
2934                 if (l->tcp_mode) {
2935                         isc_boolean_t fail = ISC_TRUE;
2936                         if (result == ISC_R_SUCCESS) {
2937                                 if (!query->first_soa_rcvd ||
2938                                      query->warn_id)
2939                                         printf(";; %s: ID mismatch: "
2940                                                "expected ID %u, got %u\n",
2941                                                query->first_soa_rcvd ?
2942                                                "WARNING" : "ERROR",
2943                                                l->sendmsg->id, id);
2944                                 if (query->first_soa_rcvd)
2945                                         fail = ISC_FALSE;
2946                                 query->warn_id = ISC_FALSE;
2947                         } else
2948                                 printf(";; ERROR: short "
2949                                        "(< header size) message\n");
2950                         if (fail) {
2951                                 isc_event_free(&event);
2952                                 clear_query(query);
2953                                 check_next_lookup(l);
2954                                 UNLOCK_LOOKUP;
2955                                 return;
2956                         }
2957                         match = ISC_TRUE;
2958                 } else if (result == ISC_R_SUCCESS)
2959                         printf(";; Warning: ID mismatch: "
2960                                "expected ID %u, got %u\n", l->sendmsg->id, id);
2961                 else
2962                         printf(";; Warning: short "
2963                                "(< header size) message received\n");
2964         }
2965
2966         if (result == ISC_R_SUCCESS && (msgflags & DNS_MESSAGEFLAG_QR) == 0)
2967                 printf(";; Warning: query response not set\n");
2968
2969         if (!match)
2970                 goto udp_mismatch;
2971
2972         result = dns_message_create(mctx, DNS_MESSAGE_INTENTPARSE, &msg);
2973         check_result(result, "dns_message_create");
2974
2975         if (key != NULL) {
2976                 if (l->querysig == NULL) {
2977                         debug("getting initial querysig");
2978                         result = dns_message_getquerytsig(l->sendmsg, mctx,
2979                                                           &l->querysig);
2980                         check_result(result, "dns_message_getquerytsig");
2981                 }
2982                 result = dns_message_setquerytsig(msg, l->querysig);
2983                 check_result(result, "dns_message_setquerytsig");
2984                 result = dns_message_settsigkey(msg, key);
2985                 check_result(result, "dns_message_settsigkey");
2986                 msg->tsigctx = l->tsigctx;
2987                 l->tsigctx = NULL;
2988                 if (l->msgcounter != 0)
2989                         msg->tcp_continuation = 1;
2990                 l->msgcounter++;
2991         }
2992
2993         debug("before parse starts");
2994         parseflags = DNS_MESSAGEPARSE_PRESERVEORDER;
2995 #ifdef DIG_SIGCHASE
2996         if (!l->sigchase) {
2997                 do_sigchase = ISC_FALSE;
2998         } else {
2999                 parseflags = 0;
3000                 do_sigchase = ISC_TRUE;
3001         }
3002 #endif
3003         if (l->besteffort) {
3004                 parseflags |= DNS_MESSAGEPARSE_BESTEFFORT;
3005                 parseflags |= DNS_MESSAGEPARSE_IGNORETRUNCATION;
3006         }
3007         result = dns_message_parse(msg, b, parseflags);
3008         if (result == DNS_R_RECOVERABLE) {
3009                 printf(";; Warning: Message parser reports malformed "
3010                        "message packet.\n");
3011                 result = ISC_R_SUCCESS;
3012         }
3013         if (result != ISC_R_SUCCESS) {
3014                 printf(";; Got bad packet: %s\n", isc_result_totext(result));
3015                 hex_dump(b);
3016                 query->waiting_connect = ISC_FALSE;
3017                 dns_message_destroy(&msg);
3018                 isc_event_free(&event);
3019                 clear_query(query);
3020                 cancel_lookup(l);
3021                 check_next_lookup(l);
3022                 UNLOCK_LOOKUP;
3023                 return;
3024         }
3025         if (msg->counts[DNS_SECTION_QUESTION] != 0) {
3026                 match = ISC_TRUE;
3027                 for (result = dns_message_firstname(msg, DNS_SECTION_QUESTION);
3028                      result == ISC_R_SUCCESS && match;
3029                      result = dns_message_nextname(msg, DNS_SECTION_QUESTION)) {
3030                         dns_name_t *name = NULL;
3031                         dns_rdataset_t *rdataset;
3032
3033                         dns_message_currentname(msg, DNS_SECTION_QUESTION,
3034                                                 &name);
3035                         for (rdataset = ISC_LIST_HEAD(name->list);
3036                              rdataset != NULL;
3037                              rdataset = ISC_LIST_NEXT(rdataset, link)) {
3038                                 if (l->rdtype != rdataset->type ||
3039                                     l->rdclass != rdataset->rdclass ||
3040                                     !dns_name_equal(l->name, name)) {
3041                                         char namestr[DNS_NAME_FORMATSIZE];
3042                                         char typebuf[DNS_RDATATYPE_FORMATSIZE];
3043                                         char classbuf[DNS_RDATACLASS_FORMATSIZE];
3044                                         dns_name_format(name, namestr,
3045                                                         sizeof(namestr));
3046                                         dns_rdatatype_format(rdataset->type,
3047                                                              typebuf,
3048                                                              sizeof(typebuf));
3049                                         dns_rdataclass_format(rdataset->rdclass,
3050                                                               classbuf,
3051                                                               sizeof(classbuf));
3052                                         printf(";; Question section mismatch: "
3053                                                "got %s/%s/%s\n",
3054                                                namestr, typebuf, classbuf);
3055                                         match = ISC_FALSE;
3056                                 }
3057                         }
3058                 }
3059                 if (!match) {
3060                         dns_message_destroy(&msg);
3061                         if (l->tcp_mode) {
3062                                 isc_event_free(&event);
3063                                 clear_query(query);
3064                                 check_next_lookup(l);
3065                                 UNLOCK_LOOKUP;
3066                                 return;
3067                         } else
3068                                 goto udp_mismatch;
3069                 }
3070         }
3071         if ((msg->flags & DNS_MESSAGEFLAG_TC) != 0 &&
3072             !l->ignore && !l->tcp_mode) {
3073                 printf(";; Truncated, retrying in TCP mode.\n");
3074                 n = requeue_lookup(l, ISC_TRUE);
3075                 n->tcp_mode = ISC_TRUE;
3076                 n->origin = query->lookup->origin;
3077                 dns_message_destroy(&msg);
3078                 isc_event_free(&event);
3079                 clear_query(query);
3080                 cancel_lookup(l);
3081                 check_next_lookup(l);
3082                 UNLOCK_LOOKUP;
3083                 return;
3084         }
3085         if ((msg->rcode == dns_rcode_servfail && !l->servfail_stops) ||
3086             (check_ra && (msg->flags & DNS_MESSAGEFLAG_RA) == 0 && l->recurse))
3087         {
3088                 dig_query_t *next = ISC_LIST_NEXT(query, link);
3089                 if (l->current_query == query)
3090                         l->current_query = NULL;
3091                 if (next != NULL) {
3092                         debug("sending query %p\n", next);
3093                         if (l->tcp_mode)
3094                                 send_tcp_connect(next);
3095                         else
3096                                 send_udp(next);
3097                 }
3098                 /*
3099                  * If our query is at the head of the list and there
3100                  * is no next, we're the only one left, so fall
3101                  * through to print the message.
3102                  */
3103                 if ((ISC_LIST_HEAD(l->q) != query) ||
3104                     (ISC_LIST_NEXT(query, link) != NULL)) {
3105                         if( l->comments == ISC_TRUE )
3106                                 printf(";; Got %s from %s, "
3107                                        "trying next server\n",
3108                                        msg->rcode == dns_rcode_servfail ?
3109                                        "SERVFAIL reply" :
3110                                        "recursion not available",
3111                                        query->servname);
3112                         clear_query(query);
3113                         check_next_lookup(l);
3114                         dns_message_destroy(&msg);
3115                         isc_event_free(&event);
3116                         UNLOCK_LOOKUP;
3117                         return;
3118                 }
3119         }
3120
3121         if (key != NULL) {
3122                 result = dns_tsig_verify(&query->recvbuf, msg, NULL, NULL);
3123                 if (result != ISC_R_SUCCESS) {
3124                         printf(";; Couldn't verify signature: %s\n",
3125                                isc_result_totext(result));
3126                         validated = ISC_FALSE;
3127                 }
3128                 l->tsigctx = msg->tsigctx;
3129                 msg->tsigctx = NULL;
3130                 if (l->querysig != NULL) {
3131                         debug("freeing querysig buffer %p", l->querysig);
3132                         isc_buffer_free(&l->querysig);
3133                 }
3134                 result = dns_message_getquerytsig(msg, mctx, &l->querysig);
3135                 check_result(result,"dns_message_getquerytsig");
3136         }
3137
3138         extrabytes = isc_buffer_remaininglength(b);
3139
3140         debug("after parse");
3141         if (l->doing_xfr && l->xfr_q == NULL) {
3142                 l->xfr_q = query;
3143                 /*
3144                  * Once we are in the XFR message, increase
3145                  * the timeout to much longer, so brief network
3146                  * outages won't cause the XFR to abort
3147                  */
3148                 if (timeout != INT_MAX && l->timer != NULL) {
3149                         unsigned int local_timeout;
3150
3151                         if (timeout == 0) {
3152                                 if (l->tcp_mode)
3153                                         local_timeout = TCP_TIMEOUT * 4;
3154                                 else
3155                                         local_timeout = UDP_TIMEOUT * 4;
3156                         } else {
3157                                 if (timeout < (INT_MAX / 4))
3158                                         local_timeout = timeout * 4;
3159                                 else
3160                                         local_timeout = INT_MAX;
3161                         }
3162                         debug("have local timeout of %d", local_timeout);
3163                         isc_interval_set(&l->interval, local_timeout, 0);
3164                         result = isc_timer_reset(l->timer,
3165                                                  isc_timertype_once,
3166                                                  NULL,
3167                                                  &l->interval,
3168                                                  ISC_FALSE);
3169                         check_result(result, "isc_timer_reset");
3170                 }
3171         }
3172
3173         if (!l->doing_xfr || l->xfr_q == query) {
3174                 if (msg->rcode != dns_rcode_noerror &&
3175                     (l->origin != NULL || l->need_search)) {
3176                         if (!next_origin(msg, query) || showsearch) {
3177                                 printmessage(query, msg, ISC_TRUE);
3178                                 received(b->used, &sevent->address, query);
3179                         }
3180                 } else if (!l->trace && !l->ns_search_only) {
3181 #ifdef DIG_SIGCHASE
3182                         if (!do_sigchase)
3183 #endif
3184                                 printmessage(query, msg, ISC_TRUE);
3185                 } else if (l->trace) {
3186                         int n = 0;
3187                         int count = msg->counts[DNS_SECTION_ANSWER];
3188
3189                         debug("in TRACE code");
3190                         if (!l->ns_search_only)
3191                                 printmessage(query, msg, ISC_TRUE);
3192
3193                         l->rdtype = l->qrdtype;
3194                         if (l->trace_root || (l->ns_search_only && count > 0)) {
3195                                 if (!l->trace_root)
3196                                         l->rdtype = dns_rdatatype_soa;
3197                                 n = followup_lookup(msg, query,
3198                                                     DNS_SECTION_ANSWER);
3199                                 l->trace_root = ISC_FALSE;
3200                         } else if (count == 0)
3201                                 n = followup_lookup(msg, query,
3202                                                     DNS_SECTION_AUTHORITY);
3203                         if (n == 0)
3204                                 docancel = ISC_TRUE;
3205                 } else {
3206                         debug("in NSSEARCH code");
3207
3208                         if (l->trace_root) {
3209                                 /*
3210                                  * This is the initial NS query.
3211                                  */
3212                                 int n;
3213
3214                                 l->rdtype = dns_rdatatype_soa;
3215                                 n = followup_lookup(msg, query,
3216                                                     DNS_SECTION_ANSWER);
3217                                 if (n == 0)
3218                                         docancel = ISC_TRUE;
3219                                 l->trace_root = ISC_FALSE;
3220                         } else
3221 #ifdef DIG_SIGCHASE
3222                                 if (!do_sigchase)
3223 #endif
3224                                 printmessage(query, msg, ISC_TRUE);
3225                 }
3226 #ifdef DIG_SIGCHASE
3227                 if (do_sigchase) {
3228                         chase_msg = isc_mem_allocate(mctx,
3229                                                      sizeof(dig_message_t));
3230                         if (chase_msg == NULL) {
3231                                 fatal("Memory allocation failure in %s:%d",
3232                                       __FILE__, __LINE__);
3233                         }
3234                         ISC_LIST_INITANDAPPEND(chase_message_list, chase_msg,
3235                                                link);
3236                         if (dns_message_create(mctx, DNS_MESSAGE_INTENTPARSE,
3237                                                &msg_temp) != ISC_R_SUCCESS) {
3238                                 fatal("dns_message_create in %s:%d",
3239                                       __FILE__, __LINE__);
3240                         }
3241
3242                         isc_buffer_usedregion(b, &r);
3243                         result = isc_buffer_allocate(mctx, &buf, r.length);
3244
3245                         check_result(result, "isc_buffer_allocate");
3246                         result =  isc_buffer_copyregion(buf, &r);
3247                         check_result(result, "isc_buffer_copyregion");
3248
3249                         result =  dns_message_parse(msg_temp, buf, 0);
3250
3251                         isc_buffer_free(&buf);
3252                         chase_msg->msg = msg_temp;
3253
3254                         chase_msg2 = isc_mem_allocate(mctx,
3255                                                       sizeof(dig_message_t));
3256                         if (chase_msg2 == NULL) {
3257                                 fatal("Memory allocation failure in %s:%d",
3258                                       __FILE__, __LINE__);
3259                         }
3260                         ISC_LIST_INITANDAPPEND(chase_message_list2, chase_msg2,
3261                                                link);
3262                         chase_msg2->msg = msg;
3263                 }
3264 #endif
3265         }
3266
3267 #ifdef DIG_SIGCHASE
3268         if (l->sigchase && ISC_LIST_EMPTY(lookup_list)) {
3269                 sigchase(msg_temp);
3270         }
3271 #endif
3272
3273         if (l->pending)
3274                 debug("still pending.");
3275         if (l->doing_xfr) {
3276                 if (query != l->xfr_q) {
3277                         dns_message_destroy(&msg);
3278                         isc_event_free(&event);
3279                         query->waiting_connect = ISC_FALSE;
3280                         UNLOCK_LOOKUP;
3281                         return;
3282                 }
3283                 if (!docancel)
3284                         docancel = check_for_more_data(query, msg, sevent);
3285                 if (docancel) {
3286                         dns_message_destroy(&msg);
3287                         clear_query(query);
3288                         cancel_lookup(l);
3289                         check_next_lookup(l);
3290                 }
3291         } else {
3292
3293                 if (msg->rcode == dns_rcode_noerror || l->origin == NULL) {
3294
3295 #ifdef DIG_SIGCHASE
3296                         if (!l->sigchase)
3297 #endif
3298                                 received(b->used, &sevent->address, query);
3299                 }
3300
3301                 if (!query->lookup->ns_search_only)
3302                         query->lookup->pending = ISC_FALSE;
3303                 if (!query->lookup->ns_search_only ||
3304                     query->lookup->trace_root || docancel) {
3305 #ifdef DIG_SIGCHASE
3306                         if (!do_sigchase)
3307 #endif
3308                                 dns_message_destroy(&msg);
3309
3310                         cancel_lookup(l);
3311                 }
3312                 clear_query(query);
3313                 check_next_lookup(l);
3314         }
3315         if (msg != NULL) {
3316 #ifdef DIG_SIGCHASE
3317                 if (do_sigchase)
3318                         msg = NULL;
3319                 else
3320 #endif
3321                         dns_message_destroy(&msg);
3322         }
3323         isc_event_free(&event);
3324         UNLOCK_LOOKUP;
3325         return;
3326
3327  udp_mismatch:
3328         isc_buffer_invalidate(&query->recvbuf);
3329         isc_buffer_init(&query->recvbuf, query->recvspace, COMMSIZE);
3330         ISC_LIST_ENQUEUE(query->recvlist, &query->recvbuf, link);
3331         result = isc_socket_recvv(query->sock, &query->recvlist, 1,
3332                                   global_task, recv_done, query);
3333         check_result(result, "isc_socket_recvv");
3334         recvcount++;
3335         isc_event_free(&event);
3336         UNLOCK_LOOKUP;
3337         return;
3338 }
3339
3340 /*%
3341  * Turn a name into an address, using system-supplied routines.  This is
3342  * used in looking up server names, etc... and needs to use system-supplied
3343  * routines, since they may be using a non-DNS system for these lookups.
3344  */
3345 isc_result_t
3346 get_address(char *host, in_port_t port, isc_sockaddr_t *sockaddr) {
3347         int count;
3348         isc_result_t result;
3349
3350         isc_app_block();
3351         result = bind9_getaddresses(host, port, sockaddr, 1, &count);
3352         isc_app_unblock();
3353         if (result != ISC_R_SUCCESS)
3354                 return (result);
3355
3356         INSIST(count == 1);
3357
3358         return (ISC_R_SUCCESS);
3359 }
3360
3361 /*%
3362  * Initiate either a TCP or UDP lookup
3363  */
3364 void
3365 do_lookup(dig_lookup_t *lookup) {
3366
3367         REQUIRE(lookup != NULL);
3368
3369         debug("do_lookup()");
3370         lookup->pending = ISC_TRUE;
3371         if (lookup->tcp_mode)
3372                 send_tcp_connect(ISC_LIST_HEAD(lookup->q));
3373         else
3374                 send_udp(ISC_LIST_HEAD(lookup->q));
3375 }
3376
3377 /*%
3378  * Start everything in action upon task startup.
3379  */
3380 void
3381 onrun_callback(isc_task_t *task, isc_event_t *event) {
3382         UNUSED(task);
3383
3384         isc_event_free(&event);
3385         LOCK_LOOKUP;
3386         start_lookup();
3387         UNLOCK_LOOKUP;
3388 }
3389
3390 /*%
3391  * Make everything on the lookup queue go away.  Mainly used by the
3392  * SIGINT handler.
3393  */
3394 void
3395 cancel_all(void) {
3396         dig_lookup_t *l, *n;
3397         dig_query_t *q, *nq;
3398
3399         debug("cancel_all()");
3400
3401         LOCK_LOOKUP;
3402         if (free_now) {
3403                 UNLOCK_LOOKUP;
3404                 return;
3405         }
3406         cancel_now = ISC_TRUE;
3407         if (current_lookup != NULL) {
3408                 if (current_lookup->timer != NULL)
3409                         isc_timer_detach(&current_lookup->timer);
3410                 q = ISC_LIST_HEAD(current_lookup->q);
3411                 while (q != NULL) {
3412                         debug("canceling query %p, belonging to %p",
3413                               q, current_lookup);
3414                         nq = ISC_LIST_NEXT(q, link);
3415                         if (q->sock != NULL) {
3416                                 isc_socket_cancel(q->sock, NULL,
3417                                                   ISC_SOCKCANCEL_ALL);
3418                         } else {
3419                                 clear_query(q);
3420                         }
3421                         q = nq;
3422                 }
3423         }
3424         l = ISC_LIST_HEAD(lookup_list);
3425         while (l != NULL) {
3426                 n = ISC_LIST_NEXT(l, link);
3427                 ISC_LIST_DEQUEUE(lookup_list, l, link);
3428                 try_clear_lookup(l);
3429                 l = n;
3430         }
3431         UNLOCK_LOOKUP;
3432 }
3433
3434 /*%
3435  * Destroy all of the libs we are using, and get everything ready for a
3436  * clean shutdown.
3437  */
3438 void
3439 destroy_libs(void) {
3440 #ifdef DIG_SIGCHASE
3441         void * ptr;
3442         dig_message_t *chase_msg;
3443 #endif
3444 #ifdef WITH_IDN
3445         isc_result_t result;
3446 #endif
3447
3448         debug("destroy_libs()");
3449         if (global_task != NULL) {
3450                 debug("freeing task");
3451                 isc_task_detach(&global_task);
3452         }
3453         /*
3454          * The taskmgr_destroy() call blocks until all events are cleared
3455          * from the task.
3456          */
3457         if (taskmgr != NULL) {
3458                 debug("freeing taskmgr");
3459                 isc_taskmgr_destroy(&taskmgr);
3460         }
3461         LOCK_LOOKUP;
3462         REQUIRE(sockcount == 0);
3463         REQUIRE(recvcount == 0);
3464         REQUIRE(sendcount == 0);
3465
3466         INSIST(ISC_LIST_HEAD(lookup_list) == NULL);
3467         INSIST(current_lookup == NULL);
3468         INSIST(!free_now);
3469
3470         free_now = ISC_TRUE;
3471
3472         lwres_conf_clear(lwctx);
3473         lwres_context_destroy(&lwctx);
3474
3475         flush_server_list();
3476
3477         clear_searchlist();
3478
3479 #ifdef WITH_IDN
3480         result = dns_name_settotextfilter(NULL);
3481         check_result(result, "dns_name_settotextfilter");
3482 #endif
3483         dns_name_destroy();
3484
3485         if (commctx != NULL) {
3486                 debug("freeing commctx");
3487                 isc_mempool_destroy(&commctx);
3488         }
3489         if (socketmgr != NULL) {
3490                 debug("freeing socketmgr");
3491                 isc_socketmgr_destroy(&socketmgr);
3492         }
3493         if (timermgr != NULL) {
3494                 debug("freeing timermgr");
3495                 isc_timermgr_destroy(&timermgr);
3496         }
3497         if (key != NULL) {
3498                 debug("freeing key %p", key);
3499                 dns_tsigkey_detach(&key);
3500         }
3501         if (namebuf != NULL)
3502                 isc_buffer_free(&namebuf);
3503
3504         if (is_dst_up) {
3505                 debug("destroy DST lib");
3506                 dst_lib_destroy();
3507                 is_dst_up = ISC_FALSE;
3508         }
3509         if (entp != NULL) {
3510                 debug("detach from entropy");
3511                 isc_entropy_detach(&entp);
3512         }
3513
3514         UNLOCK_LOOKUP;
3515         DESTROYLOCK(&lookup_lock);
3516 #ifdef DIG_SIGCHASE
3517
3518         debug("Destroy the messages kept for sigchase");
3519         /* Destroy the messages kept for sigchase */
3520         chase_msg = ISC_LIST_HEAD(chase_message_list);
3521
3522         while (chase_msg != NULL) {
3523                 INSIST(chase_msg->msg != NULL);
3524                 dns_message_destroy(&(chase_msg->msg));
3525                 ptr = chase_msg;
3526                 chase_msg = ISC_LIST_NEXT(chase_msg, link);
3527                 isc_mem_free(mctx, ptr);
3528         }
3529
3530         chase_msg = ISC_LIST_HEAD(chase_message_list2);
3531
3532         while (chase_msg != NULL) {
3533                 INSIST(chase_msg->msg != NULL);
3534                 dns_message_destroy(&(chase_msg->msg));
3535                 ptr = chase_msg;
3536                 chase_msg = ISC_LIST_NEXT(chase_msg, link);
3537                 isc_mem_free(mctx, ptr);
3538         }
3539         if (dns_name_dynamic(&chase_name))
3540                 free_name(&chase_name, mctx);
3541 #if DIG_SIGCHASE_TD
3542         if (dns_name_dynamic(&chase_current_name))
3543                 free_name(&chase_current_name, mctx);
3544         if (dns_name_dynamic(&chase_authority_name))
3545                 free_name(&chase_authority_name, mctx);
3546 #endif
3547 #if DIG_SIGCHASE_BU
3548         if (dns_name_dynamic(&chase_signame))
3549                 free_name(&chase_signame, mctx);
3550 #endif
3551
3552         debug("Destroy memory");
3553
3554 #endif
3555         if (memdebugging != 0)
3556                 isc_mem_stats(mctx, stderr);
3557         if (mctx != NULL)
3558                 isc_mem_destroy(&mctx);
3559 }
3560
3561 #ifdef WITH_IDN
3562 static void
3563 initialize_idn(void) {
3564         idn_result_t r;
3565         isc_result_t result;
3566
3567 #ifdef HAVE_SETLOCALE
3568         /* Set locale */
3569         (void)setlocale(LC_ALL, "");
3570 #endif
3571         /* Create configuration context. */
3572         r = idn_nameinit(1);
3573         if (r != idn_success)
3574                 fatal("idn api initialization failed: %s",
3575                       idn_result_tostring(r));
3576
3577         /* Set domain name -> text post-conversion filter. */
3578         result = dns_name_settotextfilter(output_filter);
3579         check_result(result, "dns_name_settotextfilter");
3580 }
3581
3582 static isc_result_t
3583 output_filter(isc_buffer_t *buffer, unsigned int used_org,
3584               isc_boolean_t absolute)
3585 {
3586         char tmp1[MAXDLEN], tmp2[MAXDLEN];
3587         size_t fromlen, tolen;
3588         isc_boolean_t end_with_dot;
3589
3590         /*
3591          * Copy contents of 'buffer' to 'tmp1', supply trailing dot
3592          * if 'absolute' is true, and terminate with NUL.
3593          */
3594         fromlen = isc_buffer_usedlength(buffer) - used_org;
3595         if (fromlen >= MAXDLEN)
3596                 return (ISC_R_SUCCESS);
3597         memcpy(tmp1, (char *)isc_buffer_base(buffer) + used_org, fromlen);
3598         end_with_dot = (tmp1[fromlen - 1] == '.') ? ISC_TRUE : ISC_FALSE;
3599         if (absolute && !end_with_dot) {
3600                 fromlen++;
3601                 if (fromlen >= MAXDLEN)
3602                         return (ISC_R_SUCCESS);
3603                 tmp1[fromlen - 1] = '.';
3604         }
3605         tmp1[fromlen] = '\0';
3606
3607         /*
3608          * Convert contents of 'tmp1' to local encoding.
3609          */
3610         if (idn_decodename(IDN_DECODE_APP, tmp1, tmp2, MAXDLEN) != idn_success)
3611                 return (ISC_R_SUCCESS);
3612         strcpy(tmp1, tmp2);
3613
3614         /*
3615          * Copy the converted contents in 'tmp1' back to 'buffer'.
3616          * If we have appended trailing dot, remove it.
3617          */
3618         tolen = strlen(tmp1);
3619         if (absolute && !end_with_dot && tmp1[tolen - 1] == '.')
3620                 tolen--;
3621
3622         if (isc_buffer_length(buffer) < used_org + tolen)
3623                 return (ISC_R_NOSPACE);
3624
3625         isc_buffer_subtract(buffer, isc_buffer_usedlength(buffer) - used_org);
3626         memcpy(isc_buffer_used(buffer), tmp1, tolen);
3627         isc_buffer_add(buffer, tolen);
3628
3629         return (ISC_R_SUCCESS);
3630 }
3631
3632 static idn_result_t
3633 append_textname(char *name, const char *origin, size_t namesize) {
3634         size_t namelen = strlen(name);
3635         size_t originlen = strlen(origin);
3636
3637         /* Already absolute? */
3638         if (namelen > 0 && name[namelen - 1] == '.')
3639                 return idn_success;
3640
3641         /* Append dot and origin */
3642
3643         if (namelen + 1 + originlen >= namesize)
3644                 return idn_buffer_overflow;
3645
3646         name[namelen++] = '.';
3647         (void)strcpy(name + namelen, origin);
3648         return idn_success;
3649 }
3650
3651 static void
3652 idn_check_result(idn_result_t r, const char *msg) {
3653         if (r != idn_success) {
3654                 exitcode = 1;
3655                 fatal("%s: %s", msg, idn_result_tostring(r));
3656         }
3657 }
3658 #endif /* WITH_IDN */
3659
3660 #ifdef DIG_SIGCHASE
3661 void
3662 print_type(dns_rdatatype_t type)
3663 {
3664         isc_buffer_t * b = NULL;
3665         isc_result_t result;
3666         isc_region_t r;
3667
3668         result = isc_buffer_allocate(mctx, &b, 4000);
3669         check_result(result, "isc_buffer_allocate");
3670
3671         result = dns_rdatatype_totext(type, b);
3672         check_result(result, "print_type");
3673
3674         isc_buffer_usedregion(b, &r);
3675         r.base[r.length] = '\0';
3676
3677         printf("%s", r.base);
3678
3679         isc_buffer_free(&b);
3680 }
3681
3682 void
3683 dump_database_section(dns_message_t *msg, int section)
3684 {
3685         dns_name_t *msg_name=NULL;
3686
3687         dns_rdataset_t *rdataset;
3688
3689         do {
3690                 dns_message_currentname(msg, section, &msg_name);
3691
3692                 for (rdataset = ISC_LIST_HEAD(msg_name->list); rdataset != NULL;
3693                      rdataset = ISC_LIST_NEXT(rdataset, link)) {
3694                         dns_name_print(msg_name, stdout);
3695                         printf("\n");
3696                         print_rdataset(msg_name, rdataset, mctx);
3697                         printf("end\n");
3698                 }
3699                 msg_name = NULL;
3700         } while (dns_message_nextname(msg, section) == ISC_R_SUCCESS);
3701 }
3702
3703 void
3704 dump_database(void) {
3705         dig_message_t * msg;
3706
3707         for (msg = ISC_LIST_HEAD(chase_message_list);  msg != NULL;
3708              msg = ISC_LIST_NEXT(msg, link)) {
3709                 if (dns_message_firstname(msg->msg, DNS_SECTION_ANSWER)
3710                     == ISC_R_SUCCESS)
3711                         dump_database_section(msg->msg, DNS_SECTION_ANSWER);
3712
3713                 if (dns_message_firstname(msg->msg, DNS_SECTION_AUTHORITY)
3714                     == ISC_R_SUCCESS)
3715                         dump_database_section(msg->msg, DNS_SECTION_AUTHORITY);
3716
3717                 if (dns_message_firstname(msg->msg, DNS_SECTION_ADDITIONAL)
3718                     == ISC_R_SUCCESS)
3719                         dump_database_section(msg->msg, DNS_SECTION_ADDITIONAL);
3720         }
3721 }
3722
3723
3724 dns_rdataset_t *
3725 search_type(dns_name_t *name, dns_rdatatype_t type, dns_rdatatype_t covers) {
3726         dns_rdataset_t *rdataset;
3727         dns_rdata_sig_t siginfo;
3728         dns_rdata_t sigrdata = DNS_RDATA_INIT;
3729         isc_result_t result;
3730
3731         for (rdataset = ISC_LIST_HEAD(name->list); rdataset != NULL;
3732              rdataset = ISC_LIST_NEXT(rdataset, link)) {
3733                 if (type == dns_rdatatype_any) {
3734                         if (rdataset->type != dns_rdatatype_rrsig)
3735                                 return (rdataset);
3736                 } else if ((type == dns_rdatatype_rrsig) &&
3737                            (rdataset->type == dns_rdatatype_rrsig)) {
3738                         result = dns_rdataset_first(rdataset);
3739                         check_result(result, "empty rdataset");
3740                         dns_rdataset_current(rdataset, &sigrdata);
3741                         result = dns_rdata_tostruct(&sigrdata, &siginfo, NULL);
3742                         check_result(result, "sigrdata tostruct siginfo");
3743
3744                         if ((siginfo.covered == covers) ||
3745                             (covers == dns_rdatatype_any)) {
3746                                 dns_rdata_reset(&sigrdata);
3747                                 dns_rdata_freestruct(&siginfo);
3748                                 return (rdataset);
3749                         }
3750                         dns_rdata_reset(&sigrdata);
3751                         dns_rdata_freestruct(&siginfo);
3752                 } else if (rdataset->type == type)
3753                         return (rdataset);
3754         }
3755         return (NULL);
3756 }
3757
3758 dns_rdataset_t *
3759 chase_scanname_section(dns_message_t *msg, dns_name_t *name,
3760                        dns_rdatatype_t type, dns_rdatatype_t covers,
3761                        int section)
3762 {
3763         dns_rdataset_t *rdataset;
3764         dns_name_t *msg_name = NULL;
3765
3766         do {
3767                 dns_message_currentname(msg, section, &msg_name);
3768                 if (dns_name_compare(msg_name, name) == 0) {
3769                         rdataset = search_type(msg_name, type, covers);
3770                         if (rdataset != NULL)
3771                                 return (rdataset);
3772                 }
3773                 msg_name = NULL;
3774         } while (dns_message_nextname(msg, section) == ISC_R_SUCCESS);
3775
3776         return (NULL);
3777 }
3778
3779
3780 dns_rdataset_t *
3781 chase_scanname(dns_name_t *name, dns_rdatatype_t type, dns_rdatatype_t covers)
3782 {
3783         dns_rdataset_t *rdataset = NULL;
3784         dig_message_t * msg;
3785
3786         for (msg = ISC_LIST_HEAD(chase_message_list2);  msg != NULL;
3787              msg = ISC_LIST_NEXT(msg, link)) {
3788                 if (dns_message_firstname(msg->msg, DNS_SECTION_ANSWER)
3789                     == ISC_R_SUCCESS)
3790                         rdataset = chase_scanname_section(msg->msg, name,
3791                                                           type, covers,
3792                                                           DNS_SECTION_ANSWER);
3793                         if (rdataset != NULL)
3794                                 return (rdataset);
3795                 if (dns_message_firstname(msg->msg, DNS_SECTION_AUTHORITY)
3796                     == ISC_R_SUCCESS)
3797                         rdataset =
3798                                 chase_scanname_section(msg->msg, name,
3799                                                        type, covers,
3800                                                        DNS_SECTION_AUTHORITY);
3801                         if (rdataset != NULL)
3802                                 return (rdataset);
3803                 if (dns_message_firstname(msg->msg, DNS_SECTION_ADDITIONAL)
3804                     == ISC_R_SUCCESS)
3805                         rdataset =
3806                                 chase_scanname_section(msg->msg, name, type,
3807                                                        covers,
3808                                                        DNS_SECTION_ADDITIONAL);
3809                         if (rdataset != NULL)
3810                                 return (rdataset);
3811         }
3812
3813         return (NULL);
3814 }
3815
3816 dns_rdataset_t *
3817 sigchase_scanname(dns_rdatatype_t type, dns_rdatatype_t covers,
3818                   isc_boolean_t * lookedup, dns_name_t *rdata_name)
3819 {
3820         dig_lookup_t *lookup;
3821         isc_buffer_t *b = NULL;
3822         isc_region_t r;
3823         isc_result_t result;
3824         dns_rdataset_t * temp;
3825         dns_rdatatype_t querytype;
3826
3827         temp = chase_scanname(rdata_name, type, covers);
3828         if (temp != NULL)
3829                 return (temp);
3830
3831         if (*lookedup == ISC_TRUE)
3832                 return (NULL);
3833
3834         lookup = clone_lookup(current_lookup, ISC_TRUE);
3835         lookup->trace_root = ISC_FALSE;
3836         lookup->new_search = ISC_TRUE;
3837
3838         result = isc_buffer_allocate(mctx, &b, BUFSIZE);
3839         check_result(result, "isc_buffer_allocate");
3840         result = dns_name_totext(rdata_name, ISC_FALSE, b);
3841         check_result(result, "dns_name_totext");
3842         isc_buffer_usedregion(b, &r);
3843         r.base[r.length] = '\0';
3844         strcpy(lookup->textname, (char*)r.base);
3845         isc_buffer_free(&b);
3846
3847         if (type ==  dns_rdatatype_rrsig)
3848                 querytype = covers;
3849         else
3850                 querytype = type;
3851
3852         if (querytype == 0 || querytype == 255) {
3853                 printf("Error in the queried type: %d\n", querytype);
3854                 return (NULL);
3855         }
3856
3857         lookup->rdtype = querytype;
3858         lookup->rdtypeset = ISC_TRUE;
3859         lookup->qrdtype = querytype;
3860         *lookedup = ISC_TRUE;
3861
3862         ISC_LIST_APPEND(lookup_list, lookup, link);
3863         printf("\n\nLaunch a query to find a RRset of type ");
3864         print_type(type);
3865         printf(" for zone: %s\n", lookup->textname);
3866         return (NULL);
3867 }
3868
3869 void
3870 insert_trustedkey(dst_key_t **keyp)
3871 {
3872         if (*keyp == NULL)
3873                 return;
3874         if (tk_list.nb_tk >= MAX_TRUSTED_KEY)
3875                 return;
3876
3877         tk_list.key[tk_list.nb_tk++] = *keyp;
3878         *keyp = NULL;
3879         return;
3880 }
3881
3882 void
3883 clean_trustedkey()
3884 {
3885         int i = 0;
3886
3887         for (i= 0; i < MAX_TRUSTED_KEY; i++) {
3888                 if (tk_list.key[i] != NULL) {
3889                         dst_key_free(&tk_list.key[i]);
3890                         tk_list.key[i] = NULL;
3891                 } else
3892                         break;
3893         }
3894         tk_list.nb_tk = 0;
3895         return;
3896 }
3897
3898 char alphnum[] =
3899         "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
3900
3901 isc_result_t
3902 removetmpkey(isc_mem_t *mctx, const char *file)
3903 {
3904         char *tempnamekey = NULL;
3905         int tempnamekeylen;
3906         isc_result_t result;
3907
3908         tempnamekeylen = strlen(file)+10;
3909
3910         tempnamekey = isc_mem_allocate(mctx, tempnamekeylen);
3911         if (tempnamekey == NULL)
3912                 return (ISC_R_NOMEMORY);
3913
3914         memset(tempnamekey, 0, tempnamekeylen);
3915
3916         strcat(tempnamekey, file);
3917         strcat(tempnamekey,".key");
3918         isc_file_remove(tempnamekey);
3919
3920         result = isc_file_remove(tempnamekey);
3921         isc_mem_free(mctx, tempnamekey);
3922         return (result);
3923 }
3924
3925 isc_result_t
3926 opentmpkey(isc_mem_t *mctx, const char *file, char **tempp, FILE **fp) {
3927         FILE *f = NULL;
3928         isc_result_t result;
3929         char *tempname = NULL;
3930         char *tempnamekey = NULL;
3931         int tempnamelen;
3932         int tempnamekeylen;
3933         char *x;
3934         char *cp;
3935         isc_uint32_t which;
3936
3937         while (1) {
3938                 tempnamelen = strlen(file) + 20;
3939                 tempname = isc_mem_allocate(mctx, tempnamelen);
3940                 if (tempname == NULL)
3941                         return (ISC_R_NOMEMORY);
3942                 memset(tempname, 0, tempnamelen);
3943
3944                 result = isc_file_mktemplate(file, tempname, tempnamelen);
3945                 if (result != ISC_R_SUCCESS)
3946                         goto cleanup;
3947
3948                 cp = tempname;
3949                 while (*cp != '\0')
3950                         cp++;
3951                 if (cp == tempname) {
3952                         isc_mem_free(mctx, tempname);
3953                         return (ISC_R_FAILURE);
3954                 }
3955
3956                 x = cp--;
3957                 while (cp >= tempname && *cp == 'X') {
3958                         isc_random_get(&which);
3959                         *cp = alphnum[which % (sizeof(alphnum) - 1)];
3960                         x = cp--;
3961                 }
3962
3963                 tempnamekeylen = tempnamelen+5;
3964                 tempnamekey = isc_mem_allocate(mctx, tempnamekeylen);
3965                 if (tempnamekey == NULL)
3966                         return (ISC_R_NOMEMORY);
3967
3968                 memset(tempnamekey, 0, tempnamekeylen);
3969                 strncpy(tempnamekey, tempname, tempnamelen);
3970                 strcat(tempnamekey ,".key");
3971
3972
3973                 if (isc_file_exists(tempnamekey)) {
3974                         isc_mem_free(mctx, tempnamekey);
3975                         isc_mem_free(mctx, tempname);
3976                         continue;
3977                 }
3978
3979                 if ((f = fopen(tempnamekey, "w")) == NULL) {
3980                         printf("get_trusted_key(): trusted key not found %s\n",
3981                                tempnamekey);
3982                         return (ISC_R_FAILURE);
3983                 }
3984                 break;
3985         }
3986         isc_mem_free(mctx, tempnamekey);
3987         *tempp = tempname;
3988         *fp = f;
3989         return (ISC_R_SUCCESS);
3990
3991  cleanup:
3992         isc_mem_free(mctx, tempname);
3993
3994         return (result);
3995 }
3996
3997
3998 isc_result_t
3999 get_trusted_key(isc_mem_t *mctx)
4000 {
4001         isc_result_t result;
4002         const char *filename = NULL;
4003         char *filetemp = NULL;
4004         char buf[1500];
4005         FILE *fp, *fptemp;
4006         dst_key_t *key = NULL;
4007
4008         result = isc_file_exists(trustedkey);
4009         if (result !=  ISC_TRUE) {
4010                 result = isc_file_exists("/etc/trusted-key.key");
4011                 if (result !=  ISC_TRUE) {
4012                         result = isc_file_exists("./trusted-key.key");
4013                         if (result !=  ISC_TRUE)
4014                                 return (ISC_R_FAILURE);
4015                         else
4016                                 filename = "./trusted-key.key";
4017                 } else
4018                         filename = "/etc/trusted-key.key";
4019         } else
4020                 filename = trustedkey;
4021
4022         if (filename == NULL) {
4023                 printf("No trusted key\n");
4024                 return (ISC_R_FAILURE);
4025         }
4026
4027         if ((fp = fopen(filename, "r")) == NULL) {
4028                 printf("get_trusted_key(): trusted key not found %s\n",
4029                        filename);
4030                 return (ISC_R_FAILURE);
4031         }
4032         while (fgets(buf, sizeof(buf), fp) != NULL) {
4033                 result = opentmpkey(mctx,"tmp_file", &filetemp, &fptemp);
4034                 if (result != ISC_R_SUCCESS) {
4035                         fclose(fp);
4036                         return (ISC_R_FAILURE);
4037                 }
4038                 if (fputs(buf, fptemp) < 0) {
4039                         fclose(fp);
4040                         fclose(fptemp);
4041                         return (ISC_R_FAILURE);
4042                 }
4043                 fclose(fptemp);
4044                 result = dst_key_fromnamedfile(filetemp, DST_TYPE_PUBLIC,
4045                                                mctx, &key);
4046                 removetmpkey(mctx, filetemp);
4047                 isc_mem_free(mctx, filetemp);
4048                 if (result !=  ISC_R_SUCCESS) {
4049                         fclose(fp);
4050                         return (ISC_R_FAILURE);
4051                 }
4052 #if 0
4053                 dst_key_tofile(key, DST_TYPE_PUBLIC,"/tmp");
4054 #endif
4055                 insert_trustedkey(&key);
4056                 if (key != NULL)
4057                         dst_key_free(&key);
4058         }
4059         return (ISC_R_SUCCESS);
4060 }
4061
4062
4063 static void
4064 nameFromString(const char *str, dns_name_t *p_ret) {
4065         size_t len = strlen(str);
4066         isc_result_t result;
4067         isc_buffer_t buffer;
4068         dns_fixedname_t fixedname;
4069
4070         REQUIRE(p_ret != NULL);
4071         REQUIRE(str != NULL);
4072
4073         isc_buffer_init(&buffer, str, len);
4074         isc_buffer_add(&buffer, len);
4075
4076         dns_fixedname_init(&fixedname);
4077         result = dns_name_fromtext(dns_fixedname_name(&fixedname), &buffer,
4078                                    dns_rootname, ISC_TRUE, NULL);
4079         check_result(result, "nameFromString");
4080
4081         if (dns_name_dynamic(p_ret))
4082                 free_name(p_ret, mctx);
4083
4084         result = dns_name_dup(dns_fixedname_name(&fixedname), mctx, p_ret);
4085         check_result(result, "nameFromString");
4086 }
4087
4088
4089 #if DIG_SIGCHASE_TD
4090 isc_result_t
4091 prepare_lookup(dns_name_t *name)
4092 {
4093         isc_result_t result;
4094         dig_lookup_t *lookup = NULL;
4095         dig_server_t *s;
4096         void *ptr;
4097
4098         lookup = clone_lookup(current_lookup, ISC_TRUE);
4099         lookup->trace_root = ISC_FALSE;
4100         lookup->new_search = ISC_TRUE;
4101         lookup->trace_root_sigchase = ISC_FALSE;
4102
4103         strncpy(lookup->textname, lookup->textnamesigchase, MXNAME);
4104
4105         lookup->rdtype = lookup->rdtype_sigchase;
4106         lookup->rdtypeset = ISC_TRUE;
4107         lookup->qrdtype = lookup->qrdtype_sigchase;
4108
4109         s = ISC_LIST_HEAD(lookup->my_server_list);
4110         while (s != NULL) {
4111                 debug("freeing server %p belonging to %p",
4112                       s, lookup);
4113                 ptr = s;
4114                 s = ISC_LIST_NEXT(s, link);
4115                 ISC_LIST_DEQUEUE(lookup->my_server_list,
4116                                  (dig_server_t *)ptr, link);
4117                 isc_mem_free(mctx, ptr);
4118         }
4119
4120
4121         for (result = dns_rdataset_first(chase_nsrdataset);
4122              result == ISC_R_SUCCESS;
4123              result = dns_rdataset_next(chase_nsrdataset)) {
4124                 char namestr[DNS_NAME_FORMATSIZE];
4125                 dns_rdata_ns_t ns;
4126                 dns_rdata_t rdata = DNS_RDATA_INIT;
4127                 dig_server_t * srv = NULL;
4128 #define __FOLLOW_GLUE__
4129 #ifdef __FOLLOW_GLUE__
4130                 isc_buffer_t *b = NULL;
4131                 isc_result_t result;
4132                 isc_region_t r;
4133                 dns_rdataset_t *rdataset = NULL;
4134                 isc_boolean_t true = ISC_TRUE;
4135 #endif
4136
4137                 memset(namestr, 0, DNS_NAME_FORMATSIZE);
4138
4139                 dns_rdataset_current(chase_nsrdataset, &rdata);
4140
4141                 result = dns_rdata_tostruct(&rdata, &ns, NULL);
4142                 check_result(result, "dns_rdata_tostruct");
4143
4144 #ifdef __FOLLOW_GLUE__
4145
4146                 result = advanced_rrsearch(&rdataset, &ns.name,
4147                                            dns_rdatatype_aaaa,
4148                                            dns_rdatatype_any, &true);
4149                 if (result == ISC_R_SUCCESS) {
4150                         for (result = dns_rdataset_first(rdataset);
4151                              result == ISC_R_SUCCESS;
4152                              result = dns_rdataset_next(rdataset)) {
4153                                 dns_rdata_t aaaa = DNS_RDATA_INIT;
4154                                 dns_rdataset_current(rdataset, &aaaa);
4155
4156                                 result = isc_buffer_allocate(mctx, &b, 80);
4157                                 check_result(result, "isc_buffer_allocate");
4158
4159                                 dns_rdata_totext(&aaaa, &ns.name, b);
4160                                 isc_buffer_usedregion(b, &r);
4161                                 r.base[r.length] = '\0';
4162                                 strncpy(namestr, (char*)r.base,
4163                                         DNS_NAME_FORMATSIZE);
4164                                 isc_buffer_free(&b);
4165                                 dns_rdata_reset(&aaaa);
4166
4167
4168                                 srv = make_server(namestr, namestr);
4169
4170                                 ISC_LIST_APPEND(lookup->my_server_list,
4171                                                 srv, link);
4172                         }
4173                 }
4174
4175                 rdataset = NULL;
4176                 result = advanced_rrsearch(&rdataset, &ns.name, dns_rdatatype_a,
4177                                            dns_rdatatype_any, &true);
4178                 if (result == ISC_R_SUCCESS) {
4179                         for (result = dns_rdataset_first(rdataset);
4180                              result == ISC_R_SUCCESS;
4181                              result = dns_rdataset_next(rdataset)) {
4182                                 dns_rdata_t a = DNS_RDATA_INIT;
4183                                 dns_rdataset_current(rdataset, &a);
4184
4185                                 result = isc_buffer_allocate(mctx, &b, 80);
4186                                 check_result(result, "isc_buffer_allocate");
4187
4188                                 dns_rdata_totext(&a, &ns.name, b);
4189                                 isc_buffer_usedregion(b, &r);
4190                                 r.base[r.length] = '\0';
4191                                 strncpy(namestr, (char*)r.base,
4192                                         DNS_NAME_FORMATSIZE);
4193                                 isc_buffer_free(&b);
4194                                 dns_rdata_reset(&a);
4195                                 printf("ns name: %s\n", namestr);
4196
4197
4198                                 srv = make_server(namestr, namestr);
4199
4200                                 ISC_LIST_APPEND(lookup->my_server_list,
4201                                                 srv, link);
4202                         }
4203                 }
4204 #else
4205
4206                 dns_name_format(&ns.name, namestr, sizeof(namestr));
4207                 printf("ns name: ");
4208                 dns_name_print(&ns.name, stdout);
4209                 printf("\n");
4210                 srv = make_server(namestr, namestr);
4211
4212                 ISC_LIST_APPEND(lookup->my_server_list, srv, link);
4213
4214 #endif
4215                 dns_rdata_freestruct(&ns);
4216                 dns_rdata_reset(&rdata);
4217
4218         }
4219
4220         ISC_LIST_APPEND(lookup_list, lookup, link);
4221         printf("\nLaunch a query to find a RRset of type ");
4222         print_type(lookup->rdtype);
4223         printf(" for zone: %s", lookup->textname);
4224         printf(" with nameservers:");
4225         printf("\n");
4226         print_rdataset(name, chase_nsrdataset, mctx);
4227         return (ISC_R_SUCCESS);
4228 }
4229
4230
4231 isc_result_t
4232 child_of_zone(dns_name_t * name, dns_name_t * zone_name,
4233               dns_name_t * child_name)
4234 {
4235         dns_namereln_t name_reln;
4236         int orderp;
4237         unsigned int nlabelsp;
4238
4239         name_reln = dns_name_fullcompare(name, zone_name, &orderp, &nlabelsp);
4240         if (name_reln != dns_namereln_subdomain ||
4241             dns_name_countlabels(name) <= dns_name_countlabels(zone_name) + 1) {
4242                 printf("\n;; ERROR : ");
4243                 dns_name_print(name, stdout);
4244                 printf(" is not a subdomain of: ");
4245                 dns_name_print(zone_name, stdout);
4246                 printf(" FAILED\n\n");
4247                 return (ISC_R_FAILURE);
4248         }
4249
4250         dns_name_getlabelsequence(name,
4251                                   dns_name_countlabels(name) -
4252                                   dns_name_countlabels(zone_name) -1,
4253                                   dns_name_countlabels(zone_name) +1,
4254                                   child_name);
4255         return (ISC_R_SUCCESS);
4256 }
4257
4258 isc_result_t
4259 grandfather_pb_test(dns_name_t *zone_name, dns_rdataset_t  *sigrdataset)
4260 {
4261         isc_result_t result;
4262         dns_rdata_t sigrdata = DNS_RDATA_INIT;
4263         dns_rdata_sig_t siginfo;
4264
4265         result = dns_rdataset_first(sigrdataset);
4266         check_result(result, "empty RRSIG dataset");
4267         dns_rdata_init(&sigrdata);
4268
4269         do {
4270                 dns_rdataset_current(sigrdataset, &sigrdata);
4271
4272                 result = dns_rdata_tostruct(&sigrdata, &siginfo, NULL);
4273                 check_result(result, "sigrdata tostruct siginfo");
4274
4275                 if (dns_name_compare(&siginfo.signer, zone_name) == 0) {
4276                         dns_rdata_freestruct(&siginfo);
4277                         dns_rdata_reset(&sigrdata);
4278                         return (ISC_R_SUCCESS);
4279                 }
4280
4281                 dns_rdata_freestruct(&siginfo);
4282                 dns_rdata_reset(&sigrdata);
4283
4284         } while (dns_rdataset_next(chase_sigkeyrdataset) == ISC_R_SUCCESS);
4285
4286         dns_rdata_reset(&sigrdata);
4287
4288         return (ISC_R_FAILURE);
4289 }
4290
4291
4292 isc_result_t
4293 initialization(dns_name_t *name)
4294 {
4295         isc_result_t   result;
4296         isc_boolean_t  true = ISC_TRUE;
4297
4298         chase_nsrdataset = NULL;
4299         result = advanced_rrsearch(&chase_nsrdataset, name, dns_rdatatype_ns,
4300                                    dns_rdatatype_any, &true);
4301         if (result != ISC_R_SUCCESS) {
4302                 printf("\n;; NS RRset is missing to continue validation:"
4303                        " FAILED\n\n");
4304                 return (ISC_R_FAILURE);
4305         }
4306         INSIST(chase_nsrdataset != NULL);
4307         prepare_lookup(name);
4308
4309         dup_name(name, &chase_current_name, mctx);
4310
4311         return (ISC_R_SUCCESS);
4312 }
4313 #endif
4314
4315 void
4316 print_rdataset(dns_name_t *name, dns_rdataset_t *rdataset, isc_mem_t *mctx)
4317 {
4318         isc_buffer_t *b = NULL;
4319         isc_result_t result;
4320         isc_region_t r;
4321
4322         result = isc_buffer_allocate(mctx, &b, 9000);
4323         check_result(result, "isc_buffer_allocate");
4324
4325         printrdataset(name, rdataset, b);
4326
4327         isc_buffer_usedregion(b, &r);
4328         r.base[r.length] = '\0';
4329
4330
4331         printf("%s\n", r.base);
4332
4333         isc_buffer_free(&b);
4334 }
4335
4336
4337 void
4338 dup_name(dns_name_t *source, dns_name_t *target, isc_mem_t *mctx) {
4339         isc_result_t result;
4340
4341         if (dns_name_dynamic(target))
4342                 free_name(target, mctx);
4343         result = dns_name_dup(source, mctx, target);
4344         check_result(result, "dns_name_dup");
4345 }
4346
4347 void
4348 free_name(dns_name_t *name, isc_mem_t *mctx) {
4349         dns_name_free(name, mctx);
4350         dns_name_init(name, NULL);
4351 }
4352
4353 /*
4354  *
4355  * take a DNSKEY RRset and the RRSIG RRset corresponding in parameter
4356  * return ISC_R_SUCCESS if the DNSKEY RRset contains a trusted_key
4357  *                      and the RRset is valid
4358  * return ISC_R_NOTFOUND if not contains trusted key
4359                         or if the RRset isn't valid
4360  * return ISC_R_FAILURE if problem
4361  *
4362  */
4363 isc_result_t
4364 contains_trusted_key(dns_name_t *name, dns_rdataset_t *rdataset,
4365                      dns_rdataset_t *sigrdataset,
4366                      isc_mem_t *mctx)
4367 {
4368         isc_result_t result;
4369         dns_rdata_t rdata = DNS_RDATA_INIT;
4370         dst_key_t *trustedKey = NULL;
4371         dst_key_t *dnsseckey = NULL;
4372         int i;
4373
4374         if (name == NULL || rdataset == NULL)
4375                 return (ISC_R_FAILURE);
4376
4377         result = dns_rdataset_first(rdataset);
4378         check_result(result, "empty rdataset");
4379
4380         do {
4381                 dns_rdataset_current(rdataset, &rdata);
4382                 INSIST(rdata.type == dns_rdatatype_dnskey);
4383
4384                 result = dns_dnssec_keyfromrdata(name, &rdata,
4385                                                  mctx, &dnsseckey);
4386                 check_result(result, "dns_dnssec_keyfromrdata");
4387
4388
4389                 for (i = 0; i < tk_list.nb_tk; i++) {
4390                         if (dst_key_compare(tk_list.key[i], dnsseckey)
4391                             == ISC_TRUE) {
4392                                 dns_rdata_reset(&rdata);
4393
4394                                 printf(";; Ok, find a Trusted Key in the "
4395                                        "DNSKEY RRset: %d\n",
4396                                        dst_key_id(dnsseckey));
4397                                 if (sigchase_verify_sig_key(name, rdataset,
4398                                                             dnsseckey,
4399                                                             sigrdataset,
4400                                                             mctx)
4401                                     == ISC_R_SUCCESS) {
4402                                         dst_key_free(&dnsseckey);
4403                                         dnsseckey = NULL;
4404                                         return (ISC_R_SUCCESS);
4405                                 }
4406                         }
4407                 }
4408
4409                 dns_rdata_reset(&rdata);
4410                 if (dnsseckey != NULL)
4411                         dst_key_free(&dnsseckey);
4412         } while (dns_rdataset_next(rdataset) == ISC_R_SUCCESS);
4413
4414         if (trustedKey != NULL)
4415                 dst_key_free(&trustedKey);
4416         trustedKey = NULL;
4417
4418         return (ISC_R_NOTFOUND);
4419 }
4420
4421 isc_result_t
4422 sigchase_verify_sig(dns_name_t *name, dns_rdataset_t *rdataset,
4423                     dns_rdataset_t *keyrdataset,
4424                     dns_rdataset_t *sigrdataset,
4425                     isc_mem_t *mctx)
4426 {
4427         isc_result_t result;
4428         dns_rdata_t keyrdata = DNS_RDATA_INIT;
4429         dst_key_t *dnsseckey = NULL;
4430
4431         result = dns_rdataset_first(keyrdataset);
4432         check_result(result, "empty DNSKEY dataset");
4433         dns_rdata_init(&keyrdata);
4434
4435         do {
4436                 dns_rdataset_current(keyrdataset, &keyrdata);
4437                 INSIST(keyrdata.type == dns_rdatatype_dnskey);
4438
4439                 result = dns_dnssec_keyfromrdata(name, &keyrdata,
4440                                                  mctx, &dnsseckey);
4441                 check_result(result, "dns_dnssec_keyfromrdata");
4442
4443                 result = sigchase_verify_sig_key(name, rdataset, dnsseckey,
4444                                                  sigrdataset, mctx);
4445                 if (result == ISC_R_SUCCESS) {
4446                         dns_rdata_reset(&keyrdata);
4447                         dst_key_free(&dnsseckey);
4448                         return (ISC_R_SUCCESS);
4449                 }
4450                 dst_key_free(&dnsseckey);
4451                 dns_rdata_reset(&keyrdata);
4452         } while (dns_rdataset_next(chase_keyrdataset) == ISC_R_SUCCESS);
4453
4454         dns_rdata_reset(&keyrdata);
4455
4456         return (ISC_R_NOTFOUND);
4457 }
4458
4459 isc_result_t
4460 sigchase_verify_sig_key(dns_name_t *name, dns_rdataset_t *rdataset,
4461                         dst_key_t *dnsseckey, dns_rdataset_t *sigrdataset,
4462                         isc_mem_t *mctx)
4463 {
4464         isc_result_t result;
4465         dns_rdata_t sigrdata = DNS_RDATA_INIT;
4466         dns_rdata_sig_t siginfo;
4467
4468         result = dns_rdataset_first(sigrdataset);
4469         check_result(result, "empty RRSIG dataset");
4470         dns_rdata_init(&sigrdata);
4471
4472         do {
4473                 dns_rdataset_current(sigrdataset, &sigrdata);
4474
4475                 result = dns_rdata_tostruct(&sigrdata, &siginfo, NULL);
4476                 check_result(result, "sigrdata tostruct siginfo");
4477
4478                 /*
4479                  * Test if the id of the DNSKEY is
4480                  * the id of the DNSKEY signer's
4481                  */
4482                 if (siginfo.keyid == dst_key_id(dnsseckey)) {
4483
4484                         result = dns_rdataset_first(rdataset);
4485                         check_result(result, "empty DS dataset");
4486
4487                         result = dns_dnssec_verify(name, rdataset, dnsseckey,
4488                                                    ISC_FALSE, mctx, &sigrdata);
4489
4490                         printf(";; VERIFYING ");
4491                         print_type(rdataset->type);
4492                         printf(" RRset for ");
4493                         dns_name_print(name, stdout);
4494                         printf(" with DNSKEY:%d: %s\n", dst_key_id(dnsseckey),
4495                                isc_result_totext(result));
4496
4497                         if (result == ISC_R_SUCCESS) {
4498                                 dns_rdata_reset(&sigrdata);
4499                                 return (result);
4500                         }
4501                 }
4502                 dns_rdata_freestruct(&siginfo);
4503                 dns_rdata_reset(&sigrdata);
4504
4505         } while (dns_rdataset_next(chase_sigkeyrdataset) == ISC_R_SUCCESS);
4506
4507         dns_rdata_reset(&sigrdata);
4508
4509         return (ISC_R_NOTFOUND);
4510 }
4511
4512
4513 isc_result_t
4514 sigchase_verify_ds(dns_name_t *name, dns_rdataset_t *keyrdataset,
4515                    dns_rdataset_t *dsrdataset, isc_mem_t *mctx)
4516 {
4517         isc_result_t result;
4518         dns_rdata_t keyrdata = DNS_RDATA_INIT;
4519         dns_rdata_t newdsrdata = DNS_RDATA_INIT;
4520         dns_rdata_t dsrdata = DNS_RDATA_INIT;
4521         dns_rdata_ds_t dsinfo;
4522         dst_key_t *dnsseckey = NULL;
4523         unsigned char dsbuf[DNS_DS_BUFFERSIZE];
4524
4525         result = dns_rdataset_first(dsrdataset);
4526         check_result(result, "empty DSset dataset");
4527         do {
4528                 dns_rdataset_current(dsrdataset, &dsrdata);
4529
4530                 result = dns_rdata_tostruct(&dsrdata, &dsinfo, NULL);
4531                 check_result(result, "dns_rdata_tostruct for DS");
4532
4533                 result = dns_rdataset_first(keyrdataset);
4534                 check_result(result, "empty KEY dataset");
4535
4536                 do {
4537                         dns_rdataset_current(keyrdataset, &keyrdata);
4538                         INSIST(keyrdata.type == dns_rdatatype_dnskey);
4539
4540                         result = dns_dnssec_keyfromrdata(name, &keyrdata,
4541                                                          mctx, &dnsseckey);
4542                         check_result(result, "dns_dnssec_keyfromrdata");
4543
4544                         /*
4545                          * Test if the id of the DNSKEY is the
4546                          * id of DNSKEY referenced by the DS
4547                          */
4548                         if (dsinfo.key_tag == dst_key_id(dnsseckey)) {
4549
4550                                 result = dns_ds_buildrdata(name, &keyrdata,
4551                                                            dsinfo.digest_type,
4552                                                            dsbuf, &newdsrdata);
4553                                 dns_rdata_freestruct(&dsinfo);
4554
4555                                 if (result != ISC_R_SUCCESS) {
4556                                         dns_rdata_reset(&keyrdata);
4557                                         dns_rdata_reset(&newdsrdata);
4558                                         dns_rdata_reset(&dsrdata);
4559                                         dst_key_free(&dnsseckey);
4560                                         dns_rdata_freestruct(&dsinfo);
4561                                         printf("Oops: impossible to build"
4562                                                " new DS rdata\n");
4563                                         return (result);
4564                                 }
4565
4566
4567                                 if (dns_rdata_compare(&dsrdata,
4568                                                       &newdsrdata) == 0) {
4569                                         printf(";; OK a DS valids a DNSKEY"
4570                                                " in the RRset\n");
4571                                         printf(";; Now verify that this"
4572                                                " DNSKEY validates the "
4573                                                "DNSKEY RRset\n");
4574
4575                                         result = sigchase_verify_sig_key(name,
4576                                                          keyrdataset,
4577                                                          dnsseckey,
4578                                                          chase_sigkeyrdataset,
4579                                                          mctx);
4580                                         if (result ==  ISC_R_SUCCESS) {
4581                                                 dns_rdata_reset(&keyrdata);
4582                                                 dns_rdata_reset(&newdsrdata);
4583                                                 dns_rdata_reset(&dsrdata);
4584                                                 dst_key_free(&dnsseckey);
4585
4586                                                 return (result);
4587                                         }
4588                                 } else {
4589                                         printf(";; This DS is NOT the DS for"
4590                                                " the chasing KEY: FAILED\n");
4591                                 }
4592
4593                                 dns_rdata_reset(&newdsrdata);
4594                         }
4595                         dst_key_free(&dnsseckey);
4596                         dns_rdata_reset(&keyrdata);
4597                         dnsseckey = NULL;
4598                 } while (dns_rdataset_next(chase_keyrdataset) == ISC_R_SUCCESS);
4599                 dns_rdata_reset(&dsrdata);
4600
4601         } while (dns_rdataset_next(chase_dsrdataset) == ISC_R_SUCCESS);
4602
4603         dns_rdata_reset(&keyrdata);
4604         dns_rdata_reset(&newdsrdata);
4605         dns_rdata_reset(&dsrdata);
4606
4607         return (ISC_R_NOTFOUND);
4608 }
4609
4610 /*
4611  *
4612  * take a pointer on a rdataset in parameter and try to resolv it.
4613  * the searched rrset is a rrset on 'name' with type 'type'
4614  * (and if the type is a rrsig the signature cover 'covers').
4615  * the lookedup is to known if you have already done the query on the net.
4616  * ISC_R_SUCCESS: if we found the rrset
4617  * ISC_R_NOTFOUND: we do not found the rrset in cache
4618  * and we do a query on the net
4619  * ISC_R_FAILURE: rrset not found
4620  */
4621 isc_result_t
4622 advanced_rrsearch(dns_rdataset_t **rdataset, dns_name_t *name,
4623                   dns_rdatatype_t type, dns_rdatatype_t covers,
4624                   isc_boolean_t *lookedup)
4625 {
4626         isc_boolean_t  tmplookedup;
4627
4628         INSIST(rdataset != NULL);
4629
4630         if (*rdataset != NULL)
4631                 return (ISC_R_SUCCESS);
4632
4633         tmplookedup = *lookedup;
4634         if ((*rdataset = sigchase_scanname(type, covers,
4635                                            lookedup, name)) == NULL) {
4636                 if (tmplookedup)
4637                         return (ISC_R_FAILURE);
4638                 return (ISC_R_NOTFOUND);
4639         }
4640         *lookedup = ISC_FALSE;
4641         return (ISC_R_SUCCESS);
4642 }
4643
4644
4645
4646 #if DIG_SIGCHASE_TD
4647 void
4648 sigchase_td(dns_message_t *msg)
4649 {
4650         isc_result_t result;
4651         dns_name_t *name = NULL;
4652         isc_boolean_t have_answer = ISC_FALSE;
4653         isc_boolean_t true = ISC_TRUE;
4654
4655         if ((result = dns_message_firstname(msg, DNS_SECTION_ANSWER))
4656             == ISC_R_SUCCESS) {
4657                 dns_message_currentname(msg, DNS_SECTION_ANSWER, &name);
4658                 if (current_lookup->trace_root_sigchase) {
4659                         initialization(name);
4660                         return;
4661                 }
4662                 have_answer = true;
4663         } else {
4664                 if (!current_lookup->trace_root_sigchase) {
4665                         result = dns_message_firstname(msg,
4666                                                        DNS_SECTION_AUTHORITY);
4667                         if (result == ISC_R_SUCCESS)
4668                                 dns_message_currentname(msg,
4669                                                         DNS_SECTION_AUTHORITY,
4670                                                         &name);
4671                         chase_nsrdataset
4672                                 = chase_scanname_section(msg, name,
4673                                                          dns_rdatatype_ns,
4674                                                          dns_rdatatype_any,
4675                                                          DNS_SECTION_AUTHORITY);
4676                         dup_name(name, &chase_authority_name, mctx);
4677                         if (chase_nsrdataset != NULL) {
4678                                 have_delegation_ns = ISC_TRUE;
4679                                 printf("no response but there is a delegation"
4680                                        " in authority section:");
4681                                 dns_name_print(name, stdout);
4682                                 printf("\n");
4683                         } else {
4684                                 printf("no response and no delegation in "
4685                                        "authority section but a reference"
4686                                        " to: ");
4687                                 dns_name_print(name, stdout);
4688                                 printf("\n");
4689                                 error_message = msg;
4690                         }
4691                 } else {
4692                         printf(";; NO ANSWERS: %s\n",
4693                                isc_result_totext(result));
4694                         free_name(&chase_name, mctx);
4695                         clean_trustedkey();
4696                         return;
4697                 }
4698         }
4699
4700
4701         if (have_answer) {
4702                 chase_rdataset
4703                         = chase_scanname_section(msg, &chase_name,
4704                                                  current_lookup
4705                                                  ->rdtype_sigchase,
4706                                                  dns_rdatatype_any,
4707                                                  DNS_SECTION_ANSWER);
4708                 if (chase_rdataset != NULL)
4709                         have_response = ISC_TRUE;
4710         }
4711
4712         result = advanced_rrsearch(&chase_keyrdataset,
4713                                    &chase_current_name,
4714                                    dns_rdatatype_dnskey,
4715                                    dns_rdatatype_any,
4716                                    &chase_keylookedup);
4717         if (result == ISC_R_FAILURE) {
4718                 printf("\n;; DNSKEY is missing to continue validation:"
4719                        " FAILED\n\n");
4720                 goto cleanandgo;
4721         }
4722         if (result == ISC_R_NOTFOUND)
4723                 return;
4724         INSIST(chase_keyrdataset != NULL);
4725         printf("\n;; DNSKEYset:\n");
4726         print_rdataset(&chase_current_name , chase_keyrdataset, mctx);
4727
4728
4729         result = advanced_rrsearch(&chase_sigkeyrdataset,
4730                                    &chase_current_name,
4731                                    dns_rdatatype_rrsig,
4732                                    dns_rdatatype_dnskey,
4733                                    &chase_sigkeylookedup);
4734         if (result == ISC_R_FAILURE) {
4735                 printf("\n;; RRSIG of DNSKEY is missing to continue validation:"
4736                        " FAILED\n\n");
4737                 goto cleanandgo;
4738         }
4739         if (result == ISC_R_NOTFOUND)
4740                 return;
4741         INSIST(chase_sigkeyrdataset != NULL);
4742         printf("\n;; RRSIG of the DNSKEYset:\n");
4743         print_rdataset(&chase_current_name , chase_sigkeyrdataset, mctx);
4744
4745
4746         if (!chase_dslookedup && !chase_nslookedup) {
4747                 if (!delegation_follow) {
4748                         result = contains_trusted_key(&chase_current_name,
4749                                                       chase_keyrdataset,
4750                                                       chase_sigkeyrdataset,
4751                                                       mctx);
4752                 } else {
4753                         INSIST(chase_dsrdataset != NULL);
4754                         INSIST(chase_sigdsrdataset != NULL);
4755                         result = sigchase_verify_ds(&chase_current_name,
4756                                                     chase_keyrdataset,
4757                                                     chase_dsrdataset,
4758                                                     mctx);
4759                 }
4760
4761                 if (result != ISC_R_SUCCESS) {
4762                         printf("\n;; chain of trust can't be validated:"
4763                                " FAILED\n\n");
4764                         goto cleanandgo;
4765                 } else {
4766                         chase_dsrdataset = NULL;
4767                         chase_sigdsrdataset = NULL;
4768                 }
4769         }
4770
4771         if (have_response || (!have_delegation_ns && !have_response)) {
4772                 /* test if it's a grand father case */
4773
4774                 if (have_response) {
4775                         result = advanced_rrsearch(&chase_sigrdataset,
4776                                                    &chase_name,
4777                                                    dns_rdatatype_rrsig,
4778                                                    current_lookup
4779                                                    ->rdtype_sigchase,
4780                                                    &true);
4781                         if (result == ISC_R_FAILURE) {
4782                                 printf("\n;; RRset is missing to continue"
4783                                        " validation SHOULD NOT APPEND:"
4784                                        " FAILED\n\n");
4785                                 goto cleanandgo;
4786                         }
4787
4788                 } else {
4789                         result = advanced_rrsearch(&chase_sigrdataset,
4790                                                    &chase_authority_name,
4791                                                    dns_rdatatype_rrsig,
4792                                                    dns_rdatatype_any,
4793                                                    &true);
4794                         if (result == ISC_R_FAILURE) {
4795                                 printf("\n;; RRSIG is missing  to continue"
4796                                        " validation SHOULD NOT APPEND:"
4797                                        " FAILED\n\n");
4798                                 goto cleanandgo;
4799                         }
4800                 }
4801                 result =  grandfather_pb_test(&chase_current_name,
4802                                               chase_sigrdataset);
4803                 if (result != ISC_R_SUCCESS) {
4804                         dns_name_t tmp_name;
4805
4806                         printf("\n;; We are in a Grand Father Problem:"
4807                                " See 2.2.1 in RFC 3568\n");
4808                         chase_rdataset = NULL;
4809                         chase_sigrdataset = NULL;
4810                         have_response = ISC_FALSE;
4811                         have_delegation_ns = ISC_FALSE;
4812
4813                         dns_name_init(&tmp_name, NULL);
4814                         result = child_of_zone(&chase_name, &chase_current_name,
4815                                                &tmp_name);
4816                         if (dns_name_dynamic(&chase_authority_name))
4817                                 free_name(&chase_authority_name, mctx);
4818                         dup_name(&tmp_name, &chase_authority_name, mctx);
4819                         printf(";; and we try to continue chain of trust"
4820                                " validation of the zone: ");
4821                         dns_name_print(&chase_authority_name, stdout);
4822                         printf("\n");
4823                         have_delegation_ns = ISC_TRUE;
4824                 } else {
4825                         if (have_response)
4826                                 goto finalstep;
4827                         else
4828                                 chase_sigrdataset = NULL;
4829                 }
4830         }
4831
4832         if (have_delegation_ns) {
4833                 chase_nsrdataset = NULL;
4834                 result = advanced_rrsearch(&chase_nsrdataset,
4835                                            &chase_authority_name,
4836                                            dns_rdatatype_ns,
4837                                            dns_rdatatype_any,
4838                                            &chase_nslookedup);
4839                 if (result == ISC_R_FAILURE) {
4840                         printf("\n;;NSset is missing to continue validation:"
4841                                " FAILED\n\n");
4842                         goto cleanandgo;
4843                 }
4844                 if (result == ISC_R_NOTFOUND) {
4845                         return;
4846                 }
4847                 INSIST(chase_nsrdataset != NULL);
4848
4849                 result = advanced_rrsearch(&chase_dsrdataset,
4850                                            &chase_authority_name,
4851                                            dns_rdatatype_ds,
4852                                            dns_rdatatype_any,
4853                                            &chase_dslookedup);
4854                 if (result == ISC_R_FAILURE) {
4855                         printf("\n;; DSset is missing to continue validation:"
4856                                " FAILED\n\n");
4857                         goto cleanandgo;
4858                 }
4859                 if (result == ISC_R_NOTFOUND)
4860                         return;
4861                 INSIST(chase_dsrdataset != NULL);
4862                 printf("\n;; DSset:\n");
4863                 print_rdataset(&chase_authority_name , chase_dsrdataset, mctx);
4864
4865                 result = advanced_rrsearch(&chase_sigdsrdataset,
4866                                            &chase_authority_name,
4867                                            dns_rdatatype_rrsig,
4868                                            dns_rdatatype_ds,
4869                                            &true);
4870                 if (result != ISC_R_SUCCESS) {
4871                         printf("\n;; DSset is missing to continue validation:"
4872                                " FAILED\n\n");
4873                         goto cleanandgo;
4874                 }
4875                 printf("\n;; RRSIGset of DSset\n");
4876                 print_rdataset(&chase_authority_name,
4877                                chase_sigdsrdataset, mctx);
4878                 INSIST(chase_sigdsrdataset != NULL);
4879
4880                 result = sigchase_verify_sig(&chase_authority_name,
4881                                              chase_dsrdataset,
4882                                              chase_keyrdataset,
4883                                              chase_sigdsrdataset, mctx);
4884                 if (result != ISC_R_SUCCESS) {
4885                         printf("\n;; Impossible to verify the DSset:"
4886                                " FAILED\n\n");
4887                         goto cleanandgo;
4888                 }
4889                 chase_keyrdataset = NULL;
4890                 chase_sigkeyrdataset = NULL;
4891
4892
4893                 prepare_lookup(&chase_authority_name);
4894
4895                 have_response = ISC_FALSE;
4896                 have_delegation_ns = ISC_FALSE;
4897                 delegation_follow = ISC_TRUE;
4898                 error_message = NULL;
4899                 dup_name(&chase_authority_name, &chase_current_name, mctx);
4900                 free_name(&chase_authority_name, mctx);
4901                 return;
4902         }
4903
4904
4905         if (error_message != NULL) {
4906                 dns_rdataset_t *rdataset;
4907                 dns_rdataset_t *sigrdataset;
4908                 dns_name_t rdata_name;
4909                 isc_result_t ret = ISC_R_FAILURE;
4910
4911                 dns_name_init(&rdata_name, NULL);
4912                 result = prove_nx(error_message, &chase_name,
4913                                   current_lookup->rdclass_sigchase,
4914                                   current_lookup->rdtype_sigchase, &rdata_name,
4915                                   &rdataset, &sigrdataset);
4916                 if (rdataset == NULL || sigrdataset == NULL ||
4917                     dns_name_countlabels(&rdata_name) == 0) {
4918                         printf("\n;; Impossible to verify the non-existence,"
4919                                " the NSEC RRset can't be validated:"
4920                                " FAILED\n\n");
4921                         goto cleanandgo;
4922                 }
4923                 ret = sigchase_verify_sig(&rdata_name, rdataset,
4924                                           chase_keyrdataset,
4925                                           sigrdataset, mctx);
4926                 if (ret != ISC_R_SUCCESS) {
4927                         free_name(&rdata_name, mctx);
4928                         printf("\n;; Impossible to verify the NSEC RR to prove"
4929                                " the non-existence : FAILED\n\n");
4930                         goto cleanandgo;
4931                 }
4932                 free_name(&rdata_name, mctx);
4933                 if (result != ISC_R_SUCCESS) {
4934                         printf("\n;; Impossible to verify the non-existence:"
4935                                " FAILED\n\n");
4936                         goto cleanandgo;
4937                 } else {
4938                         printf("\n;; OK the query doesn't have response but"
4939                                " we have validate this fact : SUCCESS\n\n");
4940                         goto cleanandgo;
4941                 }
4942         }
4943
4944  cleanandgo:
4945         printf(";; cleanandgo \n");
4946         if (dns_name_dynamic(&chase_current_name))
4947                 free_name(&chase_current_name, mctx);
4948         if (dns_name_dynamic(&chase_authority_name))
4949                 free_name(&chase_authority_name, mctx);
4950         clean_trustedkey();
4951         return;
4952
4953         finalstep :
4954                 result = advanced_rrsearch(&chase_rdataset, &chase_name,
4955                                            current_lookup->rdtype_sigchase,
4956                                            dns_rdatatype_any ,
4957                                            &true);
4958         if (result == ISC_R_FAILURE) {
4959                 printf("\n;; RRsig of RRset is missing to continue validation"
4960                        " SHOULD NOT APPEND: FAILED\n\n");
4961                 goto cleanandgo;
4962         }
4963         result = sigchase_verify_sig(&chase_name, chase_rdataset,
4964                                      chase_keyrdataset,
4965                                      chase_sigrdataset, mctx);
4966         if (result != ISC_R_SUCCESS) {
4967                 printf("\n;; Impossible to verify the RRset : FAILED\n\n");
4968                 /*
4969                   printf("RRset:\n");
4970                   print_rdataset(&chase_name , chase_rdataset, mctx);
4971                   printf("DNSKEYset:\n");
4972                   print_rdataset(&chase_name , chase_keyrdataset, mctx);
4973                   printf("RRSIG of RRset:\n");
4974                   print_rdataset(&chase_name , chase_sigrdataset, mctx);
4975                   printf("\n");
4976                 */
4977                 goto cleanandgo;
4978         } else {
4979                 printf("\n;; The Answer:\n");
4980                 print_rdataset(&chase_name , chase_rdataset, mctx);
4981
4982                 printf("\n;; FINISH : we have validate the DNSSEC chain"
4983                        " of trust: SUCCESS\n\n");
4984                 goto cleanandgo;
4985         }
4986 }
4987
4988 #endif
4989
4990
4991 #if DIG_SIGCHASE_BU
4992
4993 isc_result_t
4994 getneededrr(dns_message_t *msg)
4995 {
4996         isc_result_t result;
4997         dns_name_t *name = NULL;
4998         dns_rdata_t sigrdata = DNS_RDATA_INIT;
4999         dns_rdata_sig_t siginfo;
5000         isc_boolean_t   true = ISC_TRUE;
5001
5002         if ((result = dns_message_firstname(msg, DNS_SECTION_ANSWER))
5003             != ISC_R_SUCCESS) {
5004                 printf(";; NO ANSWERS: %s\n", isc_result_totext(result));
5005
5006                 if (chase_name.ndata == NULL)
5007                         return (ISC_R_ADDRNOTAVAIL);
5008         } else {
5009                 dns_message_currentname(msg, DNS_SECTION_ANSWER, &name);
5010         }
5011
5012         /* What do we chase? */
5013         if (chase_rdataset == NULL) {
5014                 result = advanced_rrsearch(&chase_rdataset, name,
5015                                            dns_rdatatype_any,
5016                                            dns_rdatatype_any, &true);
5017                 if (result != ISC_R_SUCCESS) {
5018                         printf("\n;; No Answers: Validation FAILED\n\n");
5019                         return (ISC_R_NOTFOUND);
5020                 }
5021                 dup_name(name, &chase_name, mctx);
5022                 printf(";; RRset to chase:\n");
5023                 print_rdataset(&chase_name, chase_rdataset, mctx);
5024         }
5025         INSIST(chase_rdataset != NULL);
5026
5027
5028         if (chase_sigrdataset == NULL) {
5029                 result = advanced_rrsearch(&chase_sigrdataset, name,
5030                                            dns_rdatatype_rrsig,
5031                                            chase_rdataset->type,
5032                                            &chase_siglookedup);
5033                 if (result == ISC_R_FAILURE) {
5034                         printf("\n;; RRSIG is missing for continue validation:"
5035                                " FAILED\n\n");
5036                         if (dns_name_dynamic(&chase_name))
5037                                 free_name(&chase_name, mctx);
5038                         return (ISC_R_NOTFOUND);
5039                 }
5040                 if (result == ISC_R_NOTFOUND) {
5041                         return (ISC_R_NOTFOUND);
5042                 }
5043                 printf("\n;; RRSIG of the RRset to chase:\n");
5044                 print_rdataset(&chase_name, chase_sigrdataset, mctx);
5045         }
5046         INSIST(chase_sigrdataset != NULL);
5047
5048
5049         /* first find the DNSKEY name */
5050         result = dns_rdataset_first(chase_sigrdataset);
5051         check_result(result, "empty RRSIG dataset");
5052         dns_rdataset_current(chase_sigrdataset, &sigrdata);
5053         result = dns_rdata_tostruct(&sigrdata, &siginfo, NULL);
5054         check_result(result, "sigrdata tostruct siginfo");
5055         dup_name(&siginfo.signer, &chase_signame, mctx);
5056         dns_rdata_freestruct(&siginfo);
5057         dns_rdata_reset(&sigrdata);
5058
5059         /* Do we have a key?  */
5060         if (chase_keyrdataset == NULL) {
5061                 result = advanced_rrsearch(&chase_keyrdataset,
5062                                            &chase_signame,
5063                                            dns_rdatatype_dnskey,
5064                                            dns_rdatatype_any,
5065                                            &chase_keylookedup);
5066                 if (result == ISC_R_FAILURE) {
5067                         printf("\n;; DNSKEY is missing to continue validation:"
5068                                " FAILED\n\n");
5069                         free_name(&chase_signame, mctx);
5070                         if (dns_name_dynamic(&chase_name))
5071                                 free_name(&chase_name, mctx);
5072                         return (ISC_R_NOTFOUND);
5073                 }
5074                 if (result == ISC_R_NOTFOUND) {
5075                         free_name(&chase_signame, mctx);
5076                         return (ISC_R_NOTFOUND);
5077                 }
5078                 printf("\n;; DNSKEYset that signs the RRset to chase:\n");
5079                 print_rdataset(&chase_signame, chase_keyrdataset, mctx);
5080         }
5081         INSIST(chase_keyrdataset != NULL);
5082
5083         if (chase_sigkeyrdataset == NULL) {
5084                 result = advanced_rrsearch(&chase_sigkeyrdataset,
5085                                            &chase_signame,
5086                                            dns_rdatatype_rrsig,
5087                                            dns_rdatatype_dnskey,
5088                                            &chase_sigkeylookedup);
5089                 if (result == ISC_R_FAILURE) {
5090                         printf("\n;; RRSIG for DNSKEY  is missing  to continue"
5091                                " validation : FAILED\n\n");
5092                         free_name(&chase_signame, mctx);
5093                         if (dns_name_dynamic(&chase_name))
5094                                 free_name(&chase_name, mctx);
5095                         return (ISC_R_NOTFOUND);
5096                 }
5097                 if (result == ISC_R_NOTFOUND) {
5098                         free_name(&chase_signame, mctx);
5099                         return (ISC_R_NOTFOUND);
5100                 }
5101                 printf("\n;; RRSIG of the DNSKEYset that signs the "
5102                        "RRset to chase:\n");
5103                 print_rdataset(&chase_signame, chase_sigkeyrdataset, mctx);
5104         }
5105         INSIST(chase_sigkeyrdataset != NULL);
5106
5107
5108         if (chase_dsrdataset == NULL) {
5109                 result = advanced_rrsearch(&chase_dsrdataset, &chase_signame,
5110                                            dns_rdatatype_ds,
5111                                            dns_rdatatype_any,
5112                 &chase_dslookedup);
5113                 if (result == ISC_R_FAILURE) {
5114                         printf("\n;; WARNING There is no DS for the zone: ");
5115                         dns_name_print(&chase_signame, stdout);
5116                         printf("\n");
5117                 }
5118                 if (result == ISC_R_NOTFOUND) {
5119                         free_name(&chase_signame, mctx);
5120                         return (ISC_R_NOTFOUND);
5121                 }
5122                 if (chase_dsrdataset != NULL) {
5123                         printf("\n;; DSset of the DNSKEYset\n");
5124                         print_rdataset(&chase_signame, chase_dsrdataset, mctx);
5125                 }
5126         }
5127
5128         if (chase_dsrdataset != NULL) {
5129                 /*
5130                  * if there is no RRSIG of DS,
5131                  * we don't want to search on the network
5132                  */
5133                 result = advanced_rrsearch(&chase_sigdsrdataset,
5134                                            &chase_signame,
5135                                            dns_rdatatype_rrsig,
5136                                            dns_rdatatype_ds, &true);
5137                 if (result == ISC_R_FAILURE) {
5138                         printf(";; WARNING : NO RRSIG DS : RRSIG DS"
5139                                " should come with DS\n");
5140                         /*
5141                          * We continue even the DS couldn't be validated,
5142                          * because the DNSKEY could be a Trusted Key.
5143                          */
5144                         chase_dsrdataset = NULL;
5145                 } else {
5146                         printf("\n;; RRSIG of the DSset of the DNSKEYset\n");
5147                         print_rdataset(&chase_signame, chase_sigdsrdataset,
5148                                        mctx);
5149                 }
5150         }
5151         return (1);
5152 }
5153
5154
5155
5156 void
5157 sigchase_bu(dns_message_t *msg)
5158 {
5159         isc_result_t result;
5160         int ret;
5161
5162         if (tk_list.nb_tk == 0) {
5163                 result = get_trusted_key(mctx);
5164                 if (result != ISC_R_SUCCESS) {
5165                         printf("No trusted keys present\n");
5166                         return;
5167                 }
5168         }
5169
5170
5171         ret = getneededrr(msg);
5172         if (ret == ISC_R_NOTFOUND)
5173                 return;
5174
5175         if (ret == ISC_R_ADDRNOTAVAIL) {
5176                 /* We have no response */
5177                 dns_rdataset_t *rdataset;
5178                 dns_rdataset_t *sigrdataset;
5179                 dns_name_t rdata_name;
5180                 dns_name_t query_name;
5181
5182
5183                 dns_name_init(&query_name, NULL);
5184                 dns_name_init(&rdata_name, NULL);
5185                 nameFromString(current_lookup->textname, &query_name);
5186
5187                 result = prove_nx(msg, &query_name, current_lookup->rdclass,
5188                                   current_lookup->rdtype, &rdata_name,
5189                                   &rdataset, &sigrdataset);
5190                 free_name(&query_name, mctx);
5191                 if (rdataset == NULL || sigrdataset == NULL ||
5192                     dns_name_countlabels(&rdata_name) == 0) {
5193                         printf("\n;; Impossible to verify the Non-existence,"
5194                                " the NSEC RRset can't be validated: "
5195                                "FAILED\n\n");
5196                         clean_trustedkey();
5197                         return;
5198                 }
5199
5200                 if (result != ISC_R_SUCCESS) {
5201                         printf("\n No Answers and impossible to prove the"
5202                                " unsecurity : Validation FAILED\n\n");
5203                         clean_trustedkey();
5204                         return;
5205                 }
5206                 printf(";; An NSEC prove the non-existence of a answers,"
5207                        " Now we want validate this NSEC\n");
5208
5209                 dup_name(&rdata_name, &chase_name, mctx);
5210                 free_name(&rdata_name, mctx);
5211                 chase_rdataset =  rdataset;
5212                 chase_sigrdataset = sigrdataset;
5213                 chase_keyrdataset = NULL;
5214                 chase_sigkeyrdataset = NULL;
5215                 chase_dsrdataset = NULL;
5216                 chase_sigdsrdataset = NULL;
5217                 chase_siglookedup = ISC_FALSE;
5218                 chase_keylookedup = ISC_FALSE;
5219                 chase_dslookedup = ISC_FALSE;
5220                 chase_sigdslookedup = ISC_FALSE;
5221                 sigchase(msg);
5222                 clean_trustedkey();
5223                 return;
5224         }
5225
5226
5227         printf("\n\n\n;; WE HAVE MATERIAL, WE NOW DO VALIDATION\n");
5228
5229         result = sigchase_verify_sig(&chase_name, chase_rdataset,
5230                                      chase_keyrdataset,
5231                                      chase_sigrdataset, mctx);
5232         if (result != ISC_R_SUCCESS) {
5233                 free_name(&chase_name, mctx);
5234                 free_name(&chase_signame, mctx);
5235                 printf(";; No DNSKEY is valid to check the RRSIG"
5236                        " of the RRset: FAILED\n");
5237                 clean_trustedkey();
5238                 return;
5239         }
5240         printf(";; OK We found DNSKEY (or more) to validate the RRset\n");
5241
5242         result = contains_trusted_key(&chase_signame, chase_keyrdataset,
5243                                       chase_sigkeyrdataset, mctx);
5244         if (result ==  ISC_R_SUCCESS) {
5245                 free_name(&chase_name, mctx);
5246                 free_name(&chase_signame, mctx);
5247                 printf("\n;; Ok this DNSKEY is a Trusted Key,"
5248                        " DNSSEC validation is ok: SUCCESS\n\n");
5249                 clean_trustedkey();
5250                 return;
5251         }
5252
5253         printf(";; Now, we are going to validate this DNSKEY by the DS\n");
5254
5255         if (chase_dsrdataset == NULL) {
5256                 free_name(&chase_name, mctx);
5257                 free_name(&chase_signame, mctx);
5258                 printf(";; the DNSKEY isn't trusted-key and there isn't"
5259                        " DS to validate the DNSKEY: FAILED\n");
5260                 clean_trustedkey();
5261                 return;
5262         }
5263
5264         result =  sigchase_verify_ds(&chase_signame, chase_keyrdataset,
5265                                      chase_dsrdataset, mctx);
5266         if (result !=  ISC_R_SUCCESS) {
5267                 free_name(&chase_signame, mctx);
5268                 free_name(&chase_name, mctx);
5269                 printf(";; ERROR no DS validates a DNSKEY in the"
5270                        " DNSKEY RRset: FAILED\n");
5271                 clean_trustedkey();
5272                 return;
5273         } else
5274                 printf(";; OK this DNSKEY (validated by the DS) validates"
5275                        " the RRset of the DNSKEYs, thus the DNSKEY validates"
5276                        " the RRset\n");
5277         INSIST(chase_sigdsrdataset != NULL);
5278
5279         dup_name(&chase_signame, &chase_name, mctx);
5280         free_name(&chase_signame, mctx);
5281         chase_rdataset = chase_dsrdataset;
5282         chase_sigrdataset = chase_sigdsrdataset;
5283         chase_keyrdataset = NULL;
5284         chase_sigkeyrdataset = NULL;
5285         chase_dsrdataset = NULL;
5286         chase_sigdsrdataset = NULL;
5287         chase_siglookedup = chase_keylookedup = ISC_FALSE;
5288         chase_dslookedup = chase_sigdslookedup = ISC_FALSE;
5289
5290         printf(";; Now, we want to validate the DS :  recursive call\n");
5291         sigchase(msg);
5292         return;
5293 }
5294 #endif
5295
5296 void
5297 sigchase(dns_message_t *msg) {
5298 #if DIG_SIGCHASE_TD
5299         if (current_lookup->do_topdown) {
5300                 sigchase_td(msg);
5301                 return;
5302         }
5303 #endif
5304 #if DIG_SIGCHASE_BU
5305         sigchase_bu(msg);
5306         return;
5307 #endif
5308 }
5309
5310
5311 /*
5312  * return 1  if name1  <  name2
5313  *        0  if name1  == name2
5314  *        -1 if name1  >  name2
5315  *    and -2 if problem
5316  */
5317 int
5318 inf_name(dns_name_t *name1, dns_name_t *name2)
5319 {
5320         dns_label_t  label1;
5321         dns_label_t  label2;
5322         unsigned int nblabel1;
5323         unsigned int nblabel2;
5324         int min_lum_label;
5325         int i;
5326         int ret = -2;
5327
5328         nblabel1 = dns_name_countlabels(name1);
5329         nblabel2 = dns_name_countlabels(name2);
5330
5331         if (nblabel1 >= nblabel2)
5332                 min_lum_label = nblabel2;
5333         else
5334                 min_lum_label = nblabel1;
5335
5336
5337         for (i=1 ; i < min_lum_label; i++) {
5338                 dns_name_getlabel(name1, nblabel1 -1  - i, &label1);
5339                 dns_name_getlabel(name2, nblabel2 -1  - i, &label2);
5340                 if ((ret = isc_region_compare(&label1, &label2)) != 0) {
5341                         if (ret < 0)
5342                                 return (-1);
5343                         else if (ret > 0)
5344                                 return (1);
5345                 }
5346         }
5347         if (nblabel1 == nblabel2)
5348                 return (0);
5349
5350         if (nblabel1 < nblabel2)
5351                 return (-1);
5352         else
5353                 return (1);
5354 }
5355
5356 /**
5357  *
5358  *
5359  *
5360  */
5361 isc_result_t
5362 prove_nx_domain(dns_message_t *msg,
5363                 dns_name_t *name,
5364                 dns_name_t *rdata_name,
5365                 dns_rdataset_t **rdataset,
5366                 dns_rdataset_t **sigrdataset)
5367 {
5368         isc_result_t ret = ISC_R_FAILURE;
5369         isc_result_t result = ISC_R_NOTFOUND;
5370         dns_rdataset_t *nsecset = NULL;
5371         dns_rdataset_t *signsecset = NULL ;
5372         dns_rdata_t nsec = DNS_RDATA_INIT;
5373         dns_name_t *nsecname;
5374         dns_rdata_nsec_t nsecstruct;
5375
5376         if ((result = dns_message_firstname(msg, DNS_SECTION_AUTHORITY))
5377             != ISC_R_SUCCESS) {
5378                 printf(";; nothing in authority section : impossible to"
5379                        " validate the non-existence : FAILED\n");
5380                 return (ISC_R_FAILURE);
5381         }
5382
5383         do {
5384                 nsecname = NULL;
5385                 dns_message_currentname(msg, DNS_SECTION_AUTHORITY, &nsecname);
5386                 nsecset = search_type(nsecname, dns_rdatatype_nsec,
5387                                       dns_rdatatype_any);
5388                 if (nsecset == NULL)
5389                         continue;
5390
5391                 printf("There is a NSEC for this zone in the"
5392                        " AUTHORITY section:\n");
5393                 print_rdataset(nsecname, nsecset, mctx);
5394
5395                 for (result = dns_rdataset_first(nsecset);
5396                      result == ISC_R_SUCCESS;
5397                      result = dns_rdataset_next(nsecset)) {
5398                         dns_rdataset_current(nsecset, &nsec);
5399
5400
5401                         signsecset
5402                                 = chase_scanname_section(msg, nsecname,
5403                                                  dns_rdatatype_rrsig,
5404                                                  dns_rdatatype_nsec,
5405                                                  DNS_SECTION_AUTHORITY);
5406                         if (signsecset == NULL) {
5407                                 printf(";; no RRSIG NSEC in authority section:"
5408                                        " impossible to validate the "
5409                                        "non-existence: FAILED\n");
5410                                 return (ISC_R_FAILURE);
5411                         }
5412
5413                         ret = dns_rdata_tostruct(&nsec, &nsecstruct, NULL);
5414                         check_result(ret,"dns_rdata_tostruct");
5415
5416                         if ((inf_name(nsecname, &nsecstruct.next) == 1 &&
5417                              inf_name(name, &nsecstruct.next) == 1) ||
5418                             (inf_name(name, nsecname) == 1 &&
5419                              inf_name(&nsecstruct.next, name) == 1)) {
5420                                 dns_rdata_freestruct(&nsecstruct);
5421                                 *rdataset = nsecset;
5422                                 *sigrdataset = signsecset;
5423                                 dup_name(nsecname, rdata_name, mctx);
5424
5425                                 return (ISC_R_SUCCESS);
5426                         }
5427
5428                         dns_rdata_freestruct(&nsecstruct);
5429                         dns_rdata_reset(&nsec);
5430                 }
5431         } while (dns_message_nextname(msg, DNS_SECTION_AUTHORITY)
5432                  == ISC_R_SUCCESS);
5433
5434         *rdataset = NULL;
5435         *sigrdataset =  NULL;
5436         rdata_name = NULL;
5437         return (ISC_R_FAILURE);
5438 }
5439
5440 /**
5441  *
5442  *
5443  *
5444  *
5445  *
5446  */
5447 isc_result_t
5448 prove_nx_type(dns_message_t *msg, dns_name_t *name, dns_rdataset_t *nsecset,
5449               dns_rdataclass_t class, dns_rdatatype_t type,
5450               dns_name_t *rdata_name, dns_rdataset_t **rdataset,
5451               dns_rdataset_t **sigrdataset)
5452 {
5453         isc_result_t ret;
5454         dns_rdataset_t *signsecset;
5455         dns_rdata_t nsec = DNS_RDATA_INIT;
5456
5457         UNUSED(class);
5458
5459         ret = dns_rdataset_first(nsecset);
5460         check_result(ret,"dns_rdataset_first");
5461
5462         dns_rdataset_current(nsecset, &nsec);
5463
5464         ret = dns_nsec_typepresent(&nsec, type);
5465         if (ret == ISC_R_SUCCESS)
5466                 printf("OK the NSEC said that the type doesn't exist \n");
5467
5468         signsecset = chase_scanname_section(msg, name,
5469                                             dns_rdatatype_rrsig,
5470                                             dns_rdatatype_nsec,
5471                                             DNS_SECTION_AUTHORITY);
5472         if (signsecset == NULL) {
5473                 printf("There isn't RRSIG NSEC for the zone \n");
5474                 return (ISC_R_FAILURE);
5475         }
5476         dup_name(name, rdata_name, mctx);
5477         *rdataset = nsecset;
5478         *sigrdataset = signsecset;
5479
5480         return (ret);
5481 }
5482
5483 /**
5484  *
5485  *
5486  *
5487  *
5488  */
5489 isc_result_t
5490 prove_nx(dns_message_t *msg, dns_name_t *name, dns_rdataclass_t class,
5491          dns_rdatatype_t type, dns_name_t *rdata_name,
5492          dns_rdataset_t **rdataset, dns_rdataset_t **sigrdataset)
5493 {
5494         isc_result_t ret;
5495         dns_rdataset_t *nsecset = NULL;
5496
5497         printf("We want to prove the non-existence of a type of rdata %d"
5498                " or of the zone: \n", type);
5499
5500         if ((ret = dns_message_firstname(msg, DNS_SECTION_AUTHORITY))
5501             != ISC_R_SUCCESS) {
5502                 printf(";; nothing in authority section : impossible to"
5503                        " validate the non-existence : FAILED\n");
5504                 return (ISC_R_FAILURE);
5505         }
5506
5507         nsecset = chase_scanname_section(msg, name, dns_rdatatype_nsec,
5508                                          dns_rdatatype_any,
5509                                          DNS_SECTION_AUTHORITY);
5510         if (nsecset != NULL) {
5511                 printf("We have a NSEC for this zone :OK\n");
5512                 ret = prove_nx_type(msg, name, nsecset, class,
5513                                     type, rdata_name, rdataset,
5514                                     sigrdataset);
5515                 if (ret != ISC_R_SUCCESS) {
5516                         printf("prove_nx: ERROR type exist\n");
5517                         return (ret);
5518                 } else {
5519                         printf("prove_nx: OK type does not exist\n");
5520                         return (ISC_R_SUCCESS);
5521                 }
5522         } else {
5523                 printf("there is no NSEC for this zone: validating "
5524                        "that the zone doesn't exist\n");
5525                 ret = prove_nx_domain(msg, name, rdata_name,
5526                                       rdataset, sigrdataset);
5527                 return (ret);
5528         }
5529         /* Never get here */
5530 }
5531 #endif