/*
 * wificap — the serial console.
 *
 * This is how a demo is driven and how the host-side Python tool talks to the
 * board. Commands are one word plus arguments; every reply is one line
 * starting with a tag (OK, ERR, STAT, AP, HS), so the same interface serves a
 * human watching a terminal and a script parsing it.
 *
 * It is built on esp_console's REPL rather than on a hand-rolled read loop,
 * and that is worth recording because the hand-rolled version looked like it
 * worked. Driving the USB serial/JTAG peripheral directly -- either with
 * usb_serial_jtag_read_bytes() or by calling usb_serial_jtag_vfs_use_driver()
 * and reading stdin -- fights whatever the console layer has already set up on
 * the same peripheral. The failure is quiet and asymmetric: ESP_LOGx output
 * keeps appearing, because logging goes straight to the console driver, while
 * every printf() from the command task vanishes and every keystroke from the
 * host is dropped. A board in that state looks alive and completely ignores
 * you. esp_console owns the peripheral and does the VFS setup properly.
 *
 * SPDX-License-Identifier: MIT
 */

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

#include "esp_app_desc.h"
#include "esp_console.h"
#include "esp_log.h"
#include "esp_rom_crc.h"
#include "freertos/FreeRTOS.h"
#include "linenoise/linenoise.h"

#include "bsp/esp-bsp.h"

#include "wcap.h"

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

/* ------------------------------------------------------------------ */

static bool parse_mac(const char *s, uint8_t out[6])
{
    unsigned v[6];
    if (sscanf(s, "%x:%x:%x:%x:%x:%x", &v[0], &v[1], &v[2], &v[3], &v[4], &v[5]) != 6 &&
        sscanf(s, "%2x%2x%2x%2x%2x%2x", &v[0], &v[1], &v[2], &v[3], &v[4], &v[5]) != 6) {
        return false;
    }
    for (int i = 0; i < 6; i++) {
        if (v[i] > 0xff) return false;
        out[i] = (uint8_t)v[i];
    }
    return true;
}

/*
 * One line, fixed field order, key=value. Parsed by the host tool; appending
 * fields is safe, reordering is not.
 */
static int cmd_stat(int argc, char **argv)
{
    (void)argc; (void)argv;

    wcap_status_t st;
    wcap_status_get(&st);

    printf("STAT mode=%s rec=%s ch=%u band=%s plan=%u/%u sweeps=%lu "
           "frames=%lu fps=%lu beacons=%lu eapol=%lu aps=%u "
           "written=%lu bytes=%lu drop=%lu sd=%d hs=%u complete=%lu "
           "crackable=%d file=%s target=%02x:%02x:%02x:%02x:%02x:%02x\n",
           st.mode == WCAP_MODE_PARKED ? "park" : "survey",
           st.rec == WCAP_REC_OFF ? "off" : st.rec == WCAP_REC_HANDSHAKE ? "hs" : "all",
           st.channel, st.is_5g ? "5g" : "2g",
           st.n_available, (unsigned)WCAP_N_CHANNELS,
           (unsigned long)st.sweeps,
           (unsigned long)st.frames_seen, (unsigned long)st.fps,
           (unsigned long)st.beacons, (unsigned long)st.eapol,
           st.n_aps,
           (unsigned long)st.written, (unsigned long)st.bytes,
           (unsigned long)st.dropped_ring,
           st.sd_ok ? 1 : 0,
           st.n_hs, (unsigned long)st.hs_complete,
           st.any_crackable ? 1 : 0,
           st.path[0] ? st.path : "-",
           st.have_target ? st.target[0] : 0, st.have_target ? st.target[1] : 0,
           st.have_target ? st.target[2] : 0, st.have_target ? st.target[3] : 0,
           st.have_target ? st.target[4] : 0, st.have_target ? st.target[5] : 0);
    fflush(stdout);
    return 0;
}

