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