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