chiark / gitweb /
it made an asynch query
[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  *
41  * adns new-resolver [RES-OPTIONS...]                         => RESOLVER
42  *        options:
43  *         -errfile stdout|stderr       (stderr is the default)
44  *         -noerrprint
45  *         -errcallback CALLBACK    results in  eval CALLBACK [list MESSAGE]
46  *         -noenv|-debug|-logpid
47  *         -checkc-entex
48  *         -checkc-freq
49  *         -reverse
50  *         -reverse-any ZONE-A-LIKE
51  *         -config CONFIG-STRING
52  *
53  * adns destroy-resolver RESOLVER
54  */
55
56 #include "tables.h"
57 #include "hbytes.h"
58
59 /*---------- important types and forward declarations ----------*/
60
61 typedef struct Query Query;
62 typedef struct Resolver Resolver;
63 typedef struct OptionInfo OptionInfo;
64 static void asynch_check(Resolver *res);
65 static void asynch_sethandlers(Resolver *res, int shutdown);
66 static void asynch_query_dispose(Tcl_Interp *interp, Query *query);
67
68 /*---------- common resolver/query option processing ----------*/
69
70 typedef struct {
71   /* this struct type is used to hold both resolver and query options */
72   /* common to resolver and query: */
73   unsigned long aflags;
74   unsigned long sflags;
75   /* resolver: */
76   FILE *errfile;
77   Tcl_Obj *errcallback;
78   const char *config_string;
79   /* query: */
80   Resolver *resolver;
81   const char *reverseany;
82 } OptionParse;
83
84 struct OptionInfo {
85   const char *name;
86   int (*fn)(Tcl_Interp *ip, const OptionInfo *oi, Tcl_Obj *arg,
87             OptionParse *op);
88   int takesarg;
89   unsigned long flags_add, flags_remove;
90 };
91
92 enum {
93   oisf_makedefault= 0x0001,
94   oisf_reverse=     0x0002
95 };
96
97 static int oiufn_f(const OptionInfo *oi, unsigned long *flags) {
98   *flags &= ~oi->flags_remove;
99   *flags |= oi->flags_add;
100   return TCL_OK;
101 }
102 static int oifn_fa(Tcl_Interp *ip, const OptionInfo *oi, Tcl_Obj *arg,
103                    OptionParse *op) { return oiufn_f(oi,&op->aflags); }
104 static int oifn_fs(Tcl_Interp *ip, const OptionInfo *oi, Tcl_Obj *arg,
105                    OptionParse *op) { return oiufn_f(oi,&op->sflags); }
106
107 static int oifn_reverse_any(Tcl_Interp *ip, const OptionInfo *oi,
108                             Tcl_Obj *arg, OptionParse *op) {
109   return pat_string(ip,arg,&op->reverseany);
110 }
111
112 #define OIFA1(t,f,r) { "-" #f, oifn_fa, 0, adns_##t##_##f, r }
113 #define OIFA2(t,f,g) { "-" #f "-" #g, oifn_fa, 0, adns_##t##_##f##_##g, 0 }
114 #define OIFS(f) { "-" #f, oifn_fs, 0, oisf_##f, 0 }
115 #define OICA(o) { "-" #o, oifn_##o, 1 }
116
117 static int parse_options(Tcl_Interp *ip, int objc, Tcl_Obj *const *objv,
118                          const OptionInfo opttable[], OptionParse *op) {
119   const OptionInfo *oi;
120   const void *oi_v;
121   Tcl_Obj *arg;
122   int rc;
123
124   objc--; objv++;
125   for (;;) {
126     if (!objc--) break;
127     rc= pat_enum(ip, *objv++, &oi_v, opttable, sizeof(OptionInfo),
128                  "query or resolver option");
129     if (rc) return rc;
130     oi= oi_v;
131
132     if (oi->takesarg) {
133       if (!objc--) {
134         setstringresult(ip,"missing value for option");
135         return TCL_ERROR;
136       }
137       arg= *objv++;
138     } else {
139       arg= 0;
140     }
141     rc= oi->fn(ip,oi,arg,op);
142     if (rc) return rc;
143   }
144   return TCL_OK;
145 }
146
147 /*---------- resolver management ----------*/
148
149 struct Resolver {
150   int ix; /* first! */
151   Tcl_Interp *interp;
152   adns_state ads;
153   Tcl_TimerToken timertoken;
154   int maxfd;
155   fd_set handling[3];
156 };
157
158 static int oifn_errfile(Tcl_Interp *ip, const OptionInfo *oi,
159                         Tcl_Obj *arg, OptionParse *op) {
160   int rc;
161   const char *str;
162   
163   rc= pat_string(ip,arg,&str);  if (rc) return rc;
164   if (!strcmp(str,"stderr")) op->errfile= stderr;
165   else if (!strcmp(str,"stdout")) op->errfile= stdout;
166   else return staticerr(ip,"-errfile argument must be stderr or stdout",0);
167
168   op->aflags &= ~adns_if_noerrprint;
169   op->errcallback= 0;
170   return TCL_OK;
171 }
172
173 static int oifn_errcallback(Tcl_Interp *ip, const OptionInfo *oi,
174                             Tcl_Obj *arg, OptionParse *op) {
175   op->errcallback= arg;
176   op->aflags &= ~adns_if_noerrprint;
177   op->errfile= 0;
178   return TCL_OK;
179 }
180
181 static int oifn_config(Tcl_Interp *ip, const OptionInfo *oi,
182                        Tcl_Obj *arg, OptionParse *op) {
183   return pat_string(ip,arg,&op->config_string);
184 }
185
186 static const OptionInfo resolver_optioninfos[]= {
187   OIFA1(if,noenv, 0),
188   OIFA1(if,debug, adns_if_noerrprint),
189   OIFA1(if,logpid, adns_if_noerrprint),
190   OIFA1(if,noerrprint, adns_if_debug),
191   OIFA2(if,checkc,entex),
192   OIFA2(if,checkc,freq),
193   OIFS(makedefault),
194   OICA(errfile),
195   OICA(errcallback),
196   OICA(config),
197   { 0 }
198 };
199
200 static void adnslogfn_callback(adns_state ads, void *logfndata,
201                                const char *fmt, va_list al) {
202   abort(); /* fixme implement adns_logcallbackfn */
203 }
204
205 static void destroy_resolver(Tcl_Interp *ip, Resolver *res) {
206   void *query_v;
207   adns_query aqu;
208   
209   if (res->ads) {
210     /* although adns would throw these away for us, we need to
211      * destroy our own data too and only adns has a list of them */
212     for (;;) {
213       adns_forallqueries_begin(res->ads);
214       aqu= adns_forallqueries_next(res->ads, &query_v);
215       if (!aqu) break;
216       asynch_query_dispose(ip, query_v);
217     }
218     adns_finish(res->ads);
219   }
220   asynch_sethandlers(res,1);
221   TFREE(res);
222   /* fixme what about the default resolver */
223 }
224
225 static void destroy_resolver_idtabcb(Tcl_Interp *ip, void *resolver_v) {
226   destroy_resolver(ip,resolver_v);
227 }
228
229 int do_adns_destroy_resolver(ClientData cd, Tcl_Interp *ip, void *res_v) {
230   destroy_resolver(ip,res_v);
231   tabledataid_disposing(ip,res_v,&adnstcl_resolvers);
232   return TCL_OK;
233 }
234
235 int do_adns_new_resolver(ClientData cd, Tcl_Interp *ip,
236                          int objc, Tcl_Obj *const *objv,
237                          void **result) {
238   OptionParse op;
239   Resolver *res=0;
240   int rc, i, ec;
241
242   op.aflags= adns_if_noautosys;
243   op.sflags= 0;
244   op.errfile= 0;
245   op.errcallback= 0;
246   op.config_string= 0;
247   rc= parse_options(ip,objc,objv,resolver_optioninfos,&op);
248   if (rc) goto x_rc;
249
250   res= TALLOC(sizeof(*res)); assert(res);
251   res->ix= -1;
252   res->interp= ip;
253   res->ads= 0;
254   res->timertoken= 0;
255   res->maxfd= 0;
256   for (i=0; i<3; i++) FD_ZERO(&res->handling[i]);
257
258   if (op.aflags & adns_if_noerrprint) {
259     op.errfile= 0;
260     op.errcallback= 0;
261   }
262
263   ec= adns_init_logfn(&res->ads, op.aflags, op.config_string,
264                       op.errcallback ? adnslogfn_callback : 0,
265                       op.errcallback ? (void*)op.errcallback
266                       : (void*)op.errfile);
267   if (ec) { rc= posixerr(ip,ec,"create adns resolver"); goto x_rc; }
268
269   if (op.errcallback)
270     Tcl_IncrRefCount(op.errcallback);
271
272   *result= res;
273   return TCL_OK;
274
275  x_rc:
276   if (res) {
277     if (res->ads) adns_finish(res->ads);
278     TFREE(res);
279   }
280   return rc;
281 }
282
283 const IdDataSpec adnstcl_resolvers= {
284   "adns-res", "adns-resolvers-table", destroy_resolver_idtabcb
285 };
286
287 /*---------- query, query option and answers - common stuff ----------*/
288
289 #define RRTYPE_EXACTLY(t) { #t, adns_r_##t }
290 #define RRTYPE_RAW(t) { #t, adns_r_##t##_raw }
291 #define RRTYPE_PLUS(t) { #t "+", adns_r_##t }
292 #define RRTYPE_MINUS(t) { #t "-", adns_r_##t##_raw }
293
294 const AdnsTclRRTypeInfo adnstclrrtypeinfos[]= {
295   RRTYPE_EXACTLY(a),
296   RRTYPE_EXACTLY(cname),
297   RRTYPE_EXACTLY(hinfo),
298   RRTYPE_EXACTLY(addr),
299
300   RRTYPE_RAW(ns),
301   RRTYPE_RAW(mx),
302
303   RRTYPE_EXACTLY(soa),
304   RRTYPE_EXACTLY(ptr),
305   RRTYPE_EXACTLY(rp),
306
307   RRTYPE_MINUS(soa),
308   RRTYPE_MINUS(ptr),
309   RRTYPE_MINUS(rp),
310   { 0 }
311 };
312
313 static int oifn_resolver(Tcl_Interp *ip, const OptionInfo *oi,
314                          Tcl_Obj *arg, OptionParse *op) {
315   void *val_v;
316   int rc;
317   
318   rc= pat_iddata(ip,arg,&val_v,&adnstcl_resolvers);
319   if (rc) return rc;
320   op->resolver= val_v;
321   return TCL_OK;
322 }
323
324 static const OptionInfo query_optioninfos[]= {
325   OIFA1(qf,search,0),
326   OIFA1(qf,usevc,0),
327   OIFA2(qf,quoteok,query),
328   OIFA2(qf,quoteok,anshost),
329   OIFA2(qf,quotefail,cname),
330   OIFA2(qf,cname,loose),
331   OIFA2(qf,cname,forbid),
332   OICA(resolver),
333   OIFS(reverse),
334   { "-reverse-any", oifn_reverse_any, 1 },
335   { 0 }
336 };
337
338 static int query_submit(Tcl_Interp *ip,
339                         const AdnsTclRRTypeInfo *type, const char *domain,
340                         int queryopts_objc, Tcl_Obj *const *queryopts_objv,
341                         adns_query *aqu_r, void *context, OptionParse *op) {
342   struct sockaddr sa;
343   static const int aftry[]= { AF_INET, AF_INET6 };
344   int rc, r, ec;
345   adns_state ads;
346   
347   op->aflags= adns_qf_owner;
348   op->sflags= 0;
349   op->resolver= 0; /* fixme default */
350   op->reverseany= 0;
351   rc= parse_options(ip, queryopts_objc,queryopts_objv, query_optioninfos,op);
352   if (rc) return rc;
353
354   if (op->reverseany || (op->sflags & oisf_reverse)) {
355     const int *af;
356     for (af=aftry; af < af + sizeof(af)/sizeof(*af); af++) {
357       memset(&sa,0,sizeof(sa));
358       sa.sa_family= *af;
359       r= inet_pton(*af,domain,&sa);
360       if (!r) goto af_found;
361     }
362     return staticerr(ip,"invalid address for adns reverse submit","");
363   af_found:;
364   }
365
366   ads= op->resolver->ads;
367
368   if (op->reverseany) {
369     ec= adns_submit_reverse_any(ads, &sa, op->reverseany,
370                                 type->number, op->aflags, context, aqu_r);
371   } else if (op->sflags & oisf_reverse) {
372     ec= adns_submit_reverse(ads, &sa,
373                             type->number, op->aflags, context, aqu_r);
374   } else {
375     ec= adns_submit(ads, domain,
376                     type->number, op->aflags, context, aqu_r);
377   }
378   if (ec)
379     return posixerr(ip,ec,"submit adns query");
380
381   return TCL_OK;
382 }
383
384 #define RESULTSTATUS_LLEN 4
385 #define RESULTLIST_LLEN 7
386
387 static void make_resultstatus(Tcl_Interp *ip, adns_status status,
388                               Tcl_Obj *results[RESULTSTATUS_LLEN]) {
389   results[0]= ret_string(ip, adns_errtypeabbrev(status));
390   results[1]= ret_int(ip, status);
391   results[2]= ret_string(ip, adns_errabbrev(status));
392   results[3]= ret_string(ip, adns_strerror(status));
393 }
394
395 static Tcl_Obj *make_resultrdata(Tcl_Interp *ip, adns_answer *answer) {
396   Tcl_Obj **rdata, *rl;
397   int i, rrsz;
398   adns_status st;
399   char *datap, *rdatastring;
400   
401   rdata= TALLOC(sizeof(*rdata) * answer->nrrs);
402   for (i=0, datap=answer->rrs.untyped;
403        i<answer->nrrs;
404        i++, datap += rrsz) {
405     st= adns_rr_info(answer->type, 0,0, &rrsz, datap, &rdatastring);
406     assert(!st);
407     rdata[i]= ret_string(ip, rdatastring);
408     free(rdatastring);
409   }
410   rl= Tcl_NewListObj(answer->nrrs, rdata);
411   TFREE(rdata);
412   return rl;
413 }
414
415 static void make_resultlist(Tcl_Interp *ip, adns_answer *answer,
416                             Tcl_Obj *results[RESULTLIST_LLEN]) {
417
418   make_resultstatus(ip, answer->status, results);
419   assert(RESULTSTATUS_LLEN==4);
420   results[4]= ret_string(ip, answer->owner);
421   results[5]= ret_string(ip, answer->cname ? answer->cname : "");
422   results[6]= make_resultrdata(ip, answer);
423 }
424
425 /*---------- synchronous query handling ----------*/
426
427 static int synch(Tcl_Interp *ip, const AdnsTclRRTypeInfo *rrtype,
428                  const char *domain,
429                  int objc, Tcl_Obj *const *objv, adns_answer **answer_r) {
430   adns_query aqu;
431   OptionParse op;
432   Resolver *res;
433   int rc, ec;
434   
435   rc= query_submit(ip,rrtype,domain,objc,objv,&aqu,0,&op);
436   if (rc) return rc;
437
438   res= op.resolver;
439   ec= adns_wait(res->ads,&aqu,answer_r,0);
440   assert(!ec);
441
442   asynch_check(res);
443   return TCL_OK;
444 }
445
446 int do_adns_lookup(ClientData cd, Tcl_Interp *ip,
447                    const AdnsTclRRTypeInfo *rrtype,
448                    const char *domain,
449                    int objc, Tcl_Obj *const *objv,
450                    Tcl_Obj **result) {
451   int rc;
452   adns_answer *answer;
453   
454   rc= synch(ip,rrtype,domain,objc,objv,&answer);  if (rc) return rc;
455
456   if (answer->status) {
457     Tcl_Obj *problem[RESULTSTATUS_LLEN];
458     make_resultstatus(ip, answer->status, problem);
459     *result= Tcl_NewListObj(RESULTSTATUS_LLEN, problem);
460   } else {
461     *result= make_resultrdata(ip, answer);
462   }
463   free(answer);
464   return TCL_OK;
465 }
466
467 int do_adns_synch(ClientData cd, Tcl_Interp *ip,
468                   const AdnsTclRRTypeInfo *rrtype,
469                   const char *domain,
470                   int objc, Tcl_Obj *const *objv,
471                   Tcl_Obj **result) {
472   int rc;
473   adns_answer *answer;
474   Tcl_Obj *results[RESULTLIST_LLEN];
475
476   rc= synch(ip,rrtype,domain,objc,objv,&answer);  if (rc) return rc;
477   make_resultlist(ip,answer,results);
478   free(answer);
479   *result= Tcl_NewListObj(RESULTLIST_LLEN, results);
480   return TCL_OK;
481 }
482
483 /*---------- asynchronous query handling ----------*/
484
485 struct Query {
486   int ix; /* first! */
487   Resolver *res;
488   adns_query aqu;
489   ScriptToInvoke on_yes, on_no, on_fail;
490   Tcl_Obj *xargs;
491 };
492
493 static void asynch_timerhandler(void *res_v) {
494   Resolver *res= res_v;
495   res->timertoken= 0;
496   adns_processtimeouts(res->ads,0);
497   asynch_check(res);
498 }
499
500 static void asynch_filehandler(void *res_v, int mask) {
501   Resolver *res= res_v;
502   int ec;
503   
504   ec= adns_processany(res->ads);
505   if (ec) adns_globalsystemfailure(res->ads);
506   asynch_check(res);
507 }
508
509 static void asynch_sethandlers(Resolver *res, int shutdown) {
510   fd_set want[3];
511   int maxfd;
512   struct timeval tv_buf, *timeout;
513   int i, fd;
514
515   timeout= 0;
516   maxfd= 0;
517   for (i=0; i<3; i++) FD_ZERO(&want[i]);
518
519   if (!shutdown)
520     adns_beforeselect(res->ads,&maxfd,&want[0],&want[1],&want[2],
521                       &timeout,&tv_buf,0);
522
523   for (fd= 0; fd < maxfd || fd < res->maxfd; fd++)
524     for (i=0; i<3; i++)
525       if (!!FD_ISSET(fd, &res->handling[i])
526           != !!FD_ISSET(fd, &want[i])) {
527         int mask=0;
528         if (FD_ISSET(fd, &want[0])) mask |= TCL_READABLE;
529         if (FD_ISSET(fd, &want[1])) mask |= TCL_WRITABLE;
530         if (FD_ISSET(fd, &want[2])) mask |= TCL_EXCEPTION;
531         if (mask) Tcl_CreateFileHandler(fd,mask,asynch_filehandler,res);
532         else Tcl_DeleteFileHandler(fd);
533       }
534
535   Tcl_DeleteTimerHandler(res->timertoken);
536
537   if (timeout) {
538     int milliseconds;
539
540     if (timeout->tv_sec >= INT_MAX/1000 - 1)
541       milliseconds= INT_MAX;
542     else
543       milliseconds= timeout->tv_sec * 1000 +
544         (timeout->tv_usec + 999) / 1000;
545     
546     res->timertoken=
547       Tcl_CreateTimerHandler(milliseconds,asynch_timerhandler,res);
548   }
549 }
550
551 static void asynch_check(Resolver *res) {
552   Tcl_Interp *interp= res->interp;
553   adns_query aqu;
554   adns_answer *answer;
555   void *query_v;
556   Query *query;
557   ScriptToInvoke *si;
558   int ec;
559   Tcl_Obj *results[RESULTLIST_LLEN];
560
561   for (;;) {
562     aqu= 0;
563     ec= adns_check(res->ads, &aqu, &answer, &query_v);
564     if (ec==ESRCH || ec==EAGAIN) break;
565     assert(!ec);
566     query= query_v;
567
568     query->aqu= 0;
569     tabledataid_disposing(interp, query, &adnstcl_queries);
570
571     si= (!answer->status ? &query->on_yes
572          : answer->status > adns_s_max_tempfail ? &query->on_no
573          : &query->on_fail);
574
575     make_resultlist(interp, answer, results);
576     free(answer);
577     scriptinv_invoke(si, RESULTLIST_LLEN, results);
578     asynch_query_dispose(interp, query);
579   }
580
581   asynch_sethandlers(res,0);
582 }
583     
584 int do_adns_asynch(ClientData cd, Tcl_Interp *ip,
585                    Tcl_Obj *on_yes, Tcl_Obj *on_no,
586                    Tcl_Obj *on_fail, Tcl_Obj *xargs,
587                    const AdnsTclRRTypeInfo *rrtype, const char *domain,
588                    int objc, Tcl_Obj *const *objv, void **result) {
589   Query *query;
590   int rc;
591   Resolver *res=0;
592   OptionParse op;
593   
594   query= TALLOC(sizeof(*query));
595   query->ix= -1;
596   query->aqu= 0;
597   scriptinv_init(&query->on_yes);
598   scriptinv_init(&query->on_no);
599   scriptinv_init(&query->on_fail);
600   query->xargs= 0;
601
602   rc= query_submit(ip,rrtype,domain,objc,objv,&query->aqu,query,&op);
603   if (rc) goto x_rc;
604
605   res= op.resolver;
606
607   rc= scriptinv_set(&query->on_yes, ip,on_yes);   if (rc) goto x_rc;
608   rc= scriptinv_set(&query->on_no,  ip,on_no);    if (rc) goto x_rc;
609   rc= scriptinv_set(&query->on_fail,ip,on_fail);  if (rc) goto x_rc;
610   query->xargs= xargs;
611   Tcl_IncrRefCount(xargs);
612   *result= query;
613   query= 0; /* do not dispose */
614   rc= TCL_OK;
615
616  x_rc:
617   if (query) asynch_query_dispose(ip, query);
618   if (res) asynch_sethandlers(res,0);
619   return rc;
620 }
621
622 int do_adns_asynch_cancel(ClientData cd, Tcl_Interp *ip, void *query_v) {
623   Query *query= query_v;
624   Resolver *res= query->res;
625   asynch_query_dispose(ip, query);
626   asynch_sethandlers(res,0);
627   return TCL_OK;
628 }
629
630 static void asynch_query_dispose(Tcl_Interp *interp, Query *query) {
631   tabledataid_disposing(interp, query, &adnstcl_queries);
632   scriptinv_cancel(&query->on_yes);
633   scriptinv_cancel(&query->on_no);
634   scriptinv_cancel(&query->on_fail);
635   if (query->xargs) Tcl_DecrRefCount(query->xargs);
636   if (query->aqu) adns_cancel(query->aqu);
637   TFREE(query);
638 }
639
640 static void destroy_query_idtabcb(Tcl_Interp *interp, void *query_v) {
641   asynch_query_dispose(interp, query_v);
642 }
643
644 const IdDataSpec adnstcl_queries= {
645   "adns", "adns-query-table", destroy_query_idtabcb
646 };