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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "conf.h"
static char *
trim(char *s)
{
char *e;
while (isspace((unsigned char)*s))
s++;
e = s + strlen(s);
while (e > s && isspace((unsigned char)e[-1]))
*--e = '\0';
return s;
}
int
conf_load(struct conf *cf, const char *path)
{
FILE *f;
char line[1024], *eq, *k, *v;
memset(cf, 0, sizeof(*cf));
if ((f = fopen(path, "r")) == NULL)
return -1;
while (fgets(line, sizeof(line), f) != NULL && cf->n < CONF_MAX) {
k = trim(line);
if (*k == '#' || *k == '\0' || (eq = strchr(k, '=')) == NULL)
continue;
*eq = '\0';
/* trailing comment: whitespace followed by '#' */
for (v = eq + 1; *v; v++)
if (*v == '#' && isspace((unsigned char)v[-1])) {
*v = '\0';
break;
}
k = trim(k);
v = trim(eq + 1);
cf->keys[cf->n] = strdup(k);
cf->vals[cf->n] = strdup(v);
cf->n++;
}
fclose(f);
return 0;
}
const char *
conf_get(const struct conf *cf, const char *key, const char *def)
{
int i;
for (i = 0; i < cf->n; i++)
if (strcmp(cf->keys[i], key) == 0)
return cf->vals[i];
return def;
}
static const char *
next_item(const char *p, size_t *len)
{
while (*p == ',' || isspace((unsigned char)*p))
p++;
/* Commas separate groups; spaces may be part of an LDAP group name. */
*len = strcspn(p, ",");
while (*len > 0 && isspace((unsigned char)p[*len - 1]))
(*len)--;
return *len ? p : NULL;
}
int
list_has(const char *list, const char *item)
{
const char *p = list;
size_t len, ilen = strlen(item);
if (list == NULL || ilen == 0)
return 0;
while ((p = next_item(p, &len)) != NULL) {
if (len == ilen && strncmp(p, item, len) == 0)
return 1;
p += len;
}
return 0;
}
int
list_intersects(const char *a, const char *b)
{
const char *p = a;
size_t len;
char item[128];
if (a == NULL || b == NULL)
return 0;
while ((p = next_item(p, &len)) != NULL) {
if (len < sizeof(item)) {
memcpy(item, p, len);
item[len] = '\0';
if (list_has(b, item))
return 1;
}
p += len;
}
return 0;
}