/*
 * wificap — promiscuous receive, EAPOL-Key parsing, handshake tracking.
 *
 * Everything inside promisc_cb() runs in the Wi-Fi driver task. It must stay
 * short: no allocation, no logging, no file I/O, and nothing that blocks. The
 * frame is copied into a ring buffer and the writer task does the SD card.
 *
 * SPDX-License-Identifier: MIT
 */

#include <string.h>

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

#include "wcap.h"

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

RingbufHandle_t wcap_ring;

/* ------------------------------------------------------------------ */
/* Channel plan                                                        */
/* ------------------------------------------------------------------ */

const uint8_t wcap_plan[WCAP_N_CHANNELS] = {
    /* 2.4 GHz, non-overlapping */
    1, 6, 11,
    /* U-NII-1 */
    36, 40, 44, 48,
    /* U-NII-3 */
    149, 153, 157, 161, 165,
    /* U-NII-2A (DFS) */
    52, 56, 60, 64,
    /* U-NII-2C (DFS) */
    100, 104, 108, 112, 116, 120, 124, 128, 132, 136, 140, 144,
};

const char *const wcap_frame_tag[WCAP_FR_MAX] = {
    "BCN", "PRB", "AUT", "MGT", "EAP", "DAT", "CTL",
};

uint16_t wcap_chan_to_freq(uint8_t ch)
{
    if (ch == 14) return 2484;
    if (ch <= 13) return 2407 + (uint16_t)ch * 5;
    return 5000 + (uint16_t)ch * 5;
}

/* ------------------------------------------------------------------ */
/* Shared state                                                        */
/* ------------------------------------------------------------------ */

static portMUX_TYPE s_mux = portMUX_INITIALIZER_UNLOCKED;
static wcap_status_t s_st;
static wcap_ap_t s_aps[WCAP_MAX_APS];
static wcap_hs_t s_hs[WCAP_MAX_HS];

/* See the capstone scanner for why the channel comes from the scheduler and
 * never from rx_ctrl: on a Wi-Fi 6 part the rx_ctrl channel field can be four
 * bits wide, which cannot hold a 5 GHz channel number at all. */
static volatile uint8_t s_cur_channel = 1;
static volatile uint8_t s_cur_plan_index;
static volatile wcap_mode_t s_mode = WCAP_MODE_SURVEY;
static volatile wcap_rec_t s_rec = WCAP_REC_OFF;
static volatile bool s_have_target;
static uint8_t s_target[6];

void wcap_status_get(wcap_status_t *out)
{
    portENTER_CRITICAL(&s_mux);
    *out = s_st;
    portEXIT_CRITICAL(&s_mux);
}

uint32_t wcap_tick_ms(void)
{
    return (uint32_t)(esp_timer_get_time() / 1000);
}

void wcap_set_channel(uint8_t ch)
{
    s_cur_channel = ch;
    for (int i = 0; i < WCAP_N_CHANNELS; i++) {
        if (wcap_plan[i] == ch) { s_cur_plan_index = (uint8_t)i; break; }
    }
    portENTER_CRITICAL(&s_mux);
    s_st.channel = ch;
    s_st.is_5g = wcap_is_5g(ch);
    s_st.frames_this_dwell = 0;
    portEXIT_CRITICAL(&s_mux);
}

void wcap_set_mode(wcap_mode_t m)
{
    s_mode = m;
    portENTER_CRITICAL(&s_mux);
    s_st.mode = m;
    portEXIT_CRITICAL(&s_mux);
}

void wcap_set_rec(wcap_rec_t r)
{
    s_rec = r;
    portENTER_CRITICAL(&s_mux);
    s_st.rec = r;
    portEXIT_CRITICAL(&s_mux);
}

void wcap_set_target(const uint8_t bssid[6])
{
    portENTER_CRITICAL(&s_mux);
    memcpy(s_target, bssid, 6);
    memcpy(s_st.target, bssid, 6);
    s_st.have_target = true;
    s_st.target_ssid[0] = '\0';
    for (int i = 0; i < WCAP_MAX_APS; i++) {
        if (s_aps[i].used && memcmp(s_aps[i].bssid, bssid, 6) == 0) {
            memcpy(s_st.target_ssid, s_aps[i].ssid, WCAP_SSID_MAX);
            break;
        }
    }
    portEXIT_CRITICAL(&s_mux);
    s_have_target = true;
}