static int cmd_aps(int argc, char **argv)
{
    (void)argc; (void)argv;

    /*
     * static, not automatic. The whole AP table is ~2.3 KB and the console
     * task's stack is smaller than that, so taking a copy on the stack
     * overflows it and panics the task -- which presents as the console
     * simply going silent. Safe because the REPL runs one command at a time.
     */
    static wcap_ap_t aps[WCAP_MAX_APS];
    const int n = wcap_ap_list(aps, WCAP_MAX_APS);
    /* Data first, summary last. The OK line is the host's terminator, so
     * printing it first makes every record after it unreadable to a reader
     * that stops on OK -- which is exactly what the host tool does. */
    for (int i = 0; i < n; i++) {
        printf("AP %02x:%02x:%02x:%02x:%02x:%02x ch=%u rssi=%d beacons=%u ssid=%s\n",
               aps[i].bssid[0], aps[i].bssid[1], aps[i].bssid[2],
               aps[i].bssid[3], aps[i].bssid[4], aps[i].bssid[5],
               aps[i].channel, aps[i].rssi, aps[i].beacons,
               aps[i].ssid[0] ? aps[i].ssid : "<hidden>");
    }
    printf("OK %d ap(s)\n", n);
    fflush(stdout);
    return 0;
}

static int cmd_hs(int argc, char **argv)
{
    (void)argc; (void)argv;

    static wcap_hs_t hs[WCAP_MAX_HS];   /* see cmd_aps: console stack is small */
    const int n = wcap_hs_list(hs, WCAP_MAX_HS);
    for (int i = 0; i < n; i++) {
        printf("HS ap=%02x:%02x:%02x:%02x:%02x:%02x sta=%02x:%02x:%02x:%02x:%02x:%02x "
               "m=%c%c%c%c pmkid=%d crackable=%d\n",
               hs[i].ap[0], hs[i].ap[1], hs[i].ap[2],
               hs[i].ap[3], hs[i].ap[4], hs[i].ap[5],
               hs[i].sta[0], hs[i].sta[1], hs[i].sta[2],
               hs[i].sta[3], hs[i].sta[4], hs[i].sta[5],
               (hs[i].seen & WCAP_M1) ? '1' : '-',
               (hs[i].seen & WCAP_M2) ? '2' : '-',
               (hs[i].seen & WCAP_M3) ? '3' : '-',
               (hs[i].seen & WCAP_M4) ? '4' : '-',
               hs[i].pmkid ? 1 : 0,
               wcap_hs_crackable(hs[i].seen) ? 1 : 0);
    }
    printf("OK %d pair(s) m1_keydata=%u\n", n, wcap_last_m1_kdl());
    fflush(stdout);
    return 0;
}

static int cmd_survey(int argc, char **argv)
{
    (void)argc; (void)argv;
    wcap_set_mode(WCAP_MODE_SURVEY);
    printf("OK survey\n");
    fflush(stdout);
    return 0;
}

static int cmd_park(int argc, char **argv)
{
    if (argc < 2) { printf("ERR park needs a channel\n"); fflush(stdout); return 1; }
    const int ch = atoi(argv[1]);
    if (ch <= 0 || ch > 177) { printf("ERR bad channel\n"); fflush(stdout); return 1; }

    wcap_set_mode(WCAP_MODE_PARKED);
    if (!wcap_tune((uint8_t)ch)) {
        printf("ERR radio refused channel %d\n", ch);
        fflush(stdout);
        return 1;
    }
    printf("OK parked ch=%d\n", ch);
    fflush(stdout);
    return 0;
}

static int cmd_target(int argc, char **argv)
{
    if (argc < 2) { printf("ERR target needs a bssid\n"); fflush(stdout); return 1; }

    uint8_t mac[6];
    if (!parse_mac(argv[1], mac)) { printf("ERR bad bssid\n"); fflush(stdout); return 1; }

    wcap_set_target(mac);
    const uint8_t ch = wcap_ap_channel(mac);
    if (ch) {
        wcap_set_mode(WCAP_MODE_PARKED);
        if (wcap_tune(ch)) {
            printf("OK target set, parked ch=%u\n", ch);
        } else {
            printf("ERR target set but radio refused ch=%u\n", ch);
        }
    } else {
        /*
         * No channel for this BSSID means the survey never heard it. Say so
         * rather than parking on a guess: parking on the wrong channel gives
         * an empty capture for a reason nobody can see.
         */
        printf("OK target set; channel unknown, run survey or park manually\n");
    }
    fflush(stdout);
    return 0;
}

static int cmd_notarget(int argc, char **argv)
{
    (void)argc; (void)argv;
    wcap_clear_target();
    printf("OK target cleared\n");
    fflush(stdout);
    return 0;
}

