root/trunk/cfg.c

Revision 840, 13.9 kB (checked in by michael, 15 months ago)

email address changed

  • Property svn:keywords set to Id URL Rev
Line 
1/* $Id$
2 * $URL$
3 * $URL$
4 *
5 * config file stuff
6 *
7 * Copyright (C) 1999, 2000 Michael Reinelt <michael@reinelt.co.at>
8 * Copyright (C) 2004 The LCD4Linux Team <lcd4linux-devel@users.sourceforge.net>
9 *
10 * This file is part of LCD4Linux.
11 *
12 * LCD4Linux is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2, or (at your option)
15 * any later version.
16 *
17 * LCD4Linux is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 * GNU General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, write to the Free Software
24 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
25 *
26 */
27
28/*
29 * exported functions:
30 *
31 * cfg_init (source)
32 *   read configuration from source
33 *   returns  0 if successful
34 *   returns -1 in case of an error
35 *
36 * cfg_source (void)
37 *   returns the file the configuration was read from
38 *
39 * cfg_cmd (arg)
40 *   allows us to overwrite entries in the
41 *   config-file from the command line.
42 *   arg is 'key=value'
43 *   cfg_cmd can be called _before_ cfg_read()
44 *   returns 0 if ok, -1 if arg cannot be parsed
45 *
46 * cfg_list (section)
47 *   returns a list of all keys in the specified section
48 *   This list was allocated be cfg_list() and must be
49 *   freed by the caller!
50 *
51 * cfg_get_raw (section, key, defval)
52 *   return the a value for a given key in a given section
53 *   or <defval> if key does not exist. Does NOT evaluate
54 *   the expression. Therefore used to get the expression
55 *   itself!
56 *
57 * cfg_get (section, key, defval)
58 *   return the a value for a given key in a given section
59 *   or <defval> if key does not exist. The specified
60 *   value in the config is treated as a expression and
61 *   is evaluated!
62 *
63 * cfg_number (section, key, defval, min, int max, *value)
64 *   return the a value for a given key in a given section
65 *   convert it into a number with syntax checking
66 *   check if its in a given range. As it uses cfg_get()
67 *   internally, the evaluator is used here, too.
68 *
69 */
70
71
72#include "config.h"
73
74#include <stdlib.h>
75#include <stdio.h>
76#include <string.h>
77#include <ctype.h>
78#include <errno.h>
79
80#include <unistd.h>
81#include <sys/stat.h>
82
83#include "debug.h"
84#include "evaluator.h"
85#include "cfg.h"
86
87#ifdef WITH_DMALLOC
88#include <dmalloc.h>
89#endif
90
91typedef struct {
92    char *key;
93    char *val;
94    int lock;
95} ENTRY;
96
97
98static char *Config_File = NULL;
99static ENTRY *Config = NULL;
100static int nConfig = 0;
101
102
103/* bsearch compare function for config entries */
104static int c_lookup(const void *a, const void *b)
105{
106    char *key = (char *) a;
107    ENTRY *entry = (ENTRY *) b;
108
109    return strcasecmp(key, entry->key);
110}
111
112
113/* qsort compare function for variables */
114static int c_sort(const void *a, const void *b)
115{
116    ENTRY *ea = (ENTRY *) a;
117    ENTRY *eb = (ENTRY *) b;
118
119    return strcasecmp(ea->key, eb->key);
120}
121
122
123/* remove leading and trailing whitespace */
124static char *strip(char *s, const int strip_comments)
125{
126    char *p;
127
128    while (isblank(*s))
129  s++;
130
131    for (p = s; *p; p++) {
132  if (*p == '"')
133      do
134    p++;
135      while (*p && *p != '\n' && *p != '"');
136  if (*p == '\'')
137      do
138    p++;
139      while (*p && *p != '\n' && *p != '\'');
140  if (*p == '\n' || (strip_comments && *p == '#' && (p == s || *(p - 1) != '\\'))) {
141      *p = '\0';
142      break;
143  }
144    }
145
146    for (p--; p > s && isblank(*p); p--)
147  *p = '\0';
148
149    return s;
150}
151
152
153/* unquote a string */
154static char *dequote(char *string)
155{
156    int quote = 0;
157    char *s = string;
158    char *p = string;
159
160    do {
161  if (*s == '\'') {
162      quote = !quote;
163      *p++ = *s;
164  } else if (quote && *s == '\\') {
165      s++;
166      if (*s >= '0' && *s <= '7') {
167    int n;
168    unsigned int c = 0;
169    sscanf(s, "%3o%n", &c, &n);
170    if (c == 0 || c > 255) {
171        error("WARNING: illegal '\\' in <%s>", string);
172    } else {
173        *p++ = c;
174        s += n - 1;
175    }
176      } else {
177    *p++ = *s;
178      }
179  } else {
180      *p++ = *s;
181  }
182    } while (*s++);
183
184    return string;
185}
186
187
188/* which if a string contains only valid chars */
189/* i.e. start with a char and contains chars and nums */
190static int validchars(const char *string, const int numstart)
191{
192    const char *c;
193
194    for (c = string; *c; c++) {
195  /* first and following chars */
196  if ((*c >= 'A' && *c <= 'Z') || (*c >= 'a' && *c <= 'z') || (*c == '_'))
197      continue;
198  /* number as first or following char */
199  if ((numstart || c > string) && *c >= '0' && *c <= '9')
200      continue;
201  /* only following chars */
202  if ((c > string) && ((*c == '.') || (*c == '-')))
203      continue;
204  return 0;
205    }
206    return 1;
207}
208
209
210static void cfg_add(const char *section, const char *key, const char *val, const int lock)
211{
212    char *buffer;
213    ENTRY *entry;
214
215    /* allocate buffer  */
216    buffer = malloc(strlen(section) + strlen(key) + 2);
217    *buffer = '\0';
218
219    /* prepare section.key */
220    if (section != NULL && *section != '\0') {
221  strcpy(buffer, section);
222  strcat(buffer, ".");
223    }
224    strcat(buffer, key);
225
226    /* does the key already exist? */
227    entry = bsearch(buffer, Config, nConfig, sizeof(ENTRY), c_lookup);
228
229    if (entry != NULL) {
230  if (entry->lock > lock)
231      return;
232  debug("Warning: key <%s>: value <%s> overwritten with <%s>", buffer, entry->val, val);
233  free(buffer);
234  if (entry->val)
235      free(entry->val);
236  entry->val = dequote(strdup(val));
237  return;
238    }
239
240    nConfig++;
241    Config = realloc(Config, nConfig * sizeof(ENTRY));
242    Config[nConfig - 1].key = buffer;
243    Config[nConfig - 1].val = dequote(strdup(val));
244    Config[nConfig - 1].lock = lock;
245
246    qsort(Config, nConfig, sizeof(ENTRY), c_sort);
247
248}
249
250
251int cfg_cmd(const char *arg)
252{
253    char *key, *val;
254    char *buffer;
255
256    buffer = strdup(arg);
257    key = strip(buffer, 0);
258    for (val = key; *val; val++) {
259  if (*val == '=') {
260      *val++ = '\0';
261      break;
262  }
263    }
264    if (*key == '\0' || *val == '\0') {
265  free(buffer);
266  return -1;
267    }
268
269    if (!validchars(key, 0)) {
270  free(buffer);
271  return -1;
272    }
273
274    cfg_add("", key, val, 1);
275
276    free(buffer);
277    return 0;
278}
279
280
281char *cfg_list(const char *section)
282{
283    int i, len;
284    char *key, *list;
285
286    /* calculate key length */
287    len = strlen(section) + 1;
288
289    /* prepare search key */
290    key = malloc(len + 1);
291    strcpy(key, section);
292    strcat(key, ".");
293
294    /* start with empty string */
295    list = malloc(1);
296    *list = '\0';
297
298    /* search matching entries */
299    for (i = 0; i < nConfig; i++) {
300  if (strncasecmp(Config[i].key, key, len) == 0) {
301      list = realloc(list, strlen(list) + strlen(Config[i].key) - len + 2);
302      if (*list != '\0')
303    strcat(list, "|");
304      strcat(list, Config[i].key + len);
305  }
306    }
307
308    free(key);
309    return list;
310}
311
312
313static char *cfg_lookup(const char *section, const char *key)
314{
315    int len;
316    char *buffer;
317    ENTRY *entry;
318
319    /* calculate key length */
320    len = strlen(key) + 1;
321    if (section != NULL)
322  len += strlen(section) + 1;
323
324    /* allocate buffer  */
325    buffer = malloc(len);
326    *buffer = '\0';
327
328    /* prepare section:key */
329    if (section != NULL && *section != '\0') {
330  strcpy(buffer, section);
331  strcat(buffer, ".");
332    }
333    strcat(buffer, key);
334
335    /* search entry */
336    entry = bsearch(buffer, Config, nConfig, sizeof(ENTRY), c_lookup);
337
338    /* free buffer again */
339    free(buffer);
340
341    if (entry != NULL)
342  return entry->val;
343
344    return NULL;
345}
346
347
348char *cfg_get_raw(const char *section, const char *key, const char *defval)
349{
350    char *val = cfg_lookup(section, key);
351
352    if (val != NULL)
353  return val;
354
355    return (char *) defval;
356}
357
358
359char *cfg_get(const char *section, const char *key, const char *defval)
360{
361    char *expression;
362    char *retval;
363    void *tree = NULL;
364    RESULT result = { 0, 0, 0, NULL };
365
366    expression = cfg_lookup(section, key);
367
368    if (expression != NULL) {
369  if (*expression == '\0')
370      return "";
371  if (Compile(expression, &tree) == 0 && Eval(tree, &result) == 0) {
372      retval = strdup(R2S(&result));
373      DelTree(tree);
374      DelResult(&result);
375      return (retval);
376  }
377  DelTree(tree);
378  DelResult(&result);
379    }
380    if (defval)
381  return strdup(defval);
382    return NULL;
383}
384
385
386int cfg_number(const char *section, const char *key, const int defval, const int min, const int max, int *value)
387{
388    char *expression;
389    void *tree = NULL;
390    RESULT result = { 0, 0, 0, NULL };
391
392    /* start with default value */
393    /* in case of an (uncatched) error, you have the */
394    /* default value set, which may be handy... */
395    *value = defval;
396
397    expression = cfg_get_raw(section, key, NULL);
398    if (expression == NULL || *expression == '\0') {
399  return 0;
400    }
401
402    if (Compile(expression, &tree) != 0) {
403  DelTree(tree);
404  return -1;
405    }
406    if (Eval(tree, &result) != 0) {
407  DelTree(tree);
408  DelResult(&result);
409  return -1;
410    }
411    *value = R2N(&result);
412    DelTree(tree);
413    DelResult(&result);
414
415    if (*value < min) {
416  error("bad '%s.%s' value '%d' in %s, minimum is %d", section, key, *value, cfg_source(), min);
417  *value = min;
418  return -1;
419    }
420
421    if (max > min && max != -1 && *value > max) {
422  error("bad '%s.%s' value '%d' in %s, maximum is %d", section, key, *value, cfg_source(), max);
423  *value = max;
424  return -1;
425    }
426
427    return 1;
428}
429
430
431static int cfg_check_source(const char *file)
432{
433    /* as passwords and commands are stored in the config file,
434     * we will check that:
435     * - file is a normal file (or /dev/null)
436     * - file owner is owner of program
437     * - file is not accessible by group
438     * - file is not accessible by other
439     */
440
441    struct stat stbuf;
442    uid_t uid, gid;
443    int error;
444
445    uid = geteuid();
446    gid = getegid();
447
448    if (stat(file, &stbuf) == -1) {
449  error("stat(%s) failed: %s", file, strerror(errno));
450  return -1;
451    }
452    if (S_ISCHR(stbuf.st_mode) && strcmp(file, "/dev/null") == 0)
453  return 0;
454
455    error = 0;
456    if (!S_ISREG(stbuf.st_mode)) {
457  error("security error: '%s' is not a regular file", file);
458  error = -1;
459    }
460    if (stbuf.st_uid != uid || stbuf.st_gid != gid) {
461  error("security error: owner and/or group of '%s' don't match", file);
462  error = -1;
463    }
464    if (stbuf.st_mode & S_IRWXG || stbuf.st_mode & S_IRWXO) {
465  error("security error: group or other have access to '%s'", file);
466  error = -1;
467    }
468    return error;
469}
470
471
472static int cfg_read(const char *file)
473{
474    FILE *stream;
475    char buffer[256];
476    char section[256];
477    char *line, *key, *val, *end;
478    int section_open, section_close;
479    int error, lineno;
480
481    stream = fopen(file, "r");
482    if (stream == NULL) {
483  error("open(%s) failed: %s", file, strerror(errno));
484  return -1;
485    }
486
487    /* start with empty section */
488    strcpy(section, "");
489
490    error = 0;
491    lineno = 0;
492    while ((line = fgets(buffer, 256, stream)) != NULL) {
493
494  /* increment line number */
495  lineno++;
496
497  /* skip empty lines */
498  if (*(line = strip(line, 1)) == '\0')
499      continue;
500
501  /* reset section flags */
502  section_open = 0;
503  section_close = 0;
504
505  /* key is first word */
506  key = line;
507
508  /* search first blank between key and value */
509  for (val = line; *val; val++) {
510      if (isblank(*val)) {
511    *val++ = '\0';
512    break;
513      }
514  }
515
516  /* strip value */
517  val = strip(val, 1);
518
519  /* search end of value */
520  if (*val)
521      for (end = val; *(end + 1); end++);
522  else
523      end = val;
524
525  /* if last char is '{', a section has been opened */
526  if (*end == '{') {
527      section_open = 1;
528      *end = '\0';
529      val = strip(val, 0);
530  }
531
532  /* provess "value" in double-quotes */
533  if (*val == '"' && *end == '"') {
534      *end = '\0';
535      val++;
536  }
537
538  /* if key is '}', a section has been closed */
539  if (strcmp(key, "}") == 0) {
540      section_close = 1;
541      *key = '\0';
542  }
543
544  /* sanity check: '}' should be the only char in a line */
545  if (section_close && (section_open || *val != '\0')) {
546      error("error in config file '%s' line %d: garbage after '}'", file, lineno);
547      error = 1;
548      break;
549  }
550
551  /* check key for valid chars */
552  if (!validchars(key, 0)) {
553      error("error in config file '%s' line %d: key '%s' is invalid", file, lineno, key);
554      error = 1;
555      break;
556  }
557
558  /* on section-open, check value for valid chars */
559  if (section_open && !validchars(val, 1)) {
560      error("error in config file '%s' line %d: section '%s' is invalid", file, lineno, val);
561      error = 1;
562      break;
563  }
564
565  /* on section-open, append new section name */
566  if (section_open) {
567      /* is the section[] array big enough? */
568      if (strlen(section) + strlen(key) + 3 > sizeof(section)) {
569    error("error in config file '%s' line %d: section buffer overflow", file, lineno);
570    error = 1;
571    break;
572      }
573      if (*section != '\0')
574    strcat(section, ".");
575      strcat(section, key);
576      if (*val != '\0') {
577    strcat(section, ":");
578    strcat(section, val);
579      }
580      continue;
581  }
582
583  /* on section-close, remove last section name */
584  if (section_close) {
585      /* sanity check: section already empty? */
586      if (*section == '\0') {
587    error("error in config file '%s' line %d: unmatched closing brace", file, lineno);
588    error = 1;
589    break;
590      }
591
592      end = strrchr(section, '.');
593      if (end == NULL)
594    *section = '\0';
595      else
596    *end = '\0';
597      continue;
598  }
599
600  /* finally: add key */
601  cfg_add(section, key, val, 0);
602
603    }
604
605    /* sanity check: are the braces balanced? */
606    if (!error && *section != '\0') {
607  error("error in config file '%s' line %d: unbalanced braces", file, lineno);
608  error = 1;
609    }
610
611    fclose(stream);
612
613    return -error;
614}
615
616
617int cfg_init(const char *file)
618{
619    if (cfg_check_source(file) == -1) {
620  return -1;
621    }
622
623    if (cfg_read(file) < 0)
624  return -1;
625
626    if (Config_File)
627  free(Config_File);
628    Config_File = strdup(file);
629
630    return 0;
631}
632
633
634char *cfg_source(void)
635{
636    if (Config_File)
637  return Config_File;
638    else
639  return "";
640}
641
642
643int cfg_exit(void)
644{
645    int i;
646    for (i = 0; i < nConfig; i++) {
647  if (Config[i].key)
648      free(Config[i].key);
649  if (Config[i].val)
650      free(Config[i].val);
651    }
652
653    if (Config) {
654  free(Config);
655  Config = NULL;
656    }
657
658    if (Config_File) {
659  free(Config_File);
660  Config_File = NULL;
661    }
662
663    return 0;
664}
Note: See TracBrowser for help on using the browser.