void wcap_clear_target(void)
{
    s_have_target = false;
    portENTER_CRITICAL(&s_mux);
    s_st.have_target = false;
    s_st.target_ssid[0] = '\0';
    portEXIT_CRITICAL(&s_mux);
}

uint8_t wcap_ap_channel(const uint8_t bssid[6])
{
    uint8_t ch = 0;
    portENTER_CRITICAL(&s_mux);
    for (int i = 0; i < WCAP_MAX_APS; i++) {
        if (s_aps[i].used && memcmp(s_aps[i].bssid, bssid, 6) == 0) {
            ch = s_aps[i].channel;
            break;
        }
    }
    portEXIT_CRITICAL(&s_mux);
    return ch;
}

int wcap_ap_list(wcap_ap_t *out, int max)
{
    int n = 0;
    portENTER_CRITICAL(&s_mux);
    for (int i = 0; i < WCAP_MAX_APS && n < max; i++) {
        if (s_aps[i].used) out[n++] = s_aps[i];
    }
    portEXIT_CRITICAL(&s_mux);
    return n;
}

int wcap_hs_list(wcap_hs_t *out, int max)
{
    int n = 0;
    portENTER_CRITICAL(&s_mux);
    for (int i = 0; i < WCAP_MAX_HS && n < max; i++) {
        if (s_hs[i].used) out[n++] = s_hs[i];
    }
    portEXIT_CRITICAL(&s_mux);
    return n;
}

/* Publishers used by the scheduler in scan.c and the writer in pcap.c. */

void wcap_plan_publish(const bool *avail, uint8_t n)
{
    portENTER_CRITICAL(&s_mux);
    for (int i = 0; i < WCAP_N_CHANNELS; i++) s_st.available[i] = avail[i];
    s_st.n_available = n;
    portEXIT_CRITICAL(&s_mux);
}

void wcap_fps_publish(uint32_t fps)
{
    portENTER_CRITICAL(&s_mux);
    s_st.fps = fps;
    if (fps > s_st.fps_peak) s_st.fps_peak = fps;
    portEXIT_CRITICAL(&s_mux);
}

void wcap_dwell_publish(uint16_t total_ms, uint32_t elapsed_ms)
{
    portENTER_CRITICAL(&s_mux);
    s_st.dwell_ms = total_ms;
    s_st.dwell_elapsed_ms = elapsed_ms;
    portEXIT_CRITICAL(&s_mux);
}

void wcap_sweep_tick(void)
{
    portENTER_CRITICAL(&s_mux);
    s_st.sweeps++;
    portEXIT_CRITICAL(&s_mux);
}

void wcap_write_publish(uint32_t frames, uint32_t bytes)
{
    portENTER_CRITICAL(&s_mux);
    s_st.written = frames;
    s_st.bytes = bytes;
    portEXIT_CRITICAL(&s_mux);
}

void wcap_sd_publish(bool ok, const char *path)
{
    portENTER_CRITICAL(&s_mux);
    s_st.sd_ok = ok;
    if (path) {
        strncpy(s_st.path, path, sizeof(s_st.path) - 1);
        s_st.path[sizeof(s_st.path) - 1] = '\0';
    } else {
        s_st.path[0] = '\0';
    }
    portEXIT_CRITICAL(&s_mux);
}

void wcap_active_set(bool on)
{
    portENTER_CRITICAL(&s_mux);
    s_st.active = on;
    portEXIT_CRITICAL(&s_mux);
}

bool wcap_ap_ssid(const uint8_t bssid[6], char *out, size_t n)
{
    bool found = false;
    portENTER_CRITICAL(&s_mux);
    for (int i = 0; i < WCAP_MAX_APS; i++) {
        if (s_aps[i].used && memcmp(s_aps[i].bssid, bssid, 6) == 0) {
            strncpy(out, s_aps[i].ssid, n - 1);
            out[n - 1] = '\0';
            found = (out[0] != '\0');
            break;
        }
    }
    portEXIT_CRITICAL(&s_mux);
    return found;
}

void wcap_banner_set(const char *text)
{
    portENTER_CRITICAL(&s_mux);
    strncpy(s_st.banner, text, WCAP_BANNER_MAX - 1);
    s_st.banner[WCAP_BANNER_MAX - 1] = '\0';
    s_st.banner_ms = wcap_tick_ms();
    portEXIT_CRITICAL(&s_mux);
}

