changeset 0:9f8d79c98fd2 0.4.0

initial public release
author Arkadiusz Juszczyk <ark@wobblyhead.net>
date 2026-10-26 11:29 +0100
parents
children 30f396bc751c
files .hgignore CHANGES LICENSE README.md conf/conf.sample conf/pf.conf.sample conf/rc.d/botblockd conf/whitelist.sample man/botblockd.8 src/Makefile src/botblockd.h src/config.c src/ip.c src/logtail.c src/main.c src/pf.c src/suspect.c src/whitelist.c
diffstat 18 files changed, 2519 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/.hgignore	Mon Oct 26 11:29:10 2026 +0100
@@ -0,0 +1,4 @@
+syntax=regex
+\.DS_Store
+\.orig$
+^VERSION$
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/CHANGES	Mon Oct 26 11:29:10 2026 +0100
@@ -0,0 +1,4 @@
+
+Changes with botblockd 0.4.0                                     25 Oct 2026
+
+    *) First public release.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/LICENSE	Mon Oct 26 11:29:10 2026 +0100
@@ -0,0 +1,22 @@
+Copyright (c) 2026 Arkadiusz Juszczyk <ark@wobblyhead.net>.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+1. Redistributions of source code must retain the above copyright notice,
+   this list of conditions and the following disclaimer.
+2. Redistributions in binary form must reproduce the above copyright notice,
+   this list of conditions and the following disclaimer in the documentation
+   and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGE.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/README.md	Mon Oct 26 11:29:10 2026 +0100
@@ -0,0 +1,100 @@
+# botblockd
+
+A small FreeBSD daemon that blocks abusive web clients at the firewall.
+
+botblockd tails an nginx access log, counts HTTP error responses per
+source IP, and adds persistent offenders to a `pf` table so they are
+dropped at the host edge. It reinforces application-level decisions
+(rate limits, web application firewall rules) at the network layer, 
+where they are cheap to enforce.
+
+IPv4 only. No external dependencies: it uses the FreeBSD base system
+toolchain, headers and `pfctl`.
+
+## How it works
+
+Every source address that receives an error response becomes a suspect. A
+periodic sweep evaluates suspects through a small state machine:
+
+- An inspection window (a number of seconds or requests, whichever comes
+  first) decides whether a suspect's error balance warrants a block.
+- A blocked address is released after a configurable interval into a
+  probation period, during which renewed bad behaviour re-blocks it.
+- Suspects that stop causing errors are forgotten after a cooldown.
+
+Successful requests count against errors. A client is blocked only when
+its errors reach a minimum count and outnumber its successful requests.
+An occasional error among normal requests does not block a client, and a
+client can clear itself by behaving.
+
+Which status codes count as errors is configurable; anything else counts
+as success.
+
+## Safety
+
+A whitelist file of addresses that are never blocked keeps operators
+from being locked out.
+
+The daemon treats the `pf` table as its own and flushes it at startup
+and on shutdown. When it blocks an address, it also kills that
+address's existing `pf` states, so open connections are cut off.
+
+## Requirements
+
+- FreeBSD. Tested on FreeBSD 15.
+- `pf` enabled, with a `botblock` table and a matching block rule.
+
+## Install
+
+Source releases and install notes are on the project page,
+<https://www.wobblyhead.net/projects/botblockd.html>.
+
+To build and install from an unpacked source release:
+
+    make -C src
+    make -C src install
+
+## pf setup
+
+botblockd manages a `pf` table named `botblock`; you provide the table
+and the rule. A sample is installed at
+`share/examples/botblockd/pf.conf.sample`:
+
+    table <botblock> persist
+    block in quick from <botblock>
+
+Splice it into your ruleset and reload with `pfctl -f /etc/pf.conf`.
+
+## Run
+
+    sysrc botblockd_enable=YES
+    service botblockd start
+
+The configuration is read from `/usr/local/etc/botblockd/conf`; copy
+`conf.sample` from the same directory and edit it. Send `SIGHUP` (or
+`service botblockd reload`) to re-read it. If the new configuration or
+whitelist has an error, the reload is rejected and the daemon keeps
+running with the previous one; the error goes to the system log. Run
+`botblockd check` as root to see errors before reloading.
+
+## Commands
+
+    botblockd run [-f]        run the daemon (-f: foreground)
+    botblockd check           validate configuration and exit
+    botblockd list            list currently blocked addresses
+    botblockd unblock <addr>  remove an address from the block table
+    botblockd unblock -a      clear the whole table
+
+The daemon logs to syslog under the `daemon` facility.
+
+See `botblockd(8)` for the full configuration reference.
+
+## Bugs
+
+Report bugs by email to ark@wobblyhead.net. Include the version, which
+`botblockd help` prints on its first line, and the relevant lines from
+the system log.
+
+## Licence
+
+BSD 2-Clause. See [LICENSE](LICENSE).
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/conf/conf.sample	Mon Oct 26 11:29:10 2026 +0100
@@ -0,0 +1,41 @@
+# botblockd configuration example.
+#
+# Every setting below is shown commented out at its compiled-in default,
+# which is what botblockd uses when the setting is absent or no config
+# file exists.  Uncomment a line and change the value to override it.  A
+# setting that is present must have a valid value: on a malformed value
+# botblockd refuses to start, or rejects the reload, rather than silently
+# falling back to the default.  Unknown settings and lines that are not
+# KEY=VALUE are errors too.  Numbers must be positive integers, paths
+# must be absolute.
+
+# Inspection window: time or request count, whichever triggers first.
+#INSPECT_SECONDS=30
+#INSPECT_REQUEST_COUNT=20
+
+# Minimum number of errors a suspect must have caused before it is first
+# blocked.  A floor against one-shot 404/499 false positives -- a real
+# bot reliably causes more than one error.
+#MIN_ERROR_COUNT=2
+
+# Which HTTP status codes count as errors.  Comma-separated list of
+# single codes and lo-hi ranges, e.g. 401,403,404,444 or 400-599.
+# Anything not listed counts as a successful request.
+#ERROR_STATUSES=400-599
+
+# Cooldown: forget a suspect after this many seconds without errors;
+# successful requests do not keep it.  An address on probation is
+# forgotten this many seconds after its block was lifted.
+#COOLDOWN_SECONDS=600
+
+# Block duration in seconds: how long an IP stays in the pf table before
+# the block is lifted and the IP enters probation.
+#BLOCK_SECONDS=600
+
+# Input: nginx access log in combined format, raw or syslog-aggregated.
+# Followed across rotation.  A reload that changes it is rejected; a
+# change takes effect on restart.
+#INPUT_LOG=/var/log/nginx/access.log
+
+# Whitelist: one IPv4 address or CIDR subnet per line.
+#WHITELIST_FILE=/usr/local/etc/botblockd/whitelist
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/conf/pf.conf.sample	Mon Oct 26 11:29:10 2026 +0100
@@ -0,0 +1,12 @@
+# botblockd uses this pf table.  Include the table definition and a
+# matching block rule in the pf configuration, /etc/pf.conf by
+# default.
+#
+# `persist` keeps the table across `pfctl -f` reloads.  The table is
+# not file-backed; botblockd flushes it at startup and on exit.
+
+table <botblock> persist
+
+# Drop blocked sources early.  Place ahead of any pass rules that
+# would otherwise let them through.
+block in quick from <botblock>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/conf/rc.d/botblockd	Mon Oct 26 11:29:10 2026 +0100
@@ -0,0 +1,27 @@
+#!/bin/sh
+
+# PROVIDE: botblockd
+# REQUIRE: LOGIN pf
+# KEYWORD: shutdown
+
+. /etc/rc.subr
+
+name="botblockd"
+rcvar=${name}_enable
+
+load_rc_config "$name"
+
+: ${botblockd_enable:=NO}
+: ${botblockd_pidfile:=/var/run/${name}.pid}
+: ${botblockd_configfile:=%%PREFIX%%/etc/${name}/conf}
+
+# botblockd detaches itself via daemon(3) and writes its own pidfile;
+# the "run" verb starts the daemon.
+pidfile="${botblockd_pidfile}"
+command="%%PREFIX%%/sbin/${name}"
+command_args="run -c ${botblockd_configfile} -p ${pidfile}"
+
+# reload sends SIGHUP via the pidfile; botblockd re-reads config/whitelist
+extra_commands="reload"
+
+run_rc_command "$1"
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/conf/whitelist.sample	Mon Oct 26 11:29:10 2026 +0100
@@ -0,0 +1,7 @@
+# botblockd whitelist.  One IPv4 address or CIDR subnet per line.
+# Comments start with '#'.
+#
+# Example:
+# 192.0.2.10
+# 198.51.100.7
+# 203.0.113.0/24
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/man/botblockd.8	Mon Oct 26 11:29:10 2026 +0100
@@ -0,0 +1,268 @@
+.\" SPDX-License-Identifier: BSD-2-Clause
+.\" Copyright (c) 2026 Arkadiusz Juszczyk <ark@wobblyhead.net>
+.\"
+.Dd October 25, 2026
+.Dt BOTBLOCKD 8
+.Os
+.Sh NAME
+.Nm botblockd
+.Nd nginx-to-pf bot blocker
+.Sh SYNOPSIS
+.Nm
+.Cm run
+.Op Fl f
+.Op Fl c Ar config
+.Op Fl p Ar pidfile
+.Nm
+.Cm check
+.Op Fl c Ar config
+.Nm
+.Cm list
+.Nm
+.Cm unblock
+.Ar address ...
+.Nm
+.Cm unblock Fl a
+.Nm
+.Cm help
+.Sh DESCRIPTION
+.Nm
+tails an nginx access log via
+.Xr kqueue 2 ,
+counts HTTP error responses per source IP, and blocks persistently
+abusive clients at the host
+.Xr pf 4
+firewall by adding them to the
+.Sy botblock
+table.
+It reads the standard combined log format, accepting both the raw form
+and the form produced when
+.Xr syslogd 8
+aggregates the log with a prepended syslog header.
+The log is followed across rotation and truncation.
+Only IPv4 is handled.
+.Pp
+Each source that produces an error response becomes a suspect.
+A periodic sweep evaluates suspects and moves them through a small state
+machine.
+An inspection window of
+.Va INSPECT_SECONDS
+seconds or
+.Va INSPECT_REQUEST_COUNT
+requests, whichever comes first, decides whether the error balance
+warrants a block.
+A blocked IP is released after
+.Va BLOCK_SECONDS
+seconds into a probation period, during which renewed bad behaviour
+re-blocks it.
+Suspects that cause no further errors are dropped after
+.Va COOLDOWN_SECONDS
+seconds.
+Successful requests count against errors.
+A client is blocked only when its errors reach
+.Va MIN_ERROR_COUNT
+and outnumber its successful requests.
+An occasional error among normal requests does not block a client, and a
+client can clear itself by behaving.
+.Pp
+A whitelist file protects operators.
+It lists addresses that are never blocked.
+.Pp
+.Nm
+logs to
+.Xr syslog 3
+under the
+.Dv LOG_DAEMON
+facility.
+The
+.Xr pf 4
+.Sy botblock
+table must exist and be referenced by a block rule in the host ruleset;
+a sample is installed under
+.Pa share/examples/botblockd .
+.Nm
+treats the table as its own and flushes it at startup and on exit.
+When an address is blocked, its existing
+.Xr pf 4
+states are killed as well, so connections it has already established
+are cut off.
+.Sh COMMANDS
+.Bl -tag -width "unblock"
+.It Cm run
+Run the daemon.
+It detaches into the background unless
+.Fl f
+is given, and writes a pidfile.
+The configuration, the whitelist, the input log and the
+.Sy botblock
+table are checked before detaching, so a problem with any of them is
+reported in the exit status.
+.It Cm check
+Parse the configuration and whitelist, open the input log, verify that
+the
+.Sy botblock
+table is loaded in
+.Xr pf 4 ,
+report the result, and exit.
+The table is only read, never modified.
+Run this as root before sending
+.Dv SIGHUP :
+a failed reload is reported only in the system log.
+.It Cm list
+Print the addresses currently in the
+.Sy botblock
+table.
+.It Cm unblock Ar address ...
+Remove one or more addresses from the
+.Sy botblock
+table.
+.It Cm unblock Fl a
+Remove all addresses from the table.
+.It Cm help
+Print the version and a usage summary.
+.El
+.Sh OPTIONS
+.Bl -tag -width Fl
+.It Fl c Ar config
+Read configuration from
+.Ar config
+instead of the default.
+With
+.Cm run ,
+the path must be absolute, so that a reload finds the file after the
+daemon has changed to the root directory.
+.It Fl f
+Run in the foreground without detaching, mirroring log output to
+standard error.
+.It Fl p Ar pidfile
+Write the pidfile to
+.Ar pidfile
+instead of the default.
+.El
+.Sh CONFIGURATION
+The configuration file holds
+.Sy KEY=VALUE
+lines.
+Blank lines and lines whose first non-blank character is
+.Ql #
+are ignored.
+Unset keys keep their compiled-in defaults, and if the file does not
+exist, all defaults apply.
+A key that is present must have a valid value.
+Numbers must be positive integers, and paths must be absolute.
+A malformed value, an unknown key or a line that is not
+.Sy KEY=VALUE
+is an error rather than ignored: at startup
+.Nm
+exits, and a reload is rejected.
+.Bl -tag -width "INSPECT_REQUEST_COUNT"
+.It Va INSPECT_SECONDS
+Length of the inspection window in seconds.
+The default is 30.
+.It Va INSPECT_REQUEST_COUNT
+Request count that also closes the inspection window.
+The default is 20.
+.It Va MIN_ERROR_COUNT
+Minimum number of errors a suspect must have caused before it is
+first blocked.
+Errors are counted from the first one and are not reset when the
+inspection window closes.
+The default is 2.
+.It Va ERROR_STATUSES
+Which HTTP status codes count as errors, as a comma-separated list of
+single codes and
+.Ar lo Ns - Ns Ar hi
+ranges, for example
+.Ql 401,403,404,444
+or
+.Ql 400-599 .
+Any status not listed counts as a successful request.
+The default is
+.Ql 400-599 .
+.It Va COOLDOWN_SECONDS
+A suspect that has caused no error for this many seconds is
+forgotten; successful requests do not keep it.
+An address on probation is forgotten this many seconds after its
+block was lifted.
+The default is 600.
+.It Va BLOCK_SECONDS
+How long, in seconds, an address stays blocked before entering probation.
+The default is 600.
+.It Va INPUT_LOG
+Path of the nginx access log to tail.
+A reload that changes it is rejected; the change takes effect when
+the daemon is restarted.
+The default is
+.Pa /var/log/nginx/access.log .
+.It Va WHITELIST_FILE
+Path of the whitelist, one IPv4 address or CIDR subnet per line.
+A bare address is treated as a single host
+.Pq Li /32 ;
+a prefix length must be between 1 and 32, as
+.Li /0
+would whitelist every address.
+Host bits below the prefix are accepted and masked off, so
+.Li 10.0.0.5/24
+is the same as
+.Li 10.0.0.0/24 .
+Blanks around an entry, blank lines and lines whose first non-blank
+character is
+.Ql #
+are ignored; any other line that does not parse fails startup or
+reload, just like a malformed configuration value.
+A missing file leaves the whitelist empty; a file that exists but
+cannot be read is an error.
+The default is
+.Pa /usr/local/etc/botblockd/whitelist .
+.El
+.Sh FILES
+.Bl -tag -width "/usr/local/etc/botblockd/whitelist"
+.It Pa /usr/local/etc/botblockd/conf
+Configuration file
+.It Pa /usr/local/etc/botblockd/whitelist
+IP whitelist
+.It Pa /usr/local/etc/rc.d/botblockd
+.Xr rc 8
+Startup script
+.It Pa /var/run/botblockd.pid
+Default pidfile
+.El
+.Sh SIGNALS
+.Bl -tag -width SIGTERM
+.It Dv SIGTERM , SIGINT
+Graceful shutdown; flush the
+.Xr pf 4
+table before exiting.
+.It Dv SIGHUP
+Reload the configuration file and whitelist.
+If either has an error, or
+.Va INPUT_LOG
+has changed, the reload is rejected: the error is logged and the
+previous configuration and whitelist stay in effect.
+.El
+.Sh EXIT STATUS
+.Cm run
+exits 0 when stopped by a signal and 1 on any error, at startup or
+while running.
+The other commands exit 0 on success and 1 on failure.
+.Sh SEE ALSO
+.Xr kqueue 2 ,
+.Xr syslog 3 ,
+.Xr pf 4 ,
+.Xr pfctl 8 ,
+.Xr rc 8 ,
+.Xr syslogd 8
+.Sh AUTHORS
+.An Arkadiusz Juszczyk Aq Mt ark@wobblyhead.net
+.Sh CAVEATS
+Only IPv4 is handled.
+Log lines from IPv6 clients are skipped, so these clients are never
+blocked.
+.Pp
+.Cm unblock
+works on the
+.Xr pf 4
+table only and does not inform a running daemon.
+The daemon still counts a manually unblocked address as blocked until
+its block interval ends, so the address is not blocked again before
+then, whatever errors it causes.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/Makefile	Mon Oct 26 11:29:10 2026 +0100
@@ -0,0 +1,44 @@
+# vim:ts=8:
+PROG=	botblockd
+SRCS=	main.c config.c ip.c whitelist.c pf.c suspect.c logtail.c
+MAN=	${PROG}.8
+WARNS=	6
+
+# pidfile(3) lives in libutil
+LDADD=	-lutil
+
+# man page and packaging payload live outside src/
+.PATH:	${.CURDIR}/../man
+
+# Default to /usr/local-style layout; the port can override PREFIX if needed.
+PREFIX?=	/usr/local
+BINDIR=		${PREFIX}/sbin
+MANDIR=		${PREFIX}/share/man/man
+CFLAGS+=	-DPREFIX=\"${PREFIX}\"
+
+# release tarballs carry a one-line VERSION file at the top level
+BOTBLOCKD_VERSION!=	cat ${.CURDIR}/../VERSION 2>/dev/null || echo unknown
+CFLAGS+=	-DBOTBLOCKD_VERSION=\"${BOTBLOCKD_VERSION}\"
+
+# Where the extras go
+ETCDIR=		${PREFIX}/etc/botblockd
+RCDIR=		${PREFIX}/etc/rc.d
+EXAMPLESDIR=	${PREFIX}/share/examples/${PROG}
+CONFDIR=	${.CURDIR}/../conf
+CONF_FILES=	conf.sample whitelist.sample
+EXAMPLE_FILES=	pf.conf.sample
+
+afterinstall:
+	${INSTALL} -d ${DESTDIR}${ETCDIR}
+	${INSTALL} -d ${DESTDIR}${RCDIR}
+	${INSTALL} -d ${DESTDIR}${EXAMPLESDIR}
+.for f in ${CONF_FILES}
+	${INSTALL} -m 644 ${CONFDIR}/${f} ${DESTDIR}${ETCDIR}/${f}
+.endfor
+	${INSTALL} -m 555 ${CONFDIR}/rc.d/botblockd ${DESTDIR}${RCDIR}/botblockd
+	sed -i '' "s|%%PREFIX%%|${PREFIX}|g" ${DESTDIR}${RCDIR}/botblockd
+.for f in ${EXAMPLE_FILES}
+	${INSTALL} -m 644 ${CONFDIR}/${f} ${DESTDIR}${EXAMPLESDIR}/${f}
+.endfor
+
+.include <bsd.prog.mk>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/botblockd.h	Mon Oct 26 11:29:10 2026 +0100
@@ -0,0 +1,80 @@
+/*
+ * Copyright (c) 2026 Arkadiusz Juszczyk <ark@wobblyhead.net>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#ifndef BOTBLOCKD_H
+#define BOTBLOCKD_H
+
+#include <sys/types.h>
+#include <signal.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <time.h>
+
+/* ---- compile-time paths and constants (PREFIX from the Makefile) ---- */
+
+#define DEF_CONF            PREFIX "/etc/botblockd/conf"
+#define DEF_PIDFILE         "/var/run/botblockd.pid"
+#define PF_TABLE            "botblock"
+#define NSTATUS             1000    /* HTTP status codes are 0..999 */
+
+/* ---- shared configuration ---- */
+
+struct config {
+    int     inspect_secs;
+    int     inspect_count;
+    int     min_errors;
+    int     cooldown_secs;
+    int     block_secs;
+    char    input_log[512];
+    char    whitelist[512];
+    bool    status_is_err[NSTATUS]; /* true if the code counts as error */
+};
+
+extern struct config cfg;
+
+/* ---- config.c ---- */
+
+int            parse_config(const char *path, struct config *out);
+char          *read_entry(FILE *fp, char **line, size_t *cap, int *lineno);
+bool           status_is_error(int code);
+
+/* ---- ip.c ---- */
+
+int            parse_ipv4(const char *s, uint32_t *out);
+int            parse_cidr(const char *s, uint32_t *net, uint32_t *mask);
+const char    *ip_str(uint32_t ip);
+
+/* ---- whitelist.c ---- */
+
+int            load_whitelist(const char *path);
+bool           is_whitelisted(uint32_t ip);
+
+/* ---- pf.c ---- */
+
+int            pf_block(uint32_t ip);
+int            pf_unblock(uint32_t ip);
+int            pf_show(bool quiet);
+int            pf_flush(void);
+
+/* ---- suspect.c ---- */
+
+void           process_request(uint32_t ip, int status);
+void           sweep(void);
+
+/* ---- logtail.c ---- */
+
+int            tail_open(void);
+int            tail_log(void);
+
+/* ---- main.c ---- */
+
+extern volatile sig_atomic_t running;
+extern volatile sig_atomic_t reload_pending;
+void           config_reload(void);
+time_t         monotime(void);
+
+#endif /* BOTBLOCKD_H */
--- /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);
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/ip.c	Mon Oct 26 11:29:10 2026 +0100
@@ -0,0 +1,115 @@
+/*
+ * Copyright (c) 2026 Arkadiusz Juszczyk <ark@wobblyhead.net>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <sys/types.h>
+#include <sys/socket.h>
+
+#include <netinet/in.h>
+#include <arpa/inet.h>
+
+#include <errno.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "botblockd.h"
+
+/*
+ * parse_ipv4 - parse the first whitespace-delimited token as IPv4
+ *
+ * The token ends at end of string or at the first space, tab or
+ * newline.  Output is in network byte order, as inet_pton(3) gives it.
+ *
+ * Parameters:
+ *   s   - start of string (not modified)
+ *   out - output for parsed IP (network byte order)
+ *
+ * Returns: 0 on success, -1 if token is empty, too long, or invalid
+ */
+int
+parse_ipv4(const char *s, uint32_t *out)
+{
+    struct in_addr ia;
+    char buf[INET_ADDRSTRLEN];
+    size_t n;
+
+    n = strcspn(s, " \t\n");
+    if (n == 0 || n >= sizeof(buf))
+        return (-1);
+    memcpy(buf, s, n);
+    buf[n] = '\0';
+    if (inet_pton(AF_INET, buf, &ia) != 1)
+        return (-1);
+    *out = ia.s_addr;
+    return (0);
+}
+
+/*
+ * parse_cidr - parse "A.B.C.D" or "A.B.C.D/N" into network and mask
+ *
+ * A bare address is treated as a single host (/32).  A prefix length N
+ * must be 1..32: /0 would whitelist every address and is rejected as
+ * too wide to be intentional.  Host bits below the prefix are accepted
+ * and masked off, so a non-canonical entry such as 10.0.0.5/24 is
+ * stored as the 10.0.0.0/24 network.  Outputs are network byte order.
+ *
+ * Parameters:
+ *   s    - entry text (a whole whitelist line, no surrounding space)
+ *   net  - output: network address with host bits cleared
+ *   mask - output: netmask
+ *
+ * Returns: 0 on success, -1 on a malformed address or prefix
+ */
+int
+parse_cidr(const char *s, uint32_t *net, uint32_t *mask)
+{
+    struct in_addr ia;
+    char buf[INET_ADDRSTRLEN + 3];      /* address, "/" and 2 digits */
+    char *endp, *slash;
+    long prefix;
+
+    if (strlcpy(buf, s, sizeof(buf)) >= sizeof(buf))
+        return (-1);
+    prefix = 32;
+    slash = strchr(buf, '/');
+    if (slash != NULL) {
+        *slash = '\0';
+        errno = 0;
+        prefix = strtol(slash + 1, &endp, 10);
+        if (endp == slash + 1 || *endp != '\0' || errno != 0 ||
+            prefix < 1 || prefix > 32)
+            return (-1);
+    }
+    if (inet_pton(AF_INET, buf, &ia) != 1)
+        return (-1);
+
+    /* prefix is 1..32, so the shift is 0..31 and defined */
+    *mask = htonl(0xffffffffu << (32 - prefix));
+    *net = ia.s_addr & *mask;
+    return (0);
+}
+
+/*
+ * ip_str - format an IP (network byte order) as dotted-quad text
+ *
+ * The text is kept in a static buffer that the next call overwrites.
+ *
+ * Parameters:
+ *   ip - IPv4 address (network byte order)
+ *
+ * Returns: the text, or "?" if the address cannot be formatted
+ */
+const char *
+ip_str(uint32_t ip)
+{
+    static char buf[INET_ADDRSTRLEN];
+    struct in_addr ia;
+
+    ia.s_addr = ip;
+    if (inet_ntop(AF_INET, &ia, buf, sizeof(buf)) == NULL)
+        return ("?");
+    return (buf);
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/logtail.c	Mon Oct 26 11:29:10 2026 +0100
@@ -0,0 +1,369 @@
+/*
+ * Copyright (c) 2026 Arkadiusz Juszczyk <ark@wobblyhead.net>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <sys/param.h>
+#include <sys/event.h>
+#include <sys/stat.h>
+
+#include <errno.h>
+#include <fcntl.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+#include <syslog.h>
+#include <time.h>
+#include <unistd.h>
+
+#include "botblockd.h"
+
+/*
+ * Two arrangements of the standard nginx combined log are accepted on
+ * the same input file:
+ *
+ *   raw combined, IP at offset 0:
+ *     <ip> - <user> [<time>] "<req>" <status> <bytes> "<ref>" "<ua>"
+ *
+ *   syslog-aggregate combined, with a BSD-syslog header prepended by
+ *   the host syslogd ahead of the original combined line:
+ *     <mon> <day> <hh:mm:ss> <host> <tag>: <ip> - - [<time>] "<req>" ...
+ *
+ * parse_line tries the IP at offset 0 first; on failure it tries once
+ * more right after the first ": ", which ends the syslog header.  Both
+ * formats yield the same (ip, status) extraction.  Unrelated lines
+ * that share the file (newsyslog rotation markers, other facilities)
+ * lack a parseable IPv4 at either position and drop out without
+ * touching counters.  Text further into a line is never searched for
+ * an address, since other programs may log text chosen by a client.
+ */
+
+/*
+ * The log is tracked by the file it refers to, not by name.  Once a
+ * second, the file INPUT_LOG names is compared with the file being read.
+ * When it names a different file (rotation), the rest of the current
+ * file is read and the new one is read from its start.  Lines written
+ * to the old file after that are not seen.  While INPUT_LOG cannot be
+ * accessed, the current file is still read.
+ */
+
+static int      log_fd = -1;
+static bool     path_missing;   /* INPUT_LOG could not be accessed */
+static size_t   line_len;       /* bytes held in linebuf */
+static char     linebuf[8192];  /* partial line carried across reads */
+static char     readbuf[65536];
+static int      kq = -1;
+
+/*
+ * parse_line - extract IP and status from a combined-log line
+ *
+ * Parameters:
+ *   line       - input log line (not modified)
+ *   ip_out     - output for parsed IP (network byte order)
+ *   status_out - output pointer for HTTP status code
+ *
+ * Returns: 0 on success, -1 if line cannot be parsed
+ */
+static int
+parse_line(const char *line, uint32_t *ip_out, int *status_out)
+{
+    const char *p, *q;
+    char *endp;
+    long st;
+
+    p = line;
+    if (parse_ipv4(p, ip_out) != 0) {
+        p = strstr(line, ": ");
+        if (p == NULL)
+            return (-1);
+        p += 2;
+        if (parse_ipv4(p, ip_out) != 0)
+            return (-1);
+    }
+
+    /* status: find closing quote of request, then read number */
+    q = strchr(p, '"');
+    if (q == NULL)
+        return (-1);
+    q = strchr(q + 1, '"');
+    if (q == NULL)
+        return (-1);
+    q++;
+    while (*q == ' ')
+        q++;
+    st = strtol(q, &endp, 10);
+    if (endp == q || st < 0 || st >= NSTATUS ||
+        (*endp != ' ' && *endp != '\n' && *endp != '\0'))
+        return (-1);
+    *status_out = (int)st;
+    return (0);
+}
+
+/*
+ * feed - split read data into lines and process each complete line
+ *
+ * A line longer than the buffer is cut; the fields parse_line needs
+ * come first, so the rest is dropped.
+ *
+ * Parameters:
+ *   p - data
+ *   n - length of data
+ */
+static void
+feed(const char *p, size_t n)
+{
+    uint32_t ip;
+    int status;
+    size_t i;
+
+    for (i = 0; i < n; i++) {
+        if (line_len < sizeof(linebuf) - 1)
+            linebuf[line_len++] = p[i];
+        if (p[i] != '\n')
+            continue;
+        linebuf[line_len] = '\0';
+        line_len = 0;
+        if (parse_line(linebuf, &ip, &status) == 0)
+            process_request(ip, status);
+    }
+}
+
+/*
+ * drain - read and process what has been appended to the log
+ */
+static void
+drain(void)
+{
+    ssize_t r;
+
+    while ((r = read(log_fd, readbuf, sizeof(readbuf))) > 0)
+        feed(readbuf, (size_t)r);
+}
+
+/*
+ * watch - register a log file descriptor with the kqueue
+ *
+ * Writes to the file wake the loop to read.
+ *
+ * Parameters:
+ *   fd - open log file
+ *
+ * Returns: 0 on success, -1 on failure (logged)
+ */
+static int
+watch(int fd)
+{
+    struct kevent ev;
+
+    EV_SET(&ev, fd, EVFILT_VNODE, EV_ADD | EV_CLEAR,
+        NOTE_WRITE | NOTE_EXTEND, 0, NULL);
+    if (kevent(kq, &ev, 1, NULL, 0, NULL) < 0) {
+        syslog(LOG_ERR, "kevent add: %s", strerror(errno));
+        return (-1);
+    }
+    return (0);
+}
+
+/*
+ * open_log - open INPUT_LOG for reading
+ *
+ * Parameters:
+ *   at_end - true to skip the existing content
+ *
+ * Returns: file descriptor, or -1 with errno set
+ */
+static int
+open_log(bool at_end)
+{
+    int fd, saved;
+
+    fd = open(cfg.input_log, O_RDONLY | O_CLOEXEC);
+    if (fd < 0)
+        return (-1);
+    if (at_end && lseek(fd, 0, SEEK_END) < 0) {
+        saved = errno;
+        close(fd);
+        errno = saved;
+        return (-1);
+    }
+    return (fd);
+}
+
+/*
+ * path_gone - note that INPUT_LOG cannot be accessed
+ *
+ * Logs a warning only the first time, so a lasting problem is logged
+ * once.
+ *
+ * Returns: 0, for check_path to pass on
+ */
+static int
+path_gone(void)
+{
+    if (!path_missing)
+        syslog(LOG_WARNING, "cannot access %s: %s", cfg.input_log,
+            strerror(errno));
+    path_missing = true;
+    return (0);
+}
+
+/*
+ * check_path - follow rotation and truncation of the log
+ *
+ * If INPUT_LOG names the file being read and that file has shrunk
+ * below the read position (truncated in place), reading restarts from
+ * its beginning.  If INPUT_LOG names a different file, the rest of the
+ * current file is read, then the new file becomes current and is read
+ * from its start.  If INPUT_LOG cannot be accessed, a warning is
+ * logged once and the current file stays in use.
+ *
+ * Returns: 0 on success, -1 on a fatal error (logged)
+ */
+static int
+check_path(void)
+{
+    struct stat sf, sp;
+    int fd;
+
+    if (stat(cfg.input_log, &sp) != 0)
+        return (path_gone());
+    if (path_missing)
+        syslog(LOG_NOTICE, "%s is available again", cfg.input_log);
+    path_missing = false;
+
+    if (fstat(log_fd, &sf) != 0) {
+        syslog(LOG_ERR, "fstat %s: %s", cfg.input_log,
+            strerror(errno));
+        return (-1);
+    }
+
+    /* same file: only check for truncation */
+    if (sp.st_dev == sf.st_dev && sp.st_ino == sf.st_ino) {
+        if (lseek(log_fd, 0, SEEK_CUR) > sf.st_size) {
+            syslog(LOG_NOTICE, "%s truncated, reading from start",
+                cfg.input_log);
+            lseek(log_fd, 0, SEEK_SET);
+            line_len = 0;
+            drain();
+        }
+        return (0);
+    }
+
+    fd = open_log(false);
+    if (fd < 0)
+        return (path_gone());
+    if (watch(fd) != 0) {
+        close(fd);
+        return (-1);
+    }
+    drain();
+    close(log_fd);              /* also removes its kqueue watch */
+    log_fd = fd;
+    line_len = 0;
+    syslog(LOG_INFO, "%s rotated, reading new file", cfg.input_log);
+
+    /* lines written before the watch was set raise no event */
+    drain();
+    return (0);
+}
+
+/*
+ * tail_open - open the configured log, positioned at its end
+ *
+ * Called before the daemon detaches, so a wrong INPUT_LOG fails the
+ * start with an exit status, and by the check verb.
+ *
+ * Returns: 0 on success, -1 on failure (logged)
+ */
+int
+tail_open(void)
+{
+    log_fd = open_log(true);
+    if (log_fd < 0) {
+        syslog(LOG_ERR, "cannot open %s: %s", cfg.input_log,
+            strerror(errno));
+        return (-1);
+    }
+    line_len = 0;
+    return (0);
+}
+
+/*
+ * tail_log - main event loop: follow the log and run the sweep
+ *
+ * Needs a log opened by tail_open.  Sleeps in kevent until the log is
+ * written to, or for at most a second.  Every wakeup reads the log;
+ * once a second INPUT_LOG is checked for rotation and truncation.
+ *
+ * The sweep runs at most once per sweep interval: half of
+ * inspect_secs, but between 1 and 10 seconds, so the cost of the
+ * suspect walk stays bounded regardless of log activity.
+ *
+ * A SIGHUP reloads the configuration.  SIGTERM and SIGINT interrupt
+ * kevent, so the loop ends promptly.
+ *
+ * Returns: 0 on shutdown by signal, -1 on a fatal error (logged)
+ */
+int
+tail_log(void)
+{
+    const struct timespec timeout = { .tv_sec = 1 };
+    struct kevent ev;
+    time_t now, last_sweep_at, last_check_at;
+    int rc, sweep_interval;
+
+    rc = -1;
+    kq = kqueue();
+    if (kq < 0) {
+        syslog(LOG_ERR, "kqueue: %s", strerror(errno));
+        goto out;
+    }
+    if (watch(log_fd) != 0)
+        goto out;
+    syslog(LOG_INFO, "reading logfile %s", cfg.input_log);
+
+    rc = 0;
+    last_sweep_at = 0;
+    last_check_at = 0;
+
+    while (running) {
+        if (reload_pending) {
+            reload_pending = 0;
+            config_reload();
+        }
+
+        if (kevent(kq, NULL, 0, &ev, 1, &timeout) < 0) {
+            if (errno == EINTR)
+                continue;
+            syslog(LOG_ERR, "kevent wait: %s", strerror(errno));
+            rc = -1;
+            break;
+        }
+
+        drain();
+
+        now = monotime();
+        if (now != last_check_at) {
+            last_check_at = now;
+            if (check_path() != 0) {
+                rc = -1;
+                break;
+            }
+        }
+
+        /* recompute each pass so a reload takes effect */
+        sweep_interval = MAX(1, MIN(10, cfg.inspect_secs / 2));
+        if (now - last_sweep_at >= sweep_interval) {
+            sweep();
+            last_sweep_at = now;
+        }
+    }
+
+out:
+    if (log_fd >= 0)
+        close(log_fd);
+    if (kq >= 0)
+        close(kq);
+    return (rc);
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/main.c	Mon Oct 26 11:29:10 2026 +0100
@@ -0,0 +1,428 @@
+/*
+ * Copyright (c) 2026 Arkadiusz Juszczyk <ark@wobblyhead.net>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <sys/types.h>
+
+#include <errno.h>
+#include <libutil.h>
+#include <signal.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <syslog.h>
+#include <time.h>
+#include <unistd.h>
+
+#include "botblockd.h"
+
+volatile sig_atomic_t running = 1;
+volatile sig_atomic_t reload_pending;
+
+static const char *conf_path = DEF_CONF;
+static const char *pid_path = DEF_PIDFILE;
+
+/*
+ * usage - print the command summary
+ *
+ * Parameters:
+ *   fp - stream to print to (stdout for help, stderr for errors)
+ */
+static void
+usage(FILE *fp)
+{
+    fprintf(fp,
+        "usage: botblockd run [-f] [-c config] [-p pidfile]\n"
+        "       botblockd check [-c config]\n"
+        "       botblockd list\n"
+        "       botblockd unblock <address>... | -a\n"
+        "       botblockd help\n");
+}
+
+/*
+ * monotime - current time in whole seconds since boot
+ *
+ * Unaffected by changes to the wall clock, so durations stay correct
+ * across clock steps.
+ *
+ * Returns: seconds of CLOCK_MONOTONIC
+ */
+time_t
+monotime(void)
+{
+    struct timespec ts;
+
+    clock_gettime(CLOCK_MONOTONIC, &ts);
+    return (ts.tv_sec);
+}
+
+/*
+ * config_load - read configuration and whitelist, then apply them
+ *
+ * The configuration is parsed into a local copy, starting from the
+ * compiled-in defaults, so a key removed since the last load reverts
+ * to its default.  cfg and the whitelist are replaced only when both
+ * have been read without error.  On a reload, a changed INPUT_LOG is
+ * an error: following a different log needs a restart.
+ *
+ * Parameters:
+ *   reload - true for a SIGHUP reload, false at startup and for check
+ *
+ * Returns: 0 on success, -1 on failure (logged); on failure cfg and
+ *   the whitelist are unchanged
+ */
+static int
+config_load(bool reload)
+{
+    struct config c;
+
+    if (parse_config(conf_path, &c) != 0)
+        return (-1);
+    if (reload && strcmp(c.input_log, cfg.input_log) != 0) {
+        syslog(LOG_ERR, "config: INPUT_LOG changed to %s, a restart "
+            "is needed to apply it", c.input_log);
+        return (-1);
+    }
+    if (load_whitelist(c.whitelist) != 0)
+        return (-1);
+    cfg = c;
+    return (0);
+}
+
+/*
+ * config_reload - re-read configuration and whitelist
+ *
+ * Invoked from the event loop when a SIGHUP has been latched, off the
+ * signal path so file and syslog calls stay async-signal-safe.  If the
+ * reload fails, the previous configuration and whitelist stay in
+ * effect.
+ */
+void
+config_reload(void)
+{
+    if (config_load(true) != 0) {
+        syslog(LOG_ERR, "config reload failed, previous configuration "
+            "stays in effect");
+        return;
+    }
+    syslog(LOG_NOTICE, "config reloaded (SIGHUP)");
+}
+
+/*
+ * sighandler - latch shutdown and reload requests
+ *
+ * SIGTERM/SIGINT request graceful shutdown; SIGHUP requests a config
+ * reload.  Only sets sig_atomic_t flags; the actual work happens in
+ * the event loop.
+ *
+ * Parameters:
+ *   sig - signal number
+ */
+static void
+sighandler(int sig)
+{
+    switch (sig) {
+    case SIGTERM:
+    case SIGINT:
+        running = 0;
+        break;
+    case SIGHUP:
+        reload_pending = 1;
+        break;
+    }
+}
+
+/*
+ * install_signals - wire up the daemon signal handlers
+ */
+static void
+install_signals(void)
+{
+    struct sigaction sa;
+
+    sigemptyset(&sa.sa_mask);
+    sa.sa_flags = 0;
+    sa.sa_handler = sighandler;
+    sigaction(SIGTERM, &sa, NULL);
+    sigaction(SIGINT, &sa, NULL);
+    sigaction(SIGHUP, &sa, NULL);
+    sa.sa_handler = SIG_IGN;
+    sigaction(SIGPIPE, &sa, NULL);
+}
+
+/*
+ * cmd_run - run the daemon
+ *
+ * Everything that can fail at startup (configuration, whitelist, input
+ * log, a second instance, the pf table) is checked before detaching
+ * via daemon(3), so the exit status reports it.  -f keeps the daemon
+ * in the foreground.  The pf table is flushed at startup, as entries
+ * left by an earlier unclean exit have no record here and would never
+ * expire, and again on exit.
+ *
+ * Parameters:
+ *   argc, argv - verb-relative arguments (argv[0] is "run")
+ *
+ * Returns: 0 on shutdown by signal, 1 on any failure
+ */
+static int
+cmd_run(int argc, char *argv[])
+{
+    struct pidfh *pfh;
+    pid_t otherpid;
+    int ch, rc;
+    bool foreground = false;
+
+    while ((ch = getopt(argc, argv, "c:fp:")) != -1) {
+        switch (ch) {
+        case 'c':
+            conf_path = optarg;
+            break;
+        case 'f':
+            foreground = true;
+            break;
+        case 'p':
+            pid_path = optarg;
+            break;
+        default:
+            usage(stderr);
+            return (1);
+        }
+    }
+    if (optind != argc) {
+        usage(stderr);
+        return (1);
+    }
+
+    /* mirror to stderr only in the foreground; syslogd timestamps */
+    openlog("botblockd", LOG_PID | (foreground ? LOG_PERROR : 0),
+        LOG_DAEMON);
+    /* daemon(3) changes to /, so a reload needs an absolute path */
+    if (conf_path[0] != '/') {
+        syslog(LOG_ERR, "config path must be absolute: %s", conf_path);
+        return (1);
+    }
+    if (config_load(false) != 0)
+        return (1);
+    if (tail_open() != 0)
+        return (1);
+
+    pfh = pidfile_open(pid_path, 0600, &otherpid);
+    if (pfh == NULL) {
+        if (errno == EEXIST) {
+            syslog(LOG_ERR, "already running, pid %ld",
+                (long)otherpid);
+            return (1);
+        }
+        syslog(LOG_WARNING, "cannot open pidfile %s: %s",
+            pid_path, strerror(errno));
+    }
+
+    rc = 1;
+    if (pf_flush() != 0) {
+        syslog(LOG_ERR, "cannot flush pf table '%s'", PF_TABLE);
+        goto out;
+    }
+    if (!foreground && daemon(0, 0) == -1) {
+        syslog(LOG_ERR, "daemon: %s", strerror(errno));
+        goto out;
+    }
+    if (pfh != NULL)
+        pidfile_write(pfh);
+
+    install_signals();
+
+    syslog(LOG_NOTICE, "botblockd %s started", BOTBLOCKD_VERSION);
+    rc = (tail_log() == 0) ? 0 : 1;
+
+    syslog(LOG_NOTICE, "shutting down, flushing pf table");
+    if (pf_flush() != 0) {
+        syslog(LOG_ERR, "cannot flush pf table '%s'", PF_TABLE);
+        rc = 1;
+    }
+
+out:
+    if (pfh != NULL)
+        pidfile_remove(pfh);
+    return (rc);
+}
+
+/*
+ * cmd_check - validate configuration and exit
+ *
+ * Checks the configuration, the whitelist, the input log and the pf
+ * table.
+ *
+ * Parameters:
+ *   argc, argv - verb-relative arguments (argv[0] is "check")
+ *
+ * Returns: 0 on success, 1 on bad arguments or a failed check
+ */
+static int
+cmd_check(int argc, char *argv[])
+{
+    int ch;
+
+    while ((ch = getopt(argc, argv, "c:")) != -1) {
+        switch (ch) {
+        case 'c':
+            conf_path = optarg;
+            break;
+        default:
+            usage(stderr);
+            return (1);
+        }
+    }
+    if (optind != argc) {
+        usage(stderr);
+        return (1);
+    }
+
+    openlog("botblockd", LOG_PID | LOG_PERROR, LOG_DAEMON);
+    if (config_load(false) != 0)
+        return (1);
+    if (tail_open() != 0)
+        return (1);
+    if (pf_show(true) != 0) {
+        syslog(LOG_ERR, "pf table '%s' unavailable; ensure pf is "
+            "enabled and the table is defined in pf.conf", PF_TABLE);
+        return (1);
+    }
+    printf("config OK\n");
+    return (0);
+}
+
+/*
+ * cmd_list - print the current contents of the pf block table
+ *
+ * Parameters:
+ *   argc - verb-relative argument count, 1 as list takes no arguments
+ *
+ * Returns: 0 on success, 1 on bad arguments or failure
+ */
+static int
+cmd_list(int argc)
+{
+    if (argc != 1) {
+        usage(stderr);
+        return (1);
+    }
+    return (pf_show(false) == 0 ? 0 : 1);
+}
+
+/*
+ * cmd_unblock - remove addresses from the pf block table
+ *
+ * With -a, flushes the whole table; otherwise removes each address
+ * argument.  Operates directly on the pf table, so it does not need a
+ * running daemon.
+ *
+ * Parameters:
+ *   argc, argv - verb-relative arguments (argv[0] is "unblock")
+ *
+ * Returns: 0 if all requested removals succeeded, 1 otherwise
+ */
+static int
+cmd_unblock(int argc, char *argv[])
+{
+    uint32_t ip;
+    int ch, i, rc = 0;
+    bool all = false;
+
+    while ((ch = getopt(argc, argv, "a")) != -1) {
+        switch (ch) {
+        case 'a':
+            all = true;
+            break;
+        default:
+            usage(stderr);
+            return (1);
+        }
+    }
+    argc -= optind;
+    argv += optind;
+
+    if (all) {
+        if (argc > 0) {
+            fprintf(stderr, "unblock: -a takes no addresses\n");
+            return (1);
+        }
+        if (pf_flush() != 0) {
+            fprintf(stderr, "unblock: failed to flush table\n");
+            return (1);
+        }
+        printf("all entries cleared\n");
+        return (0);
+    }
+
+    if (argc == 0) {
+        usage(stderr);
+        return (1);
+    }
+
+    for (i = 0; i < argc; i++) {
+        if (parse_ipv4(argv[i], &ip) != 0) {
+            fprintf(stderr, "unblock: invalid address '%s'\n",
+                argv[i]);
+            rc = 1;
+            continue;
+        }
+        if (pf_unblock(ip) != 0) {
+            fprintf(stderr, "unblock: failed to remove %s\n",
+                argv[i]);
+            rc = 1;
+            continue;
+        }
+        printf("removed %s\n", ip_str(ip));
+    }
+    return (rc);
+}
+
+/*
+ * main - botblockd: block web clients that cause HTTP errors, using pf
+ *
+ * botblockd follows an nginx access log, counts error responses per
+ * source address and adds persistent offenders to a pf table.  The
+ * first argument selects the command; the remaining arguments are
+ * parsed by the command.  Running the daemon is explicit (the "run"
+ * command), since the rc script is the usual caller.
+ *
+ * Parameters:
+ *   argc, argv - command line
+ *
+ * Returns: exit status of the command, 1 for a missing or unknown
+ *   command
+ */
+int
+main(int argc, char *argv[])
+{
+    const char *verb;
+
+    if (argc < 2) {
+        usage(stderr);
+        return (1);
+    }
+    verb = argv[1];
+
+    if (strcmp(verb, "run") == 0)
+        return (cmd_run(argc - 1, argv + 1));
+    if (strcmp(verb, "check") == 0)
+        return (cmd_check(argc - 1, argv + 1));
+    if (strcmp(verb, "list") == 0)
+        return (cmd_list(argc - 1));
+    if (strcmp(verb, "unblock") == 0)
+        return (cmd_unblock(argc - 1, argv + 1));
+    if (strcmp(verb, "help") == 0 || strcmp(verb, "-h") == 0 ||
+        strcmp(verb, "--help") == 0) {
+        printf("botblockd %s\n", BOTBLOCKD_VERSION);
+        usage(stdout);
+        return (0);
+    }
+
+    fprintf(stderr, "botblockd: unknown command '%s'\n", verb);
+    usage(stderr);
+    return (1);
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/pf.c	Mon Oct 26 11:29:10 2026 +0100
@@ -0,0 +1,201 @@
+/*
+ * Copyright (c) 2026 Arkadiusz Juszczyk <ark@wobblyhead.net>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <sys/types.h>
+#include <sys/wait.h>
+
+#include <errno.h>
+#include <fcntl.h>
+#include <signal.h>
+#include <spawn.h>
+#include <stdint.h>
+#include <string.h>
+#include <syslog.h>
+#include <unistd.h>
+
+#include "botblockd.h"
+
+#define PFCTL_PATH  "/sbin/pfctl"
+
+extern char **environ;
+
+/*
+ * pfctl - run pfctl with the given arguments, report success
+ *
+ * pfctl is started directly, without a shell, and inherits our
+ * environment, stdin, stdout and stderr, so -T show output reaches the
+ * terminal for the list verb.  All signals are reset to their default
+ * action and unblocked in the child, so the SIGPIPE we ignore does not
+ * carry over.
+ *
+ * Parameters:
+ *   argv    - NULL-terminated argument vector, argv[0] is "pfctl"
+ *   discard - true to send pfctl's stdout to /dev/null, stderr is kept
+ *
+ * Returns: 0 if pfctl ran and exited with status 0, -1 otherwise
+ */
+static int
+pfctl(const char *argv[], bool discard)
+{
+    posix_spawn_file_actions_t fa;
+    posix_spawnattr_t attr;
+    sigset_t sigs;
+    pid_t pid;
+    int err, status;
+
+    posix_spawn_file_actions_init(&fa);
+    if (discard)
+        posix_spawn_file_actions_addopen(&fa, STDOUT_FILENO,
+            "/dev/null", O_WRONLY, 0);
+    posix_spawnattr_init(&attr);
+    posix_spawnattr_setflags(&attr,
+        POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK);
+    sigfillset(&sigs);
+    posix_spawnattr_setsigdefault(&attr, &sigs);
+    sigemptyset(&sigs);
+    posix_spawnattr_setsigmask(&attr, &sigs);
+
+    err = posix_spawn(&pid, PFCTL_PATH, &fa, &attr,
+        __DECONST(char **, argv), environ);
+    posix_spawnattr_destroy(&attr);
+    posix_spawn_file_actions_destroy(&fa);
+    if (err != 0) {
+        syslog(LOG_ERR, "cannot run %s: %s", PFCTL_PATH, strerror(err));
+        return (-1);
+    }
+
+    /* a signal arriving while pfctl runs must not abandon the child */
+    while (waitpid(pid, &status, 0) == -1) {
+        if (errno != EINTR) {
+            syslog(LOG_ERR, "waitpid: %s", strerror(errno));
+            return (-1);
+        }
+    }
+    if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
+        return (-1);
+    return (0);
+}
+
+/*
+ * pf_table_op - run "pfctl -q -t <table> -T <op> [arg]", report success
+ *
+ * -q drops pfctl's "N addresses added/deleted" messages but keeps
+ * errors and the output of -T show.
+ *
+ * Parameters:
+ *   op      - pfctl table operation (add, delete, show, flush)
+ *   arg     - address argument, or NULL for whole-table operations
+ *   discard - true to send pfctl's stdout to /dev/null
+ *
+ * Returns: 0 on success, -1 on failure
+ */
+static int
+pf_table_op(const char *op, const char *arg, bool discard)
+{
+    /* a NULL arg ends the vector early */
+    const char *argv[] = {
+        "pfctl", "-q", "-t", PF_TABLE, "-T", op, arg, NULL
+    };
+
+    return (pfctl(argv, discard));
+}
+
+/*
+ * pf_kill_states - remove all pf states originating from an address
+ *
+ * The block rule only applies to packets without a state, so
+ * connections already established by the address would otherwise
+ * survive the block.  -q drops pfctl's "killed N states" message.
+ *
+ * Parameters:
+ *   ips - IPv4 address as a string
+ *
+ * Returns: 0 on success, -1 on failure
+ */
+static int
+pf_kill_states(const char *ips)
+{
+    const char *argv[] = { "pfctl", "-q", "-k", ips, NULL };
+
+    return (pfctl(argv, false));
+}
+
+/*
+ * pf_block - add an IP to the pf block table and cut its connections
+ *
+ * The address is added to the table before its states are killed, so
+ * it cannot open a new connection in between.  A failure to kill the
+ * states is logged but does not fail the block.
+ *
+ * Parameters:
+ *   ip - IPv4 address (network byte order)
+ *
+ * Returns: 0 on success, -1 on failure
+ */
+int
+pf_block(uint32_t ip)
+{
+    const char *ips = ip_str(ip);
+
+    if (pf_table_op("add", ips, false) != 0) {
+        syslog(LOG_ERR, "pf block failed for %s", ips);
+        return (-1);
+    }
+    if (pf_kill_states(ips) != 0)
+        syslog(LOG_WARNING, "cannot kill pf states for %s", ips);
+    syslog(LOG_NOTICE, "%s blocked", ips);
+    return (0);
+}
+
+/*
+ * pf_unblock - remove an IP from the pf block table
+ *
+ * Parameters:
+ *   ip - IPv4 address (network byte order)
+ *
+ * Returns: 0 on success, -1 on failure
+ */
+int
+pf_unblock(uint32_t ip)
+{
+    return (pf_table_op("delete", ip_str(ip), false));
+}
+
+/*
+ * pf_show - print the block table, or only check that it is available
+ *
+ * With quiet, the check verb catches a missing table up front rather
+ * than having the first block attempt fail at runtime.  stdout is
+ * discarded so the table's contents are not printed, but pfctl's
+ * stderr is kept so its diagnostic (a missing table, pf disabled, or a
+ * permission error) reaches the operator.
+ *
+ * Parameters:
+ *   quiet - true to check the table without printing it
+ *
+ * Returns: 0 if the table is present and readable, -1 otherwise
+ */
+int
+pf_show(bool quiet)
+{
+    return (pf_table_op("show", NULL, quiet));
+}
+
+/*
+ * pf_flush - remove every entry from the block table
+ *
+ * Used by the "unblock -a" CLI verb, and at daemon startup and
+ * shutdown to leave no blocks without a record behind.  Flushing the
+ * whole table is correct in all cases: botblockd owns the table, so
+ * any entry in it is one it placed.
+ *
+ * Returns: 0 on success, -1 on failure
+ */
+int
+pf_flush(void)
+{
+    return (pf_table_op("flush", NULL, false));
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/suspect.c	Mon Oct 26 11:29:10 2026 +0100
@@ -0,0 +1,256 @@
+/*
+ * Copyright (c) 2026 Arkadiusz Juszczyk <ark@wobblyhead.net>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <sys/types.h>
+#include <sys/tree.h>
+
+#include <inttypes.h>
+#include <stdlib.h>
+#include <syslog.h>
+#include <time.h>
+
+#include "botblockd.h"
+
+/*
+ * blocked_at carries three states together with is_blocked:
+ *  - is_blocked, blocked_at != 0: pf entry active since blocked_at
+ *  - !is_blocked, blocked_at != 0: probation (block expired but
+ *    counters and the suspect record persist for re-block evaluation)
+ *  - !is_blocked, blocked_at == 0: fresh suspect, never blocked
+ *
+ * Times are monotime() seconds, counted from boot.  No block can be
+ * placed within the first second of uptime, so 0 stays free as the
+ * never-blocked marker.
+ *
+ * Field order keeps the 4-byte and 1-byte fields together so the
+ * struct is 64 bytes on 64-bit platforms, a malloc(3) size class.
+ */
+struct suspect {
+    uint32_t        ip;            /* network byte order, RB key */
+    uint32_t        errors;        /* saturates at UINT32_MAX */
+    uint32_t        successes;     /* saturates at UINT32_MAX */
+    bool            is_blocked;
+    RB_ENTRY(suspect) entry;
+    time_t          first_seen_at;
+    time_t          last_error_at;
+    time_t          blocked_at;
+};
+
+RB_HEAD(suspect_tree, suspect);
+
+/*
+ * suspect_cmp - order two suspects by address, for the tree
+ *
+ * Parameters:
+ *   a, b - suspects to compare
+ *
+ * Returns: -1, 0 or 1 as a's address is below, equal to or above b's
+ */
+static int
+suspect_cmp(const struct suspect *a, const struct suspect *b)
+{
+    if (a->ip < b->ip)
+        return (-1);
+    if (a->ip > b->ip)
+        return (1);
+    return (0);
+}
+
+RB_GENERATE_STATIC(suspect_tree, suspect, entry, suspect_cmp);
+
+static struct suspect_tree suspects = RB_INITIALIZER(&suspects);
+
+/*
+ * suspect_drop - log why a suspect is forgotten, then remove it
+ *
+ * Parameters:
+ *   s      - suspect to remove and free
+ *   reason - log text after the address
+ */
+static void
+suspect_drop(struct suspect *s, const char *reason)
+{
+    syslog(LOG_INFO, "%s %s", ip_str(s->ip), reason);
+    RB_REMOVE(suspect_tree, &suspects, s);
+    free(s);
+}
+
+/*
+ * suspect_block - log a verdict and add the suspect to the pf table
+ *
+ * The suspect counts as blocked only if pf_block succeeds.  Otherwise
+ * it is left as it was, and the next sweep reaches the same verdict
+ * and tries again.
+ *
+ * Parameters:
+ *   s      - suspect to block
+ *   now    - current monotime()
+ *   reason - log text after the address
+ */
+static void
+suspect_block(struct suspect *s, time_t now, const char *reason)
+{
+    syslog(LOG_NOTICE, "%s %s (%" PRIu32 " err, %" PRIu32 " ok)",
+        ip_str(s->ip), reason, s->errors, s->successes);
+    if (pf_block(s->ip) != 0)
+        return;
+    s->is_blocked = true;
+    s->blocked_at = now;
+}
+
+/*
+ * process_request - fold one parsed log request into the suspect pool
+ *
+ * Pure counter update.  Whitelisted sources are dropped up front so the
+ * pool stays clean of them.  Error status: ensure a suspect entry exists,
+ * then increment errors and refresh last_error_at.  Non-error status:
+ * increment successes only if the IP is already a suspect; good traffic
+ * alone never enters the pool.
+ *
+ * Parameters:
+ *   ip     - source address (network byte order)
+ *   status - HTTP status code
+ */
+void
+process_request(uint32_t ip, int status)
+{
+    struct suspect key, *s;
+    time_t now;
+
+    if (is_whitelisted(ip))
+        return;
+
+    now = monotime();
+
+    key.ip = ip;
+    s = RB_FIND(suspect_tree, &suspects, &key);
+
+    if (status_is_error(status)) {
+        if (s == NULL) {
+            s = calloc(1, sizeof(*s));
+            if (s == NULL)
+                return;
+            s->ip = ip;
+            s->first_seen_at = now;
+            RB_INSERT(suspect_tree, &suspects, s);
+            syslog(LOG_INFO, "%s suspect (%d)", ip_str(s->ip), status);
+        }
+        if (s->errors < UINT32_MAX)
+            s->errors++;
+        s->last_error_at = now;
+    } else if (s != NULL && s->successes < UINT32_MAX) {
+        s->successes++;
+    }
+}
+
+/*
+ * sweep - evaluate every suspect entry and apply state transitions
+ *
+ * All block/unblock/cleanup decisions happen here; the per-line path
+ * does pure counter updates.  Per suspect, takes one of:
+ *  - drop on whitelist hit (unblocking first if needed),
+ *  - lift block once block_secs has elapsed (probation start, record
+ *    kept, counters intact),
+ *  - on probation: re-block on new errors with bad balance, else drop
+ *    once block_secs + cooldown_secs has elapsed,
+ *  - fresh: drop if no errors for cooldown_secs, else apply the
+ *    inspection-window verdict.
+ *
+ * Counter preservation across block boundaries is intentional: a
+ * heavily-bad balance cannot be flipped by silence alone, only by
+ * actual successful traffic during probation.
+ */
+void
+sweep(void)
+{
+    struct suspect *s, *next_s;
+    time_t now;
+
+    now = monotime();
+
+    /*
+     * Each suspect falls into exactly one of four cases, tested in
+     * priority order; every case ends in continue so the cascade does
+     * not fall through.  The order matters: a whitelist hit wins over
+     * any block state, and an active block is handled before the
+     * probation and fresh-suspect cases that key off blocked_at.
+     */
+    RB_FOREACH_SAFE(s, suspect_tree, &suspects, next_s) {
+        /*
+         * Case 1: became whitelisted after entering the pool (added to
+         * the whitelist file and reloaded).  Lift any live block so no
+         * stale pf entry is left behind, then forget the suspect.
+         */
+        if (is_whitelisted(s->ip)) {
+            if (s->is_blocked && pf_unblock(s->ip) != 0)
+                syslog(LOG_WARNING, "cannot unblock %s",
+                    ip_str(s->ip));
+            suspect_drop(s, "cleared whitelisted");
+            continue;
+        }
+
+        /*
+         * Case 2: currently blocked.  Hold the pf entry until
+         * block_secs has elapsed, then lift it into probation -- the
+         * record and counters are kept so a repeat offender is caught
+         * by case 3 rather than starting over as a fresh suspect.
+         */
+        if (s->is_blocked) {
+            if (now - s->blocked_at > cfg.block_secs) {
+                if (pf_unblock(s->ip) != 0)
+                    syslog(LOG_WARNING, "cannot unblock %s",
+                        ip_str(s->ip));
+                s->is_blocked = false;
+                syslog(LOG_NOTICE, "%s probation start",
+                    ip_str(s->ip));
+            }
+            continue;
+        }
+
+        /*
+         * Case 3: probation -- block already lifted, record retained.
+         * Re-block at once if the IP has errored again since the block
+         * was placed and its balance is still bad; otherwise forget it
+         * once a full block_secs + cooldown_secs has passed clean.
+         */
+        if (s->blocked_at != 0) {
+            if (s->last_error_at > s->blocked_at &&
+                s->errors > s->successes)
+                suspect_block(s, now, "probation violation");
+            else if (now - s->blocked_at >
+                (time_t)cfg.block_secs + cfg.cooldown_secs)
+                suspect_drop(s, "cleared probation");
+            continue;
+        }
+
+        /*
+         * Case 4: fresh suspect, never blocked (blocked_at == 0).
+         * First, forget it if it has gone quiet for cooldown_secs --
+         * a stray error that never recurred.
+         */
+        if (now - s->last_error_at > cfg.cooldown_secs) {
+            suspect_drop(s, "cleared cooldown");
+            continue;
+        }
+
+        /*
+         * Otherwise, once the inspection window closes -- by elapsed
+         * time or by request count, whichever comes first -- render a
+         * verdict: block if errors reached min_errors and outnumber
+         * successes.  The window is not restarted: once it has closed,
+         * the counters keep accumulating and the suspect is judged
+         * again at every sweep until it is blocked or goes quiet for
+         * cooldown_secs.
+         */
+        if (now - s->first_seen_at > cfg.inspect_secs ||
+            (uint64_t)s->errors + s->successes >=
+                (uint64_t)cfg.inspect_count) {
+            if (s->errors >= (uint32_t)cfg.min_errors &&
+                s->errors > s->successes)
+                suspect_block(s, now, "window verdict");
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/whitelist.c	Mon Oct 26 11:29:10 2026 +0100
@@ -0,0 +1,139 @@
+/*
+ * Copyright (c) 2026 Arkadiusz Juszczyk <ark@wobblyhead.net>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <sys/types.h>
+#include <sys/queue.h>
+
+#include <errno.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <syslog.h>
+
+#include "botblockd.h"
+
+struct wl {
+    SLIST_ENTRY(wl) next;
+    uint32_t        net;           /* network address, network order */
+    uint32_t        mask;          /* netmask, network order */
+};
+
+SLIST_HEAD(wl_head, wl);
+static struct wl_head wl = SLIST_HEAD_INITIALIZER(wl);
+
+/*
+ * free_list - free all entries of a whitelist
+ *
+ * Parameters:
+ *   head - list to empty
+ */
+static void
+free_list(struct wl_head *head)
+{
+    struct wl *e;
+
+    while ((e = SLIST_FIRST(head)) != NULL) {
+        SLIST_REMOVE_HEAD(head, next);
+        free(e);
+    }
+}
+
+/*
+ * load_whitelist - read a whitelist file and replace the current list
+ *
+ * The file is read into a new list; the current list is replaced only
+ * if the whole file is read without error, otherwise it stays in use.
+ * Each entry is an IPv4 address or CIDR subnet (see parse_cidr).  Blank
+ * lines and lines whose first non-blank character is '#' are skipped.
+ * An entry that fails to parse fails the load, mirroring the strict
+ * config parser: an operator typo must not be silently dropped.  A
+ * missing file is not an error and gives an empty whitelist.
+ *
+ * Parameters:
+ *   path - whitelist file
+ *
+ * Returns: 0 on success, -1 on an unreadable file or invalid entry
+ */
+int
+load_whitelist(const char *path)
+{
+    struct wl_head nwl = SLIST_HEAD_INITIALIZER(nwl);
+    struct wl *e;
+    FILE *fp;
+    size_t cap = 0;
+    char *entry, *line = NULL;
+    uint32_t mask, net;
+    int count = 0, lineno = 0, rc = 0;
+
+    fp = fopen(path, "r");
+    if (fp == NULL) {
+        if (errno != ENOENT) {
+            syslog(LOG_ERR, "cannot open whitelist %s: %s",
+                path, strerror(errno));
+            return (-1);
+        }
+        syslog(LOG_NOTICE, "no whitelist at %s", path);
+        free_list(&wl);
+        return (0);
+    }
+
+    while ((entry = read_entry(fp, &line, &cap, &lineno)) != NULL) {
+        if (parse_cidr(entry, &net, &mask) != 0) {
+            syslog(LOG_ERR, "whitelist: invalid entry '%s' on line %d",
+                entry, lineno);
+            rc = -1;
+            break;
+        }
+        e = malloc(sizeof(*e));
+        if (e == NULL) {
+            syslog(LOG_ERR, "whitelist: out of memory");
+            rc = -1;
+            break;
+        }
+        e->net = net;
+        e->mask = mask;
+        SLIST_INSERT_HEAD(&nwl, e, next);
+        count++;
+    }
+    if (rc == 0 && ferror(fp)) {
+        syslog(LOG_ERR, "cannot read whitelist %s", path);
+        rc = -1;
+    }
+    free(line);
+    fclose(fp);
+    if (rc != 0) {
+        free_list(&nwl);
+        return (rc);
+    }
+
+    free_list(&wl);
+    SLIST_SWAP(&wl, &nwl, wl);
+    syslog(LOG_INFO, "loaded %d whitelist entries", count);
+    return (0);
+}
+
+/*
+ * is_whitelisted - report whether an IP is exempt from blocking
+ *
+ * Matches the entries of the whitelist file (host or CIDR subnet).
+ *
+ * Parameters:
+ *   ip - IPv4 address (network byte order)
+ *
+ * Returns: true if whitelisted, false otherwise
+ */
+bool
+is_whitelisted(uint32_t ip)
+{
+    struct wl *e;
+
+    SLIST_FOREACH(e, &wl, next) {
+        if ((ip & e->mask) == e->net)
+            return (true);
+    }
+    return (false);
+}