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