/* ------------------------------------------------------------------ */
/* 802.11 header walking                                              */
/* ------------------------------------------------------------------ */

#define FC_TYPE(p)  (((p)[0] >> 2) & 0x03)
#define FC_SUB(p)   (((p)[0] >> 4) & 0x0F)
#define FC_TODS(p)  ((p)[1] & 0x01)
#define FC_FROMDS(p)((p)[1] & 0x02)
#define FC_PROT(p)  ((p)[1] & 0x40)
#define FC_ORDER(p) ((p)[1] & 0x80)

/*
 * Length of the MAC header for a data frame. Four things can lengthen it and
 * all four occur in the wild:
 *   - addr4, when both ToDS and FromDS are set (a WDS/mesh frame)
 *   - the 2-byte QoS control field, on any QoS subtype
 *   - the 4-byte HT control field, when the Order bit is set on a QoS frame
 * Getting this wrong does not throw an error, it just makes the LLC/SNAP
 * check fail, so EAPOL frames are silently never recognised.
 */
static int data_hdr_len(const uint8_t *p)
{
    int n = 24;
    if (FC_TODS(p) && FC_FROMDS(p)) n += 6;
    if (FC_SUB(p) & 0x08) {
        n += 2;
        if (FC_ORDER(p)) n += 4;
    }
    return n;
}

/* ------------------------------------------------------------------ */
/* EAPOL-Key                                                          */
/* ------------------------------------------------------------------ */

/*
 * Offsets inside the EAPOL-Key body, from RFC 3748 / IEEE 802.1X-2010 and
 * 802.11-2016 12.7.2. The MIC is assumed 16 bytes, which holds for every AKM
 * a classroom WPA2 network will use; the SHA-384 suites widen it and would
 * shift key_data_len. Flagged rather than handled, because a demo that quietly
 * mis-parses is worse than one that says what it does not cover.
 */
#define EK_DESC_TYPE   0
#define EK_KEY_INFO    1
#define EK_KEY_LEN     3
#define EK_REPLAY      5
#define EK_NONCE      13
#define EK_IV         45
#define EK_RSC        61
#define EK_ID         69
#define EK_MIC        77
#define EK_KDL        93
#define EK_MIN_LEN    95

#define KI_PAIRWISE 0x0008
#define KI_INSTALL  0x0040
#define KI_ACK      0x0080
#define KI_MIC      0x0100
#define KI_SECURE   0x0200

static inline uint16_t be16(const uint8_t *p) { return (uint16_t)((p[0] << 8) | p[1]); }

/*
 * Returns 1..4 for a four-way handshake message, or 0 for anything else
 * (group rekey, EAPOL-Start, a truncated frame).
 *
 * The M2-versus-M4 distinction is the only subtle one: both are from the
 * supplicant with a MIC and no ACK. M2 carries the RSN IE in its key data and
 * is not yet Secure; M4 is Secure with empty key data. Checking only the
 * Secure bit misclassifies some implementations, and checking only key data
 * length misclassifies others, so check both.
 */
/*
 * Pull the PMKID out of an M1's key data.
 *
 * M1 carries key data as a sequence of KDEs. The PMKID one is a vendor
 * specific element: 0xDD, length 0x14, the RSN OUI 00:0F:AC, data type 0x04,
 * then the 16-byte PMKID. Walk the elements rather than assuming the PMKID is
 * first, because it is not always the only KDE present.
 *
 * Why this is worth having: a PMKID is on its own enough to mount the same
 * offline dictionary attack as a full handshake, and it arrives in M1 -- the
 * AP's first message -- so it does not need a client to be present at all.
 */
/* Key-data length of the most recent M1, for diagnosis. See eapol_msg(). */
static volatile uint16_t s_m1_kdl;

uint16_t wcap_last_m1_kdl(void) { return s_m1_kdl; }

static bool kde_find_pmkid(const uint8_t *kd, uint16_t len, uint8_t out[16])
{
    static const uint8_t rsn_oui[3] = { 0x00, 0x0f, 0xac };

    uint16_t i = 0;
    while (i + 2 <= len) {
        const uint8_t id = kd[i];
        const uint8_t elen = kd[i + 1];
        if ((uint32_t)i + 2 + elen > len) break;

        if (id == 0xDD && elen >= 4 + 16 &&
            memcmp(kd + i + 2, rsn_oui, 3) == 0 &&
            kd[i + 5] == 0x04) {
            memcpy(out, kd + i + 6, 16);
            /* All-zero is what some APs send when they have no PMKSA to
             * offer. It parses as a PMKID and is useless, so reject it here
             * rather than report a hash nobody can crack. */
            for (int b = 0; b < 16; b++) {
                if (out[b] != 0) return true;
            }
            return false;
        }
        i = (uint16_t)(i + 2 + elen);
    }
    return false;
}

