summaryrefslogtreecommitdiff
path: root/libc/string/config.c
blob: 58716b9224b87188bf1d72211734ed005757ccaa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/* config.c: Config file reader.
 *
 * Copyright 1999 D. Jeff Dionne, <jeff@rt-control.com>
 *
 * This is free software, under the LGPL V2.0
 */

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <cfgfile.h>

/* This is a quick and dirty config file parser.  It reads the file once for
 * each request, there is no cache.  Each line must be less than 128bytes.
 */

static char *args[16];
static char cfgbuf[128];

static char *
ws(char **buf)
{
  char *b = *buf;
  char *p;

  /* eat ws */
  while (*b &&
	 (*b == ' '  ||
	  *b == '\n' ||
	  *b == '\t')) b++;
  p = b;

  /* find the end */
  while (*p &&
	 !(*p == ' '  ||
	   *p == '\n' ||
	   *p == '\t')) p++;
  *p = 0;
  *buf = p+1;
  return b;
}

char **
cfgread(FILE *fp)
{
  char *ebuf;
  char *p;
  int i;

  if (!fp) {
    errno = EIO;
    return (void *)0;
  }
  
  while (fgets(cfgbuf, sizeof(cfgbuf), fp)) {

    /* ship comment lines */
    if (cfgbuf[0] == '#') continue;

    ebuf = cfgbuf + strlen(cfgbuf);

    p = cfgbuf;
    for (i = 0; i < 16 && p < ebuf; i++) {
      args[i] = ws(&p);
    }
    args[i] = (void *)0;

    /* return if we found something */
    if (strlen(args[0])) return args;
  }
  return (void *)0;
}

char **
cfgfind(FILE *fp, char *var)
{
  char **ret;
  char search[80];

  if (!fp || !var) {
    errno = EIO;
    return (void *)0;
  }

  strncpy(search, var, sizeof(search));

  fseek(fp, 0, SEEK_SET);
  while ((ret = cfgread(fp))) {
    if (!strcmp(ret[0], search)) return ret;
  }
  return (void *)0;
}