static int cmd_rec(int argc, char **argv)
{
    if (argc < 2) { printf("ERR rec needs hs|all|off\n"); fflush(stdout); return 1; }

    if (!strcmp(argv[1], "off")) {
        wcap_set_rec(WCAP_REC_OFF);
        wcap_pcap_close();
        printf("OK rec off\n");
    } else if (!strcmp(argv[1], "hs") || !strcmp(argv[1], "all")) {
        if (wcap_pcap_open() != ESP_OK) {
            printf("ERR cannot open capture file (SD card?)\n");
            fflush(stdout);
            return 1;
        }
        wcap_set_rec(!strcmp(argv[1], "hs") ? WCAP_REC_HANDSHAKE : WCAP_REC_ALL);
        wcap_status_t st;
        wcap_status_get(&st);
        printf("OK rec %s file=%s\n", argv[1], st.path);
    } else {
        printf("ERR rec needs hs|all|off\n");
        fflush(stdout);
        return 1;
    }
    fflush(stdout);
    return 0;
}

/*
 * Dump recovered PMKIDs in hashcat's 22000 format, so the output of a demo is
 * a line you can paste straight into a cracking run rather than something
 * that needs converting first:
 *
 *   WPA*01*<pmkid>*<ap mac>*<sta mac>*<essid hex>***
 *
 * The 01 is the PMKID message type; 02 would be a full EAPOL handshake, which
 * cannot be expressed in one line and belongs in the pcap instead.
 */
static void hex_append(char *dst, size_t cap, const uint8_t *src, size_t n)
{
    size_t used = strlen(dst);
    for (size_t i = 0; i < n && used + 2 < cap; i++) {
        snprintf(dst + used, cap - used, "%02x", src[i]);
        used += 2;
    }
}

static int cmd_pmkid_list(int argc, char **argv)
{
    (void)argc; (void)argv;

    static wcap_hs_t hs[WCAP_MAX_HS];   /* see cmd_aps: console stack is small */
    const int n = wcap_hs_list(hs, WCAP_MAX_HS);
    int found = 0;

    for (int i = 0; i < n; i++) {
        if (!hs[i].pmkid) continue;
        found++;

        char ssid[WCAP_SSID_MAX] = {0};
        wcap_ap_ssid(hs[i].ap, ssid, sizeof(ssid));

        char line[200] = {0};
        strcpy(line, "WPA*01*");
        hex_append(line, sizeof(line), hs[i].pmkid_val, 16);
        strncat(line, "*", sizeof(line) - strlen(line) - 1);
        hex_append(line, sizeof(line), hs[i].ap, 6);
        strncat(line, "*", sizeof(line) - strlen(line) - 1);
        hex_append(line, sizeof(line), hs[i].sta, 6);
        strncat(line, "*", sizeof(line) - strlen(line) - 1);
        hex_append(line, sizeof(line), (const uint8_t *)ssid, strlen(ssid));
        strncat(line, "***", sizeof(line) - strlen(line) - 1);

        printf("PMKID %s\n", line);
        printf("PMKIDSSID %s\n", ssid[0] ? ssid : "<unknown>");
    }

    printf("OK %d pmkid(s)\n", found);
    fflush(stdout);
    return 0;
}

/*
 * The active probe. Separate command, never implied by any other, and it
 * refuses to guess: without an SSID the association request has nowhere to
 * go, and the SSID is also salted into the PMKID itself.
 */
static int cmd_attack(int argc, char **argv)
{
    if (argc < 2) {
        printf("ERR attack needs a bssid (run survey first)\n");
        fflush(stdout);
        return 1;
    }

    uint8_t mac[6];
    if (!parse_mac(argv[1], mac)) { printf("ERR bad bssid\n"); fflush(stdout); return 1; }

    const uint8_t ch = wcap_ap_channel(mac);
    if (!ch) {
        printf("ERR unknown BSSID; run 'survey' so its channel and SSID are known\n");
        fflush(stdout);
        return 1;
    }

    char ssid[WCAP_SSID_MAX] = {0};
    if (!wcap_ap_ssid(mac, ssid, sizeof(ssid))) {
        printf("ERR no SSID known for that BSSID (hidden network?)\n");
        fflush(stdout);
        return 1;
    }

    const uint32_t wait = (argc >= 3) ? (uint32_t)atoi(argv[2]) * 1000u : 6000u;

    printf("OK transmitting: associating to %s on ch %u for up to %lus\n",
           ssid, ch, (unsigned long)(wait / 1000));
    fflush(stdout);

    const esp_err_t err = wcap_pmkid_probe(mac, ch, ssid, wait);
    if (err == ESP_OK) {
        printf("OK pmkid captured; 'pmkid' to print it\n");
    } else if (err == ESP_ERR_NOT_FOUND) {
        printf("ERR no PMKID offered (no PMK caching, WPA3/SAE, or no answer)\n");
    } else {
        printf("ERR probe failed: %s\n", esp_err_to_name(err));
    }
    fflush(stdout);
    return err == ESP_OK ? 0 : 1;
}

