chiark / gitweb /
d57c49bf1ba3e2efee7f11add33135a8e450e671
[chiark-tcl.git] / adns / adns.c
1 /*
2  */
3 /*
4  * adns lookup TYPE DOMAIN [QUERY-OPTIONS]                    => [list RDATA]
5  *    if no or dontknow, throws an exception, with errorCode one of
6  *         ADNS permfail 300 nxdomain {No such domain}
7  *         ADNS permfail 301 nodata {No such data}
8  *         ADNS tempfail ERROR-CODE ERROR-NAME ERROR-STRING
9  *    where
10  *         ERROR-CODE is the numerical adns status value
11  *         ERROR-NAME is the symbolic adns status value (in lowercase)
12  *         ERROR-STRING is the result of adns_strstatus
13  *
14  * adns synch TYPE DOMAIN [QUERY-OPTIONS]                     => RESULTS
15  *        RESULTS is [list ok|permfail|tempfail
16  *                         ERROR-CODE ERROR-NAME ERROR-STRING  \
17  *                         OWNER CNAME                         \
18  *                         [list RDATA ...]]
19  *        OWNER is the RR owner
20  *        CNAME is the empty string or the canonical name if we went
21  *                  via a CNAME
22  *
23  * adns asynch ON-YES ON-NO ON-DONTKNOW XARGS \
24  *             TYPE DOMAIN \
25  *             [QUERY-OPTIONS]                               => QUERY-ID
26  *        calls, later,
27  *           [concat ON-YES|ON-NO|ON-DONTKNOW XARGS RESULTS]
28  * adns asynch-cancel QUERY-ID
29  *
30  * QUERY-OPTIONS are zero or more of
31  *         -resolver RESOLVER  (see adns new-resolver)
32  *                 default is to use a default resolver
33  *         -search
34  *         -usevc
35  *         -quoteok-query
36  *         -quoteok-anshost
37  *         -quotefail-cname
38  *         -cname-loose
39  *         -cname-forbid
40  *         -reverse
41  *         -reverse-any ZONE-A-LIKE
42  *
43  * adns new-resolver [RES-OPTIONS...]                         => RESOLVER
44  *        options:
45  *         -errfile stdout|stderr       (stderr is the default)
46  *         -noerrprint
47  *         -errcallback CALLBACK    results in  eval CALLBACK [list MESSAGE]
48  *         -noenv|-debug|-logpid
49  *         -checkc-entex
50  *         -checkc-freq
51  *         -config CONFIG-STRING
52  *
53  * adns set-default-resolver RESOLVER
54  *        cancels any outstanding queries from a previous anonymous
55  *        default resolver
56  *
57  * adns destroy-resolver RESOLVER
58  *        cancels outstanding queries
59  */
60
61 #define _GNU_SOURCE
62
63 #include <stdio.h>
64
65 #include "tables.h"
66 #include "hbytes.h"
67
68 /*---------- important types and forward declarations ----------*/
69
70 typedef struct Query Query;
71 typedef struct Resolver Resolver;
72 typedef struct OptionInfo OptionInfo;
73
74 static void asynch_sethandlers(Resolver *res);
75 static void asynch_cancelhandlers(Resolver *res);
76 static void asynch_perturbed(Resolver *res);
77
78 static void asynch_query_dispose(Tcl_Interp *interp, Query *query);
79
80 #define ASSOC_DEFAULTRES "adns-defaultresolver"
81
82 /*---------- common resolver/query option processing ----------*/
83
84 typedef struct {
85   /* this struct type is used to hold both resolver and query options */
86   /* common to resolver and query: */
87   unsigned long aflags;
88   unsigned long sflags;
89   /* resolver: */
90   FILE *errfile;
91   Tcl_Obj *errcallback;
92   const char *config_string;
93   /* query: */
94   Resolver *resolver;
95   const char *reverseany;
96 } OptionParse;
97
98 struct OptionInfo {
99   const char *name;
100   int (*fn)(Tcl_Interp *ip, const OptionInfo *oi, Tcl_Obj *arg,
101             OptionParse *op);
102   int takesarg;
103   unsigned long flags_add, flags_remove;
104 };
105
106 enum {
107   oisf_reverse=     0x0002
108 };
109
110 static int oiufn_f(const OptionInfo *oi, unsigned long *flags) {
111   *flags &= ~oi->flags_remove;
112   *flags |= oi->flags_add;
113   return TCL_OK;
114 }
115 static int oifn_fa(Tcl_Interp *ip, const OptionInfo *oi, Tcl_Obj *arg,
116                    OptionParse *op) { return oiufn_f(oi,&op->aflags); }
117 static int oifn_fs(Tcl_Interp *ip, const OptionInfo *oi, Tcl_Obj *arg,
118                    OptionParse *op) { return oiufn_f(oi,&op->sflags); }
119
120 static int oifn_reverse_any(Tcl_Interp *ip, const OptionInfo *oi,
121                             Tcl_Obj *arg, OptionParse *op) {
122   return pat_string(ip,arg,&op->reverseany);
123 }
124
125 #define OIFA1(t,f,r) { "-" #f, oifn_fa, 0, adns_##t##_##f, r }
126 #define OIFA2(t,f,g) { "-" #f "-" #g, oifn_fa, 0, adns_##t##_##f##_##g, 0 }
127 #define OIFS(f) { "-" #f, oifn_fs, 0, oisf_##f, 0 }
128 #define OICA(o) { "-" #o, oifn_##o, 1 }
129
130 static void optparse_blank(OptionParse *op) {
131   memset(op,0,sizeof(*op));
132   op->errfile= stderr;
133   op->errcallback= 0;
134   op->config_string= 0;
135 }
136
137 static int parse_options(Tcl_Interp *ip, int objc, Tcl_Obj *const *objv,
138                          const OptionInfo opttable[], OptionParse *op) {
139   const OptionInfo *oi;
140   const void *oi_v;
141   Tcl_Obj *arg;
142   int rc;
143
144   objc--; objv++;
145   for (;;) {
146     if (!objc--) break;
147     rc= pat_enum(ip, *objv++, &oi_v, opttable, sizeof(OptionInfo),
148                  "query or resolver option");
149     if (rc) return rc;
150     oi= oi_v;
151
152     if (oi->takesarg) {
153       if (!objc--) {
154         setstringresult(ip,"missing value for option");
155         return TCL_ERROR;
156       }
157       arg= *objv++;
158     } else {
159       arg= 0;
160     }
161     rc= oi->fn(ip,oi,arg,op);
162     if (rc) return rc;
163   }
164   return TCL_OK;
165 }
166
167 /*---------- resolver management ----------*/
168
169 struct Resolver {
170   int ix; /* first! */
171   Tcl_Interp *interp;
172   adns_state ads;
173   Tcl_TimerToken timertoken;
174   int maxfd;
175   fd_set handling[3];
176   ScriptToInvoke errcallback;
177   Tcl_Obj *errstring_accum;
178 };
179
180 /* The default resolver is recorded using Tcl_SetAssocData with key
181  * ASSOC_DEFAULTRES to record the Resolver*.  If it was explicitly
182  * created with `adns new-resolver' then ix will be >=0, and the
183  * resolver will be destroyed - leaving no default - when explicitly
184  * requested.  If it was implicitly created (by starting a query when
185  * there is no default) then ix will be -1.  */
186
187 static int oifn_errfile(Tcl_Interp *ip, const OptionInfo *oi,
188                         Tcl_Obj *arg, OptionParse *op) {
189   int rc;
190   const char *str;
191   
192   rc= pat_string(ip,arg,&str);  if (rc) return rc;
193   if (!strcmp(str,"stderr")) op->errfile= stderr;
194   else if (!strcmp(str,"stdout")) op->errfile= stdout;
195   else return staticerr(ip,"-errfile argument must be stderr or stdout",0);
196
197   op->aflags &= ~adns_if_noerrprint;
198   op->errcallback= 0;
199   return TCL_OK;
200 }
201
202 static int oifn_errcallback(Tcl_Interp *ip, const OptionInfo *oi,
203                             Tcl_Obj *arg, OptionParse *op) {
204   op->errcallback= arg;
205   op->aflags &= ~adns_if_noerrprint;
206   op->errfile= 0;
207   return TCL_OK;
208 }
209
210 static int oifn_config(Tcl_Interp *ip, const OptionInfo *oi,
211                        Tcl_Obj *arg, OptionParse *op) {
212   return pat_string(ip,arg,&op->config_string);
213 }
214
215 static const OptionInfo resolver_optioninfos[]= {
216   OIFA1(if,noenv, 0),
217   OIFA1(if,debug, adns_if_noerrprint),
218   OIFA1(if,logpid, adns_if_noerrprint),
219   OIFA1(if,noerrprint, adns_if_debug),
220   OIFA2(if,checkc,entex),
221   OIFA2(if,checkc,freq),
222   OICA(errfile),
223   OICA(errcallback),
224   OICA(config),
225   { 0 }
226 };
227
228 static void adnslogfn_flushmessage(Resolver *res) {
229   scriptinv_invoke(&res->errcallback, 1, &res->errstring_accum);
230   Tcl_SetObjLength(res->errstring_accum, 0);
231 }
232
233 static void adnslogfn_callback(adns_state ads, void *logfndata,
234                                const char *fmt, va_list al) {
235   Resolver *res= logfndata;
236   int l, newline;
237   char *str;
238
239   l= vasprintf(&str,fmt,al);
240   if (l<0) {
241     posixerr(res->interp,errno,"construct adns log callback string");
242     Tcl_BackgroundError(res->interp);
243   }
244
245   if (l==0) { free(str); return; }
246   if ((newline= l>0 && str[l-1]=='\n')) l--;
247
248   if (!res->errstring_accum) {
249     res->errstring_accum= Tcl_NewStringObj(str,l);
250     Tcl_IncrRefCount(res->errstring_accum);
251   } else {
252     Tcl_AppendToObj(res->errstring_accum,str,l);
253   }
254   free(str);
255
256   if (newline)
257     adnslogfn_flushmessage(res);
258 }
259
260 static Resolver *default_resolver(Tcl_Interp *ip) {
261   return Tcl_GetAssocData(ip,ASSOC_DEFAULTRES,0);
262 }
263
264 static void destroy_resolver(Tcl_Interp *ip, Resolver *res) {
265   void *query_v;
266   int logstring_len;
267   char *rstr;
268   adns_query aqu;
269  
270   if (res == default_resolver(ip))
271     Tcl_DeleteAssocData(ip,ASSOC_DEFAULTRES);
272  
273   if (res->errstring_accum) {
274     rstr= Tcl_GetStringFromObj(res->errstring_accum, &logstring_len);
275     assert(rstr);
276     if (logstring_len)
277       adnslogfn_flushmessage(res);
278   }
279
280   if (res->ads) {
281     /* although adns would throw these away for us, we need to
282      * destroy our own data too and only adns has a list of them */
283     for (;;) {
284       adns_forallqueries_begin(res->ads);
285       aqu= adns_forallqueries_next(res->ads, &query_v);
286       if (!aqu) break;
287       asynch_query_dispose(ip, query_v);
288     }
289     adns_finish(res->ads);
290     res->ads= 0;
291   }
292   asynch_cancelhandlers(res);
293   scriptinv_cancel(&res->errcallback);
294   Tcl_EventuallyFree(res, Tcl_Free);
295 }
296
297 static void destroy_resolver_idtabcb(Tcl_Interp *ip, void *resolver_v) {
298   destroy_resolver(ip,resolver_v);
299 }
300 static void destroy_resolver_defcb(ClientData resolver_v, Tcl_Interp *ip) {
301   destroy_resolver(ip,resolver_v);
302 }
303
304 int do_adns_destroy_resolver(ClientData cd, Tcl_Interp *ip, void *res_v) {
305   tabledataid_disposing(ip,res_v,&adnstcl_resolvers);
306   destroy_resolver(ip,res_v);
307   return TCL_OK;
308 }
309
310 static int create_resolver(Tcl_Interp *ip, const OptionParse *op,
311                            Resolver **res_r) {
312   Resolver *res=0;
313   int rc, i, ec;
314   
315   res= TALLOC(sizeof(*res));  assert(res);
316   res->ix= -1;
317   res->interp= ip;
318   res->ads= 0;
319   res->timertoken= 0;
320   res->maxfd= 0;
321   for (i=0; i<3; i++) FD_ZERO(&res->handling[i]);
322   scriptinv_init(&res->errcallback);
323   res->errstring_accum= 0;
324
325   if (op->errcallback)
326     scriptinv_set(&res->errcallback, ip, op->errcallback, 0);
327
328   ec= adns_init_logfn(&res->ads,
329                       op->aflags | adns_if_noautosys,
330                       op->config_string,
331                       op->errcallback ? adnslogfn_callback : 0,
332                       op->errcallback ? (void*)res : (void*)op->errfile);
333   if (ec) { rc= posixerr(ip,ec,"create adns resolver"); goto x_rc; }
334
335   *res_r= res;
336   return TCL_OK;
337
338  x_rc:
339   if (res) {
340     if (res->ads) adns_finish(res->ads);
341     TFREE(res);
342   }
343   return rc;
344 }  
345
346 int do_adns_new_resolver(ClientData cd, Tcl_Interp *ip,
347                          int objc, Tcl_Obj *const *objv,
348                          void **result) {
349   OptionParse op;
350   Resolver *res=0;
351   int rc;
352
353   optparse_blank(&op);
354   rc= parse_options(ip,objc,objv,resolver_optioninfos,&op);
355   if (rc) return rc;
356
357   if (op.aflags & adns_if_noerrprint) {
358     op.errfile= 0;
359     op.errcallback= 0;
360   }
361
362   rc= create_resolver(ip, &op, &res);
363   if (rc) return rc;
364
365   *result= res;
366   return TCL_OK;
367 }
368
369 int do_adns_set_default_resolver(ClientData cd, Tcl_Interp *ip, void *res_v) {
370   Resolver *res= res_v;
371   Tcl_DeleteAssocData(ip,ASSOC_DEFAULTRES);
372   Tcl_SetAssocData(ip, ASSOC_DEFAULTRES, 0, res);
373   return TCL_OK;
374 }
375
376 const IdDataSpec adnstcl_resolvers= {
377   "adns-res", "adns-resolvers-table", destroy_resolver_idtabcb
378 };
379
380 /*---------- query, query option and answers - common stuff ----------*/
381
382 #define RRTYPE_EXACTLY(t) { #t, adns_r_##t }
383 #define RRTYPE_RAW(t) { #t, adns_r_##t##_raw }
384 #define RRTYPE_PLUS(t) { #t "+", adns_r_##t }
385 #define RRTYPE_MINUS(t) { #t "-", adns_r_##t##_raw }
386
387 const AdnsTclRRTypeInfo adnstclrrtypeinfos[]= {
388   RRTYPE_EXACTLY(a),
389   RRTYPE_EXACTLY(cname),
390   RRTYPE_EXACTLY(hinfo),
391   RRTYPE_EXACTLY(addr),
392
393   RRTYPE_RAW(ns),
394   RRTYPE_RAW(mx),
395
396   RRTYPE_EXACTLY(soa),
397   RRTYPE_EXACTLY(ptr),
398   RRTYPE_EXACTLY(rp),
399
400   RRTYPE_MINUS(soa),
401   RRTYPE_MINUS(ptr),
402   RRTYPE_MINUS(rp),
403   { 0 }
404 };
405
406 static int oifn_resolver(Tcl_Interp *ip, const OptionInfo *oi,
407                          Tcl_Obj *arg, OptionParse *op) {
408   void *val_v;
409   int rc;
410   
411   rc= pat_iddata(ip,arg,&val_v,&adnstcl_resolvers);
412   if (rc) return rc;
413   op->resolver= val_v;
414   return TCL_OK;
415 }
416
417 static const OptionInfo query_optioninfos[]= {
418   OIFA1(qf,search,0),
419   OIFA1(qf,usevc,0),
420   OIFA2(qf,quoteok,query),
421   OIFA2(qf,quoteok,anshost),
422   OIFA2(qf,quotefail,cname),
423   OIFA2(qf,cname,loose),
424   OIFA2(qf,cname,forbid),
425   OICA(resolver),
426   OIFS(reverse),
427   { "-reverse-any", oifn_reverse_any, 1 },
428   { 0 }
429 };
430
431 static int query_submit(Tcl_Interp *ip,
432                         const AdnsTclRRTypeInfo *type, const char *domain,
433                         int queryopts_objc, Tcl_Obj *const *queryopts_objv,
434                         adns_query *aqu_r, void *context, Resolver **res_r) {
435   struct sockaddr sa;
436   static const int aftry[]= { AF_INET, AF_INET6 };
437   OptionParse op;
438   OptionParse res_op;
439   int rc, r, ec;
440   adns_state ads;
441   
442   op.aflags= adns_qf_owner;
443   op.sflags= 0;
444   op.resolver= 0;
445   op.reverseany= 0;
446   rc= parse_options(ip, queryopts_objc,queryopts_objv, query_optioninfos,&op);
447   if (rc) return rc;
448
449   if (!op.resolver) {
450     op.resolver= default_resolver(ip);
451     if (!op.resolver) {
452       optparse_blank(&res_op);
453       rc= create_resolver(ip, &res_op, &op.resolver);
454       if (rc) return rc;
455
456       Tcl_SetAssocData(ip, ASSOC_DEFAULTRES,
457                        destroy_resolver_defcb, op.resolver);
458     }
459   }
460
461   *res_r= op.resolver;
462   
463   if (op.reverseany || (op.sflags & oisf_reverse)) {
464     const int *af;
465     for (af=aftry; af < af + sizeof(af)/sizeof(*af); af++) {
466       memset(&sa,0,sizeof(sa));
467       sa.sa_family= *af;
468       r= inet_pton(*af,domain,&sa);
469       if (!r) goto af_found;
470     }
471     return staticerr(ip,"invalid address for adns reverse submit","");
472   af_found:;
473   }
474
475   ads= op.resolver->ads;
476
477   if (op.reverseany) {
478     ec= adns_submit_reverse_any(ads, &sa, op.reverseany,
479                                 type->number, op.aflags, context, aqu_r);
480   } else if (op.sflags & oisf_reverse) {
481     ec= adns_submit_reverse(ads, &sa,
482                             type->number, op.aflags, context, aqu_r);
483   } else {
484     ec= adns_submit(ads, domain,
485                     type->number, op.aflags, context, aqu_r);
486   }
487   if (ec)
488     return posixerr(ip,ec,"submit adns query");
489
490   return TCL_OK;
491 }
492
493 #define RESULTSTATUS_LLEN 4
494 #define RESULTLIST_LLEN 7
495
496 static void make_resultstatus(Tcl_Interp *ip, adns_status status,
497                               Tcl_Obj *results[RESULTSTATUS_LLEN]) {
498   results[0]= ret_string(ip, adns_errtypeabbrev(status));
499   results[1]= ret_int(ip, status);
500   results[2]= ret_string(ip, adns_errabbrev(status));
501   results[3]= ret_string(ip, adns_strerror(status));
502 }
503
504 static Tcl_Obj *make_resultrdata(Tcl_Interp *ip, adns_answer *answer) {
505   Tcl_Obj **rdata, *rl;
506   int i, rrsz;
507   adns_status st;
508   char *datap, *rdatastring;
509   
510   rdata= TALLOC(sizeof(*rdata) * answer->nrrs);
511   for (i=0, datap=answer->rrs.untyped;
512        i<answer->nrrs;
513        i++, datap += rrsz) {
514     st= adns_rr_info(answer->type, 0,0, &rrsz, datap, &rdatastring);
515     assert(!st);
516     rdata[i]= ret_string(ip, rdatastring);
517     free(rdatastring);
518   }
519   rl= Tcl_NewListObj(answer->nrrs, rdata);
520   TFREE(rdata);
521   return rl;
522 }
523
524 static void make_resultlist(Tcl_Interp *ip, adns_answer *answer,
525                             Tcl_Obj *results[RESULTLIST_LLEN]) {
526
527   make_resultstatus(ip, answer->status, results);
528   assert(RESULTSTATUS_LLEN==4);
529   results[4]= ret_string(ip, answer->owner);
530   results[5]= ret_string(ip, answer->cname ? answer->cname : "");
531   results[6]= make_resultrdata(ip, answer);
532 }
533
534 /*---------- synchronous query handling ----------*/
535
536 static int synch(Tcl_Interp *ip, const AdnsTclRRTypeInfo *rrtype,
537                  const char *domain,
538                  int objc, Tcl_Obj *const *objv, adns_answer **answer_r) {
539   adns_query aqu;
540   Resolver *res;
541   int rc, ec;
542   
543   rc= query_submit(ip,rrtype,domain,objc,objv,&aqu,0,&res);
544   if (rc) return rc;
545
546   ec= adns_wait(res->ads,&aqu,answer_r,0);
547   assert(!ec);
548
549   asynch_perturbed(res);
550   return TCL_OK;
551 }
552
553 int do_adns_lookup(ClientData cd, Tcl_Interp *ip,
554                    const AdnsTclRRTypeInfo *rrtype,
555                    const char *domain,
556                    int objc, Tcl_Obj *const *objv,
557                    Tcl_Obj **result) {
558   int rc;
559   adns_answer *answer;
560   
561   rc= synch(ip,rrtype,domain,objc,objv,&answer);  if (rc) return rc;
562
563   if (answer->status) {
564     Tcl_Obj *problem[RESULTSTATUS_LLEN];
565     make_resultstatus(ip, answer->status, problem);
566     *result= Tcl_NewListObj(RESULTSTATUS_LLEN, problem);
567   } else {
568     *result= make_resultrdata(ip, answer);
569   }
570   free(answer);
571   return TCL_OK;
572 }
573
574 int do_adns_synch(ClientData cd, Tcl_Interp *ip,
575                   const AdnsTclRRTypeInfo *rrtype,
576                   const char *domain,
577                   int objc, Tcl_Obj *const *objv,
578                   Tcl_Obj **result) {
579   int rc;
580   adns_answer *answer;
581   Tcl_Obj *results[RESULTLIST_LLEN];
582
583   rc= synch(ip,rrtype,domain,objc,objv,&answer);  if (rc) return rc;
584   make_resultlist(ip,answer,results);
585   free(answer);
586   *result= Tcl_NewListObj(RESULTLIST_LLEN, results);
587   return TCL_OK;
588 }
589
590 /*---------- asynchronous query handling ----------*/
591
592 struct Query {
593   int ix; /* first! */
594   Resolver *res;
595   adns_query aqu;
596   ScriptToInvoke on_yes, on_no, on_fail;
597   Tcl_Obj *xargs;
598 };
599
600 static void asynch_check_now(Resolver *res);
601
602 static void asynch_timerhandler(void *res_v) {
603   Resolver *res= res_v;
604   res->timertoken= 0;
605   adns_processtimeouts(res->ads,0);
606   asynch_check_now(res);
607 }
608
609 static void asynch_filehandler(void *res_v, int mask) {
610   Resolver *res= res_v;
611   int ec;
612   
613   ec= adns_processany(res->ads);
614   if (ec) adns_globalsystemfailure(res->ads);
615   asynch_check_now(res);
616 }
617
618 static void asynch_sethandlers_generic(Resolver *res,
619                                        int shutdown /*from _cancelhandlers*/,
620                                        int immediate /*from _perturbed*/) {
621   fd_set want[3];
622   int maxfd;
623   struct timeval tv_buf, *timeout;
624   int i, fd;
625
626   timeout= 0;
627   maxfd= 0;
628   for (i=0; i<3; i++) FD_ZERO(&want[i]);
629
630   if (!shutdown)
631     adns_beforeselect(res->ads,&maxfd,&want[0],&want[1],&want[2],
632                       &timeout,&tv_buf,0);
633
634   for (fd= 0; fd < maxfd || fd < res->maxfd; fd++)
635     for (i=0; i<3; i++)
636       if (!!FD_ISSET(fd, &res->handling[i])
637           != !!FD_ISSET(fd, &want[i])) {
638         int mask=0;
639         if (FD_ISSET(fd, &want[0])) mask |= TCL_READABLE;
640         if (FD_ISSET(fd, &want[1])) mask |= TCL_WRITABLE;
641         if (FD_ISSET(fd, &want[2])) mask |= TCL_EXCEPTION;
642         if (mask) {
643           Tcl_CreateFileHandler(fd,mask,asynch_filehandler,res);
644           FD_SET(fd, &res->handling[i]);
645         } else {
646           Tcl_DeleteFileHandler(fd);
647           FD_CLR(fd, &res->handling[i]);
648         }
649       }
650   res->maxfd= maxfd;
651
652   Tcl_DeleteTimerHandler(res->timertoken);
653
654   if (immediate) {
655     res->timertoken= Tcl_CreateTimerHandler(0,asynch_timerhandler,res);
656   } else if (timeout) {
657     int milliseconds;
658
659     if (timeout->tv_sec >= INT_MAX/1000 - 1)
660       milliseconds= INT_MAX;
661     else
662       milliseconds= timeout->tv_sec * 1000 +
663         (timeout->tv_usec + 999) / 1000;
664     
665     res->timertoken=
666       Tcl_CreateTimerHandler(milliseconds,asynch_timerhandler,res);
667   }
668 }
669
670 static void asynch_sethandlers(Resolver *res) {
671   asynch_sethandlers_generic(res,0,0);
672 }
673 static void asynch_cancelhandlers(Resolver *res) {
674   asynch_sethandlers_generic(res,1,0);
675 }
676 static void asynch_perturbed(Resolver *res) {
677   asynch_sethandlers_generic(res,0,1);
678 }
679
680 static void asynch_check_now(Resolver *res) {
681   Tcl_Interp *interp= res->interp;
682   adns_query aqu;
683   adns_answer *answer;
684   void *query_v;
685   Query *query;
686   ScriptToInvoke *si;
687   int ec;
688   Tcl_Obj *results[RESULTLIST_LLEN];
689
690   Tcl_Preserve(res);
691   
692   for (;;) {
693     if (!res->ads) { /* oh, it has been destroyed! */
694       Tcl_Release(res);
695       return;
696     }
697
698     aqu= 0;
699     ec= adns_check(res->ads, &aqu, &answer, &query_v);
700     if (ec==ESRCH || ec==EAGAIN) break;
701     assert(!ec);
702     query= query_v;
703
704     query->aqu= 0;
705     tabledataid_disposing(interp, query, &adnstcl_queries);
706
707     si= (!answer->status ? &query->on_yes
708          : answer->status > adns_s_max_tempfail ? &query->on_no
709          : &query->on_fail);
710
711     make_resultlist(interp, answer, results);
712     free(answer);
713     scriptinv_invoke(si, RESULTLIST_LLEN, results);
714     asynch_query_dispose(interp, query);
715   }
716
717   asynch_sethandlers(res);
718
719   Tcl_Release(res);
720 }
721     
722 int do_adns_asynch(ClientData cd, Tcl_Interp *ip,
723                    Tcl_Obj *on_yes, Tcl_Obj *on_no,
724                    Tcl_Obj *on_fail, Tcl_Obj *xargs,
725                    const AdnsTclRRTypeInfo *rrtype, const char *domain,
726                    int objc, Tcl_Obj *const *objv, void **result) {
727   Query *query;
728   int rc;
729   Resolver *res= 0;
730   
731   query= TALLOC(sizeof(*query));
732   query->ix= -1;
733   query->aqu= 0;
734   scriptinv_init(&query->on_yes);
735   scriptinv_init(&query->on_no);
736   scriptinv_init(&query->on_fail);
737   query->xargs= 0;
738
739   rc= query_submit(ip,rrtype,domain,objc,objv,&query->aqu,query,&query->res);
740   if (rc) goto x_rc;
741
742   res= query->res;
743
744   rc= scriptinv_set(&query->on_yes, ip,on_yes, xargs);  if (rc) goto x_rc;
745   rc= scriptinv_set(&query->on_no,  ip,on_no,  xargs);  if (rc) goto x_rc;
746   rc= scriptinv_set(&query->on_fail,ip,on_fail,xargs);  if (rc) goto x_rc;
747   query->xargs= xargs;
748   Tcl_IncrRefCount(xargs);
749   *result= query;
750   query= 0; /* do not dispose */
751   rc= TCL_OK;
752
753  x_rc:
754   if (query) asynch_query_dispose(ip, query);
755   if (res) asynch_perturbed(res);
756   return rc;
757 }
758
759 int do_adns_asynch_cancel(ClientData cd, Tcl_Interp *ip, void *query_v) {
760   Query *query= query_v;
761   Resolver *res= query->res;
762   asynch_query_dispose(ip, query);
763   asynch_perturbed(res);
764   return TCL_OK;
765 }
766
767 static void asynch_query_dispose(Tcl_Interp *interp, Query *query) {
768   tabledataid_disposing(interp, query, &adnstcl_queries);
769   scriptinv_cancel(&query->on_yes);
770   scriptinv_cancel(&query->on_no);
771   scriptinv_cancel(&query->on_fail);
772   if (query->xargs) Tcl_DecrRefCount(query->xargs);
773   if (query->aqu) adns_cancel(query->aqu);
774   TFREE(query);
775 }
776
777 static void destroy_query_idtabcb(Tcl_Interp *interp, void *query_v) {
778   asynch_query_dispose(interp, query_v);
779 }
780
781 const IdDataSpec adnstcl_queries= {
782   "adns", "adns-query-table", destroy_query_idtabcb
783 };