/*
 * wificap — SD card mount and the pcap writer task.
 *
 * Frames are written in classic pcap format with a radiotap pseudo-header, so
 * the resulting file opens in Wireshark and feeds aircrack-ng with no
 * conversion step. Radiotap is what carries the signal strength and the
 * channel; without it the capture is just bare 802.11 frames and every
 * per-frame RSSI is lost, which is most of what makes a capture readable
 * after the fact.
 *
 * SPDX-License-Identifier: MIT
 */

#include <dirent.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>

#include "esp_log.h"
#include "esp_timer.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"

#include "bsp/esp-bsp.h"

#include "wcap.h"

static const char *TAG = "wcap.pcap";

static FILE *s_fp;
static uint32_t s_frames;
static uint32_t s_bytes;
static char s_path[48];

/* ------------------------------------------------------------------ */
/* pcap and radiotap on-disk layout                                   */
/* ------------------------------------------------------------------ */

#define PCAP_MAGIC_USEC 0xa1b2c3d4u
#define LINKTYPE_IEEE802_11_RADIOTAP 127

typedef struct __attribute__((packed)) {
    uint32_t magic;
    uint16_t v_major;
    uint16_t v_minor;
    int32_t  thiszone;
    uint32_t sigfigs;
    uint32_t snaplen;
    uint32_t network;
} pcap_file_hdr_t;

typedef struct __attribute__((packed)) {
    uint32_t ts_sec;
    uint32_t ts_usec;
    uint32_t incl_len;
    uint32_t orig_len;
} pcap_pkt_hdr_t;

/*
 * Radiotap present-bitmap bits, from the radiotap spec. Fields must appear in
 * bit order and each is aligned to its own natural size -- get either wrong
 * and Wireshark reports a malformed header rather than guessing.
 *
 *   bit 1  FLAGS           u8
 *   bit 2  RATE            u8
 *   bit 3  CHANNEL         u16 freq + u16 flags, 2-byte aligned
 *   bit 5  DBM_ANTSIGNAL   s8
 *   bit 6  DBM_ANTNOISE    s8
 *
 * Laid out below that gives 8 + 1 + 1 + 4 + 1 + 1 = 16 bytes with the u16
 * pair landing on an even offset, so no padding is needed anywhere.
 */
#define RT_PRESENT ((1u << 1) | (1u << 2) | (1u << 3) | (1u << 5) | (1u << 6))

#define RT_CHAN_TURBO   0x0010
#define RT_CHAN_CCK     0x0020
#define RT_CHAN_OFDM    0x0040
#define RT_CHAN_2GHZ    0x0080
#define RT_CHAN_5GHZ    0x0100

/*
 * Radiotap FLAGS bit 0x10: "frame includes the FCS".
 *
 * The Wi-Fi driver hands the promiscuous callback a frame whose sig_len
 * counts the four-byte FCS at the end. Without this bit a dissector parses
 * the frame correctly and then finds four bytes it cannot account for, and
 * marks it malformed -- so a capture that is byte-for-byte correct shows up
 * as ~78% malformed in Wireshark, mostly beacons, with the length and the
 * captured length equal so it does not even look like truncation. One bit.
 */
#define RT_F_FCS        0x10

typedef struct __attribute__((packed)) {
    uint8_t  it_version;
    uint8_t  it_pad;
    uint16_t it_len;
    uint32_t it_present;
    uint8_t  flags;
    uint8_t  rate;
    uint16_t chan_freq;
    uint16_t chan_flags;
    int8_t   antsignal;
    int8_t   antnoise;
} radiotap_hdr_t;

_Static_assert(sizeof(radiotap_hdr_t) == 16, "radiotap header must be 16 bytes");

/* ------------------------------------------------------------------ */
/* SD card                                                            */
/* ------------------------------------------------------------------ */

esp_err_t wcap_sd_mount(void)
{
    /*
     * The SD card and the LCD share SPI2 on this board, and that is by
     * design: the BSP's bsp_spi_init() is idempotent behind a
     * `spi_initialized` guard and both bsp_sdcard_mount() and
     * bsp_display_new() call it, with the bus configured for a full-screen
     * LCD transaction. So the order of display and card bring-up does not
     * matter. What the sharing does cost is contention -- a display flush and
     * an SD write serialise against each other -- which is why the UI
     * repaints at a few hertz and the writer batches.
     */
    esp_err_t err = bsp_sdcard_mount();
    if (err != ESP_OK) {
        ESP_LOGE(TAG, "SD mount failed: %s", esp_err_to_name(err));
        ESP_LOGE(TAG, "card must be FAT32; check it is seated");
        wcap_sd_publish(false, NULL);
        return err;
    }
    ESP_LOGI(TAG, "SD mounted at %s", BSP_SD_MOUNT_POINT);
    wcap_sd_publish(true, NULL);
    return ESP_OK;
}

/* Next free capture file, so a demo can be run repeatedly without clobbering
 * the previous take. */
static void next_path(char *out, size_t n)
{
    for (int i = 0; i < 1000; i++) {
        snprintf(out, n, "%s/wcap%03d.pcap", BSP_SD_MOUNT_POINT, i);
        struct stat st;
        if (stat(out, &st) != 0) return;
    }
    snprintf(out, n, "%s/wcap999.pcap", BSP_SD_MOUNT_POINT);
}

