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