static int eapol_msg(const uint8_t *k, uint32_t avail, bool *pmkid_out,
                     uint8_t pmkid_val[16])
{
    if (avail < EK_MIN_LEN) return 0;

    const uint16_t ki = be16(k + EK_KEY_INFO);
    const uint16_t kdl = be16(k + EK_KDL);

    if (!(ki & KI_PAIRWISE)) return 0;

    const bool install = ki & KI_INSTALL;
    const bool ack     = ki & KI_ACK;
    const bool mic     = ki & KI_MIC;
    const bool secure  = ki & KI_SECURE;

    if (!mic && ack) {
        /* M1. Key data here, if any, is where the PMKID lives. */
        if (pmkid_out) {
            *pmkid_out = false;
            if (kdl > 0 && avail >= (uint32_t)EK_MIN_LEN + kdl && pmkid_val) {
                *pmkid_out = kde_find_pmkid(k + EK_MIN_LEN, kdl, pmkid_val);
            }
        }
        /*
         * Remember how much key data M1 carried, so "this AP offers no
         * PMKID" can be told apart from "this AP sent KDEs we did not
         * recognise". Without it both look like pmkid=0 and the difference
         * is the difference between a fact about the AP and a bug here.
         */
        s_m1_kdl = kdl;
        return 1;
    }
    if (mic && ack && install) return 3;
    if (mic && !ack) return (secure || kdl == 0) ? 4 : 2;
    return 0;
}

/* Record a handshake message against its (AP, STA) pair. Caller holds s_mux. */
static void hs_note(const uint8_t *ap, const uint8_t *sta, int msg, bool pmkid,
                    const uint8_t *pmkid_val)
{
    wcap_hs_t *slot = NULL, *free_slot = NULL, *oldest = NULL;

    for (int i = 0; i < WCAP_MAX_HS; i++) {
        wcap_hs_t *h = &s_hs[i];
        if (!h->used) { if (!free_slot) free_slot = h; continue; }
        if (memcmp(h->ap, ap, 6) == 0 && memcmp(h->sta, sta, 6) == 0) {
            slot = h;
            break;
        }
        if (!oldest || (int32_t)(h->last_ms - oldest->last_ms) < 0) oldest = h;
    }

    if (!slot) {
        slot = free_slot ? free_slot : oldest;
        if (!slot) return;
        memset(slot, 0, sizeof(*slot));
        memcpy(slot->ap, ap, 6);
        memcpy(slot->sta, sta, 6);
        slot->used = true;
        if (s_st.n_hs < WCAP_MAX_HS) s_st.n_hs++;
    }

    const bool was = wcap_hs_crackable(slot->seen);
    const bool had_pmkid = slot->pmkid;

    slot->seen |= (uint8_t)(1u << (msg - 1));
    if (pmkid && pmkid_val) {
        slot->pmkid = true;
        memcpy(slot->pmkid_val, pmkid_val, 16);
    }
    slot->last_ms = wcap_tick_ms();

    if (slot->seen > s_st.best_seen) s_st.best_seen = slot->seen;

    /*
     * A PMKID is its own result, independent of how far the four-way got, so
     * it gets its own banner the moment it appears.
     */
    if (!had_pmkid && slot->pmkid) {
        s_st.pmkid_count++;
        snprintf(s_st.banner, WCAP_BANNER_MAX,
                 "PMKID %02x%02x%02x %02x%02x%02x%02x..",
                 slot->ap[3], slot->ap[4], slot->ap[5],
                 slot->pmkid_val[0], slot->pmkid_val[1],
                 slot->pmkid_val[2], slot->pmkid_val[3]);
        s_st.banner_ms = wcap_tick_ms();
    }

    /*
     * The banner is written exactly when a pair crosses from "not yet usable"
     * to "usable", which is the moment worth announcing. Writing it on every
     * EAPOL frame would make the interesting event invisible among the noise.
     */
    if (!was && wcap_hs_crackable(slot->seen)) {
        s_st.any_crackable = true;
        s_st.hs_complete++;
        snprintf(s_st.banner, WCAP_BANNER_MAX,
                 "HS %02x%02x%02x>%02x%02x%02x %c%c%c%c%s",
                 slot->ap[3], slot->ap[4], slot->ap[5],
                 slot->sta[3], slot->sta[4], slot->sta[5],
                 (slot->seen & WCAP_M1) ? '1' : '-',
                 (slot->seen & WCAP_M2) ? '2' : '-',
                 (slot->seen & WCAP_M3) ? '3' : '-',
                 (slot->seen & WCAP_M4) ? '4' : '-',
                 slot->pmkid ? " +PMKID" : "");
        s_st.banner_ms = wcap_tick_ms();
    }
}

