chiark / gitweb /
reassemble adns log messages
[chiark-tcl.git] / adns / adns.c
index 34ca06ce1e72055693299202c22603a5a9643104..01f0dc6718524d3a759cf47f8672591eab88ac3d 100644 (file)
  *         -reverse-any ZONE-A-LIKE
  *         -config CONFIG-STRING
  *
+ * adns set-default-resolver RESOLVER
+ *        cancels any outstanding queries from a previous anonymous
+ *        default resolver
+ *
  * adns destroy-resolver RESOLVER
+ *        cancels outstanding queries
  */
 
+#define _GNU_SOURCE
+
+#include <stdio.h>
+
 #include "tables.h"
 #include "hbytes.h"
 
 /*---------- important types and forward declarations ----------*/
 
+typedef struct Query Query;
 typedef struct Resolver Resolver;
 typedef struct OptionInfo OptionInfo;
-static void asynch_check(Resolver *res);
-static void asynch_sethandlers(Resolver *res, int shutdown);
+
+static void asynch_sethandlers(Resolver *res);
+static void asynch_cancelhandlers(Resolver *res);
+static void asynch_perturbed(Resolver *res);
+
+static void asynch_query_dispose(Tcl_Interp *interp, Query *query);
+
+#define ASSOC_DEFAULTRES "adns-defaultresolver"
 
 /*---------- common resolver/query option processing ----------*/
 
@@ -88,7 +104,6 @@ struct OptionInfo {
 };
 
 enum {
-  oisf_makedefault= 0x0001,
   oisf_reverse=     0x0002
 };
 
