view 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
line wrap: on
line source

/*
 * 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);
}