/* ------------------------------------------------------------------ */
/* Beacons: the SSID, which a handshake capture alone does not carry   */
/* ------------------------------------------------------------------ */

/*
 * A capture with a handshake but no beacon has no SSID in it, and the SSID is
 * an input to the PMK. aircrack-ng can be told the ESSID by hand, but a
 * self-contained pcap should not need that, so beacons are always recorded
 * even in handshake-only mode.
 */
static void note_beacon(const uint8_t *p, uint32_t len, int8_t rssi, uint8_t ch)
{
    if (len < 24 + 12 + 2) return;

    const uint8_t *bssid = p + 16;        /* addr3 */
    const uint8_t *ie = p + 24 + 12;
    uint32_t left = len - (24 + 12);

    char ssid[WCAP_SSID_MAX] = {0};
    while (left >= 2) {
        const uint8_t id = ie[0], ilen = ie[1];
        if ((uint32_t)ilen + 2 > left) break;
        if (id == 0) {
            uint8_t n = ilen < (WCAP_SSID_MAX - 1) ? ilen : (WCAP_SSID_MAX - 1);
            for (uint8_t i = 0; i < n; i++) {
                ssid[i] = (ie[2 + i] >= 32 && ie[2 + i] < 127) ? (char)ie[2 + i] : '.';
            }
            ssid[n] = '\0';
            break;
        }
        ie += 2 + ilen;
        left -= 2 + ilen;
    }

    portENTER_CRITICAL(&s_mux);
    wcap_ap_t *free_slot = NULL;
    wcap_ap_t *weakest = NULL;
    bool found = false;
    for (int i = 0; i < WCAP_MAX_APS; i++) {
        wcap_ap_t *a = &s_aps[i];
        if (!a->used) { if (!free_slot) free_slot = a; continue; }
        if (!weakest || a->rssi < weakest->rssi) weakest = a;
        if (memcmp(a->bssid, bssid, 6) == 0) {
            /*
             * Record the channel where this AP is heard LOUDEST, not the one
             * where it was heard last.
             *
             * 2.4 GHz channels overlap by design: a 20 MHz carrier on channel
             * 1 still puts usable energy into a receiver tuned to channel 6,
             * and for a close AP it decodes perfectly. So a strong neighbour
             * is seen on several of the planned channels, and taking the most
             * recent sighting means the stored channel is whichever one the
             * sweep happened to end on. That is not a cosmetic error -- it is
             * what the active probe and `park` tune to, so it sends the radio
             * to the wrong channel and the capture comes back empty.
             *
             * The strongest sighting is the home channel.
             */
            if (rssi > a->rssi) {
                a->rssi = rssi;
                a->channel = ch;
            }
            if (a->beacons < UINT16_MAX) a->beacons++;
            if (a->ssid[0] == '\0' && ssid[0] != '\0') memcpy(a->ssid, ssid, WCAP_SSID_MAX);
            found = true;
            break;
        }
    }
    if (!found) {
        /*
         * When the table is full, evict the weakest entry rather than drop
         * the new one. A full table that refuses new BSSIDs silently loses
         * whichever AP you walked up to last, which is usually the one you
         * came to look at -- and it looks identical to that AP not being on
         * the air. Only evict if the newcomer is actually stronger, so a
         * distant AP cannot churn the table.
         */
        wcap_ap_t *slot = free_slot;
        if (!slot && weakest && rssi > weakest->rssi) slot = weakest;

        if (slot) {
            const bool reused = slot->used;
            memset(slot, 0, sizeof(*slot));
            memcpy(slot->bssid, bssid, 6);
            memcpy(slot->ssid, ssid, WCAP_SSID_MAX);
            slot->channel = ch;
            slot->rssi = rssi;
            slot->beacons = 1;
            slot->used = true;
            if (!reused && s_st.n_aps < WCAP_MAX_APS) s_st.n_aps++;
        }
    }
    portEXIT_CRITICAL(&s_mux);
}

