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