esp_err_t wcap_pcap_open(void)
{
    if (s_fp) return ESP_OK;

    next_path(s_path, sizeof(s_path));
    s_fp = fopen(s_path, "wb");
    if (!s_fp) {
        ESP_LOGE(TAG, "cannot open %s", s_path);
        wcap_sd_publish(false, NULL);
        return ESP_FAIL;
    }

    const pcap_file_hdr_t fh = {
        .magic = PCAP_MAGIC_USEC,
        .v_major = 2,
        .v_minor = 4,
        .thiszone = 0,
        .sigfigs = 0,
        .snaplen = CONFIG_WCAP_SNAPLEN + sizeof(radiotap_hdr_t),
        .network = LINKTYPE_IEEE802_11_RADIOTAP,
    };
    if (fwrite(&fh, sizeof(fh), 1, s_fp) != 1) {
        ESP_LOGE(TAG, "header write failed");
        fclose(s_fp);
        s_fp = NULL;
        return ESP_FAIL;
    }
    fflush(s_fp);

    s_frames = 0;
    s_bytes = sizeof(fh);
    wcap_write_publish(s_frames, s_bytes);
    wcap_sd_publish(true, s_path);

    ESP_LOGI(TAG, "recording to %s", s_path);
    return ESP_OK;
}

void wcap_pcap_close(void)
{
    if (!s_fp) return;
    fflush(s_fp);
    fclose(s_fp);
    s_fp = NULL;
    ESP_LOGI(TAG, "closed %s: %lu frames, %lu bytes",
             s_path, (unsigned long)s_frames, (unsigned long)s_bytes);
}

bool wcap_pcap_is_open(void) { return s_fp != NULL; }

/* ------------------------------------------------------------------ */
/* The writer task                                                    */
/* ------------------------------------------------------------------ */

void wcap_writer_task(void *arg)
{
    (void)arg;

    uint32_t last_flush = wcap_tick_ms();

    for (;;) {
        size_t sz = 0;
        /*
         * 100 ms rather than portMAX_DELAY so the periodic flush below still
         * happens on a quiet channel. A capture that is buffered but never
         * flushed looks like a capture that is not working.
         */
        void *item = xRingbufferReceive(wcap_ring, &sz, pdMS_TO_TICKS(100));

        if (item) {
            if (sz >= sizeof(wcap_rec_hdr_t) && s_fp) {
                wcap_rec_hdr_t h;
                memcpy(&h, item, sizeof(h));
                const uint8_t *frame = (const uint8_t *)item + sizeof(h);
                const uint16_t flen = h.len;

                if ((size_t)flen + sizeof(h) <= sz) {
                    const bool g5 = wcap_is_5g(h.channel);
                    radiotap_hdr_t rt = {
                        .it_version = 0,
                        .it_pad = 0,
                        .it_len = sizeof(radiotap_hdr_t),
                        .it_present = RT_PRESENT,
                        .flags = RT_F_FCS,
                        .rate = h.rate,
                        .chan_freq = wcap_chan_to_freq(h.channel),
                        .chan_flags = (uint16_t)(g5 ? (RT_CHAN_5GHZ | RT_CHAN_OFDM)
                                                    : (RT_CHAN_2GHZ | RT_CHAN_CCK)),
                        .antsignal = h.rssi,
                        .antnoise = h.noise,
                    };
                    const pcap_pkt_hdr_t ph = {
                        .ts_sec = h.ts_sec,
                        .ts_usec = h.ts_usec,
                        .incl_len = (uint32_t)(sizeof(rt) + flen),
                        /* orig_len must be the length on the wire, so that a
                         * truncated frame is visibly truncated rather than
                         * silently short. */
                        .orig_len = (uint32_t)(sizeof(rt) + h.orig_len),
                    };

                    if (fwrite(&ph, sizeof(ph), 1, s_fp) == 1 &&
                        fwrite(&rt, sizeof(rt), 1, s_fp) == 1 &&
                        fwrite(frame, 1, flen, s_fp) == flen) {
                        s_frames++;
                        s_bytes += sizeof(ph) + sizeof(rt) + flen;
                    } else {
                        ESP_LOGE(TAG, "write failed; closing capture");
                        wcap_pcap_close();
                        wcap_set_rec(WCAP_REC_OFF);
                        wcap_banner_set("SD write failed");
                    }
                }
            }
            vRingbufferReturnItem(wcap_ring, item);
        }

        const uint32_t now = wcap_tick_ms();
        if (now - last_flush >= CONFIG_WCAP_FLUSH_MS) {
            if (s_fp) {
                /*
                 * Flush on a timer, not on every frame. The point is that the
                 * card can be pulled after a demo without a clean shutdown
                 * and still hold everything up to the last flush -- the
                 * alternative is an empty-looking file because the handshake
                 * is still sitting in a stdio buffer.
                 */
                fflush(s_fp);
                fsync(fileno(s_fp));
            }
            wcap_write_publish(s_frames, s_bytes);
            last_flush = now;
        }
    }
}