@@ -112,6 +127,13 @@ static int oifn_reverse_any(Tcl_Interp *ip, const OptionInfo *oi,
 #define OIFS(f) { "-" #f, oifn_fs, 0, oisf_##f, 0 }
 #define OICA(o) { "-" #o, oifn_##o, 1 }
 
+static void optparse_blank(OptionParse *op) {
+  memset(op,0,sizeof(*op));
+  op->errfile= stderr;
+  op->errcallback= 0;
+  op->config_string= 0;
+}
+
 static int parse_options(Tcl_Interp *ip, int objc, Tcl_Obj *const *objv,
                         const OptionInfo opttable[], OptionParse *op) {
   const OptionInfo *oi;
@@ -144,8 +166,6 @@ static int parse_options(Tcl_Interp *ip, int objc, Tcl_Obj *const *objv,
 
 /*---------- resolver management ----------*/
 
-IdDataTable adnstcl_resolvers= { "adns-res" };
-
 struct Resolver {
   int ix; /* first! */
   Tcl_Interp *interp;
@@ -153,8 +173,17 @@ struct Resolver {
   Tcl_TimerToken timertoken;
   int maxfd;
   fd_set handling[3];
+  ScriptToInvoke errcallback;
+  Tcl_Obj *errstring_accum;
 };
 
+/* The default resolver is recorded using Tcl_SetAssocData with key
+ * ASSOC_DEFAULTRES to record the Resolver*.  If it was explicitly
+ * created with `adns new-resolver' then ix will be >=0, and the
+ * resolver will be destroyed - leaving no default - when explicitly
+ * requested.  If it was implicitly created (by starting a query when
+ * there is no default) then ix will be -1.  */
+
 static int oifn_errfile(Tcl_Interp *ip, const OptionInfo *oi,
                        Tcl_Obj *arg, OptionParse *op) {
   int rc;
@@ -190,68 +219,119 @@ static const OptionInfo resolver_optioninfos[]= {
   OIFA1(if,noerrprint, adns_if_debug),
   OIFA2(if,checkc,entex),
   OIFA2(if,checkc,freq),
-  OIFS(makedefault),
   OICA(errfile),
   OICA(errcallback),
   OICA(config),
   { 0 }
 };
 
+static void adnslogfn_flushmessage(Resolver *res) {
+  scriptinv_invoke(&res->errcallback, 1, &res->errstring_accum);
+  Tcl_SetObjLength(res->errstring_accum, 0);
+}
+
 static void adnslogfn_callback(adns_state ads, void *logfndata,
                               const char *fmt, va_list al) {
-  abort(); /* fixme implement adns_logcallbackfn */
+  Resolver *res= logfndata;
+  int l, newline;
+  char *str;
+
+  l= vasprintf(&str,fmt,al);
+  if (l<0) {
+    posixerr(res->interp,errno,"construct adns log callback string");
+    Tcl_BackgroundError(res->interp);
+  }
+
+  if (l==0) { free(str); return; }
+  if ((newline= l>0 && str[l-1]=='\n')) l--;
+
+  if (!res->errstring_accum) {
+    res->errstring_accum= Tcl_NewStringObj(str,l);
+    Tcl_IncrRefCount(res->errstring_accum);
+  } else {
+    Tcl_AppendToObj(res->errstring_accum,str,l);
+  }
+  free(str);
+
+  if (newline)
+    adnslogfn_flushmessage(res);
 }
 
-int do_adns_destroy_resolver(ClientData cd, Tcl_Interp *ip, void *res_v) {
-  Resolver *res= res_v;
-  tabledataid_disposing(res,&adnstcl_resolvers);
-  if (res->ads) adns_finish(res->ads);
-  asynch_sethandlers(res,1);
+static Resolver *default_resolver(Tcl_Interp *ip) {
+  return Tcl_GetAssocData(ip,ASSOC_DEFAULTRES,0);
+}
+
+static void destroy_resolver(Tcl_Interp *ip, Resolver *res) {
+  void *query_v;
+  int logstring_len;
+  char *rstr;
+  adns_query aqu;
+  if (res == default_resolver(ip))
+    Tcl_DeleteAssocData(ip,ASSOC_DEFAULTRES);
+  if (res->errstring_accum) {
+    rstr= Tcl_GetStringFromObj(res->errstring_accum, &logstring_len);
+    assert(rstr);
+    if (logstring_len)
+      adnslogfn_flushmessage(res);
+  }
+
+  if (res->ads) {
+    /* although adns would throw these away for us, we need to
+     * destroy our own data too and only adns has a list of them */
+    for (;;) {
+      adns_forallqueries_begin(res->ads);
+      aqu= adns_forallqueries_next(res->ads, &query_v);
+      if (!aqu) break;
+      asynch_query_dispose(ip, query_v);
+    }
+    adns_finish(res->ads);
+  }
+  asynch_cancelhandlers(res);
+  scriptinv_cancel(&res->errcallback);
   TFREE(res);
-  /* fixme what about outstanding queries */
-  /* fixme what about the default resolver */
-  /* fixme what if the tcl interpreter gets deleted */
+}
+
+static void destroy_resolver_idtabcb(Tcl_Interp *ip, void *resolver_v) {
+  destroy_resolver(ip,resolver_v);
+}
+static void destroy_resolver_defcb(ClientData resolver_v, Tcl_Interp *ip) {
+  destroy_resolver(ip,resolver_v);
+}
+
+int do_adns_destroy_resolver(ClientData cd, Tcl_Interp *ip, void *res_v) {
+  destroy_resolver(ip,res_v);
+  tabledataid_disposing(ip,res_v,&adnstcl_resolvers);
   return TCL_OK;
 }
 
-int do_adns_new_resolver(ClientData cd, Tcl_Interp *ip,
-                        int objc, Tcl_Obj *const *objv,
-                        void **result) {
-  OptionParse op;
+static int create_resolver(Tcl_Interp *ip, const OptionParse *op,
+                          Resolver **res_r) {
   Resolver *res=0;
   int rc, i, ec;
-
-  op.aflags= adns_if_noautosys;
-  op.sflags= 0;
-  op.errfile= 0;
-  op.errcallback= 0;
-  op.config_string= 0;
-  rc= parse_options(ip,objc,objv,resolver_optioninfos,&op);
-  if (rc) goto x_rc;
-
-  res= TALLOC(sizeof(*res)); assert(res);
+  
+  res= TALLOC(sizeof(*res));  assert(res);
   res->ix= -1;
   res->interp= ip;
   res->ads= 0;
   res->timertoken= 0;
   res->maxfd= 0;
   for (i=0; i<3; i++) FD_ZERO(&res->handling[i]);
+  scriptinv_init(&res->errcallback);
+  res->errstring_accum= 0;
 
-  if (op.aflags & adns_if_noerrprint) {
-    op.errfile= 0;
-    op.errcallback= 0;
-  }
+  if (op->errcallback)
+    scriptinv_set(&res->errcallback, ip, op->errcallback, 0);
 
-  ec= adns_init_logfn(&res->ads, op.aflags, op.config_string,
-                     op.errcallback ? adnslogfn_callback : 0,
-                     op.errcallback ? (void*)op.errcallback
-                     : (void*)op.errfile);
+  ec= adns_init_logfn(&res->ads,
+                     op->aflags | adns_if_noautosys,
+                     op->config_string,
+                     op->errcallback ? adnslogfn_callback : 0,
+                     op->errcallback ? (void*)res : (void*)op->errfile);
   if (ec) { rc= posixerr(ip,ec,"create adns resolver"); goto x_rc; }
 
-  if (op.errcallback)
-    Tcl_IncrRefCount(op.errcallback);
-
-  *result= res;
+  *res_r= res;
   return TCL_OK;
 
  x_rc:
@@ -260,8 +340,42 @@ int do_adns_new_resolver(ClientData cd, Tcl_Interp *ip,
     TFREE(res);
   }
   return rc;
+}  
+
+int do_adns_new_resolver(ClientData cd, Tcl_Interp *ip,
+                        int objc, Tcl_Obj *const *objv,
+                        void **result) {
+  OptionParse op;
+  Resolver *res=0;
+  int rc;
+
+  optparse_blank(&op);
+  rc= parse_options(ip,objc,objv,resolver_optioninfos,&op);
+  if (rc) return rc;
+
+  if (op.aflags & adns_if_noerrprint) {
+    op.errfile= 0;
+    op.errcallback= 0;
+  }
+
+  rc= create_resolver(ip, &op, &res);
+  if (rc) return rc;
+
+  *result= res;
+  return TCL_OK;
 }
 
+int do_adns_set_default_resolver(ClientData cd, Tcl_Interp *ip, void *res_v) {
+  Resolver *res= res_v;
+  Tcl_DeleteAssocData(ip,ASSOC_DEFAULTRES);
+  Tcl_SetAssocData(ip, ASSOC_DEFAULTRES, 0, res);
+  return TCL_OK;
+}
+
+const IdDataSpec adnstcl_resolvers= {
+  "adns-res", "adns-resolvers-table", destroy_resolver_idtabcb
+};
+
 /*---------- query, query option and answers - common stuff ----------*/
 
 #define RRTYPE_EXACTLY(t) { #t, adns_r_##t }
@@ -316,18 +430,32 @@ static const OptionInfo query_optioninfos[]= {
 static int query_submit(Tcl_Interp *ip,
                        const AdnsTclRRTypeInfo *type, const char *domain,
                        int queryopts_objc, Tcl_Obj *const *queryopts_objv,
-                       adns_query *aqu_r, OptionParse *op) {
+                       adns_query *aqu_r, void *context, OptionParse *op) {
   struct sockaddr sa;
   static const int aftry[]= { AF_INET, AF_INET6 };
+  OptionParse res_op;
   int rc, r, ec;
   adns_state ads;
   
   op->aflags= adns_qf_owner;
   op->sflags= 0;
   op->resolver= 0;
+  op->reverseany= 0;
   rc= parse_options(ip, queryopts_objc,queryopts_objv, query_optioninfos,op);
   if (rc) return rc;
 
+  if (!op->resolver) {
+    op->resolver= default_resolver(ip);
+    if (!op->resolver) {
+      optparse_blank(&res_op);
+      rc= create_resolver(ip, &res_op, &op->resolver);
+      if (rc) return rc;
+
+      Tcl_SetAssocData(ip, ASSOC_DEFAULTRES,
+                      destroy_resolver_defcb, op->resolver);
+    }
+  }
+  
   if (op->reverseany || (op->sflags & oisf_reverse)) {
     const int *af;
     for (af=aftry; af < af + sizeof(af)/sizeof(*af); af++) {
@@ -344,13 +472,13 @@ static int query_submit(Tcl_Interp *ip,
 
   if (op->reverseany) {
     ec= adns_submit_reverse_any(ads, &sa, op->reverseany,
-                               type->number, op->aflags, 0, aqu_r);
+                               type->number, op->aflags, context, aqu_r);
   } else if (op->sflags & oisf_reverse) {
     ec= adns_submit_reverse(ads, &sa,
-                           type->number, op->aflags, 0, aqu_r);
+                           type->number, op->aflags, context, aqu_r);
   } else {
     ec= adns_submit(ads, domain,
-                   type->number, op->aflags, 0, aqu_r);
+                   type->number, op->aflags, context, aqu_r);
   }
   if (ec)
     return posixerr(ip,ec,"submit adns query");
@@ -370,7 +498,7 @@ static void make_resultstatus(Tcl_Interp *ip, adns_status status,
 }
 
 static Tcl_Obj *make_resultrdata(Tcl_Interp *ip, adns_answer *answer) {
-  Tcl_Obj **rdata;
+  Tcl_Obj **rdata, *rl;
   int i, rrsz;
   adns_status st;
   char *datap, *rdatastring;
@@ -384,8 +512,9 @@ static Tcl_Obj *make_resultrdata(Tcl_Interp *ip, adns_answer *answer) {
     rdata[i]= ret_string(ip, rdatastring);
     free(rdatastring);
   }
+  rl= Tcl_NewListObj(answer->nrrs, rdata);
   TFREE(rdata);
-  return Tcl_NewListObj(answer->nrrs, rdata);
+  return rl;
 }
 
 static void make_resultlist(Tcl_Interp *ip, adns_answer *answer,
@@ -408,14 +537,14 @@ static int synch(Tcl_Interp *ip, const AdnsTclRRTypeInfo *rrtype,
   Resolver *res;
   int rc, ec;
   
-  rc= query_submit(ip,rrtype,domain,objc,objv,&aqu,&op);
+  rc= query_submit(ip,rrtype,domain,objc,objv,&aqu,0,&op);
   if (rc) return rc;
 
   res= op.resolver;
   ec= adns_wait(res->ads,&aqu,answer_r,0);
   assert(!ec);
 
-  asynch_check(res);
+  asynch_perturbed(res);
   return TCL_OK;
 }
 
@@ -458,21 +587,21 @@ int do_adns_synch(ClientData cd, Tcl_Interp *ip,
 
 /*---------- asynchronous query handling ----------*/
 
-typedef struct {
+struct Query {
   int ix; /* first! */
   Resolver *res;
   adns_query aqu;
   ScriptToInvoke on_yes, on_no, on_fail;
   Tcl_Obj *xargs;
-} Query;
+};
 
-IdDataTable adnstcl_queries= { "adns" };
+static void asynch_check_now(Resolver *res);
 
 static void asynch_timerhandler(void *res_v) {
   Resolver *res= res_v;
   res->timertoken= 0;
   adns_processtimeouts(res->ads,0);
-  asynch_check(res);
+  asynch_check_now(res);
 }
 
 static void asynch_filehandler(void *res_v, int mask) {
@@ -481,10 +610,12 @@ static void asynch_filehandler(void *res_v, int mask) {
   
   ec= adns_processany(res->ads);
   if (ec) adns_globalsystemfailure(res->ads);
-  asynch_check(res);
+  asynch_check_now(res);
 }
 
-static void asynch_sethandlers(Resolver *res, int shutdown) {
+static void asynch_sethandlers_generic(Resolver *res,
+                                      int shutdown /*from _cancelhandlers*/,
+                                      int immediate /*from _perturbed*/) {
   fd_set want[3];
   int maxfd;
   struct timeval tv_buf, *timeout;
@@ -512,7 +643,9 @@ static void asynch_sethandlers(Resolver *res, int shutdown) {
 
   Tcl_DeleteTimerHandler(res->timertoken);
 
-  if (timeout) {
+  if (immediate) {
+    res->timertoken= Tcl_CreateTimerHandler(0,asynch_timerhandler,res);
+  } else if (timeout) {
     int milliseconds;
 
     if (timeout->tv_sec >= INT_MAX/1000 - 1)
@@ -526,17 +659,17 @@ static void asynch_sethandlers(Resolver *res, int shutdown) {
   }
 }
 
-static void asynch_query_dispose(Query *query) {
-  tabledataid_disposing(query, &adnstcl_queries);
-  scriptinv_cancel(&query->on_yes);
-  scriptinv_cancel(&query->on_no);
-  scriptinv_cancel(&query->on_fail);
-  if (query->xargs) Tcl_DecrRefCount(query->xargs);
-  if (query->aqu) adns_cancel(query->aqu);
-  TFREE(query);
+static void asynch_sethandlers(Resolver *res) {
+  asynch_sethandlers_generic(res,0,0);
+}
+static void asynch_cancelhandlers(Resolver *res) {
+  asynch_sethandlers_generic(res,1,0);
+}
+static void asynch_perturbed(Resolver *res) {
+  asynch_sethandlers_generic(res,0,1);
 }
 
-static void asynch_check(Resolver *res) {
+static void asynch_check_now(Resolver *res) {
   Tcl_Interp *interp= res->interp;
   adns_query aqu;
   adns_answer *answer;
@@ -547,25 +680,26 @@ static void asynch_check(Resolver *res) {
   Tcl_Obj *results[RESULTLIST_LLEN];
 
   for (;;) {
+    aqu= 0;
     ec= adns_check(res->ads, &aqu, &answer, &query_v);
     if (ec==ESRCH || ec==EAGAIN) break;
     assert(!ec);
     query= query_v;
 
     query->aqu= 0;
-    tabledataid_disposing(query, &adnstcl_queries);
+    tabledataid_disposing(interp, query, &adnstcl_queries);
 
-    si= (!answer->status ? si= &query->on_yes
+    si= (!answer->status ? &query->on_yes
         : answer->status > adns_s_max_tempfail ? &query->on_no
         : &query->on_fail);
 
     make_resultlist(interp, answer, results);
     free(answer);
     scriptinv_invoke(si, RESULTLIST_LLEN, results);
-    asynch_query_dispose(query);
+    asynch_query_dispose(interp, query);
   }
 
-  asynch_sethandlers(res,0);
+  asynch_sethandlers(res);
 }
     
 int do_adns_asynch(ClientData cd, Tcl_Interp *ip,
@@ -586,31 +720,48 @@ int do_adns_asynch(ClientData cd, Tcl_Interp *ip,
   scriptinv_init(&query->on_fail);
   query->xargs= 0;
 
-  rc= query_submit(ip,rrtype,domain,objc,objv,&query->aqu,&op);
+  rc= query_submit(ip,rrtype,domain,objc,objv,&query->aqu,query,&op);
   if (rc) goto x_rc;
 
   res= op.resolver;
 
-  rc= scriptinv_set(&query->on_yes, ip,on_yes);   if (rc) goto x_rc;
-  rc= scriptinv_set(&query->on_no,  ip,on_no);    if (rc) goto x_rc;
-  rc= scriptinv_set(&query->on_fail,ip,on_fail);  if (rc) goto x_rc;
+  rc= scriptinv_set(&query->on_yes, ip,on_yes, xargs);  if (rc) goto x_rc;
+  rc= scriptinv_set(&query->on_no,  ip,on_no,  xargs);  if (rc) goto x_rc;
+  rc= scriptinv_set(&query->on_fail,ip,on_fail,xargs);  if (rc) goto x_rc;
   query->xargs= xargs;
   Tcl_IncrRefCount(xargs);
   *result= query;
-
-  return TCL_OK;
+  query= 0; /* do not dispose */
+  rc= TCL_OK;
 
  x_rc:
-  if (query) asynch_query_dispose(query);
-  if (res) asynch_sethandlers(res,0);
+  if (query) asynch_query_dispose(ip, query);
+  if (res) asynch_perturbed(res);
   return rc;
 }
 
 int do_adns_asynch_cancel(ClientData cd, Tcl_Interp *ip, void *query_v) {
   Query *query= query_v;
   Resolver *res= query->res;
-  
-  asynch_query_dispose(query);
-  asynch_sethandlers(res,0);
+  asynch_query_dispose(ip, query);
+  asynch_perturbed(res);
   return TCL_OK;
 }
+
+static void asynch_query_dispose(Tcl_Interp *interp, Query *query) {
+  tabledataid_disposing(interp, query, &adnstcl_queries);
+  scriptinv_cancel(&query->on_yes);
+  scriptinv_cancel(&query->on_no);
+  scriptinv_cancel(&query->on_fail);
+  if (query->xargs) Tcl_DecrRefCount(query->xargs);
+  if (query->aqu) adns_cancel(query->aqu);
+  TFREE(query);
+}
+
+static void destroy_query_idtabcb(Tcl_Interp *interp, void *query_v) {
+  asynch_query_dispose(interp, query_v);
+}
+
+const IdDataSpec adnstcl_queries= {
+  "adns", "adns-query-table", destroy_query_idtabcb
+};