/*
 * wificap — dual-band 802.11 capture appliance for the IoT Security lectures
 *
 * Waveshare ESP32-C5-LCD-1.47: monitor-mode receive, EAPOL/handshake
 * detection, and pcap-with-radiotap written to a microSD card.
 *
 * THIS DEVICE ONLY EVER RECEIVES. It never associates, never probes, never
 * deauthenticates, never transmits. That is not a style preference. The whole
 * point of demonstrating this in a classroom is that the demonstration itself
 * stays on the right side of the line the wifi.html page draws: passive
 * reception of frames that were broadcast to be received. A sniffer that
 * sends a deauth to hurry a handshake along has become an attack tool, and
 * the demo has become something you cannot do in front of students.
 *
 * SPDX-License-Identifier: MIT
 */

#pragma once

#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>

#include "esp_err.h"
#include "freertos/FreeRTOS.h"
#include "freertos/ringbuf.h"

#ifdef __cplusplus
extern "C" {
#endif

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

/*
 * Survey mode walks this to find a target. It is the same arithmetic as the
 * capstone scanner but used for the opposite purpose: there, a sweep IS the
 * product; here a sweep is only how you discover which channel to stop on.
 * Handshake capture and channel hopping are mutually exclusive, which is the
 * single most important thing this firmware demonstrates.
 */
#define WCAP_N_CHANNELS 28
extern const uint8_t wcap_plan[WCAP_N_CHANNELS];

static inline bool wcap_is_5g(uint8_t ch) { return ch > 14; }
uint16_t wcap_chan_to_freq(uint8_t ch);

/* ------------------------------------------------------------------ */
/* Modes                                                               */
/* ------------------------------------------------------------------ */

typedef enum {
    WCAP_MODE_SURVEY = 0,   /* hop the plan, collect BSSIDs, write nothing */
    WCAP_MODE_PARKED,       /* sit on one channel; this is the capture mode */
} wcap_mode_t;

/* What the pcap writer is allowed to record. */
typedef enum {
    WCAP_REC_OFF = 0,
    WCAP_REC_HANDSHAKE,     /* mgmt + EAPOL only: tiny files, all the evidence */
    WCAP_REC_ALL,           /* every frame the filter passed */
} wcap_rec_t;

/* ------------------------------------------------------------------ */
/* Access points learned in survey mode                               */
/* ------------------------------------------------------------------ */

/*
 * 48, because 32 was not enough. A single enterprise access point publishes
 * one BSSID per SSID per band -- five SSIDs across two bands is ten entries
 * from one box -- so on a campus the table fills from the building you are
 * in and a nearby AP you actually care about never gets a slot.
 */
#define WCAP_MAX_APS 48
#define WCAP_SSID_MAX 33

typedef struct {
    uint8_t  bssid[6];
    char     ssid[WCAP_SSID_MAX];
    uint8_t  channel;
    int8_t   rssi;
    uint16_t beacons;
    bool     used;
} wcap_ap_t;

/* ------------------------------------------------------------------ */
/* Handshake tracking                                                 */
/* ------------------------------------------------------------------ */

/*
 * One entry per (authenticator, supplicant) pair. The four bits say which of
 * the four EAPOL-Key messages have been seen; `pmkid` records that M1 carried
 * key data, which is where a PMKID would be.
 */
#define WCAP_M1 0x1
#define WCAP_M2 0x2
#define WCAP_M3 0x4
#define WCAP_M4 0x8

#define WCAP_MAX_HS 16

typedef struct {
    uint8_t  ap[6];
    uint8_t  sta[6];
    uint8_t  seen;          /* WCAP_M1..WCAP_M4 bitmask */
    bool     pmkid;         /* M1 carried a usable PMKID KDE */
    uint8_t  pmkid_val[16];
    uint32_t last_ms;
    bool     used;
} wcap_hs_t;

/*
 * Why "crackable" is not the same as "all four".
 *
 * An offline dictionary attack needs the two nonces and one MIC over a known
 * EAPOL body. M1 carries the ANonce; M2 carries the SNonce and a MIC. So M1+M2
 * is already enough, and so is M2+M3. Waiting for all four is a mistake people
 * make because the handshake has four messages -- aircrack-ng will happily
 * work from two of them, and M4 is frequently lost to a retry.
 */
static inline bool wcap_hs_crackable(uint8_t seen)
{
    return ((seen & (WCAP_M1 | WCAP_M2)) == (WCAP_M1 | WCAP_M2)) ||
           ((seen & (WCAP_M2 | WCAP_M3)) == (WCAP_M2 | WCAP_M3));
}

/* ------------------------------------------------------------------ */
/* Live status, published for the screen and the console              */
/* ------------------------------------------------------------------ */

/* The handshake banner is a short log line, kept because it is the one event
 * in a demo that everyone in the room is waiting for. */
#define WCAP_BANNER_MAX 64

typedef struct {
    wcap_mode_t mode;
    wcap_rec_t  rec;

    /* scheduler -- drives the big channel readout, the dwell bar and the
     * per-channel heat strip, exactly as the survey scanner's screen does */
    uint8_t  channel;
    bool     is_5g;
    uint16_t dwell_ms;
    uint32_t dwell_elapsed_ms;
    uint32_t sweeps;
    uint8_t  plan_pos;
    uint8_t  n_available;
    bool     available[WCAP_N_CHANNELS];
    uint32_t hits_per_channel[WCAP_N_CHANNELS];

    bool     have_target;
    uint8_t  target[6];
    char     target_ssid[WCAP_SSID_MAX];

    /* counters */
    uint32_t frames_seen;
    uint32_t frames_this_dwell;
    uint32_t fps;
    uint32_t fps_peak;
    uint32_t beacons;
    uint32_t eapol;
    uint32_t written;        /* frames committed to the pcap */
    uint32_t dropped_ring;   /* frames lost because the writer fell behind */
    uint32_t bytes;          /* pcap payload bytes written */

    /* sd */
    bool     sd_ok;
    char     path[48];

    /* handshakes */
    uint8_t  n_hs;
    uint8_t  best_seen;      /* most complete handshake so far */
    bool     any_crackable;
    uint32_t hs_complete;    /* how many pairs reached crackable */
    uint32_t pmkid_count;    /* distinct PMKIDs recovered */
    bool     active;         /* true while the radio is TRANSMITTING */
    char     banner[WCAP_BANNER_MAX];
    uint32_t banner_ms;      /* tick when the banner was last written */

    /* last frame, for the bottom status line */
    uint8_t  last_mac[6];
    int8_t   last_rssi;
    uint8_t  last_channel;
    uint8_t  last_class;
    bool     have_last;

    uint8_t  n_aps;
} wcap_status_t;

/* Frame classes, for the status line's three-character tag. */
typedef enum {
    WCAP_FR_BEACON = 0,
    WCAP_FR_PROBE,
    WCAP_FR_AUTH,       /* auth / assoc / reassoc: the run-up to a handshake */
    WCAP_FR_MGMT,
    WCAP_FR_EAPOL,
    WCAP_FR_DATA,
    WCAP_FR_CTRL,
    WCAP_FR_MAX,
} wcap_frame_class_t;

extern const char *const wcap_frame_tag[WCAP_FR_MAX];

void wcap_status_get(wcap_status_t *out);

/* ------------------------------------------------------------------ */
/* Module interfaces                                                  */
/* ------------------------------------------------------------------ */

uint32_t wcap_tick_ms(void);

/* capture.c -- promiscuous receive, classification, EAPOL parsing */
esp_err_t wcap_capture_init(void);
esp_err_t wcap_capture_attach(void);
esp_err_t wcap_wifi_start(void);
void      wcap_set_channel(uint8_t ch);
void      wcap_set_mode(wcap_mode_t m);
void      wcap_set_rec(wcap_rec_t r);
void      wcap_set_target(const uint8_t bssid[6]);
void      wcap_clear_target(void);
void      wcap_scanner_task(void *arg);
int       wcap_ap_list(wcap_ap_t *out, int max);
int       wcap_hs_list(wcap_hs_t *out, int max);
/* Channel the survey last saw this BSSID on, or 0. */
uint8_t   wcap_ap_channel(const uint8_t bssid[6]);

/* Run the EAPOL classifier and handshake state machine against synthetic
 * frames. Writes a short result into `out`; returns the number of failures. */
int wcap_selftest(char *out, size_t n);

void wcap_active_set(bool on);

/*
 * Key-data length of the most recent EAPOL M1.
 *
 * This exists to tell two very different situations apart, which otherwise
 * both present as pmkid=0: an AP that offers no PMKID at all (M1 with no key
 * data, so nothing to find) versus an AP that sent key data this code failed
 * to parse (key data present, no PMKID KDE recognised). The first is a fact
 * about the target; the second would be a bug here.
 */
uint16_t wcap_last_m1_kdl(void);

/*
 * pmkid.c -- THE ONLY CODE PATH IN THIS FIRMWARE THAT TRANSMITS.
 *
 * Associates to one access point in order to collect the PMKID the AP
 * volunteers in EAPOL message 1, then returns the radio to receive-only.
 * Never called except by an explicit operator command.
 */
esp_err_t wcap_pmkid_probe(const uint8_t bssid[6], uint8_t channel,
                           const char *ssid, uint32_t wait_ms);

/* The SSID the survey recorded for this BSSID, or NULL. */
bool wcap_ap_ssid(const uint8_t bssid[6], char *out, size_t n);

/* scan.c -- radio bring-up and the survey/park scheduler */
bool      wcap_tune(uint8_t ch);
uint8_t   wcap_n_available(void);

/* Status publishers. The status block lives in capture.c behind its spinlock;
 * these are the only way the other modules write to it. */
void wcap_plan_publish(const bool *avail, uint8_t n);
void wcap_fps_publish(uint32_t fps);
void wcap_dwell_publish(uint16_t total_ms, uint32_t elapsed_ms);
void wcap_sweep_tick(void);
void wcap_write_publish(uint32_t frames, uint32_t bytes);
void wcap_sd_publish(bool ok, const char *path);
void wcap_banner_set(const char *text);

/* The ring buffer carrying captured frames from the Wi-Fi task to the writer. */
extern RingbufHandle_t wcap_ring;

/* pcap.c -- radiotap + pcap to the SD card */
esp_err_t wcap_sd_mount(void);
esp_err_t wcap_pcap_open(void);
void      wcap_pcap_close(void);
bool      wcap_pcap_is_open(void);
void      wcap_writer_task(void *arg);

/*
 * What goes into the ring buffer: our own metadata, then the raw 802.11
 * frame. The radiotap header is built by the writer, not here, so the Wi-Fi
 * task copies as few bytes as possible.
 */
typedef struct {
    uint32_t ts_sec;
    uint32_t ts_usec;
    int8_t   rssi;
    int8_t   noise;
    uint8_t  channel;
    uint8_t  rate;          /* 500 kbps units, 0 if unknown */
    uint16_t len;           /* bytes of frame following this header */
    uint16_t orig_len;      /* length before snaplen truncation */
} wcap_rec_hdr_t;

/* ui.c -- the screen */
esp_err_t wcap_ui_init(void);
void      wcap_ui_task(void *arg);

/* console.c -- the demo driver */
void wcap_console_start(void);

#ifdef __cplusplus
}
#endif
