comparison src/main.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/types.h>
8
9 #include <errno.h>
10 #include <libutil.h>
11 #include <signal.h>
12 #include <stdint.h>
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <string.h>
16 #include <syslog.h>
17 #include <time.h>
18 #include <unistd.h>
19
20 #include "botblockd.h"
21
22 volatile sig_atomic_t running = 1;
23 volatile sig_atomic_t reload_pending;
24
25 static const char *conf_path = DEF_CONF;
26 static const char *pid_path = DEF_PIDFILE;
27
28 /*
29 * usage - print the command summary
30 *
31 * Parameters:
32 * fp - stream to print to (stdout for help, stderr for errors)
33 */
34 static void
35 usage(FILE *fp)
36 {
37 fprintf(fp,
38 "usage: botblockd run [-f] [-c config] [-p pidfile]\n"
39 " botblockd check [-c config]\n"
40 " botblockd list\n"
41 " botblockd unblock <address>... | -a\n"
42 " botblockd help\n");
43 }
44
45 /*
46 * monotime - current time in whole seconds since boot
47 *
48 * Unaffected by changes to the wall clock, so durations stay correct
49 * across clock steps.
50 *
51 * Returns: seconds of CLOCK_MONOTONIC
52 */
53 time_t
54 monotime(void)
55 {
56 struct timespec ts;
57
58 clock_gettime(CLOCK_MONOTONIC, &ts);
59 return (ts.tv_sec);
60 }
61
62 /*
63 * config_load - read configuration and whitelist, then apply them
64 *
65 * The configuration is parsed into a local copy, starting from the
66 * compiled-in defaults, so a key removed since the last load reverts
67 * to its default. cfg and the whitelist are replaced only when both
68 * have been read without error. On a reload, a changed INPUT_LOG is
69 * an error: following a different log needs a restart.
70 *
71 * Parameters:
72 * reload - true for a SIGHUP reload, false at startup and for check
73 *
74 * Returns: 0 on success, -1 on failure (logged); on failure cfg and
75 * the whitelist are unchanged
76 */
77 static int
78 config_load(bool reload)
79 {
80 struct config c;
81
82 if (parse_config(conf_path, &c) != 0)
83 return (-1);
84 if (reload && strcmp(c.input_log, cfg.input_log) != 0) {
85 syslog(LOG_ERR, "config: INPUT_LOG changed to %s, a restart "
86 "is needed to apply it", c.input_log);
87 return (-1);
88 }
89 if (load_whitelist(c.whitelist) != 0)
90 return (-1);
91 cfg = c;
92 return (0);
93 }
94
95 /*
96 * config_reload - re-read configuration and whitelist
97 *
98 * Invoked from the event loop when a SIGHUP has been latched, off the
99 * signal path so file and syslog calls stay async-signal-safe. If the
100 * reload fails, the previous configuration and whitelist stay in
101 * effect.
102 */
103 void
104 config_reload(void)
105 {
106 if (config_load(true) != 0) {
107 syslog(LOG_ERR, "config reload failed, previous configuration "
108 "stays in effect");
109 return;
110 }
111 syslog(LOG_NOTICE, "config reloaded (SIGHUP)");
112 }
113
114 /*
115 * sighandler - latch shutdown and reload requests
116 *
117 * SIGTERM/SIGINT request graceful shutdown; SIGHUP requests a config
118 * reload. Only sets sig_atomic_t flags; the actual work happens in
119 * the event loop.
120 *
121 * Parameters:
122 * sig - signal number
123 */
124 static void
125 sighandler(int sig)
126 {
127 switch (sig) {
128 case SIGTERM:
129 case SIGINT:
130 running = 0;
131 break;
132 case SIGHUP:
133 reload_pending = 1;
134 break;
135 }
136 }
137
138 /*
139 * install_signals - wire up the daemon signal handlers
140 */
141 static void
142 install_signals(void)
143 {
144 struct sigaction sa;
145
146 sigemptyset(&sa.sa_mask);
147 sa.sa_flags = 0;
148 sa.sa_handler = sighandler;
149 sigaction(SIGTERM, &sa, NULL);
150 sigaction(SIGINT, &sa, NULL);
151 sigaction(SIGHUP, &sa, NULL);
152 sa.sa_handler = SIG_IGN;
153 sigaction(SIGPIPE, &sa, NULL);
154 }
155
156 /*
157 * cmd_run - run the daemon
158 *
159 * Everything that can fail at startup (configuration, whitelist, input
160 * log, a second instance, the pf table) is checked before detaching
161 * via daemon(3), so the exit status reports it. -f keeps the daemon
162 * in the foreground. The pf table is flushed at startup, as entries
163 * left by an earlier unclean exit have no record here and would never
164 * expire, and again on exit.
165 *
166 * Parameters:
167 * argc, argv - verb-relative arguments (argv[0] is "run")
168 *
169 * Returns: 0 on shutdown by signal, 1 on any failure
170 */
171 static int
172 cmd_run(int argc, char *argv[])
173 {
174 struct pidfh *pfh;
175 pid_t otherpid;
176 int ch, rc;
177 bool foreground = false;
178
179 while ((ch = getopt(argc, argv, "c:fp:")) != -1) {
180 switch (ch) {
181 case 'c':
182 conf_path = optarg;
183 break;
184 case 'f':
185 foreground = true;
186 break;
187 case 'p':
188 pid_path = optarg;
189 break;
190 default:
191 usage(stderr);
192 return (1);
193 }
194 }
195 if (optind != argc) {
196 usage(stderr);
197 return (1);
198 }
199
200 /* mirror to stderr only in the foreground; syslogd timestamps */
201 openlog("botblockd", LOG_PID | (foreground ? LOG_PERROR : 0),
202 LOG_DAEMON);
203 /* daemon(3) changes to /, so a reload needs an absolute path */
204 if (conf_path[0] != '/') {
205 syslog(LOG_ERR, "config path must be absolute: %s", conf_path);
206 return (1);
207 }
208 if (config_load(false) != 0)
209 return (1);
210 if (tail_open() != 0)
211 return (1);
212
213 pfh = pidfile_open(pid_path, 0600, &otherpid);
214 if (pfh == NULL) {
215 if (errno == EEXIST) {
216 syslog(LOG_ERR, "already running, pid %ld",
217 (long)otherpid);
218 return (1);
219 }
220 syslog(LOG_WARNING, "cannot open pidfile %s: %s",
221 pid_path, strerror(errno));
222 }
223
224 rc = 1;
225 if (pf_flush() != 0) {
226 syslog(LOG_ERR, "cannot flush pf table '%s'", PF_TABLE);
227 goto out;
228 }
229 if (!foreground && daemon(0, 0) == -1) {
230 syslog(LOG_ERR, "daemon: %s", strerror(errno));
231 goto out;
232 }
233 if (pfh != NULL)
234 pidfile_write(pfh);
235
236 install_signals();
237
238 syslog(LOG_NOTICE, "botblockd %s started", BOTBLOCKD_VERSION);
239 rc = (tail_log() == 0) ? 0 : 1;
240
241 syslog(LOG_NOTICE, "shutting down, flushing pf table");
242 if (pf_flush() != 0) {
243 syslog(LOG_ERR, "cannot flush pf table '%s'", PF_TABLE);
244 rc = 1;
245 }
246
247 out:
248 if (pfh != NULL)
249 pidfile_remove(pfh);
250 return (rc);
251 }
252
253 /*
254 * cmd_check - validate configuration and exit
255 *
256 * Checks the configuration, the whitelist, the input log and the pf
257 * table.
258 *
259 * Parameters:
260 * argc, argv - verb-relative arguments (argv[0] is "check")
261 *
262 * Returns: 0 on success, 1 on bad arguments or a failed check
263 */
264 static int
265 cmd_check(int argc, char *argv[])
266 {
267 int ch;
268
269 while ((ch = getopt(argc, argv, "c:")) != -1) {
270 switch (ch) {
271 case 'c':
272 conf_path = optarg;
273 break;
274 default:
275 usage(stderr);
276 return (1);
277 }
278 }
279 if (optind != argc) {
280 usage(stderr);
281 return (1);
282 }
283
284 openlog("botblockd", LOG_PID | LOG_PERROR, LOG_DAEMON);
285 if (config_load(false) != 0)
286 return (1);
287 if (tail_open() != 0)
288 return (1);
289 if (pf_show(true) != 0) {
290 syslog(LOG_ERR, "pf table '%s' unavailable; ensure pf is "
291 "enabled and the table is defined in pf.conf", PF_TABLE);
292 return (1);
293 }
294 printf("config OK\n");
295 return (0);
296 }
297
298 /*
299 * cmd_list - print the current contents of the pf block table
300 *
301 * Parameters:
302 * argc - verb-relative argument count, 1 as list takes no arguments
303 *
304 * Returns: 0 on success, 1 on bad arguments or failure
305 */
306 static int
307 cmd_list(int argc)
308 {
309 if (argc != 1) {
310 usage(stderr);
311 return (1);
312 }
313 return (pf_show(false) == 0 ? 0 : 1);
314 }
315
316 /*
317 * cmd_unblock - remove addresses from the pf block table
318 *
319 * With -a, flushes the whole table; otherwise removes each address
320 * argument. Operates directly on the pf table, so it does not need a
321 * running daemon.
322 *
323 * Parameters:
324 * argc, argv - verb-relative arguments (argv[0] is "unblock")
325 *
326 * Returns: 0 if all requested removals succeeded, 1 otherwise
327 */
328 static int
329 cmd_unblock(int argc, char *argv[])
330 {
331 uint32_t ip;
332 int ch, i, rc = 0;
333 bool all = false;
334
335 while ((ch = getopt(argc, argv, "a")) != -1) {
336 switch (ch) {
337 case 'a':
338 all = true;
339 break;
340 default:
341 usage(stderr);
342 return (1);
343 }
344 }
345 argc -= optind;
346 argv += optind;
347
348 if (all) {
349 if (argc > 0) {
350 fprintf(stderr, "unblock: -a takes no addresses\n");
351 return (1);
352 }
353 if (pf_flush() != 0) {
354 fprintf(stderr, "unblock: failed to flush table\n");
355 return (1);
356 }
357 printf("all entries cleared\n");
358 return (0);
359 }
360
361 if (argc == 0) {
362 usage(stderr);
363 return (1);
364 }
365
366 for (i = 0; i < argc; i++) {
367 if (parse_ipv4(argv[i], &ip) != 0) {
368 fprintf(stderr, "unblock: invalid address '%s'\n",
369 argv[i]);
370 rc = 1;
371 continue;
372 }
373 if (pf_unblock(ip) != 0) {
374 fprintf(stderr, "unblock: failed to remove %s\n",
375 argv[i]);
376 rc = 1;
377 continue;
378 }
379 printf("removed %s\n", ip_str(ip));
380 }
381 return (rc);
382 }
383
384 /*
385 * main - botblockd: block web clients that cause HTTP errors, using pf
386 *
387 * botblockd follows an nginx access log, counts error responses per
388 * source address and adds persistent offenders to a pf table. The
389 * first argument selects the command; the remaining arguments are
390 * parsed by the command. Running the daemon is explicit (the "run"
391 * command), since the rc script is the usual caller.
392 *
393 * Parameters:
394 * argc, argv - command line
395 *
396 * Returns: exit status of the command, 1 for a missing or unknown
397 * command
398 */
399 int
400 main(int argc, char *argv[])
401 {
402 const char *verb;
403
404 if (argc < 2) {
405 usage(stderr);
406 return (1);
407 }
408 verb = argv[1];
409
410 if (strcmp(verb, "run") == 0)
411 return (cmd_run(argc - 1, argv + 1));
412 if (strcmp(verb, "check") == 0)
413 return (cmd_check(argc - 1, argv + 1));
414 if (strcmp(verb, "list") == 0)
415 return (cmd_list(argc - 1));
416 if (strcmp(verb, "unblock") == 0)
417 return (cmd_unblock(argc - 1, argv + 1));
418 if (strcmp(verb, "help") == 0 || strcmp(verb, "-h") == 0 ||
419 strcmp(verb, "--help") == 0) {
420 printf("botblockd %s\n", BOTBLOCKD_VERSION);
421 usage(stdout);
422 return (0);
423 }
424
425 fprintf(stderr, "botblockd: unknown command '%s'\n", verb);
426 usage(stderr);
427 return (1);
428 }