static int cmd_selftest(int argc, char **argv)
{
    (void)argc; (void)argv;

    char res[96] = {0};
    const int fails = wcap_selftest(res, sizeof(res));
    printf("%s selftest %s\n", fails ? "ERR" : "OK", res);
    if (fails) printf("ERR %d check(s) failed\n", fails);
    fflush(stdout);
    return fails ? 1 : 0;
}

/* ------------------------------------------------------------------ */
/* Getting captures off the card without taking the card out            */
/* ------------------------------------------------------------------ */

/*
 * A demo where the payoff is "now eject the card, find an adapter, and plug
 * it into a laptop" loses the room. These two commands stream the capture
 * over the same serial link that is already attached, so the pcap lands on
 * the host next to the terminal that is driving the board.
 *
 * Base64 rather than raw bytes because this shares a line with log output
 * and a human-readable console; a raw binary stream would be chewed up by
 * both. The CRC is there because a serial transfer that silently drops a
 * chunk produces a pcap that opens fine and is subtly wrong.
 */

static const char B64[] =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

static void b64_line(const uint8_t *in, size_t n)
{
    char out[80];
    size_t o = 0;
    for (size_t i = 0; i < n; i += 3) {
        const uint32_t a = in[i];
        const uint32_t b = (i + 1 < n) ? in[i + 1] : 0;
        const uint32_t c = (i + 2 < n) ? in[i + 2] : 0;
        const uint32_t v = (a << 16) | (b << 8) | c;
        out[o++] = B64[(v >> 18) & 0x3f];
        out[o++] = B64[(v >> 12) & 0x3f];
        out[o++] = (i + 1 < n) ? B64[(v >> 6) & 0x3f] : '=';
        out[o++] = (i + 2 < n) ? B64[v & 0x3f] : '=';
    }
    out[o] = '\0';
    printf("B64 %s\n", out);
}

static int cmd_ls(int argc, char **argv)
{
    (void)argc; (void)argv;

    DIR *d = opendir(BSP_SD_MOUNT_POINT);
    if (!d) { printf("ERR cannot open %s\n", BSP_SD_MOUNT_POINT); fflush(stdout); return 1; }

    struct dirent *e;
    int n = 0;
    while ((e = readdir(d)) != NULL) {
        /* Long filenames are enabled, so d_name can be 255 bytes; this
         * buffer has to hold the mount point, a separator and all of it. */
        char path[300];
        snprintf(path, sizeof(path), "%s/%s", BSP_SD_MOUNT_POINT, e->d_name);
        struct stat st;
        if (stat(path, &st) == 0 && S_ISREG(st.st_mode)) {
            printf("FILE %s %ld\n", e->d_name, (long)st.st_size);
            n++;
        }
    }
    closedir(d);
    printf("OK %d file(s)\n", n);
    fflush(stdout);
    return 0;
}

static int cmd_get(int argc, char **argv)
{
    if (argc < 2) { printf("ERR get needs a filename\n"); fflush(stdout); return 1; }

    char path[80];
    if (argv[1][0] == '/') {
        snprintf(path, sizeof(path), "%s", argv[1]);
    } else {
        snprintf(path, sizeof(path), "%s/%s", BSP_SD_MOUNT_POINT, argv[1]);
    }

    /*
     * Refuse while recording. The file is open with buffered writes in
     * another task, so a transfer taken now is a torn copy of a moving
     * target -- and it would look like a complete one.
     */
    wcap_status_t st;
    wcap_status_get(&st);
    if (st.rec != WCAP_REC_OFF && !strcmp(path, st.path)) {
        printf("ERR still recording to that file; 'rec off' first\n");
        fflush(stdout);
        return 1;
    }

    FILE *f = fopen(path, "rb");
    if (!f) { printf("ERR cannot open %s\n", path); fflush(stdout); return 1; }

    struct stat sb;
    long size = (stat(path, &sb) == 0) ? (long)sb.st_size : -1;
    printf("GET %s %ld\n", path, size);

    uint8_t buf[57];          /* 57 bytes -> exactly 76 base64 characters */
    uint32_t crc = 0;
    size_t n;
    while ((n = fread(buf, 1, sizeof(buf), f)) > 0) {
        crc = esp_rom_crc32_le(crc, buf, n);
        b64_line(buf, n);
    }
    fclose(f);

    printf("END crc32=%08lx\n", (unsigned long)crc);
    fflush(stdout);
    return 0;
}

