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