comparison src/config.c @ 0:9f8d79c98fd2 0.4.0

initial public release
author Arkadiusz Juszczyk <ark@wobblyhead.net>
date 2026-10-26 11:29 +0100
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:9f8d79c98fd2
1 /*
2 * Copyright (c) 2026 Arkadiusz Juszczyk <ark@wobblyhead.net>
3 *
4 * SPDX-License-Identifier: BSD-2-Clause
5 */
6
7 #include <sys/param.h>
8
9 #include <ctype.h>
10 #include <errno.h>
11 #include <limits.h>
12 #include <stddef.h>
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <string.h>
16 #include <syslog.h>
17
18 #include "botblockd.h"
19
20 struct config cfg;
21
22 /*
23 * config_invalid - report a malformed setting value
24 *
25 * A value present in the config file must be usable. Rather than
26 * silently falling back to a default and masking an operator typo,
27 * the caller fails the whole parse.
28 *
29 * Parameters:
30 * key - setting name
31 * val - offending value text
32 *
33 * Returns: -1, for the caller to pass on
34 */
35 static int
36 config_invalid(const char *key, const char *val)
37 {
38 syslog(LOG_ERR, "config: invalid value '%s' for %s", val, key);
39 return (-1);
40 }
41
42 /*
43 * copy_path_setting - copy an absolute path config value
44 *
45 * Rejects an empty value, a relative path (the daemon changes to / when
46 * it detaches, so a relative path would resolve differently on reload),
47 * and a value that does not fit dst.
48 *
49 * Parameters:
50 * key - setting name, used only in the error message
51 * val - value text
52 * dst - destination buffer
53 * size - size of dst
54 *
55 * Returns: 0 on success, -1 on an invalid value
56 */
57 static int
58 copy_path_setting(const char *key, const char *val, char *dst,
59 size_t size)
60 {
61 if (*val != '/' || strlcpy(dst, val, size) >= size)
62 return (config_invalid(key, val));
63 return (0);
64 }
65
66 /*
67 * parse_int_setting - parse a positive integer config value
68 *
69 * Uses strtol with full error checking: rejects empty input, trailing
70 * non-digit junk, overflow, and values outside 1..INT_MAX.
71 *
72 * Parameters:
73 * key - setting name, used only in the error message
74 * val - value text (already stripped of surrounding whitespace)
75 * out - output: parsed value
76 *
77 * Returns: 0 on success, -1 on an invalid value
78 */
79 static int
80 parse_int_setting(const char *key, const char *val, int *out)
81 {
82 char *endp;
83 long lv;
84
85 errno = 0;
86 lv = strtol(val, &endp, 10);
87 if (endp == val || *endp != '\0' || errno != 0 ||
88 lv < 1 || lv > INT_MAX)
89 return (config_invalid(key, val));
90 *out = (int)lv;
91 return (0);
92 }
93
94 /*
95 * parse_status_token - parse one "N" or "lo-hi" item of an error spec
96 *
97 * Parameters:
98 * tok - single comma-delimited token, surrounding spaces tolerated
99 * lo - output: low bound
100 * hi - output: high bound (equals lo for a single code)
101 *
102 * Returns: 0 on success, -1 on malformed token or out-of-range value
103 */
104 static int
105 parse_status_token(const char *tok, int *lo, int *hi)
106 {
107 char *endp;
108 long a, b;
109
110 while (*tok == ' ' || *tok == '\t')
111 tok++;
112 errno = 0;
113 a = strtol(tok, &endp, 10);
114 if (endp == tok || a < 0 || a >= NSTATUS || errno != 0)
115 return (-1);
116 if (*endp == '-') {
117 const char *p = endp + 1;
118 b = strtol(p, &endp, 10);
119 if (endp == p || b < 0 || b >= NSTATUS || errno != 0)
120 return (-1);
121 } else {
122 b = a;
123 }
124 while (*endp == ' ' || *endp == '\t')
125 endp++;
126 if (*endp != '\0' || a > b)
127 return (-1);
128 *lo = (int)a;
129 *hi = (int)b;
130 return (0);
131 }
132
133 /*
134 * set_error_statuses - parse an error-status spec into a status bitmap
135 *
136 * Parses the comma-separated spec of individual codes and lo-hi ranges
137 * (e.g. "401,403,404,444" or "400-599") straight into the bitmap, so no
138 * raw copy is retained. An empty spec, an empty item (two commas in a
139 * row, or a leading or trailing comma) or a malformed item fails the
140 * parse.
141 *
142 * Parameters:
143 * key - setting name, used only in the error message
144 * spec - the ERROR_STATUSES value
145 * err - output: bitmap indexed by status code
146 * nbytes - size of err in bytes
147 *
148 * Returns: 0 on success, -1 on an invalid spec
149 */
150 static int
151 set_error_statuses(const char *key, const char *spec, bool *err,
152 size_t nbytes)
153 {
154 char buf[512];
155 char *tok, *rest;
156 int c, lo, hi;
157
158 if (*spec == '\0' || strlcpy(buf, spec, sizeof(buf)) >= sizeof(buf))
159 return (config_invalid(key, spec));
160
161 memset(err, 0, nbytes);
162 rest = buf;
163 while ((tok = strsep(&rest, ",")) != NULL) {
164 if (parse_status_token(tok, &lo, &hi) != 0)
165 return (config_invalid(key, spec));
166 for (c = lo; c <= hi; c++)
167 err[c] = true;
168 }
169 return (0);
170 }
171
172 /*
173 * status_is_error - report whether an HTTP status counts as an error
174 *
175 * Parameters:
176 * code - HTTP status code
177 *
178 * Returns: true if the code is in the configured error set, else false
179 */
180 bool
181 status_is_error(int code)
182 {
183 if (code < 0 || code >= NSTATUS)
184 return (false);
185 return (cfg.status_is_err[code]);
186 }
187
188 /*
189 * Settings, with their compiled-in defaults as text. Each load parses
190 * every default with the same code as a value from the file, then
191 * applies the file on top.
192 */
193 enum setting_type {
194 SET_NUMBER,
195 SET_PATH,
196 SET_STATUSES,
197 };
198
199 struct setting {
200 const char *key;
201 const char *def;
202 enum setting_type type;
203 size_t off; /* field offset in struct config */
204 size_t size; /* field size */
205 };
206
207 #define FIELD(f) \
208 offsetof(struct config, f), sizeof(((struct config *)0)->f)
209
210 static const struct setting settings[] = {
211 { "INSPECT_SECONDS", "30", SET_NUMBER, FIELD(inspect_secs) },
212 { "INSPECT_REQUEST_COUNT", "20", SET_NUMBER, FIELD(inspect_count) },
213 { "MIN_ERROR_COUNT", "2", SET_NUMBER, FIELD(min_errors) },
214 { "COOLDOWN_SECONDS", "600", SET_NUMBER, FIELD(cooldown_secs) },
215 { "BLOCK_SECONDS", "600", SET_NUMBER, FIELD(block_secs) },
216 { "ERROR_STATUSES", "400-599",
217 SET_STATUSES, FIELD(status_is_err) },
218 { "INPUT_LOG", "/var/log/nginx/access.log",
219 SET_PATH, FIELD(input_log) },
220 { "WHITELIST_FILE", PREFIX "/etc/botblockd/whitelist",
221 SET_PATH, FIELD(whitelist) },
222 };
223
224 /*
225 * apply_setting - validate one value and store it in a config
226 *
227 * Parameters:
228 * c - config to store into
229 * s - setting the value is for
230 * val - value text, stripped of surrounding whitespace
231 *
232 * Returns: 0 on success, -1 on an invalid value
233 */
234 static int
235 apply_setting(struct config *c, const struct setting *s, const char *val)
236 {
237 void *dst = (char *)c + s->off;
238
239 switch (s->type) {
240 case SET_NUMBER:
241 return (parse_int_setting(s->key, val, dst));
242 case SET_PATH:
243 return (copy_path_setting(s->key, val, dst, s->size));
244 case SET_STATUSES:
245 return (set_error_statuses(s->key, val, dst, s->size));
246 }
247 return (-1);
248 }
249
250 /*
251 * find_setting - look up a setting by key
252 *
253 * Parameters:
254 * key - setting name from the config file
255 *
256 * Returns: the setting, or NULL for an unknown key
257 */
258 static const struct setting *
259 find_setting(const char *key)
260 {
261 size_t i;
262
263 for (i = 0; i < nitems(settings); i++) {
264 if (strcmp(settings[i].key, key) == 0)
265 return (&settings[i]);
266 }
267 return (NULL);
268 }
269
270 /*
271 * apply_defaults - fill a config with the compiled-in defaults
272 *
273 * A default that does not parse is a program bug: it is logged with
274 * the setting name and the program exits.
275 *
276 * Parameters:
277 * c - config to fill
278 */
279 static void
280 apply_defaults(struct config *c)
281 {
282 size_t i;
283
284 memset(c, 0, sizeof(*c));
285 for (i = 0; i < nitems(settings); i++) {
286 if (apply_setting(c, &settings[i], settings[i].def) != 0) {
287 syslog(LOG_ERR, "config: bad compiled-in default for %s",
288 settings[i].key);
289 exit(1);
290 }
291 }
292 }
293
294 /*
295 * read_entry - read the next entry of a config or whitelist file
296 *
297 * Skips blank lines and lines whose first non-blank character is '#',
298 * and strips the blanks and the newline around the entry.
299 *
300 * Parameters:
301 * fp - file to read
302 * line - in/out: getline(3) buffer, NULL before the first call
303 * cap - in/out: size of *line, 0 before the first call
304 * lineno - in/out: line number, 0 before the first call; on return
305 * the number of the line holding the entry
306 *
307 * Returns: the entry, inside *line, or NULL at end of file or on a
308 * read error (see ferror(3))
309 */
310 char *
311 read_entry(FILE *fp, char **line, size_t *cap, int *lineno)
312 {
313 char *end, *p;
314 ssize_t n;
315
316 while ((n = getline(line, cap, fp)) != -1) {
317 (*lineno)++;
318 p = *line;
319 end = p + n;
320 while (end > p && isspace((unsigned char)end[-1]))
321 end--;
322 *end = '\0';
323 while (isspace((unsigned char)*p))
324 p++;
325 if (*p != '\0' && *p != '#')
326 return (p);
327 }
328 return (NULL);
329 }
330
331 /*
332 * parse_config - read a KEY=VALUE config file into a config
333 *
334 * The config is first set to the compiled-in defaults, so a key absent
335 * from the file has its default. Blank lines and lines whose first
336 * non-blank character is '#' are skipped. Any other line must be
337 * KEY=VALUE with a known key and a valid value; anything else fails
338 * the parse. A missing file is not an error: all settings keep their
339 * defaults. The global cfg is not touched.
340 *
341 * Parameters:
342 * path - path to config file
343 * out - output: the parsed config, undefined on failure
344 *
345 * Returns: 0 on success, -1 on an unreadable file or invalid content
346 */
347 int
348 parse_config(const char *path, struct config *out)
349 {
350 const struct setting *set;
351 FILE *fp;
352 size_t cap = 0;
353 char *eq, *key, *line = NULL, *val;
354 int lineno = 0, rc = 0;
355
356 apply_defaults(out);
357 fp = fopen(path, "r");
358 if (fp == NULL) {
359 if (errno != ENOENT) {
360 syslog(LOG_ERR, "cannot open config %s: %s",
361 path, strerror(errno));
362 return (-1);
363 }
364 syslog(LOG_NOTICE, "no config at %s, using compiled-in "
365 "defaults", path);
366 return (0);
367 }
368
369 while ((key = read_entry(fp, &line, &cap, &lineno)) != NULL) {
370 eq = strchr(key, '=');
371 if (eq == NULL) {
372 syslog(LOG_ERR, "config: line %d is not KEY=VALUE", lineno);
373 rc = -1;
374 break;
375 }
376
377 /* trim blanks around '=' so "KEY = val" still matches */
378 val = eq + 1;
379 while (eq > key && isspace((unsigned char)eq[-1]))
380 eq--;
381 *eq = '\0';
382 while (isspace((unsigned char)*val))
383 val++;
384
385 set = find_setting(key);
386 if (set == NULL) {
387 syslog(LOG_ERR, "config: unknown setting '%s'", key);
388 rc = -1;
389 break;
390 }
391 rc = apply_setting(out, set, val);
392 if (rc != 0)
393 break;
394 }
395 if (rc == 0 && ferror(fp)) {
396 syslog(LOG_ERR, "cannot read config %s", path);
397 rc = -1;
398 }
399 free(line);
400 fclose(fp);
401 return (rc);
402 }