various code improvements
[radsecproxy.git] / gconfig.c
1 /*
2  * Copyright (C) 2007, 2008 Stig Venaas <venaas@uninett.no>
3  *
4  * Permission to use, copy, modify, and distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  */
8
9 #include <string.h>
10 #include <stdarg.h>
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <limits.h>
14 #include <glob.h>
15 #include <sys/types.h>
16 #include <ctype.h>
17 #include <libgen.h>
18 #include <errno.h>
19 #include "debug.h"
20 #include "util.h"
21 #include "gconfig.h"
22
23 /* returns NULL on error, where to continue parsing if token and ok. E.g. "" will return token with empty string */
24 char *strtokenquote(char *s, char **token, char *del, char *quote, char *comment) {
25     char *t = s, *q, *r;
26
27     if (!t || !token || !del)
28         return NULL;
29     while (*t && strchr(del, *t))
30         t++;
31     if (!*t || (comment && strchr(comment, *t))) {
32         *token = NULL;
33         return t + 1; /* needs to be non-NULL, but value doesn't matter */
34     }
35     if (quote && (q = strchr(quote, *t))) {
36         t++;
37         r = t;
38         while (*t && *t != *q)
39             t++;
40         if (!*t || (t[1] && !strchr(del, t[1])))
41             return NULL;
42         *t = '\0';
43         *token = r;
44         return t + 1;
45     }
46     *token = t;
47     t++;
48     while (*t && !strchr(del, *t))
49         t++;
50     *t = '\0';
51     return t + 1;
52 }
53
54 int pushgconfdata(struct gconffile **cf, const char *data) {
55     int i;
56     struct gconffile *newcf;
57
58     if (!*cf) {
59         newcf = malloc(sizeof(struct gconffile) * 2);
60         if (!newcf)
61             return 0;
62         memset(newcf, 0, sizeof(struct gconffile) * 2);
63     } else {
64         for (i = 0; (*cf)[i].data || (*cf)[i].path; i++);
65         newcf = realloc(*cf, sizeof(struct gconffile) * (i + 2));
66         if (!newcf)
67             return 0;
68         memmove(newcf + 1, newcf, sizeof(struct gconffile) * (i + 1));
69         memset(newcf, 0, sizeof(struct gconffile));
70     }
71     newcf[0].data = data;
72     *cf = newcf;
73     return 1;
74 }
75
76 FILE *pushgconffile(struct gconffile **cf, FILE *file, const char *description) {
77     int i;
78     struct gconffile *newcf;
79     char *desc;
80
81     if (!file) {
82         debug(DBG_INFO, "could not read config from %s", description);
83         return NULL;
84     }
85     debug(DBG_DBG, "reading config from %s", description);
86
87     desc = stringcopy(description, 0);
88     if (!desc)
89         goto errmalloc;
90     
91     if (!*cf) {
92         newcf = malloc(sizeof(struct gconffile) * 2);
93         if (!newcf)
94             goto errmalloc;
95         memset(newcf, 0, sizeof(struct gconffile) * 2);
96     } else {
97         for (i = 0; (*cf)[i].data || (*cf)[i].path; i++);
98         newcf = realloc(*cf, sizeof(struct gconffile) * (i + 2));
99         if (!newcf)
100             goto errmalloc;
101         memmove(newcf + 1, newcf, sizeof(struct gconffile) * (i + 1));
102         memset(newcf, 0, sizeof(struct gconffile));
103     }
104     newcf[0].file = file;
105     newcf[0].path = desc;
106     *cf = newcf;
107     return file;
108     
109  errmalloc:
110     free(desc);
111     fclose(file);
112     debug(DBG_ERR, "malloc failed");
113     return NULL;
114 }
115
116 FILE *pushgconfpath(struct gconffile **cf, const char *path) {
117     FILE *f;
118
119     f = fopen(path, "r");
120     return pushgconffile(cf, f, path);
121 }
122
123 FILE *pushgconfpaths(struct gconffile **cf, const char *cfgpath) {
124     int i;
125     FILE *f = NULL;
126     glob_t globbuf;
127     char *path, *curfile = NULL, *dir;
128     
129     /* if cfgpath is relative, make it relative to current config */
130     if (*cfgpath == '/')
131         path = (char *)cfgpath;
132     else {
133         /* dirname may modify its argument */
134         curfile = stringcopy((*cf)->path, 0);
135         if (!curfile) {
136             debug(DBG_ERR, "malloc failed");
137             goto exit;
138         }
139         dir = dirname(curfile);
140         path = malloc(strlen(dir) + strlen(cfgpath) + 2);
141         if (!path) {
142             debug(DBG_ERR, "malloc failed");
143             goto exit;
144         }
145         strcpy(path, dir);
146         path[strlen(dir)] = '/';
147         strcpy(path + strlen(dir) + 1, cfgpath);
148     }
149     memset(&globbuf, 0, sizeof(glob_t));
150     if (glob(path, 0, NULL, &globbuf)) {
151         debug(DBG_INFO, "could not glob %s", path);
152         goto exit;
153     }
154
155     for (i = globbuf.gl_pathc - 1; i >= 0; i--) {
156         f = pushgconfpath(cf, globbuf.gl_pathv[i]);
157         if (!f)
158             break;
159     }    
160     globfree(&globbuf);
161
162  exit:    
163     if (curfile) {
164         free(curfile);
165         free(path);
166     }
167     return f;
168 }
169
170 int popgconf(struct gconffile **cf) {
171     int i;
172
173     if (!*cf)
174         return 0;
175     for (i = 0; (*cf)[i].data || (*cf)[i].path; i++);
176     if (i && (*cf)[0].file) {
177         fclose((*cf)[0].file);
178         if ((*cf)[0].path) {
179             debug(DBG_DBG, "closing config file %s", (*cf)[0].path);
180             free((*cf)[0].path);
181         }
182     }
183     if (i < 2) {
184         free(*cf);
185         *cf = NULL;
186         return 0;
187     }
188     memmove(*cf, *cf + 1, sizeof(struct gconffile) * i);
189     return 1;
190 }
191
192 void freegconf(struct gconffile **cf) {
193     int i;
194
195     if (!*cf)
196         return;
197     
198     for (i = 0; (*cf)[i].data || (*cf)[i].path; i++) {
199         if ((*cf)[i].file) {
200             fclose((*cf)[i].file);
201             if ((*cf)[i].path) {
202                 debug(DBG_DBG, "closing config file %s", (*cf)[i].path);
203                 free((*cf)[i].path);
204             }
205         }
206     }
207     free(*cf);
208     *cf = NULL;
209 }
210
211 struct gconffile *openconfigfile(const char *file) {
212     struct gconffile *cf = NULL;
213
214     if (!pushgconfpath(&cf, file)) {
215         debug(DBG_ERR, "could not read config file %s\n%s", file, strerror(errno));
216         return NULL;
217     }
218     debug(DBG_DBG, "reading config file %s", file);
219     return cf;
220 }
221
222 /* Parses config with following syntax:
223  * One of these:
224  * option-name value
225  * option-name = value
226  * Or:
227  * option-name value {
228  *     option-name [=] value
229  *     ...
230  * }
231  */
232
233 int getlinefromcf(struct gconffile *cf, char *line, const size_t size) {
234     size_t i, pos;
235     
236     if (!cf)
237         return 0;
238     
239     if (cf->file)
240         return fgets(line, size, cf->file) ? 1 : 0;
241     else if (cf->data) {
242         pos = cf->datapos;
243         if (!cf->data[pos])
244             return 0;
245         for (i = pos; cf->data[i] && cf->data[i] != '\n'; i++);
246         if (cf->data[i] == '\n')
247             i++;
248         if (i - pos > size - 1)
249             i = size - 1 + pos;
250         memcpy(line, cf->data + pos, i - pos);
251         line[i - pos] = '\0';
252         cf->datapos = i;
253         return 1;
254     }
255     return 0;
256 }
257
258 int getconfigline(struct gconffile **cf, char *block, char **opt, char **val, int *conftype) {
259     char line[1024];
260     char *tokens[3], *s;
261     int tcount;
262     
263     *opt = NULL;
264     *val = NULL;
265     *conftype = 0;
266     
267     if (!cf || !*cf || (!(*cf)->file && !(*cf)->data))
268         return 1;
269
270     for (;;) {
271         if (!getlinefromcf(*cf, line, 1024)) {
272             if (popgconf(cf))
273                 continue;
274             return 1;
275         }
276         s = line;
277         for (tcount = 0; tcount < 3; tcount++) {
278             s = strtokenquote(s, &tokens[tcount], " \t\r\n", "\"'", tcount ? NULL : "#");
279             if (!s) {
280                 debug(DBG_ERR, "Syntax error in line starting with: %s", line);
281                 return 0;
282             }
283             if (!tokens[tcount])
284                 break;
285         }
286         if (!tcount || **tokens == '#')
287             continue;
288
289         if (**tokens == '}') {
290             if (block)
291                 return 1;
292             debug(DBG_ERR, "configuration error, found } with no matching {");
293             return 0;
294         }
295         break;
296     }
297     
298     switch (tcount) {
299     case 2:
300         *opt = stringcopy(tokens[0], 0);
301         if (!*opt)
302             goto errmalloc;
303         *val = stringcopy(tokens[1], 0);
304         if (!*val)
305             goto errmalloc;
306         *conftype = CONF_STR;
307         break;
308     case 3:
309         if (tokens[1][0] == '=' && tokens[1][1] == '\0') {
310             *opt = stringcopy(tokens[0], 0);
311             if (!*opt)
312                 goto errmalloc;
313             *val = stringcopy(tokens[2], 0);
314             if (!*val)
315                 goto errmalloc;
316             *conftype = CONF_STR;
317             break;
318         }
319         if (tokens[2][0] == '{' && tokens[2][1] == '\0') {
320             *opt = stringcopy(tokens[0], 0);
321             if (!*opt)
322                 goto errmalloc;
323             *val = stringcopy(tokens[1], 0);
324             if (!*val)
325                 goto errmalloc;
326             *conftype = CONF_CBK;
327             break;
328         }
329         /* fall through */
330     default:
331         if (block)
332             debug(DBG_ERR, "configuration error in block %s, line starting with %s", block, tokens[0]);
333         else
334             debug(DBG_ERR, "configuration error, syntax error in line starting with %s", tokens[0]);
335         return 0;
336     }
337
338     if (**val)
339         return 1;
340     
341     debug(DBG_ERR, "configuration error, option %s needs a non-empty value", *opt);
342     goto errexit;
343
344  errmalloc:
345     debug(DBG_ERR, "malloc failed");
346  errexit:    
347     free(*opt);
348     *opt = NULL;
349     free(*val);
350     *val = NULL;
351     return 0;
352 }
353
354 uint8_t hexdigit2int(char d) {
355     if (d >= '0' && d <= '9')
356         return d - '0';
357     if (d >= 'a' && d <= 'f')
358         return 10 + d - 'a';
359     if (d >= 'A' && d <= 'F')
360         return 10 + d - 'A';
361     return 0;
362 }
363
364 void unhex(char *s) {
365     char *t;
366     for (t = s; *t; s++) {
367         if (*t == '%' && isxdigit(t[1]) && isxdigit(t[2])) {
368             *s = 16 * hexdigit2int(t[1]) + hexdigit2int(t[2]);
369             t += 3;
370         } else
371             *s = *t++;
372     }
373     *s = '\0';
374 }
375
376 /* returns 1 if ok, 0 on error */
377 /* caller must free returned values also on error */
378 int getgenericconfig(struct gconffile **cf, char *block, ...) {
379     va_list ap;
380     char *opt = NULL, *val, *word, *optval, **str = NULL, ***mstr = NULL, **newmstr, *endptr;
381     uint8_t *bln = NULL;
382     long int *lint = NULL;
383     int type = 0, conftype = 0, n;
384     int (*cbk)(struct gconffile **, void *, char *, char *, char *) = NULL;
385     void *cbkarg = NULL;
386
387     for (;;) {
388         free(opt);
389         if (!getconfigline(cf, block, &opt, &val, &conftype))
390             return 0;
391         if (!opt)
392             return 1;
393
394         if (conftype == CONF_STR && !strcasecmp(opt, "include")) {
395             if (!pushgconfpaths(cf, val)) {
396                 debug(DBG_ERR, "failed to include config file %s", val);
397                 goto errexit;
398             }
399             free(val);
400             continue;
401         }
402             
403         va_start(ap, block);
404         while ((word = va_arg(ap, char *))) {
405             type = va_arg(ap, int);
406             switch (type) {
407             case CONF_STR:
408                 str = va_arg(ap, char **);
409                 if (!str)
410                     goto errparam;
411                 break;
412             case CONF_MSTR:
413                 mstr = va_arg(ap, char ***);
414                 if (!mstr)
415                     goto errparam;
416                 break;
417             case CONF_BLN:
418                 bln = va_arg(ap, uint8_t *);
419                 if (!bln)
420                     goto errparam;
421                 break;
422             case CONF_LINT:
423                 lint = va_arg(ap, long int *);
424                 if (!lint)
425                     goto errparam;
426                 break;
427             case CONF_CBK:
428                 cbk = va_arg(ap, int (*)(struct gconffile **, void *, char *, char *, char *));
429                 if (!cbk)
430                     goto errparam;
431                 cbkarg = va_arg(ap, void *);
432                 break;
433             default:
434                 goto errparam;
435             }
436             if (!strcasecmp(opt, word))
437                 break;
438         }
439         va_end(ap);
440         
441         if (!word) {
442             if (block)
443                 debug(DBG_ERR, "configuration error in block %s, unknown option %s", block, opt);
444             debug(DBG_ERR, "configuration error, unknown option %s", opt);
445             goto errexit;
446         }
447
448         if (((type == CONF_STR || type == CONF_MSTR || type == CONF_BLN || type == CONF_LINT) && conftype != CONF_STR) ||
449             (type == CONF_CBK && conftype != CONF_CBK)) {
450             if (block)
451                 debug(DBG_ERR, "configuration error in block %s, wrong syntax for option %s", block, opt);
452             debug(DBG_ERR, "configuration error, wrong syntax for option %s", opt);
453             goto errexit;
454         }
455
456         switch (type) {
457         case CONF_STR:
458             if (*str) {
459                 debug(DBG_ERR, "configuration error, option %s already set to %s", opt, *str);
460                 goto errexit;
461             }
462             unhex(val);
463             *str = val;
464             break;
465         case CONF_MSTR:
466             if (*mstr)
467                 for (n = 0; (*mstr)[n]; n++);
468             else
469                 n = 0;
470             newmstr = realloc(*mstr, sizeof(char *) * (n + 2));
471             if (!newmstr) {
472                 debug(DBG_ERR, "malloc failed");
473                 goto errexit;
474             }
475             unhex(val);
476             newmstr[n] = val;
477             newmstr[n + 1] = NULL;
478             *mstr = newmstr;
479             break;
480         case CONF_BLN:
481             if (!strcasecmp(val, "on"))
482                 *bln = 1;
483             else if (!strcasecmp(val, "off"))
484                 *bln = 0;
485             else {
486                 if (block)
487                     debug(DBG_ERR, "configuration error in block %s, value for option %s must be on or off, not %s", block, opt, val);
488                 else
489                     debug(DBG_ERR, "configuration error, value for option %s must be on or off, not %s", opt, val);
490                 goto errexit;
491             }
492             break;
493         case CONF_LINT:
494             endptr = NULL;
495             *lint = strtol(val, &endptr, 0);
496             if (*lint == LONG_MIN || *lint == LONG_MAX || !endptr || endptr == val || *endptr != '\0') {
497                 if (block)
498                     debug(DBG_ERR, "configuration error in block %s, value for option %s must be an integer, not %s", block, opt, val);
499                 else
500                     debug(DBG_ERR, "configuration error, value for option %s must be an integer, not %s", opt, val);
501                 goto errexit;
502             }
503             break;
504         case CONF_CBK:
505             optval = malloc(strlen(opt) + strlen(val) + 2);
506             if (!optval) {
507                 debug(DBG_ERR, "malloc failed");
508                 goto errexit;
509             }
510             sprintf(optval, "%s %s", opt, val);
511             if (!cbk(cf, cbkarg, optval, opt, val)) {
512                 free(optval);
513                 goto errexit;
514             }
515             free(val);
516             free(optval);
517             continue;
518         default:
519             goto errparam;
520         }
521         if (block)
522             debug(DBG_DBG, "getgenericconfig: block %s: %s = %s", block, opt, val);
523         else 
524             debug(DBG_DBG, "getgenericconfig: %s = %s", opt, val);
525         if (type == CONF_BLN || type == CONF_LINT)
526             free(val);
527     }
528
529  errparam:
530     debug(DBG_ERR, "getgenericconfig: internal parameter error");
531  errexit:
532     free(opt);
533     free(val);
534     return 0;
535 }