chiark / gitweb /
c5ffed6337ea2c68fb84fdacaaefbe58bff60890
[adns.git] / src / setup.c
1 /*
2  * setup.c
3  * - configuration file parsing
4  * - management of global state
5  */
6 /*
7  *  This file is part of adns, which is
8  *    Copyright (C) 1997-2000,2003,2006,2014  Ian Jackson
9  *    Copyright (C) 2014  Mark Wooding
10  *    Copyright (C) 1999-2000,2003,2006  Tony Finch
11  *    Copyright (C) 1991 Massachusetts Institute of Technology
12  *  (See the file INSTALL for full details.)
13  *  
14  *  This program is free software; you can redistribute it and/or modify
15  *  it under the terms of the GNU General Public License as published by
16  *  the Free Software Foundation; either version 3, or (at your option)
17  *  any later version.
18  *  
19  *  This program is distributed in the hope that it will be useful,
20  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
21  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22  *  GNU General Public License for more details.
23  *  
24  *  You should have received a copy of the GNU General Public License
25  *  along with this program; if not, write to the Free Software Foundation.
26  */
27
28 #include <stdlib.h>
29 #include <errno.h>
30 #include <limits.h>
31 #include <unistd.h>
32 #include <fcntl.h>
33
34 #include <sys/types.h>
35 #include <netdb.h>
36 #include <sys/socket.h>
37 #include <netinet/in.h>
38 #include <arpa/inet.h>
39
40 #include "internal.h"
41
42 static void readconfig(adns_state ads, const char *filename, int warnmissing);
43
44 static void addserver(adns_state ads, const struct sockaddr *sa, int salen) {
45   int i;
46   adns_rr_addr *ss;
47   char buf[ADNS_ADDR2TEXT_BUFLEN];
48   
49   for (i=0; i<ads->nservers; i++) {
50     if (adns__sockaddrs_equal(sa, &ads->servers[i].addr.sa)) {
51       adns__debug(ads,-1,0,"duplicate nameserver %s ignored",
52                   adns__sockaddr_ntoa(sa, buf));
53       return;
54     }
55   }
56   
57   if (ads->nservers>=MAXSERVERS) {
58     adns__diag(ads,-1,0,"too many nameservers, ignoring %s",
59                adns__sockaddr_ntoa(sa, buf));
60     return;
61   }
62
63   ss= ads->servers+ads->nservers;
64   assert(salen <= sizeof(ss->addr));
65   ss->len = salen;
66   memcpy(&ss->addr, sa, salen);
67   ads->nservers++;
68 }
69
70 static void freesearchlist(adns_state ads) {
71   if (ads->nsearchlist) free(*ads->searchlist);
72   free(ads->searchlist);
73 }
74
75 static void saveerr(adns_state ads, int en) {
76   if (!ads->configerrno) ads->configerrno= en;
77 }
78
79 static void configparseerr(adns_state ads, const char *fn, int lno,
80                            const char *fmt, ...) {
81   va_list al;
82
83   saveerr(ads,EINVAL);
84   if (!ads->logfn || (ads->iflags & adns_if_noerrprint)) return;
85
86   if (lno==-1) adns__lprintf(ads,"adns: %s: ",fn);
87   else adns__lprintf(ads,"adns: %s:%d: ",fn,lno);
88   va_start(al,fmt);
89   adns__vlprintf(ads,fmt,al);
90   va_end(al);
91   adns__lprintf(ads,"\n");
92 }
93
94 static int nextword(const char **bufp_io, const char **word_r, int *l_r) {
95   const char *p, *q;
96
97   p= *bufp_io;
98   while (ctype_whitespace(*p)) p++;
99   if (!*p) return 0;
100
101   q= p;
102   while (*q && !ctype_whitespace(*q)) q++;
103
104   *l_r= q-p;
105   *word_r= p;
106   *bufp_io= q;
107
108   return 1;
109 }
110
111 static void ccf_nameserver(adns_state ads, const char *fn,
112                            int lno, const char *buf) {
113   adns_rr_addr a;
114   char addrbuf[ADNS_ADDR2TEXT_BUFLEN];
115   int err;
116
117   a.len= sizeof(a.addr);
118   err= adns_text2addr(buf,DNS_PORT, 0, &a.addr.sa,&a.len);
119   switch (err) {
120   case 0:
121     break;
122   case EINVAL:
123     configparseerr(ads,fn,lno,"invalid nameserver address `%s'",buf);
124     return;
125   default:
126     configparseerr(ads,fn,lno,"failed to parse nameserver address `%s': %s",
127                    buf,strerror(err));
128     return;
129   }
130   adns__debug(ads,-1,0,"using nameserver %s",
131               adns__sockaddr_ntoa(&a.addr.sa, addrbuf));
132   addserver(ads,&a.addr.sa,a.len);
133 }
134
135 static void ccf_search(adns_state ads, const char *fn,
136                        int lno, const char *buf) {
137   const char *bufp, *word;
138   char *newchars, **newptrs, **pp;
139   int count, tl, l;
140
141   if (!buf) return;
142
143   bufp= buf;
144   count= 0;
145   tl= 0;
146   while (nextword(&bufp,&word,&l)) { count++; tl += l+1; }
147
148   newptrs= malloc(sizeof(char*)*count);
149   if (!newptrs) { saveerr(ads,errno); return; }
150
151   newchars= malloc(tl);
152   if (!newchars) { saveerr(ads,errno); free(newptrs); return; }
153
154   bufp= buf;
155   pp= newptrs;
156   while (nextword(&bufp,&word,&l)) {
157     *pp++= newchars;
158     memcpy(newchars,word,l);
159     newchars += l;
160     *newchars++ = 0;
161   }
162
163   freesearchlist(ads);
164   ads->nsearchlist= count;
165   ads->searchlist= newptrs;
166 }
167
168 static int gen_pton(const char *text, int want_af, adns_sockaddr *a) {
169   int err;
170   int len;
171
172   len= sizeof(*a);
173   err= adns_text2addr(text,0, adns_qf_addrlit_scope_forbid,
174                       &a->sa, &len);
175   if (err) { assert(err == EINVAL); return 0; }
176   if (want_af != AF_UNSPEC && a->sa.sa_family != want_af) return 0;
177   return 1;
178 }
179
180 static void ccf_sortlist(adns_state ads, const char *fn,
181                          int lno, const char *buf) {
182   const char *word;
183   char tbuf[200], *slash, *ep;
184   const char *maskwhat;
185   struct sortlist *sl;
186   int l;
187   int initial= -1;
188
189   if (!buf) return;
190   
191   ads->nsortlist= 0;
192   while (nextword(&buf,&word,&l)) {
193     if (ads->nsortlist >= MAXSORTLIST) {
194       adns__diag(ads,-1,0,"too many sortlist entries,"
195                  " ignoring %.*s onwards",l,word);
196       return;
197     }
198
199     if (l >= sizeof(tbuf)) {
200       configparseerr(ads,fn,lno,"sortlist entry `%.*s' too long",l,word);
201       continue;
202     }
203     
204     memcpy(tbuf,word,l); tbuf[l]= 0;
205     slash= strchr(tbuf,'/');
206     if (slash) *slash++= 0;
207
208     sl= &ads->sortlist[ads->nsortlist];
209     if (!gen_pton(tbuf, AF_UNSPEC, &sl->base)) {
210       configparseerr(ads,fn,lno,"invalid address `%s' in sortlist",tbuf);
211       continue;
212     }
213
214     if (slash) {
215       if (slash[strspn(slash, "0123456789")]) {
216         maskwhat = "mask";
217         if (!gen_pton(slash, sl->base.sa.sa_family, &sl->mask)) {
218           configparseerr(ads,fn,lno,"invalid mask `%s' in sortlist",slash);
219           continue;
220         }
221       } else {
222         maskwhat = "prefix length";
223         initial= strtoul(slash,&ep,10);
224         if (*ep || initial>adns__addr_width(sl->base.sa.sa_family)) {
225           configparseerr(ads,fn,lno,"mask length `%s' invalid",slash);
226           continue;
227         }
228         sl->mask.sa.sa_family= sl->base.sa.sa_family;
229         adns__prefix_mask(&sl->mask, initial);
230       }
231     } else {
232       maskwhat = "implied prefix length";
233       initial= adns__guess_prefix_length(&sl->base);
234       if (initial < 0) {
235         configparseerr(ads,fn,lno, "network address `%s'"
236                        " in sortlist is not in classed ranges,"
237                        " must specify mask explicitly", tbuf);
238         continue;
239       }
240       sl->mask.sa.sa_family= sl->base.sa.sa_family;
241       adns__prefix_mask(&sl->mask, initial);
242     }
243
244     if (!adns__addr_matches(sl->base.sa.sa_family,
245                             adns__sockaddr_addr(&sl->base.sa),
246                             &sl->base,&sl->mask)) {
247       if (initial >= 0) {
248         configparseerr(ads,fn,lno, "%s %d in sortlist"
249                        " overlaps address `%s'",maskwhat,initial,tbuf);
250       } else {
251         configparseerr(ads,fn,lno, "%s `%s' in sortlist"
252                        " overlaps address `%s'",maskwhat,slash,tbuf);
253       }
254       continue;
255     }
256
257     ads->nsortlist++;
258   }
259 }
260
261 static void ccf_options(adns_state ads, const char *fn,
262                         int lno, const char *buf) {
263   const char *word, *rhs;
264   char *ep;
265   unsigned long v;
266   int i,l;
267
268   if (!buf) return;
269
270 #define OPTION__IS(s,op) (l op (sizeof(s)-1) && !memcmp(word,s,(sizeof(s)-1)))
271 #define OPTION_IS(s)     (OPTION__IS(s,==))
272 #define OPTION_STARTS(s) (OPTION__IS(s,>=) ? ((rhs=word+sizeof(s)-1)) : 0)
273
274   while (nextword(&buf,&word,&l)) {
275     if (OPTION_IS("debug")) {
276       ads->iflags |= adns_if_debug;
277       continue;
278     }
279     if (OPTION_STARTS("ndots:")) {
280       v= strtoul(rhs,&ep,10);
281       if (ep==rhs || ep != word+l || v > INT_MAX) {
282         configparseerr(ads,fn,lno,"option `%.*s' malformed"
283                        " or has bad value",l,word);
284         continue;
285       }
286       ads->searchndots= v;
287       continue;
288     }
289     if (OPTION_STARTS("adns_checkc:")) {
290       if (!strcmp(rhs,"none")) {
291         ads->iflags &= ~adns_if_checkc_freq;
292         ads->iflags |= adns_if_checkc_entex;
293       } else if (!strcmp(rhs,"entex")) {
294         ads->iflags &= ~adns_if_checkc_freq;
295         ads->iflags |= adns_if_checkc_entex;
296       } else if (!strcmp(rhs,"freq")) {
297         ads->iflags |= adns_if_checkc_freq;
298       } else {
299         configparseerr(ads,fn,lno, "option adns_checkc has bad value `%s' "
300                        "(must be none, entex or freq", rhs);
301       }
302       continue;
303     }
304     if (OPTION_STARTS("adns_af:")) {
305       word= rhs;
306       ads->iflags &= ~adns_if_afmask;
307       if (strcmp(word,"any")) for (;;) {
308         i= strcspn(word,",");
309         if (i>=4 && !memcmp(word,"ipv4",4))
310           ads->iflags |= adns_if_permit_ipv4;
311         else if (i>=4 && !memcmp(word,"ipv6",4))
312           ads->iflags |= adns_if_permit_ipv6;
313         else {
314           configparseerr(ads,fn,lno, "option adns_af has bad value `%.*s' "
315                          "(must be `any' or list {`ipv4',`ipv6'},...)",
316                          i, word);
317           break;
318         }
319         if (!word[i]) break;
320         word= word + i + 1;
321       }
322       continue;
323     }
324     if (OPTION_IS("adns_ignoreunkcfg")) {
325       ads->config_report_unknown=0;
326       continue;
327     }
328     if (/* adns's query strategy is not configurable */
329         OPTION_STARTS("timeout:") ||
330         OPTION_STARTS("attempts:") ||
331         OPTION_IS("rotate") ||
332         /* adns provides the application with knob for this */
333         OPTION_IS("no-check-names") ||
334         /* adns normally does IPv6 if the application wants it; control
335          * this with the adns_af: option if you like */
336         OPTION_IS("inet6") ||
337         /* adns does not do edns0 and this is not a problem */
338         OPTION_IS("edns0"))
339       continue;
340     if (ads->config_report_unknown)
341       adns__diag(ads,-1,0,"%s:%d: unknown option `%.*s'", fn,lno, l,word);
342   }
343
344 #undef OPTION__IS
345 #undef OPTION_IS
346 #undef OPTION_STARTS
347 }
348
349 static void ccf_clearnss(adns_state ads, const char *fn,
350                          int lno, const char *buf) {
351   ads->nservers= 0;
352 }
353
354 static void ccf_include(adns_state ads, const char *fn,
355                         int lno, const char *buf) {
356   if (!*buf) {
357     configparseerr(ads,fn,lno,"`include' directive with no filename");
358     return;
359   }
360   readconfig(ads,buf,1);
361 }
362
363 static void ccf_lookup(adns_state ads, const char *fn, int lno,
364                        const char *buf) {
365   int found_bind=0;
366   const char *word;
367   int l;
368
369   if (!*buf) {
370     configparseerr(ads,fn,lno,"`lookup' directive with no databases");
371     return;
372   }
373
374   while (nextword(&buf,&word,&l)) {
375     if (l==4 && !memcmp(word,"bind",4)) {
376       found_bind=1;
377     } else if (l==4 && !memcmp(word,"file",4)) {
378       /* ignore this and hope /etc/hosts is not essential */
379     } else if (l==2 && !memcmp(word,"yp",2)) {
380       adns__diag(ads,-1,0,"%s:%d: yp lookups not supported by adns", fn,lno);
381       found_bind=-1;
382     } else {
383       if (ads->config_report_unknown)
384         adns__diag(ads,-1,0,"%s:%d: unknown `lookup' database `%.*s'",
385                    fn,lno, l,word);
386       found_bind=-1;
387     }
388   }
389   if (!found_bind)
390     adns__diag(ads,-1,0,"%s:%d: `lookup' specified, but not `bind'", fn,lno);
391 }
392
393 static void ccf_ignore(adns_state ads, const char *fn, int lno,
394                        const char *buf) {
395 }
396
397 static const struct configcommandinfo {
398   const char *name;
399   void (*fn)(adns_state ads, const char *fn, int lno, const char *buf);
400 } configcommandinfos[]= {
401   { "nameserver",        ccf_nameserver  },
402   { "domain",            ccf_search      },
403   { "search",            ccf_search      },
404   { "sortlist",          ccf_sortlist    },
405   { "options",           ccf_options     },
406   { "clearnameservers",  ccf_clearnss    },
407   { "include",           ccf_include     },
408   { "lookup",            ccf_lookup      }, /* OpenBSD */
409   { "lwserver",          ccf_ignore      }, /* BIND9 lwresd */
410   {  0                                   }
411 };
412
413 typedef union {
414   FILE *file;
415   const char *text;
416 } getline_ctx;
417
418 static int gl_file(adns_state ads, getline_ctx *src_io, const char *filename,
419                    int lno, char *buf, int buflen) {
420   FILE *file= src_io->file;
421   int c, i;
422   char *p;
423
424   p= buf;
425   buflen--;
426   i= 0;
427     
428   for (;;) { /* loop over chars */
429     if (i == buflen) {
430       adns__diag(ads,-1,0,"%s:%d: line too long, ignored",filename,lno);
431       goto x_badline;
432     }
433     c= getc(file);
434     if (!c) {
435       adns__diag(ads,-1,0,"%s:%d: line contains nul, ignored",filename,lno);
436       goto x_badline;
437     } else if (c == '\n') {
438       break;
439     } else if (c == EOF) {
440       if (ferror(file)) {
441         saveerr(ads,errno);
442         adns__diag(ads,-1,0,"%s:%d: read error: %s",
443                    filename,lno,strerror(errno));
444         return -1;
445       }
446       if (!i) return -1;
447       break;
448     } else {
449       *p++= c;
450       i++;
451     }
452   }
453
454   *p++= 0;
455   return i;
456
457  x_badline:
458   saveerr(ads,EINVAL);
459   while ((c= getc(file)) != EOF && c != '\n');
460   return -2;
461 }
462
463 static int gl_text(adns_state ads, getline_ctx *src_io, const char *filename,
464                    int lno, char *buf, int buflen) {
465   const char *cp= src_io->text;
466   int l;
467
468   if (!cp || !*cp) return -1;
469
470   if (*cp == ';' || *cp == '\n') cp++;
471   l= strcspn(cp,";\n");
472   src_io->text = cp+l;
473
474   if (l >= buflen) {
475     adns__diag(ads,-1,0,"%s:%d: line too long, ignored",filename,lno);
476     saveerr(ads,EINVAL);
477     return -2;
478   }
479     
480   memcpy(buf,cp,l);
481   buf[l]= 0;
482   return l;
483 }
484
485 static void readconfiggeneric(adns_state ads, const char *filename,
486                               int (*getline)(adns_state ads, getline_ctx*,
487                                              const char *filename, int lno,
488                                              char *buf, int buflen),
489                               /* Returns >=0 for success, -1 for EOF or error
490                                * (error will have been reported), or -2 for
491                                * bad line was encountered, try again.
492                                */
493                               getline_ctx gl_ctx) {
494   char linebuf[2000], *p, *q;
495   int lno, l, dirl;
496   const struct configcommandinfo *ccip;
497
498   for (lno=1;
499        (l= getline(ads,&gl_ctx, filename,lno, linebuf,sizeof(linebuf))) != -1;
500        lno++) {
501     if (l == -2) continue;
502     while (l>0 && ctype_whitespace(linebuf[l-1])) l--;
503     linebuf[l]= 0;
504     p= linebuf;
505     while (ctype_whitespace(*p)) p++;
506     if (*p == '#' || *p == ';' || !*p) continue;
507     q= p;
508     while (*q && !ctype_whitespace(*q)) q++;
509     dirl= q-p;
510     for (ccip=configcommandinfos;
511          ccip->name &&
512            !(strlen(ccip->name)==dirl && !memcmp(ccip->name,p,q-p));
513          ccip++);
514     if (!ccip->name) {
515       if (ads->config_report_unknown)
516         adns__diag(ads,-1,0,"%s:%d: unknown configuration directive `%.*s'",
517                    filename,lno,(int)(q-p),p);
518       continue;
519     }
520     while (ctype_whitespace(*q)) q++;
521     ccip->fn(ads,filename,lno,q);
522   }
523 }
524
525 static const char *instrum_getenv(adns_state ads, const char *envvar) {
526   const char *value;
527
528   value= getenv(envvar);
529   if (!value) adns__debug(ads,-1,0,"environment variable %s not set",envvar);
530   else adns__debug(ads,-1,0,"environment variable %s"
531                    " set to `%s'",envvar,value);
532   return value;
533 }
534
535 static void readconfig(adns_state ads, const char *filename, int warnmissing) {
536   getline_ctx gl_ctx;
537   
538   gl_ctx.file= fopen(filename,"r");
539   if (!gl_ctx.file) {
540     if (errno == ENOENT) {
541       if (warnmissing)
542         adns__debug(ads,-1,0, "configuration file"
543                     " `%s' does not exist",filename);
544       return;
545     }
546     saveerr(ads,errno);
547     adns__diag(ads,-1,0,"cannot open configuration file `%s': %s",
548                filename,strerror(errno));
549     return;
550   }
551
552   readconfiggeneric(ads,filename,gl_file,gl_ctx);
553   
554   fclose(gl_ctx.file);
555 }
556
557 static void readconfigtext(adns_state ads, const char *text,
558                            const char *showname) {
559   getline_ctx gl_ctx;
560   
561   gl_ctx.text= text;
562   readconfiggeneric(ads,showname,gl_text,gl_ctx);
563 }
564   
565 static void readconfigenv(adns_state ads, const char *envvar) {
566   const char *filename;
567
568   if (ads->iflags & adns_if_noenv) {
569     adns__debug(ads,-1,0,"not checking environment variable `%s'",envvar);
570     return;
571   }
572   filename= instrum_getenv(ads,envvar);
573   if (filename) readconfig(ads,filename,1);
574 }
575
576 static void readconfigenvtext(adns_state ads, const char *envvar) {
577   const char *textdata;
578
579   if (ads->iflags & adns_if_noenv) {
580     adns__debug(ads,-1,0,"not checking environment variable `%s'",envvar);
581     return;
582   }
583   textdata= instrum_getenv(ads,envvar);
584   if (textdata) readconfigtext(ads,textdata,envvar);
585 }
586
587
588 int adns__setnonblock(adns_state ads, int fd) {
589   int r;
590   
591   r= fcntl(fd,F_GETFL,0); if (r<0) return errno;
592   r |= O_NONBLOCK;
593   r= fcntl(fd,F_SETFL,r); if (r<0) return errno;
594   return 0;
595 }
596
597 static int init_begin(adns_state *ads_r, adns_initflags flags,
598                       adns_logcallbackfn *logfn, void *logfndata) {
599   adns_state ads;
600   pid_t pid;
601   
602   if (flags & ~(adns_initflags)(0x4fff))
603     /* 0x4000 is reserved for `harmless' future expansion */
604     return ENOSYS;
605
606   ads= malloc(sizeof(*ads)); if (!ads) return errno;
607
608   ads->iflags= flags;
609   ads->logfn= logfn;
610   ads->logfndata= logfndata;
611   ads->configerrno= 0;
612   LIST_INIT(ads->udpw);
613   LIST_INIT(ads->tcpw);
614   LIST_INIT(ads->childw);
615   LIST_INIT(ads->output);
616   LIST_INIT(ads->intdone);
617   ads->forallnext= 0;
618   ads->nextid= 0x311f;
619   ads->nudpsockets= 0;
620   ads->tcpsocket= -1;
621   adns__vbuf_init(&ads->tcpsend);
622   adns__vbuf_init(&ads->tcprecv);
623   ads->tcprecv_skip= 0;
624   ads->nservers= ads->nsortlist= ads->nsearchlist= ads->tcpserver= 0;
625   ads->searchndots= 1;
626   ads->tcpstate= server_disconnected;
627   timerclear(&ads->tcptimeout);
628   ads->searchlist= 0;
629   ads->config_report_unknown=1;
630
631   pid= getpid();
632   ads->rand48xsubi[0]= pid;
633   ads->rand48xsubi[1]= (unsigned long)pid >> 16;
634   ads->rand48xsubi[2]= pid ^ ((unsigned long)pid >> 16);
635
636   *ads_r= ads;
637   return 0;
638 }
639
640 static int init_finish(adns_state ads) {
641   struct sockaddr_in sin;
642   struct protoent *proto;
643   struct udpsocket *udp;
644   int i;
645   int r;
646   
647   if (!ads->nservers) {
648     if (ads->logfn && ads->iflags & adns_if_debug)
649       adns__lprintf(ads,"adns: no nameservers, using IPv4 localhost\n");
650     memset(&sin, 0, sizeof(sin));
651     sin.sin_family = AF_INET;
652     sin.sin_port = htons(DNS_PORT);
653     sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
654     addserver(ads,(struct sockaddr *)&sin, sizeof(sin));
655   }
656
657   proto= getprotobyname("udp"); if (!proto) { r= ENOPROTOOPT; goto x_free; }
658   ads->nudpsockets= 0;
659   for (i=0; i<ads->nservers; i++) {
660     if (adns__udpsocket_by_af(ads, ads->servers[i].addr.sa.sa_family))
661       continue;
662     assert(ads->nudpsockets < MAXUDP);
663     udp= &ads->udpsockets[ads->nudpsockets];
664     udp->af= ads->servers[i].addr.sa.sa_family;
665     udp->fd= socket(udp->af,SOCK_DGRAM,proto->p_proto);
666     if (udp->fd < 0) { r= errno; goto x_free; }
667     ads->nudpsockets++;
668     r= adns__setnonblock(ads,udp->fd);
669     if (r) { r= errno; goto x_closeudp; }
670   }
671   
672   return 0;
673
674  x_closeudp:
675   for (i=0; i<ads->nudpsockets; i++) close(ads->udpsockets[i].fd);
676  x_free:
677   free(ads);
678   return r;
679 }
680
681 static void init_abort(adns_state ads) {
682   if (ads->nsearchlist) {
683     free(ads->searchlist[0]);
684     free(ads->searchlist);
685   }
686   free(ads);
687 }
688
689 static void logfn_file(adns_state ads, void *logfndata,
690                        const char *fmt, va_list al) {
691   vfprintf(logfndata,fmt,al);
692 }
693
694 static int init_files(adns_state *ads_r, adns_initflags flags,
695                       adns_logcallbackfn *logfn, void *logfndata) {
696   adns_state ads;
697   const char *res_options, *adns_res_options;
698   int r;
699   
700   r= init_begin(&ads, flags, logfn, logfndata);
701   if (r) return r;
702   
703   res_options= instrum_getenv(ads,"RES_OPTIONS");
704   adns_res_options= instrum_getenv(ads,"ADNS_RES_OPTIONS");
705   ccf_options(ads,"RES_OPTIONS",-1,res_options);
706   ccf_options(ads,"ADNS_RES_OPTIONS",-1,adns_res_options);
707
708   readconfig(ads,"/etc/resolv.conf",1);
709   readconfig(ads,"/etc/resolv-adns.conf",0);
710   readconfigenv(ads,"RES_CONF");
711   readconfigenv(ads,"ADNS_RES_CONF");
712
713   readconfigenvtext(ads,"RES_CONF_TEXT");
714   readconfigenvtext(ads,"ADNS_RES_CONF_TEXT");
715
716   ccf_options(ads,"RES_OPTIONS",-1,res_options);
717   ccf_options(ads,"ADNS_RES_OPTIONS",-1,adns_res_options);
718
719   ccf_search(ads,"LOCALDOMAIN",-1,instrum_getenv(ads,"LOCALDOMAIN"));
720   ccf_search(ads,"ADNS_LOCALDOMAIN",-1,instrum_getenv(ads,"ADNS_LOCALDOMAIN"));
721
722   if (ads->configerrno && ads->configerrno != EINVAL) {
723     r= ads->configerrno;
724     init_abort(ads);
725     return r;
726   }
727
728   r= init_finish(ads);
729   if (r) return r;
730
731   adns__consistency(ads,0,cc_entex);
732   *ads_r= ads;
733   return 0;
734 }
735
736 int adns_init(adns_state *ads_r, adns_initflags flags, FILE *diagfile) {
737   return init_files(ads_r, flags, logfn_file, diagfile ? diagfile : stderr);
738 }
739
740 static int init_strcfg(adns_state *ads_r, adns_initflags flags,
741                        adns_logcallbackfn *logfn, void *logfndata,
742                        const char *configtext) {
743   adns_state ads;
744   int r;
745
746   r= init_begin(&ads, flags, logfn, logfndata);
747   if (r) return r;
748
749   readconfigtext(ads,configtext,"<supplied configuration text>");
750   if (ads->configerrno) {
751     r= ads->configerrno;
752     init_abort(ads);
753     return r;
754   }
755
756   r= init_finish(ads);  if (r) return r;
757   adns__consistency(ads,0,cc_entex);
758   *ads_r= ads;
759   return 0;
760 }
761
762 int adns_init_strcfg(adns_state *ads_r, adns_initflags flags,
763                      FILE *diagfile, const char *configtext) {
764   return init_strcfg(ads_r, flags,
765                      diagfile ? logfn_file : 0, diagfile,
766                      configtext);
767 }
768
769 int adns_init_logfn(adns_state *newstate_r, adns_initflags flags,
770                     const char *configtext /*0=>use default config files*/,
771                     adns_logcallbackfn *logfn /*0=>logfndata is a FILE* */,
772                     void *logfndata /*0 with logfn==0 => discard*/) {
773   if (!logfn && logfndata)
774     logfn= logfn_file;
775   if (configtext)
776     return init_strcfg(newstate_r, flags, logfn, logfndata, configtext);
777   else
778     return init_files(newstate_r, flags, logfn, logfndata);
779 }
780
781 void adns_finish(adns_state ads) {
782   int i;
783   adns__consistency(ads,0,cc_entex);
784   for (;;) {
785     if (ads->udpw.head) adns__cancel(ads->udpw.head);
786     else if (ads->tcpw.head) adns__cancel(ads->tcpw.head);
787     else if (ads->childw.head) adns__cancel(ads->childw.head);
788     else if (ads->output.head) adns__cancel(ads->output.head);
789     else if (ads->intdone.head) adns__cancel(ads->output.head);
790     else break;
791   }
792   for (i=0; i<ads->nudpsockets; i++) close(ads->udpsockets[i].fd);
793   if (ads->tcpsocket >= 0) close(ads->tcpsocket);
794   adns__vbuf_free(&ads->tcpsend);
795   adns__vbuf_free(&ads->tcprecv);
796   freesearchlist(ads);
797   free(ads);
798 }
799
800 void adns_forallqueries_begin(adns_state ads) {
801   adns__consistency(ads,0,cc_entex);
802   ads->forallnext=
803     ads->udpw.head ? ads->udpw.head :
804     ads->tcpw.head ? ads->tcpw.head :
805     ads->childw.head ? ads->childw.head :
806     ads->output.head;
807 }
808   
809 adns_query adns_forallqueries_next(adns_state ads, void **context_r) {
810   adns_query qu, nqu;
811
812   adns__consistency(ads,0,cc_entex);
813   nqu= ads->forallnext;
814   for (;;) {
815     qu= nqu;
816     if (!qu) return 0;
817     if (qu->next) {
818       nqu= qu->next;
819     } else if (qu == ads->udpw.tail) {
820       nqu=
821         ads->tcpw.head ? ads->tcpw.head :
822         ads->childw.head ? ads->childw.head :
823         ads->output.head;
824     } else if (qu == ads->tcpw.tail) {
825       nqu=
826         ads->childw.head ? ads->childw.head :
827         ads->output.head;
828     } else if (qu == ads->childw.tail) {
829       nqu= ads->output.head;
830     } else {
831       nqu= 0;
832     }
833     if (!qu->parent) break;
834   }
835   ads->forallnext= nqu;
836   if (context_r) *context_r= qu->ctx.ext;
837   return qu;
838 }