/* ------------------------------------------------------------------ */
/* The callback                                                        */
/* ------------------------------------------------------------------ */

static wcap_frame_class_t classify(const uint8_t *p, bool is_eapol)
{
    const uint8_t t = FC_TYPE(p), s = FC_SUB(p);
    if (t == 0) {
        switch (s) {
        case 0x8: return WCAP_FR_BEACON;
        case 0x4: case 0x5: return WCAP_FR_PROBE;
        case 0x0: case 0x1: case 0x2: case 0x3: case 0xB: case 0xC:
            return WCAP_FR_AUTH;
        default: return WCAP_FR_MGMT;
        }
    }
    if (t == 2) return is_eapol ? WCAP_FR_EAPOL : WCAP_FR_DATA;
    return WCAP_FR_CTRL;
}

/* Does this frame involve the targeted BSSID at all? */
static bool matches_target(const uint8_t *p, uint32_t len)
{
    if (!s_have_target) return true;
    if (len < 16 + 6) return false;
    /* addr1, addr2, addr3 - the BSSID is one of them for anything we care
     * about, and checking all three also catches frames to and from the
     * client without having to know which direction this one went. */
    return memcmp(p + 4,  s_target, 6) == 0 ||
           memcmp(p + 10, s_target, 6) == 0 ||
           memcmp(p + 16, s_target, 6) == 0;
}

