wobblyhead hg > freebsd > botblockd
diff 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 |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/config.c Mon Oct 26 11:29:10 2026 +0100 @@ -0,0 +1,402 @@ +/* + * Copyright (c) 2026 Arkadiusz Juszczyk <ark@wobblyhead.net> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#include <sys/param.h> + +#include <ctype.h> +#include <errno.h> +#include <limits.h> +#include <stddef.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <syslog.h> + +#include "botblockd.h" + +struct config cfg; + +/* + * config_invalid - report a malformed setting value + * + * A value present in the config file must be usable. Rather than + * silently falling back to a default and masking an operator typo, + * the caller fails the whole parse. + * + * Parameters: + * key - setting name + * val - offending value text + * + * Returns: -1, for the caller to pass on + */ +static int +config_invalid(const char *key, const char *val) +{ + syslog(LOG_ERR, "config: invalid value '%s' for %s", val, key); + return (-1); +} + +/* + * copy_path_setting - copy an absolute path config value + * + * Rejects an empty value, a relative path (the daemon changes to / when + * it detaches, so a relative path would resolve differently on reload), + * and a value that does not fit dst. + * + * Parameters: + * key - setting name, used only in the error message + * val - value text + * dst - destination buffer + * size - size of dst + * + * Returns: 0 on success, -1 on an invalid value + */ +static int +copy_path_setting(const char *key, const char *val, char *dst, + size_t size) +{ + if (*val != '/' || strlcpy(dst, val, size) >= size) + return (config_invalid(key, val)); + return (0); +} + +/* + * parse_int_setting - parse a positive integer config value + * + * Uses strtol with full error checking: rejects empty input, trailing + * non-digit junk, overflow, and values outside 1..INT_MAX. + * + * Parameters: + * key - setting name, used only in the error message + * val - value text (already stripped of surrounding whitespace) + * out - output: parsed value + * + * Returns: 0 on success, -1 on an invalid value + */ +static int +parse_int_setting(const char *key, const char *val, int *out) +{ + char *endp; + long lv; + + errno = 0; + lv = strtol(val, &endp, 10); + if (endp == val || *endp != '\0' || errno != 0 || + lv < 1 || lv > INT_MAX) + return (config_invalid(key, val)); + *out = (int)lv; + return (0); +} + +/* + * parse_status_token - parse one "N" or "lo-hi" item of an error spec + * + * Parameters: + * tok - single comma-delimited token, surrounding spaces tolerated + * lo - output: low bound + * hi - output: high bound (equals lo for a single code) + * + * Returns: 0 on success, -1 on malformed token or out-of-range value + */ +static int +parse_status_token(const char *tok, int *lo, int *hi) +{ + char *endp; + long a, b; + + while (*tok == ' ' || *tok == '\t') + tok++; + errno = 0; + a = strtol(tok, &endp, 10); + if (endp == tok || a < 0 || a >= NSTATUS || errno != 0) + return (-1); + if (*endp == '-') { + const char *p = endp + 1; + b = strtol(p, &endp, 10); + if (endp == p || b < 0 || b >= NSTATUS || errno != 0) + return (-1); + } else { + b = a; + } + while (*endp == ' ' || *endp == '\t') + endp++; + if (*endp != '\0' || a > b) + return (-1); + *lo = (int)a; + *hi = (int)b; + return (0); +} + +/* + * set_error_statuses - parse an error-status spec into a status bitmap + * + * Parses the comma-separated spec of individual codes and lo-hi ranges + * (e.g. "401,403,404,444" or "400-599") straight into the bitmap, so no + * raw copy is retained. An empty spec, an empty item (two commas in a + * row, or a leading or trailing comma) or a malformed item fails the + * parse. + * + * Parameters: + * key - setting name, used only in the error message + * spec - the ERROR_STATUSES value + * err - output: bitmap indexed by status code + * nbytes - size of err in bytes + * + * Returns: 0 on success, -1 on an invalid spec + */ +static int +set_error_statuses(const char *key, const char *spec, bool *err, + size_t nbytes) +{ + char buf[512]; + char *tok, *rest; + int c, lo, hi; + + if (*spec == '\0' || strlcpy(buf, spec, sizeof(buf)) >= sizeof(buf)) + return (config_invalid(key, spec)); + + memset(err, 0, nbytes); + rest = buf; + while ((tok = strsep(&rest, ",")) != NULL) { + if (parse_status_token(tok, &lo, &hi) != 0) + return (config_invalid(key, spec)); + for (c = lo; c <= hi; c++) + err[c] = true; + } + return (0); +} + +/* + * status_is_error - report whether an HTTP status counts as an error + * + * Parameters: + * code - HTTP status code + * + * Returns: true if the code is in the configured error set, else false + */ +bool +status_is_error(int code) +{ + if (code < 0 || code >= NSTATUS) + return (false); + return (cfg.status_is_err[code]); +} + +/* + * Settings, with their compiled-in defaults as text. Each load parses + * every default with the same code as a value from the file, then + * applies the file on top. + */ +enum setting_type { + SET_NUMBER, + SET_PATH, + SET_STATUSES, +}; + +struct setting { + const char *key; + const char *def; + enum setting_type type; + size_t off; /* field offset in struct config */ + size_t size; /* field size */ +}; + +#define FIELD(f) \ + offsetof(struct config, f), sizeof(((struct config *)0)->f) + +static const struct setting settings[] = { + { "INSPECT_SECONDS", "30", SET_NUMBER, FIELD(inspect_secs) }, + { "INSPECT_REQUEST_COUNT", "20", SET_NUMBER, FIELD(inspect_count) }, + { "MIN_ERROR_COUNT", "2", SET_NUMBER, FIELD(min_errors) }, + { "COOLDOWN_SECONDS", "600", SET_NUMBER, FIELD(cooldown_secs) }, + { "BLOCK_SECONDS", "600", SET_NUMBER, FIELD(block_secs) }, + { "ERROR_STATUSES", "400-599", + SET_STATUSES, FIELD(status_is_err) }, + { "INPUT_LOG", "/var/log/nginx/access.log", + SET_PATH, FIELD(input_log) }, + { "WHITELIST_FILE", PREFIX "/etc/botblockd/whitelist", + SET_PATH, FIELD(whitelist) }, +}; + +/* + * apply_setting - validate one value and store it in a config + * + * Parameters: + * c - config to store into + * s - setting the value is for + * val - value text, stripped of surrounding whitespace + * + * Returns: 0 on success, -1 on an invalid value + */ +static int +apply_setting(struct config *c, const struct setting *s, const char *val) +{ + void *dst = (char *)c + s->off; + + switch (s->type) { + case SET_NUMBER: + return (parse_int_setting(s->key, val, dst)); + case SET_PATH: + return (copy_path_setting(s->key, val, dst, s->size)); + case SET_STATUSES: + return (set_error_statuses(s->key, val, dst, s->size)); + } + return (-1); +} + +/* + * find_setting - look up a setting by key + * + * Parameters: + * key - setting name from the config file + * + * Returns: the setting, or NULL for an unknown key + */ +static const struct setting * +find_setting(const char *key) +{ + size_t i; + + for (i = 0; i < nitems(settings); i++) { + if (strcmp(settings[i].key, key) == 0) + return (&settings[i]); + } + return (NULL); +} + +/* + * apply_defaults - fill a config with the compiled-in defaults + * + * A default that does not parse is a program bug: it is logged with + * the setting name and the program exits. + * + * Parameters: + * c - config to fill + */ +static void +apply_defaults(struct config *c) +{ + size_t i; + + memset(c, 0, sizeof(*c)); + for (i = 0; i < nitems(settings); i++) { + if (apply_setting(c, &settings[i], settings[i].def) != 0) { + syslog(LOG_ERR, "config: bad compiled-in default for %s", + settings[i].key); + exit(1); + } + } +} + +/* + * read_entry - read the next entry of a config or whitelist file + * + * Skips blank lines and lines whose first non-blank character is '#', + * and strips the blanks and the newline around the entry. + * + * Parameters: + * fp - file to read + * line - in/out: getline(3) buffer, NULL before the first call + * cap - in/out: size of *line, 0 before the first call + * lineno - in/out: line number, 0 before the first call; on return + * the number of the line holding the entry + * + * Returns: the entry, inside *line, or NULL at end of file or on a + * read error (see ferror(3)) + */ +char * +read_entry(FILE *fp, char **line, size_t *cap, int *lineno) +{ + char *end, *p; + ssize_t n; + + while ((n = getline(line, cap, fp)) != -1) { + (*lineno)++; + p = *line; + end = p + n; + while (end > p && isspace((unsigned char)end[-1])) + end--; + *end = '\0'; + while (isspace((unsigned char)*p)) + p++; + if (*p != '\0' && *p != '#') + return (p); + } + return (NULL); +} + +/* + * parse_config - read a KEY=VALUE config file into a config + * + * The config is first set to the compiled-in defaults, so a key absent + * from the file has its default. Blank lines and lines whose first + * non-blank character is '#' are skipped. Any other line must be + * KEY=VALUE with a known key and a valid value; anything else fails + * the parse. A missing file is not an error: all settings keep their + * defaults. The global cfg is not touched. + * + * Parameters: + * path - path to config file + * out - output: the parsed config, undefined on failure + * + * Returns: 0 on success, -1 on an unreadable file or invalid content + */ +int +parse_config(const char *path, struct config *out) +{ + const struct setting *set; + FILE *fp; + size_t cap = 0; + char *eq, *key, *line = NULL, *val; + int lineno = 0, rc = 0; + + apply_defaults(out); + fp = fopen(path, "r"); + if (fp == NULL) { + if (errno != ENOENT) { + syslog(LOG_ERR, "cannot open config %s: %s", + path, strerror(errno)); + return (-1); + } + syslog(LOG_NOTICE, "no config at %s, using compiled-in " + "defaults", path); + return (0); + } + + while ((key = read_entry(fp, &line, &cap, &lineno)) != NULL) { + eq = strchr(key, '='); + if (eq == NULL) { + syslog(LOG_ERR, "config: line %d is not KEY=VALUE", lineno); + rc = -1; + break; + } + + /* trim blanks around '=' so "KEY = val" still matches */ + val = eq + 1; + while (eq > key && isspace((unsigned char)eq[-1])) + eq--; + *eq = '\0'; + while (isspace((unsigned char)*val)) + val++; + + set = find_setting(key); + if (set == NULL) { + syslog(LOG_ERR, "config: unknown setting '%s'", key); + rc = -1; + break; + } + rc = apply_setting(out, set, val); + if (rc != 0) + break; + } + if (rc == 0 && ferror(fp)) { + syslog(LOG_ERR, "cannot read config %s", path); + rc = -1; + } + free(line); + fclose(fp); + return (rc); +}