static int cmd_rm(int argc, char **argv)
{
    if (argc < 2) { printf("ERR rm needs a filename\n"); fflush(stdout); return 1; }

    char path[80];
    if (argv[1][0] == '/') {
        snprintf(path, sizeof(path), "%s", argv[1]);
    } else {
        snprintf(path, sizeof(path), "%s/%s", BSP_SD_MOUNT_POINT, argv[1]);
    }

    wcap_status_t st;
    wcap_status_get(&st);
    if (st.rec != WCAP_REC_OFF && !strcmp(path, st.path)) {
        printf("ERR still recording to that file\n");
        fflush(stdout);
        return 1;
    }

    if (unlink(path) != 0) { printf("ERR cannot remove %s\n", path); fflush(stdout); return 1; }
    printf("OK removed %s\n", path);
    fflush(stdout);
    return 0;
}

/* ------------------------------------------------------------------ */

static void reg(const char *cmd, const char *help, esp_console_cmd_func_t fn,
                const char *hint)
{
    const esp_console_cmd_t c = {
        .command = cmd,
        .help = help,
        .hint = hint,
        .func = fn,
    };
    ESP_ERROR_CHECK(esp_console_cmd_register(&c));
}

void wcap_console_start(void)
{
    esp_console_repl_t *repl = NULL;

    esp_console_repl_config_t repl_cfg = ESP_CONSOLE_REPL_CONFIG_DEFAULT();
    /* No prompt and no history: the output is parsed by a script as often as
     * it is read by a person, and a prompt is just a token to strip. */
    repl_cfg.prompt = "";
    repl_cfg.max_cmdline_length = 96;
    repl_cfg.history_save_path = NULL;
    /*
     * The default REPL stack is around 1.5 KB, which is enough for commands
     * that print a line and far too little for ones that format a table. The
     * listing commands keep their buffers static for the same reason; this is
     * the margin for the formatting itself. An overflow here panics the
     * console task and the only symptom is that the board stops answering.
     */
    repl_cfg.task_stack_size = 8192;

    esp_console_dev_usb_serial_jtag_config_t dev_cfg =
        ESP_CONSOLE_DEV_USB_SERIAL_JTAG_CONFIG_DEFAULT();

    esp_err_t err = esp_console_new_repl_usb_serial_jtag(&dev_cfg, &repl_cfg, &repl);
    if (err != ESP_OK) {
        ESP_LOGE(TAG, "console init failed: %s", esp_err_to_name(err));
        return;
    }

    /*
     * Dumb mode on purpose. There is no terminal on the other end during a
     * scripted run, and linenoise's escape sequences and in-place line
     * editing are what make console output painful to parse.
     */
    linenoiseSetDumbMode(1);

    esp_console_register_help_command();
    reg("stat", "one line of machine-readable status", cmd_stat, NULL);
    reg("aps", "list access points seen during survey", cmd_aps, NULL);
    reg("hs", "list handshake progress per station pair", cmd_hs, NULL);
    reg("survey", "hop the channel plan, build the AP list", cmd_survey, NULL);
    reg("park", "stop on a channel (this is the capture mode)", cmd_park, "<ch>");
    reg("target", "filter to one BSSID and park on its channel", cmd_target, "<bssid>");
    reg("notarget", "clear the BSSID filter", cmd_notarget, NULL);
    reg("rec", "start or stop writing pcap to the SD card", cmd_rec, "hs|all|off");
    reg("ls", "list capture files on the SD card", cmd_ls, NULL);
    reg("get", "stream a capture off the card as base64", cmd_get, "<file>");
    reg("rm", "delete a capture file", cmd_rm, "<file>");
    reg("pmkid", "print recovered PMKIDs in hashcat 22000 format",
        cmd_pmkid_list, NULL);
    reg("attack", "ACTIVE: associate to one AP to collect its PMKID. "
                  "This TRANSMITS. Use only on an AP you administer.",
        cmd_attack, "<bssid> [seconds]");
    reg("selftest", "check the EAPOL parser and handshake state machine",
        cmd_selftest, NULL);

    ESP_ERROR_CHECK(esp_console_start_repl(repl));

    const esp_app_desc_t *d = esp_app_get_description();
    ESP_LOGI(TAG, "console up: wificap %s, receive-only. type 'help'", d->version);
}