static void promisc_cb(void *buf, wifi_promiscuous_pkt_type_t type)
{
    if (type == WIFI_PKT_MISC) return;

    const wifi_promiscuous_pkt_t *pkt = (const wifi_promiscuous_pkt_t *)buf;
    const uint32_t len = pkt->rx_ctrl.sig_len;
    const uint8_t *p = pkt->payload;

    if (len < 10) return;

    const uint8_t ch = s_cur_channel;
    const int8_t rssi = pkt->rx_ctrl.rssi;
    const int8_t noise = pkt->rx_ctrl.noise_floor;

    portENTER_CRITICAL_ISR(&s_mux);
    s_st.frames_seen++;
    s_st.frames_this_dwell++;
    if (s_cur_plan_index < WCAP_N_CHANNELS) {
        s_st.hits_per_channel[s_cur_plan_index]++;
    }
    portEXIT_CRITICAL_ISR(&s_mux);

    /* ---- is this an EAPOL-Key frame? ---- */
    bool is_eapol = false;
    int msg = 0;
    bool pmkid = false;
    uint8_t pmkid_val[16] = {0};
    const uint8_t *ap_addr = NULL, *sta_addr = NULL;

    if (FC_TYPE(p) == 2 && !FC_PROT(p)) {
        const int hl = data_hdr_len(p);
        /* LLC/SNAP (6) + ethertype (2) */
        if (len >= (uint32_t)hl + 8) {
            const uint8_t *llc = p + hl;
            static const uint8_t snap[6] = { 0xAA, 0xAA, 0x03, 0x00, 0x00, 0x00 };
            if (memcmp(llc, snap, 6) == 0 && be16(llc + 6) == 0x888E) {
                is_eapol = true;
                const uint8_t *e = llc + 8;              /* EAPOL header */
                if (len >= (uint32_t)hl + 8 + 4 && e[1] == 3) {
                    const uint8_t *k = e + 4;            /* EAPOL-Key body */
                    const uint32_t avail = len - (uint32_t)(hl + 8 + 4);
                    msg = eapol_msg(k, avail, &pmkid, pmkid_val);
                    if (msg) {
                        const uint16_t ki = be16(k + EK_KEY_INFO);
                        /* ACK set => from the authenticator, so addr1 is the
                         * supplicant; otherwise addr2 is. */
                        ap_addr = p + 16;                /* addr3 == BSSID */
                        sta_addr = (ki & KI_ACK) ? p + 4 : p + 10;
                    }
                }
            }
        }
    }

    const wcap_frame_class_t fc = classify(p, is_eapol);

    portENTER_CRITICAL_ISR(&s_mux);
    if (fc == WCAP_FR_BEACON) s_st.beacons++;
    if (is_eapol) s_st.eapol++;
    if (len >= 16) {
        memcpy(s_st.last_mac, p + 10, 6);   /* addr2, the transmitter */
        s_st.last_rssi = rssi;
        s_st.last_channel = ch;
        s_st.last_class = (uint8_t)fc;
        s_st.have_last = true;
    }
    if (msg && ap_addr && sta_addr) {
        hs_note(ap_addr, sta_addr, msg, pmkid, pmkid_val);
    }
    portEXIT_CRITICAL_ISR(&s_mux);

    /* Beacon parsing walks IEs, so it stays out of the critical section. */
    if (fc == WCAP_FR_BEACON) note_beacon(p, len, rssi, ch);

    /* ---- recording ---- */
    const wcap_rec_t rec = s_rec;
    if (rec == WCAP_REC_OFF || !wcap_ring) return;

    if (rec == WCAP_REC_HANDSHAKE) {
        /*
         * Management frames and EAPOL only. This is the whole reason the SD
         * bandwidth question never arises: a four-way handshake plus the
         * beacons that name the network is a few kilobytes, while recording
         * every data frame on a busy channel is megabytes a minute through an
         * SD card that shares its SPI bus with the display.
         */
        if (FC_TYPE(p) != 0 && !is_eapol) return;
    }
    if (!matches_target(p, len)) return;

    uint16_t keep = (uint16_t)(len > CONFIG_WCAP_SNAPLEN ? CONFIG_WCAP_SNAPLEN : len);

    wcap_rec_hdr_t h = {
        .ts_sec   = (uint32_t)(esp_timer_get_time() / 1000000),
        .ts_usec  = (uint32_t)(esp_timer_get_time() % 1000000),
        .rssi     = rssi,
        .noise    = noise,
        .channel  = ch,
        .rate     = 0,
        .len      = keep,
        .orig_len = (uint16_t)len,
    };

    /*
     * One ring buffer item holds the metadata and the frame together, so the
     * writer can never pair a header with the wrong payload. Zero timeout:
     * this is the Wi-Fi task, and blocking it to wait for an SD card would
     * drop far more frames than it saves.
     */
    void *slot = NULL;
    if (xRingbufferSendAcquire(wcap_ring, &slot, sizeof(h) + keep, 0) == pdTRUE) {
        memcpy(slot, &h, sizeof(h));
        memcpy((uint8_t *)slot + sizeof(h), p, keep);
        xRingbufferSendComplete(wcap_ring, slot);
    } else {
        portENTER_CRITICAL_ISR(&s_mux);
        s_st.dropped_ring++;
        portEXIT_CRITICAL_ISR(&s_mux);
    }
}

/* ------------------------------------------------------------------ */
/* Self-test                                                           */
/* ------------------------------------------------------------------ */

/*
 * Exercise the EAPOL-Key classifier and the handshake state machine with
 * synthetic key frames.
 *
 * This exists because the interesting path is the one that is hardest to
 * trigger on demand. A four-way handshake happens when some device decides
 * to associate, and the only ways to make that happen on cue are to own the
 * network or to deauthenticate somebody -- and this firmware will not
 * transmit. So the parser that decides M1 from M2 from M4 would otherwise
 * ship having never been run.
 *
 * It also gives the demo a fallback: the handshake banner can be shown to a
 * room even when nothing on the air is cooperating.
 *
 * Nothing here touches the radio or the capture file. The frames are built
 * in memory, run through the same eapol_msg() and hs_note() the live path
 * uses, and the synthetic pair is removed afterwards.
 */
