chiark / gitweb /
do not crash on disposal of sock and tuntap
[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   }
291   asynch_cancelhandlers(res);
292   scriptinv_cancel(&res->errcallback);
293   TFREE(res);
294 }
295
296 static void destroy_resolver_idtabcb(Tcl_Interp *ip, void *resolver_v) {
297   destroy_resolver(ip,resolver_v);
298 }
299 static void destroy_resolver_defcb(ClientData resolver_v, Tcl_Interp *ip) {
300   destroy_resolver(ip,resolver_v);
301 }
302
303 int do_adns_destroy_resolver(ClientData cd, Tcl_Interp *ip, void *res_v) {
304   tabledataid_disposing(ip,res_v,&adnstcl_resolvers);
305   destroy_resolver(ip,res_v);
306   return TCL_OK;
307 }
308
309 static int create_resolver(Tcl_Interp *ip, const OptionParse *op,
310                            Resolver **res_r) {
311   Resolver *res=0;
312   int rc, i, ec;
313   
314   res= TALLOC(sizeof(*res));  assert(res);
315   res->ix= -1;
316   res->interp= ip;
317   res->ads= 0;
318   res->timertoken= 0;
319   res->maxfd= 0;
320   for (i=0; i<3; i++) FD_ZERO(&res->handling[i]);
321   scriptinv_init(&res->errcallback);
322   res->errstring_accum= 0;
323
324   if (op->errcallback)
325     scriptinv_set(&res->errcallback, ip, op->errcallback, 0);
326
327   ec= adns_init_logfn(&res->ads,
328                       op->aflags | adns_if_noautosys,
329                       op->config_string,
330                       op->errcallback ? adnslogfn_callback : 0,
331                       op->errcallback ? (void*)res : (void*)op->errfile);
332   if (ec) { rc= posixerr(ip,ec,"create adns resolver"); goto x_rc; }
333
334   *res_r= res;
335   return TCL_OK;
336
337  x_rc:
338   if (res) {
339     if (res->ads) adns_finish(res->ads);
340     TFREE(res);
341   }
342   return rc;
343 }  
344
345 int do_adns_new_resolver(ClientData cd, Tcl_Interp *ip,
346                          int objc, Tcl_Obj *const *objv,
347                          void **result) {
348   OptionParse op;
349   Resolver *res=0;
350   int rc;
351
352   optparse_blank(&op);
353   rc= parse_options(ip,objc,objv,resolver_optioninfos,&op);
354   if (rc) return rc;
355
356   if (op.aflags & adns_if_noerrprint) {
357     op.errfile= 0;
358     op.errcallback= 0;
359   }
360
361   rc= create_resolver(ip, &op, &res);
362   if (rc) return rc;
363
364   *result= res;
365   return TCL_OK;
366 }
367
368 int do_adns_set_default_resolver(ClientData cd, Tcl_Interp *ip, void *res_v) {
369   Resolver *res= res_v;
370   Tcl_DeleteAssocData(ip,ASSOC_DEFAULTRES);
371   Tcl_SetAssocData(ip, ASSOC_DEFAULTRES, 0, res);
372   return TCL_OK;
373 }
374
375 const IdDataSpec adnstcl_resolvers= {
376   "adns-res", "adns-resolvers-table", destroy_resolver_idtabcb
377 };
378
379 /*---------- query, query option and answers - common stuff ----------*/
380
381 #define RRTYPE_EXACTLY(t) { #t, adns_r_##t }
382 #define RRTYPE_RAW(t) { #t, adns_r_##t##_raw }
383 #define RRTYPE_PLUS(t) { #t "+", adns_r_##t }
384 #define RRTYPE_MINUS(t) { #t "-", adns_r_##t##_raw }
385
386 const AdnsTclRRTypeInfo adnstclrrtypeinfos[]= {
387   RRTYPE_EXACTLY(a),
388   RRTYPE_EXACTLY(cname),
389   RRTYPE_EXACTLY(hinfo),
390   RRTYPE_EXACTLY(addr),
391
392   RRTYPE_RAW(ns),
393   RRTYPE_RAW(mx),
394
395   RRTYPE_EXACTLY(soa),
396   RRTYPE_EXACTLY(ptr),
397   RRTYPE_EXACTLY(rp),
398
399   RRTYPE_MINUS(soa),
400   RRTYPE_MINUS(ptr),
401   RRTYPE_MINUS(rp),
402   { 0 }
403 };
404
405 static int oifn_resolver(Tcl_Interp *ip, const OptionInfo *oi,
406                          Tcl_Obj *arg, OptionParse *op) {
407   void *val_v;
408   int rc;
409   
410   rc= pat_iddata(ip,arg,&val_v,&adnstcl_resolvers);
411   if (rc) return rc;
412   op->resolver= val_v;
413   return TCL_OK;
414 }
415
416 static const OptionInfo query_optioninfos[]= {
417   OIFA1(qf,search,0),
418   OIFA1(qf,usevc,0),
419   OIFA2(qf,quoteok,query),
420   OIFA2(qf,quoteok,anshost),
421   OIFA2(qf,quotefail,cname),
422   OIFA2(qf,cname,loose),
423   OIFA2(qf,cname,forbid),
424   OICA(resolver),
425   OIFS(reverse),
426   { "-reverse-any", oifn_reverse_any, 1 },
427   { 0 }
428 };
429
430 static int query_submit(Tcl_Interp *ip,
431                         const AdnsTclRRTypeInfo *type, const char *domain,
432                         int queryopts_objc, Tcl_Obj *const *queryopts_objv,
433                         adns_query *aqu_r, void *context, OptionParse *op) {
434   struct sockaddr sa;
435   static const int aftry[]= { AF_INET, AF_INET6 };
436   OptionParse res_op;
437   int rc, r, ec;
438   adns_state ads;
439   
440   op->aflags= adns_qf_owner;
441   op->sflags= 0;
442   op->resolver= 0;
443   op->reverseany= 0;
444   rc= parse_options(ip, queryopts_objc,queryopts_objv, query_optioninfos,op);
445   if (rc) return rc;
446
447   if (!op->resolver) {
448     op->resolver= default_resolver(ip);
449     if (!op->resolver) {
450       optparse_blank(&res_op);
451       rc= create_resolver(ip, &res_op, &op->resolver);
452       if (rc) return rc;
453
454       Tcl_SetAssocData(ip, ASSOC_DEFAULTRES,
455                        destroy_resolver_defcb, op->resolver);
456     }
457   }
458   
459   if (op->reverseany || (op->sflags & oisf_reverse)) {
460     const int *af;
461     for (af=aftry; af < af + sizeof(af)/sizeof(*af); af++) {
462       memset(&sa,0,sizeof(sa));
463       sa.sa_family= *af;
464       r= inet_pton(*af,domain,&sa);
465       if (!r) goto af_found;
466     }
467     return staticerr(ip,"invalid address for adns reverse submit","");
468   af_found:;
469   }
470
471   ads= op->resolver->ads;
472
473   if (op->reverseany) {
474     ec= adns_submit_reverse_any(ads, &sa, op->reverseany,
475                                 type->number, op->aflags, context, aqu_r);
476   } else if (op->sflags & oisf_reverse) {
477     ec= adns_submit_reverse(ads, &sa,
478                             type->number, op->aflags, context, aqu_r);
479   } else {
480     ec= adns_submit(ads, domain,
481                     type->number, op->aflags, context, aqu_r);
482   }
483   if (ec)
484     return posixerr(ip,ec,"submit adns query");
485
486   return TCL_OK;
487 }
488
489 #define RESULTSTATUS_LLEN 4
490 #define RESULTLIST_LLEN 7
491
492 static void make_resultstatus(Tcl_Interp *ip, adns_status status,
493                               Tcl_Obj *results[RESULTSTATUS_LLEN]) {
494   results[0]= ret_string(ip, adns_errtypeabbrev(status));
495   results[1]= ret_int(ip, status);
496   results[2]= ret_string(ip, adns_errabbrev(status));
497   results[3]= ret_string(ip, adns_strerror(status));
498 }
499
500 static Tcl_Obj *make_resultrdata(Tcl_Interp *ip, adns_answer *answer) {
501   Tcl_Obj **rdata, *rl;
502   int i, rrsz;
503   adns_status st;
504   char *datap, *rdatastring;
505   
506   rdata= TALLOC(sizeof(*rdata) * answer->nrrs);
507   for (i=0, datap=answer->rrs.untyped;
508        i<answer->nrrs;
509        i++, datap += rrsz) {
510     st= adns_rr_info(answer->type, 0,0, &rrsz, datap, &rdatastring);
511     assert(!st);
512     rdata[i]= ret_string(ip, rdatastring);
513     free(rdatastring);
514   }
515   rl= Tcl_NewListObj(answer->nrrs, rdata);
516   TFREE(rdata);
517   return rl;
518 }
519
520 static void make_resultlist(Tcl_Interp *ip, adns_answer *answer,
521                             Tcl_Obj *results[RESULTLIST_LLEN]) {
522
523   make_resultstatus(ip, answer->status, results);
524   assert(RESULTSTATUS_LLEN==4);
525   results[4]= ret_string(ip, answer->owner);
526   results[5]= ret_string(ip, answer->cname ? answer->cname : "");
527   results[6]= make_resultrdata(ip, answer);
528 }
529
530 /*---------- synchronous query handling ----------*/
531
532 static int synch(Tcl_Interp *ip, const AdnsTclRRTypeInfo *rrtype,
533                  const char *domain,
534                  int objc, Tcl_Obj *const *objv, adns_answer **answer_r) {
535   adns_query aqu;
536   OptionParse op;
537   Resolver *res;
538   int rc, ec;
539   
540   rc= query_submit(ip,rrtype,domain,objc,objv,&aqu,0,&op);
541   if (rc) return rc;
542
543   res= op.resolver;
544   ec= adns_wait(res->ads,&aqu,answer_r,0);
545   assert(!ec);
546
547   asynch_perturbed(res);
548   return TCL_OK;
549 }
550
551 int do_adns_lookup(ClientData cd, Tcl_Interp *ip,
552                    const AdnsTclRRTypeInfo *rrtype,
553                    const char *domain,
554                    int objc, Tcl_Obj *const *objv,
555                    Tcl_Obj **result) {
556   int rc;
557   adns_answer *answer;
558   
559   rc= synch(ip,rrtype,domain,objc,objv,&answer);  if (rc) return rc;
560
561   if (answer->status) {
562     Tcl_Obj *problem[RESULTSTATUS_LLEN];
563     make_resultstatus(ip, answer->status, problem);
564     *result= Tcl_NewListObj(RESULTSTATUS_LLEN, problem);
565   } else {
566     *result= make_resultrdata(ip, answer);
567   }
568   free(answer);
569   return TCL_OK;
570 }
571
572 int do_adns_synch(ClientData cd, Tcl_Interp *ip,
573                   const AdnsTclRRTypeInfo *rrtype,
574                   const char *domain,
575                   int objc, Tcl_Obj *const *objv,
576                   Tcl_Obj **result) {
577   int rc;
578   adns_answer *answer;
579   Tcl_Obj *results[RESULTLIST_LLEN];
580
581   rc= synch(ip,rrtype,domain,objc,objv,&answer);  if (rc) return rc;
582   make_resultlist(ip,answer,results);
583   free(answer);
584   *result= Tcl_NewListObj(RESULTLIST_LLEN, results);
585   return TCL_OK;
586 }
587
588 /*---------- asynchronous query handling ----------*/
589
590 struct Query {
591   int ix; /* first! */
592   Resolver *res;
593   adns_query aqu;
594   ScriptToInvoke on_yes, on_no, on_fail;
595   Tcl_Obj *xargs;
596 };
597
598 static void asynch_check_now(Resolver *res);
599
600 static void asynch_timerhandler(void *res_v) {
601   Resolver *res= res_v;
602   res->timertoken= 0;
603   adns_processtimeouts(res->ads,0);
604   asynch_check_now(res);
605 }
606
607 static void asynch_filehandler(void *res_v, int mask) {
608   Resolver *res= res_v;
609   int ec;
610   
611   ec= adns_processany(res->ads);
612   if (ec) adns_globalsystemfailure(res->ads);
613   asynch_check_now(res);
614 }
615
616 static void asynch_sethandlers_generic(Resolver *res,
617                                        int shutdown /*from _cancelhandlers*/,
618                                        int immediate /*from _perturbed*/) {
619   fd_set want[3];
620   int maxfd;
621   struct timeval tv_buf, *timeout;
622   int i, fd;
623
624   timeout= 0;
625   maxfd= 0;
626   for (i=0; i<3; i++) FD_ZERO(&want[i]);
627
628   if (!shutdown)
629     adns_beforeselect(res->ads,&maxfd,&want[0],&want[1],&want[2],
630                       &timeout,&tv_buf,0);
631
632   for (fd= 0; fd < maxfd || fd < res->maxfd; fd++)
633     for (i=0; i<3; i++)
634       if (!!FD_ISSET(fd, &res->handling[i])
635           != !!FD_ISSET(fd, &want[i])) {
636         int mask=0;
637         if (FD_ISSET(fd, &want[0])) mask |= TCL_READABLE;
638         if (FD_ISSET(fd, &want[1])) mask |= TCL_WRITABLE;
639         if (FD_ISSET(fd, &want[2])) mask |= TCL_EXCEPTION;
640         if (mask) {
641           Tcl_CreateFileHandler(fd,mask,asynch_filehandler,res);
642           FD_SET(fd, &res->handling[i]);
643         } else {
644           Tcl_DeleteFileHandler(fd);
645           FD_CLR(fd, &res->handling[i]);
646         }
647       }
648   res->maxfd= maxfd;
649
650   Tcl_DeleteTimerHandler(res->timertoken);
651
652   if (immediate) {
653     res->timertoken= Tcl_CreateTimerHandler(0,asynch_timerhandler,res);
654   } else if (timeout) {
655     int milliseconds;
656
657     if (timeout->tv_sec >= INT_MAX/1000 - 1)
658       milliseconds= INT_MAX;
659     else
660       milliseconds= timeout->tv_sec * 1000 +
661         (timeout->tv_usec + 999) / 1000;
662     
663     res->timertoken=
664       Tcl_CreateTimerHandler(milliseconds,asynch_timerhandler,res);
665   }
666 }
667
668 static void asynch_sethandlers(Resolver *res) {
669   asynch_sethandlers_generic(res,0,0);
670 }
671 static void asynch_cancelhandlers(Resolver *res) {
672   asynch_sethandlers_generic(res,1,0);
673 }
674 static void asynch_perturbed(Resolver *res) {
675   asynch_sethandlers_generic(res,0,1);
676 }
677
678 static void asynch_check_now(Resolver *res) {
679   Tcl_Interp *interp= res->interp;
680   adns_query aqu;
681   adns_answer *answer;
682   void *query_v;
683   Query *query;
684   ScriptToInvoke *si;
685   int ec;
686   Tcl_Obj *results[RESULTLIST_LLEN];
687
688   for (;;) {
689     aqu= 0;
690     ec= adns_check(res->ads, &aqu, &answer, &query_v);
691     if (ec==ESRCH || ec==EAGAIN) break;
692     assert(!ec);
693     query= query_v;
694
695     query->aqu= 0;
696     tabledataid_disposing(interp, query, &adnstcl_queries);
697
698     si= (!answer->status ? &query->on_yes
699          : answer->status > adns_s_max_tempfail ? &query->on_no
700          : &query->on_fail);
701
702     make_resultlist(interp, answer, results);
703     free(answer);
704     scriptinv_invoke(si, RESULTLIST_LLEN, results);
705     asynch_query_dispose(interp, query);
706   }
707
708   asynch_sethandlers(res);
709 }
710     
711 int do_adns_asynch(ClientData cd, Tcl_Interp *ip,
712                    Tcl_Obj *on_yes, Tcl_Obj *on_no,
713                    Tcl_Obj *on_fail, Tcl_Obj *xargs,
714                    const AdnsTclRRTypeInfo *rrtype, const char *domain,
715                    int objc, Tcl_Obj *const *objv, void **result) {
716   Query *query;
717   int rc;
718   Resolver *res=0;
719   OptionParse op;
720   
721   query= TALLOC(sizeof(*query));
722   query->ix= -1;
723   query->aqu= 0;
724   scriptinv_init(&query->on_yes);
725   scriptinv_init(&query->on_no);
726   scriptinv_init(&query->on_fail);
727   query->xargs= 0;
728
729   rc= query_submit(ip,rrtype,domain,objc,objv,&query->aqu,query,&op);
730   if (rc) goto x_rc;
731
732   res= op.resolver;
733
734   rc= scriptinv_set(&query->on_yes, ip,on_yes, xargs);  if (rc) goto x_rc;
735   rc= scriptinv_set(&query->on_no,  ip,on_no,  xargs);  if (rc) goto x_rc;
736   rc= scriptinv_set(&query->on_fail,ip,on_fail,xargs);  if (rc) goto x_rc;
737   query->xargs= xargs;
738   Tcl_IncrRefCount(xargs);
739   *result= query;
740   query= 0; /* do not dispose */
741   rc= TCL_OK;
742
743  x_rc:
744   if (query) asynch_query_dispose(ip, query);
745   if (res) asynch_perturbed(res);
746   return rc;
747 }
748
749 int do_adns_asynch_cancel(ClientData cd, Tcl_Interp *ip, void *query_v) {
750   Query *query= query_v;
751   Resolver *res= query->res;
752   asynch_query_dispose(ip, query);
753   asynch_perturbed(res);
754   return TCL_OK;
755 }
756
757 static void asynch_query_dispose(Tcl_Interp *interp, Query *query) {
758   tabledataid_disposing(interp, query, &adnstcl_queries);
759   scriptinv_cancel(&query->on_yes);
760   scriptinv_cancel(&query->on_no);
761   scriptinv_cancel(&query->on_fail);
762   if (query->xargs) Tcl_DecrRefCount(query->xargs);
763   if (query->aqu) adns_cancel(query->aqu);
764   TFREE(query);
765 }
766
767 static void destroy_query_idtabcb(Tcl_Interp *interp, void *query_v) {
768   asynch_query_dispose(interp, query_v);
769 }
770
771 const IdDataSpec adnstcl_queries= {
772   "adns", "adns-query-table", destroy_query_idtabcb
773 };