chiark / gitweb /
+ * Always #include <sys/types.h> before <sys/socket.h> (for FreeBSD 4.6).
[adns.git] / src / setup.c
1 /*
2  * setup.c
3  * - configuration file parsing
4  * - management of global state
5  */
6 /*
7  *  This file is
8  *    Copyright (C) 1997-1999 Ian Jackson <ian@davenant.greenend.org.uk>
9  *
10  *  It is part of adns, which is
11  *    Copyright (C) 1997-2000 Ian Jackson <ian@davenant.greenend.org.uk>
12  *    Copyright (C) 1999-2000 Tony Finch <dot@dotat.at>
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 2, 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  *  Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. 
27  */
28
29 #include <stdlib.h>
30 #include <errno.h>
31 #include <limits.h>
32 #include <unistd.h>
33 #include <fcntl.h>
34
35 #include <sys/types.h>
36 #include <netdb.h>
37 #include <sys/socket.h>
38 #include <netinet/in.h>
39 #include <arpa/inet.h>
40
41 #include "internal.h"
42
43 static void readconfig(adns_state ads, const char *filename, int warnmissing);
44
45 static void addserver(adns_state ads, struct in_addr addr) {
46   int i;
47   struct server *ss;
48   
49   for (i=0; i<ads->nservers; i++) {
50     if (ads->servers[i].addr.s_addr == addr.s_addr) {
51       adns__debug(ads,-1,0,"duplicate nameserver %s ignored",inet_ntoa(addr));
52       return;
53     }
54   }
55   
56   if (ads->nservers>=MAXSERVERS) {
57     adns__diag(ads,-1,0,"too many nameservers, ignoring %s",inet_ntoa(addr));
58     return;
59   }
60
61   ss= ads->servers+ads->nservers;
62   ss->addr= addr;
63   ads->nservers++;
64 }
65
66 static void freesearchlist(adns_state ads) {
67   if (ads->nsearchlist) free(*ads->searchlist);
68   free(ads->searchlist);
69 }
70
71 static void saveerr(adns_state ads, int en) {
72   if (!ads->configerrno) ads->configerrno= en;
73 }
74
75 static void configparseerr(adns_state ads, const char *fn, int lno,
76                            const char *fmt, ...) {
77   va_list al;
78
79   saveerr(ads,EINVAL);
80   if (!ads->diagfile || (ads->iflags & adns_if_noerrprint)) return;
81
82   if (lno==-1) fprintf(ads->diagfile,"adns: %s: ",fn);
83   else fprintf(ads->diagfile,"adns: %s:%d: ",fn,lno);
84   va_start(al,fmt);
85   vfprintf(ads->diagfile,fmt,al);
86   va_end(al);
87   fputc('\n',ads->diagfile);
88 }
89
90 static int nextword(const char **bufp_io, const char **word_r, int *l_r) {
91   const char *p, *q;
92
93   p= *bufp_io;
94   while (ctype_whitespace(*p)) p++;
95   if (!*p) return 0;
96
97   q= p;
98   while (*q && !ctype_whitespace(*q)) q++;
99
100   *l_r= q-p;
101   *word_r= p;
102   *bufp_io= q;
103
104   return 1;
105 }
106
107 static void ccf_nameserver(adns_state ads, const char *fn, int lno, const char *buf) {
108   struct in_addr ia;
109   
110   if (!inet_aton(buf,&ia)) {
111     configparseerr(ads,fn,lno,"invalid nameserver address `%s'",buf);
112     return;
113   }
114   adns__debug(ads,-1,0,"using nameserver %s",inet_ntoa(ia));
115   addserver(ads,ia);
116 }
117
118 static void ccf_search(adns_state ads, const char *fn, int lno, const char *buf) {
119   const char *bufp, *word;
120   char *newchars, **newptrs, **pp;
121   int count, tl, l;
122
123   if (!buf) return;
124
125   bufp= buf;
126   count= 0;
127   tl= 0;
128   while (nextword(&bufp,&word,&l)) { count++; tl += l+1; }
129
130   newptrs= malloc(sizeof(char*)*count);  if (!newptrs) { saveerr(ads,errno); return; }
131   newchars= malloc(tl);  if (!newchars) { saveerr(ads,errno); free(newptrs); return; }
132
133   bufp= buf;
134   pp= newptrs;
135   while (nextword(&bufp,&word,&l)) {
136     *pp++= newchars;
137     memcpy(newchars,word,l);
138     newchars += l;
139     *newchars++ = 0;
140   }
141
142   freesearchlist(ads);
143   ads->nsearchlist= count;
144   ads->searchlist= newptrs;
145 }
146
147 static void ccf_sortlist(adns_state ads, const char *fn, int lno, const char *buf) {
148   const char *word;
149   char tbuf[200], *slash, *ep;
150   struct in_addr base, mask;
151   int l;
152   unsigned long initial, baselocal;
153
154   if (!buf) return;
155   
156   ads->nsortlist= 0;
157   while (nextword(&buf,&word,&l)) {
158     if (ads->nsortlist >= MAXSORTLIST) {
159       adns__diag(ads,-1,0,"too many sortlist entries, ignoring %.*s onwards",l,word);
160       return;
161     }
162
163     if (l >= sizeof(tbuf)) {
164       configparseerr(ads,fn,lno,"sortlist entry `%.*s' too long",l,word);
165       continue;
166     }
167     
168     memcpy(tbuf,word,l); tbuf[l]= 0;
169     slash= strchr(tbuf,'/');
170     if (slash) *slash++= 0;
171     
172     if (!inet_aton(tbuf,&base)) {
173       configparseerr(ads,fn,lno,"invalid address `%s' in sortlist",tbuf);
174       continue;
175     }
176
177     if (slash) {
178       if (strchr(slash,'.')) {
179         if (!inet_aton(slash,&mask)) {
180           configparseerr(ads,fn,lno,"invalid mask `%s' in sortlist",slash);
181           continue;
182         }
183         if (base.s_addr & ~mask.s_addr) {
184           configparseerr(ads,fn,lno,
185                          "mask `%s' in sortlist overlaps address `%s'",slash,tbuf);
186           continue;
187         }
188       } else {
189         initial= strtoul(slash,&ep,10);
190         if (*ep || initial>32) {
191           configparseerr(ads,fn,lno,"mask length `%s' invalid",slash);
192           continue;
193         }
194         mask.s_addr= htonl((0x0ffffffffUL) << (32-initial));
195       }
196     } else {
197       baselocal= ntohl(base.s_addr);
198       if (!baselocal & 0x080000000UL) /* class A */
199         mask.s_addr= htonl(0x0ff000000UL);
200       else if ((baselocal & 0x0c0000000UL) == 0x080000000UL)
201         mask.s_addr= htonl(0x0ffff0000UL); /* class B */
202       else if ((baselocal & 0x0f0000000UL) == 0x0e0000000UL)
203         mask.s_addr= htonl(0x0ff000000UL); /* class C */
204       else {
205         configparseerr(ads,fn,lno,
206                        "network address `%s' in sortlist is not in classed ranges,"
207                        " must specify mask explicitly", tbuf);
208         continue;
209       }
210     }
211
212     ads->sortlist[ads->nsortlist].base= base;
213     ads->sortlist[ads->nsortlist].mask= mask;
214     ads->nsortlist++;
215   }
216 }
217
218 static void ccf_options(adns_state ads, const char *fn, int lno, const char *buf) {
219   const char *word;
220   char *ep;
221   unsigned long v;
222   int l;
223
224   if (!buf) return;
225
226   while (nextword(&buf,&word,&l)) {
227     if (l==5 && !memcmp(word,"debug",5)) {
228       ads->iflags |= adns_if_debug;
229       continue;
230     }
231     if (l>=6 && !memcmp(word,"ndots:",6)) {
232       v= strtoul(word+6,&ep,10);
233       if (l==6 || ep != word+l || v > INT_MAX) {
234         configparseerr(ads,fn,lno,"option `%.*s' malformed or has bad value",l,word);
235         continue;
236       }
237       ads->searchndots= v;
238       continue;
239     }
240     if (l>=12 && !memcmp(word,"adns_checkc:",12)) {
241       if (!strcmp(word+12,"none")) {
242         ads->iflags &= ~adns_if_checkc_freq;
243         ads->iflags |= adns_if_checkc_entex;
244       } else if (!strcmp(word+12,"entex")) {
245         ads->iflags &= ~adns_if_checkc_freq;
246         ads->iflags |= adns_if_checkc_entex;
247       } else if (!strcmp(word+12,"freq")) {
248         ads->iflags |= adns_if_checkc_freq;
249       } else {
250         configparseerr(ads,fn,lno, "option adns_checkc has bad value `%s' "
251                        "(must be none, entex or freq", word+12);
252       }
253       continue;
254     }
255     adns__diag(ads,-1,0,"%s:%d: unknown option `%.*s'", fn,lno, l,word);
256   }
257 }
258
259 static void ccf_clearnss(adns_state ads, const char *fn, int lno, const char *buf) {
260   ads->nservers= 0;
261 }
262
263 static void ccf_include(adns_state ads, const char *fn, int lno, const char *buf) {
264   if (!*buf) {
265     configparseerr(ads,fn,lno,"`include' directive with no filename");
266     return;
267   }
268   readconfig(ads,buf,1);
269 }
270
271 static void ccf_lookup(adns_state ads, const char *fn, int lno,
272                        const char *buf) {
273   int found_bind=0;
274   const char *word;
275   int l;
276
277   if (!*buf) {
278     configparseerr(ads,fn,lno,"`lookup' directive with no databases");
279     return;
280   }
281
282   while (nextword(&buf,&word,&l)) {
283     if (l==4 && !memcmp(word,"bind",4)) {
284       found_bind=1;
285     } else if (l==4 && !memcmp(word,"file",4)) {
286       /* ignore this and hope /etc/hosts is not essential */
287     } else if (l==2 && !memcmp(word,"yp",2)) {
288       adns__diag(ads,-1,0,"%s:%d: yp lookups not supported by adns", fn,lno);
289       found_bind=-1;
290     } else {
291       adns__diag(ads,-1,0,"%s:%d: unknown `lookup' database `%.*s'",
292                  fn,lno, l,word);
293       found_bind=-1;
294     }
295   }
296   if (!found_bind)
297     adns__diag(ads,-1,0,"%s:%d: `lookup' specified, but not `bind'", fn,lno);
298 }
299
300 static const struct configcommandinfo {
301   const char *name;
302   void (*fn)(adns_state ads, const char *fn, int lno, const char *buf);
303 } configcommandinfos[]= {
304   { "nameserver",        ccf_nameserver  },
305   { "domain",            ccf_search      },
306   { "search",            ccf_search      },
307   { "sortlist",          ccf_sortlist    },
308   { "options",           ccf_options     },
309   { "clearnameservers",  ccf_clearnss    },
310   { "include",           ccf_include     },
311   { "lookup",            ccf_lookup      }, /* OpenBSD */
312   {  0                                   }
313 };
314
315 typedef union {
316   FILE *file;
317   const char *text;
318 } getline_ctx;
319
320 static int gl_file(adns_state ads, getline_ctx *src_io, const char *filename,
321                    int lno, char *buf, int buflen) {
322   FILE *file= src_io->file;
323   int c, i;
324   char *p;
325
326   p= buf;
327   buflen--;
328   i= 0;
329     
330   for (;;) { /* loop over chars */
331     if (i == buflen) {
332       adns__diag(ads,-1,0,"%s:%d: line too long, ignored",filename,lno);
333       goto x_badline;
334     }
335     c= getc(file);
336     if (!c) {
337       adns__diag(ads,-1,0,"%s:%d: line contains nul, ignored",filename,lno);
338       goto x_badline;
339     } else if (c == '\n') {
340       break;
341     } else if (c == EOF) {
342       if (ferror(file)) {
343         saveerr(ads,errno);
344         adns__diag(ads,-1,0,"%s:%d: read error: %s",filename,lno,strerror(errno));
345         return -1;
346       }
347       if (!i) return -1;
348       break;
349     } else {
350       *p++= c;
351       i++;
352     }
353   }
354
355   *p++= 0;
356   return i;
357
358  x_badline:
359   saveerr(ads,EINVAL);
360   while ((c= getc(file)) != EOF && c != '\n');
361   return -2;
362 }
363
364 static int gl_text(adns_state ads, getline_ctx *src_io, const char *filename,
365                    int lno, char *buf, int buflen) {
366   const char *cp= src_io->text;
367   int l;
368
369   if (!cp || !*cp) return -1;
370
371   if (*cp == ';' || *cp == '\n') cp++;
372   l= strcspn(cp,";\n");
373   src_io->text = cp+l;
374
375   if (l >= buflen) {
376     adns__diag(ads,-1,0,"%s:%d: line too long, ignored",filename,lno);
377     saveerr(ads,EINVAL);
378     return -2;
379   }
380     
381   memcpy(buf,cp,l);
382   buf[l]= 0;
383   return l;
384 }
385
386 static void readconfiggeneric(adns_state ads, const char *filename,
387                               int (*getline)(adns_state ads, getline_ctx*,
388                                              const char *filename, int lno,
389                                              char *buf, int buflen),
390                               /* Returns >=0 for success, -1 for EOF or error
391                                * (error will have been reported), or -2 for
392                                * bad line was encountered, try again.
393                                */
394                               getline_ctx gl_ctx) {
395   char linebuf[2000], *p, *q;
396   int lno, l, dirl;
397   const struct configcommandinfo *ccip;
398
399   for (lno=1;
400        (l= getline(ads,&gl_ctx, filename,lno, linebuf,sizeof(linebuf))) != -1;
401        lno++) {
402     if (l == -2) continue;
403     while (l>0 && ctype_whitespace(linebuf[l-1])) l--;
404     linebuf[l]= 0;
405     p= linebuf;
406     while (ctype_whitespace(*p)) p++;
407     if (*p == '#' || !*p) continue;
408     q= p;
409     while (*q && !ctype_whitespace(*q)) q++;
410     dirl= q-p;
411     for (ccip=configcommandinfos;
412          ccip->name && !(strlen(ccip->name)==dirl && !memcmp(ccip->name,p,q-p));
413          ccip++);
414     if (!ccip->name) {
415       adns__diag(ads,-1,0,"%s:%d: unknown configuration directive `%.*s'",
416                  filename,lno,q-p,p);
417       continue;
418     }
419     while (ctype_whitespace(*q)) q++;
420     ccip->fn(ads,filename,lno,q);
421   }
422 }
423
424 static const char *instrum_getenv(adns_state ads, const char *envvar) {
425   const char *value;
426
427   value= getenv(envvar);
428   if (!value) adns__debug(ads,-1,0,"environment variable %s not set",envvar);
429   else adns__debug(ads,-1,0,"environment variable %s set to `%s'",envvar,value);
430   return value;
431 }
432
433 static void readconfig(adns_state ads, const char *filename, int warnmissing) {
434   getline_ctx gl_ctx;
435   
436   gl_ctx.file= fopen(filename,"r");
437   if (!gl_ctx.file) {
438     if (errno == ENOENT) {
439       if (warnmissing)
440         adns__debug(ads,-1,0,"configuration file `%s' does not exist",filename);
441       return;
442     }
443     saveerr(ads,errno);
444     adns__diag(ads,-1,0,"cannot open configuration file `%s': %s",
445                filename,strerror(errno));
446     return;
447   }
448
449   readconfiggeneric(ads,filename,gl_file,gl_ctx);
450   
451   fclose(gl_ctx.file);
452 }
453
454 static void readconfigtext(adns_state ads, const char *text, const char *showname) {
455   getline_ctx gl_ctx;
456   
457   gl_ctx.text= text;
458   readconfiggeneric(ads,showname,gl_text,gl_ctx);
459 }
460   
461 static void readconfigenv(adns_state ads, const char *envvar) {
462   const char *filename;
463
464   if (ads->iflags & adns_if_noenv) {
465     adns__debug(ads,-1,0,"not checking environment variable `%s'",envvar);
466     return;
467   }
468   filename= instrum_getenv(ads,envvar);
469   if (filename) readconfig(ads,filename,1);
470 }
471
472 static void readconfigenvtext(adns_state ads, const char *envvar) {
473   const char *textdata;
474
475   if (ads->iflags & adns_if_noenv) {
476     adns__debug(ads,-1,0,"not checking environment variable `%s'",envvar);
477     return;
478   }
479   textdata= instrum_getenv(ads,envvar);
480   if (textdata) readconfigtext(ads,textdata,envvar);
481 }
482
483
484 int adns__setnonblock(adns_state ads, int fd) {
485   int r;
486   
487   r= fcntl(fd,F_GETFL,0); if (r<0) return errno;
488   r |= O_NONBLOCK;
489   r= fcntl(fd,F_SETFL,r); if (r<0) return errno;
490   return 0;
491 }
492
493 static int init_begin(adns_state *ads_r, adns_initflags flags, FILE *diagfile) {
494   adns_state ads;
495   
496   ads= malloc(sizeof(*ads)); if (!ads) return errno;
497
498   ads->iflags= flags;
499   ads->diagfile= diagfile;
500   ads->configerrno= 0;
501   LIST_INIT(ads->udpw);
502   LIST_INIT(ads->tcpw);
503   LIST_INIT(ads->childw);
504   LIST_INIT(ads->output);
505   ads->forallnext= 0;
506   ads->nextid= 0x311f;
507   ads->udpsocket= ads->tcpsocket= -1;
508   adns__vbuf_init(&ads->tcpsend);
509   adns__vbuf_init(&ads->tcprecv);
510   ads->tcprecv_skip= 0;
511   ads->nservers= ads->nsortlist= ads->nsearchlist= ads->tcpserver= 0;
512   ads->searchndots= 1;
513   ads->tcpstate= server_disconnected;
514   timerclear(&ads->tcptimeout);
515   ads->searchlist= 0;
516
517   *ads_r= ads;
518   return 0;
519 }
520
521 static int init_finish(adns_state ads) {
522   struct in_addr ia;
523   struct protoent *proto;
524   int r;
525   
526   if (!ads->nservers) {
527     if (ads->diagfile && ads->iflags & adns_if_debug)
528       fprintf(ads->diagfile,"adns: no nameservers, using localhost\n");
529     ia.s_addr= htonl(INADDR_LOOPBACK);
530     addserver(ads,ia);
531   }
532
533   proto= getprotobyname("udp"); if (!proto) { r= ENOPROTOOPT; goto x_free; }
534   ads->udpsocket= socket(AF_INET,SOCK_DGRAM,proto->p_proto);
535   if (ads->udpsocket<0) { r= errno; goto x_free; }
536
537   r= adns__setnonblock(ads,ads->udpsocket);
538   if (r) { r= errno; goto x_closeudp; }
539   
540   return 0;
541
542  x_closeudp:
543   close(ads->udpsocket);
544  x_free:
545   free(ads);
546   return r;
547 }
548
549 static void init_abort(adns_state ads) {
550   if (ads->nsearchlist) {
551     free(ads->searchlist[0]);
552     free(ads->searchlist);
553   }
554   free(ads);
555 }
556
557 int adns_init(adns_state *ads_r, adns_initflags flags, FILE *diagfile) {
558   adns_state ads;
559   const char *res_options, *adns_res_options;
560   int r;
561   
562   r= init_begin(&ads, flags, diagfile ? diagfile : stderr);
563   if (r) return r;
564   
565   res_options= instrum_getenv(ads,"RES_OPTIONS");
566   adns_res_options= instrum_getenv(ads,"ADNS_RES_OPTIONS");
567   ccf_options(ads,"RES_OPTIONS",-1,res_options);
568   ccf_options(ads,"ADNS_RES_OPTIONS",-1,adns_res_options);
569
570   readconfig(ads,"/etc/resolv.conf",1);
571   readconfig(ads,"/etc/resolv-adns.conf",0);
572   readconfigenv(ads,"RES_CONF");
573   readconfigenv(ads,"ADNS_RES_CONF");
574
575   readconfigenvtext(ads,"RES_CONF_TEXT");
576   readconfigenvtext(ads,"ADNS_RES_CONF_TEXT");
577
578   ccf_options(ads,"RES_OPTIONS",-1,res_options);
579   ccf_options(ads,"ADNS_RES_OPTIONS",-1,adns_res_options);
580
581   ccf_search(ads,"LOCALDOMAIN",-1,instrum_getenv(ads,"LOCALDOMAIN"));
582   ccf_search(ads,"ADNS_LOCALDOMAIN",-1,instrum_getenv(ads,"ADNS_LOCALDOMAIN"));
583
584   if (ads->configerrno && ads->configerrno != EINVAL) {
585     r= ads->configerrno;
586     init_abort(ads);
587     return r;
588   }
589
590   r= init_finish(ads);
591   if (r) return r;
592
593   adns__consistency(ads,0,cc_entex);
594   *ads_r= ads;
595   return 0;
596 }
597
598 int adns_init_strcfg(adns_state *ads_r, adns_initflags flags,
599                      FILE *diagfile, const char *configtext) {
600   adns_state ads;
601   int r;
602
603   r= init_begin(&ads, flags, diagfile);  if (r) return r;
604
605   readconfigtext(ads,configtext,"<supplied configuration text>");
606   if (ads->configerrno) {
607     r= ads->configerrno;
608     init_abort(ads);
609     return r;
610   }
611
612   r= init_finish(ads);  if (r) return r;
613   adns__consistency(ads,0,cc_entex);
614   *ads_r= ads;
615   return 0;
616 }
617
618
619 void adns_finish(adns_state ads) {
620   adns__consistency(ads,0,cc_entex);
621   for (;;) {
622     if (ads->udpw.head) adns_cancel(ads->udpw.head);
623     else if (ads->tcpw.head) adns_cancel(ads->tcpw.head);
624     else if (ads->childw.head) adns_cancel(ads->childw.head);
625     else if (ads->output.head) adns_cancel(ads->output.head);
626     else break;
627   }
628   close(ads->udpsocket);
629   if (ads->tcpsocket >= 0) close(ads->tcpsocket);
630   adns__vbuf_free(&ads->tcpsend);
631   adns__vbuf_free(&ads->tcprecv);
632   freesearchlist(ads);
633   free(ads);
634 }
635
636 void adns_forallqueries_begin(adns_state ads) {
637   adns__consistency(ads,0,cc_entex);
638   ads->forallnext=
639     ads->udpw.head ? ads->udpw.head :
640     ads->tcpw.head ? ads->tcpw.head :
641     ads->childw.head ? ads->childw.head :
642     ads->output.head;
643 }
644   
645 adns_query adns_forallqueries_next(adns_state ads, void **context_r) {
646   adns_query qu, nqu;
647
648   adns__consistency(ads,0,cc_entex);
649   nqu= ads->forallnext;
650   for (;;) {
651     qu= nqu;
652     if (!qu) return 0;
653     if (qu->next) {
654       nqu= qu->next;
655     } else if (qu == ads->udpw.tail) {
656       nqu=
657         ads->tcpw.head ? ads->tcpw.head :
658         ads->childw.head ? ads->childw.head :
659         ads->output.head;
660     } else if (qu == ads->tcpw.tail) {
661       nqu=
662         ads->childw.head ? ads->childw.head :
663         ads->output.head;
664     } else if (qu == ads->childw.tail) {
665       nqu= ads->output.head;
666     } else {
667       nqu= 0;
668     }
669     if (!qu->parent) break;
670   }
671   ads->forallnext= nqu;
672   if (context_r) *context_r= qu->ctx.ext;
673   return qu;
674 }