int wcap_selftest(char *out, size_t n)
{
    /* key_info bit patterns for the four messages of the four-way handshake */
    static const struct {
        uint16_t ki;
        uint16_t kdl;
        int expect;
        const char *name;
    } cases[] = {
        { KI_PAIRWISE | KI_ACK,                                    0,  1, "M1" },
        { KI_PAIRWISE | KI_MIC,                                   22,  2, "M2" },
        { KI_PAIRWISE | KI_INSTALL | KI_ACK | KI_MIC | KI_SECURE, 56,  3, "M3" },
        { KI_PAIRWISE | KI_MIC | KI_SECURE,                        0,  4, "M4" },
    };

    uint8_t body[EK_MIN_LEN];
    int pass = 0, fail = 0;
    size_t used = 0;

    for (size_t i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) {
        memset(body, 0, sizeof(body));
        body[EK_DESC_TYPE] = 2;                       /* RSN key descriptor */
        body[EK_KEY_INFO]     = (uint8_t)(cases[i].ki >> 8);
        body[EK_KEY_INFO + 1] = (uint8_t)(cases[i].ki & 0xff);
        body[EK_KDL]     = (uint8_t)(cases[i].kdl >> 8);
        body[EK_KDL + 1] = (uint8_t)(cases[i].kdl & 0xff);

        bool pmkid = false;
        uint8_t pv[16] = {0};
        const int got = eapol_msg(body, sizeof(body), &pmkid, pv);
        const bool ok = (got == cases[i].expect);
        ok ? pass++ : fail++;

        const int w = snprintf(out + used, n > used ? n - used : 0,
                               "%s%s=%d%s", used ? " " : "",
                               cases[i].name, got, ok ? "" : "!");
        if (w > 0) used += (size_t)w;
    }

    /*
     * Now drive the state machine itself, which is where "crackable" is
     * decided. A synthetic pair under a locally-administered address so it
     * cannot collide with a real one.
     */
    static const uint8_t ap[6]  = { 0x02, 0x00, 0x00, 0x53, 0x45, 0x4c };
    static const uint8_t sta[6] = { 0x02, 0x00, 0x00, 0x54, 0x53, 0x54 };

    portENTER_CRITICAL(&s_mux);
    for (int m = 1; m <= 4; m++) hs_note(ap, sta, m, false, NULL);
    uint8_t seen = 0;
    for (int i = 0; i < WCAP_MAX_HS; i++) {
        if (s_hs[i].used && memcmp(s_hs[i].ap, ap, 6) == 0) {
            seen = s_hs[i].seen;
            /* Remove it again: a self-test must not leave a fake handshake
             * in a list someone is about to read as evidence. */
            memset(&s_hs[i], 0, sizeof(s_hs[i]));
            if (s_st.n_hs) s_st.n_hs--;
            break;
        }
    }
    portEXIT_CRITICAL(&s_mux);

    const bool sm_ok = (seen == (WCAP_M1 | WCAP_M2 | WCAP_M3 | WCAP_M4)) &&
                       wcap_hs_crackable(seen);
    sm_ok ? pass++ : fail++;

    snprintf(out + used, n > used ? n - used : 0,
             " state=%x%s", seen, sm_ok ? "" : "!");

    return fail;
}

/* ------------------------------------------------------------------ */
/* Init                                                                */
/* ------------------------------------------------------------------ */

esp_err_t wcap_capture_init(void)
{
    memset(&s_st, 0, sizeof(s_st));
    memset(s_aps, 0, sizeof(s_aps));
    memset(s_hs, 0, sizeof(s_hs));
    s_st.dwell_ms = CONFIG_WCAP_DWELL_MS;
    snprintf(s_st.banner, WCAP_BANNER_MAX, "no handshake yet");

    wcap_ring = xRingbufferCreate(CONFIG_WCAP_RING_BYTES, RINGBUF_TYPE_NOSPLIT);
    if (!wcap_ring) return ESP_ERR_NO_MEM;

    ESP_LOGI(TAG, "ring %d bytes, snaplen %d",
             CONFIG_WCAP_RING_BYTES, CONFIG_WCAP_SNAPLEN);
    return ESP_OK;
}

esp_err_t wcap_capture_attach(void)
{
    /*
     * Management AND data. Management gives beacons, probes and the
     * auth/assoc run-up; data is where EAPOL lives, so filtering data out is
     * precisely how people end up with a sniffer that "works" and never sees
     * a handshake. Control frames are left off: they are the bulk of the
     * frames on a busy channel and carry nothing this demo needs.
     */
    wifi_promiscuous_filter_t filter = {
        .filter_mask = WIFI_PROMIS_FILTER_MASK_MGMT | WIFI_PROMIS_FILTER_MASK_DATA,
    };
    ESP_ERROR_CHECK(esp_wifi_set_promiscuous_filter(&filter));
    ESP_ERROR_CHECK(esp_wifi_set_promiscuous_rx_cb(promisc_cb));
    ESP_ERROR_CHECK(esp_wifi_set_promiscuous(true));
    return ESP_OK;
}
