/*
 * Local CPU-cache timing channel demonstration.
 *
 * The receiver process is forked before the random payload is generated, so it
 * does not inherit the sender's message bits. Both processes share a
 * read-only anonymous payload mapping. Before each bit, the receiver warms one
 * cache line. The sender encodes 1 by evicting that line with CLFLUSH and 0 by
 * leaving it warm. The receiver times a reload. Separate shared atomic
 * counters only coordinate the test harness; they do not carry message bits.
 * A pipe returns decoded bits to the parent only after transmission for
 * scoring. No file, /dev/shm, socket, or network carries the payload.
 *
 * This demonstrates the cache-timing mechanism only. It is not a reproduction
 * of OpenAI's microVM setup: the processes share a physical page and a local
 * synchronization mapping on one host.
 *
 * Build/run (Linux x86-64):
 *   gcc -O2 -march=native -std=c11 -Wall -Wextra -Werror \
 *     -o /tmp/cache-poc static/code/covert-channel-cache-poc.c && /tmp/cache-poc
 */
#define _GNU_SOURCE
#define _POSIX_C_SOURCE 200809L

#include <errno.h>
#include <sched.h>
#include <signal.h>
#include <stdatomic.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/random.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#include <x86intrin.h>

#define PAYLOAD_BYTES 2
#define PAYLOAD_BITS (PAYLOAD_BYTES * 8)
#define REPEATS 31
#define CALIBRATION_SAMPLES 101
#define CACHE_LINE_BYTES 64

struct sync_state {
    _Alignas(CACHE_LINE_BYTES) _Atomic uint32_t ready;
    _Alignas(CACHE_LINE_BYTES) _Atomic uint32_t done;
};

static volatile uint8_t *probe_line;
static struct sync_state *sync_state_shared;

static uint64_t timed_reload(volatile uint8_t *line) {
    unsigned int aux;
    _mm_mfence();
    _mm_lfence();
    uint64_t start = __rdtscp(&aux);
    _mm_lfence();
    volatile uint8_t value = *line;
    (void)value;
    _mm_lfence();
    uint64_t end = __rdtscp(&aux);
    _mm_lfence();
    return end - start;
}

static void evict_line(volatile uint8_t *line) {
    _mm_clflush((const void *)line);
    _mm_mfence();
}

static uint64_t median(uint64_t *values, size_t count) {
    for (size_t i = 1; i < count; i++) {
        uint64_t value = values[i];
        size_t j = i;
        while (j > 0 && values[j - 1] > value) {
            values[j] = values[j - 1];
            j--;
        }
        values[j] = value;
    }
    return values[count / 2];
}

static int choose_cpu(void) {
    cpu_set_t allowed;
    CPU_ZERO(&allowed);
    if (sched_getaffinity(0, sizeof(allowed), &allowed) != 0) return -1;
    for (int cpu = 0; cpu < CPU_SETSIZE; cpu++) {
        if (CPU_ISSET(cpu, &allowed)) return cpu;
    }
    return -1;
}

static void pin_to_cpu(int cpu) {
    if (cpu < 0) return;
    cpu_set_t set;
    CPU_ZERO(&set);
    CPU_SET(cpu, &set);
    if (sched_setaffinity(0, sizeof(set), &set) != 0) {
        fprintf(stderr, "warning: could not pin process to CPU %d: %s\n",
                cpu, strerror(errno));
    }
}

static void wait_for_value(_Atomic uint32_t *field, uint32_t expected) {
    while (atomic_load_explicit(field, memory_order_acquire) != expected) {
        sched_yield();
    }
}

static void write_all(int fd, const uint8_t *data, size_t length) {
    size_t written = 0;
    while (written < length) {
        ssize_t n = write(fd, data + written, length - written);
        if (n < 0 && errno == EINTR) continue;
        if (n <= 0) _exit(2);
        written += (size_t)n;
    }
}

static int sender_child(int cpu, const uint8_t *bits, size_t nbits) {
    pin_to_cpu(cpu);
    size_t total = nbits * REPEATS;
    for (size_t sample = 0; sample < total; sample++) {
        uint32_t sequence = (uint32_t)sample + 1;
        wait_for_value(&sync_state_shared->ready, sequence);
        if (bits[sample % nbits] == 1) evict_line(probe_line);
        atomic_store_explicit(&sync_state_shared->done, sequence,
                              memory_order_release);
    }
    _exit(0);
}

static int receiver_child(int cpu, size_t nbits, int report_fd) {
    pin_to_cpu(cpu);

    uint64_t cold[CALIBRATION_SAMPLES];
    uint64_t warm[CALIBRATION_SAMPLES];
    for (size_t i = 0; i < CALIBRATION_SAMPLES; i++) {
        evict_line(probe_line);
        cold[i] = timed_reload(probe_line);
        (void)*probe_line;
        _mm_mfence();
        warm[i] = timed_reload(probe_line);
    }
    uint64_t cold_median = median(cold, CALIBRATION_SAMPLES);
    uint64_t warm_median = median(warm, CALIBRATION_SAMPLES);
    if (cold_median <= warm_median) {
        fprintf(stderr, "cache calibration did not separate warm and evicted loads\n");
        _exit(2);
    }
    uint64_t threshold = warm_median + (cold_median - warm_median) / 3;

    uint8_t decoded_bits[PAYLOAD_BITS];
    uint64_t timings[PAYLOAD_BITS][REPEATS];
    size_t total = nbits * REPEATS;
    for (size_t sample = 0; sample < total; sample++) {
        uint32_t sequence = (uint32_t)sample + 1;
        (void)*probe_line;
        _mm_mfence();
        atomic_store_explicit(&sync_state_shared->ready, sequence,
                              memory_order_release);
        wait_for_value(&sync_state_shared->done, sequence);
        timings[sample % nbits][sample / nbits] = timed_reload(probe_line);
    }

    for (size_t bit = 0; bit < nbits; bit++) {
        size_t evicted = 0;
        for (size_t repeat = 0; repeat < REPEATS; repeat++) {
            if (timings[bit][repeat] > threshold) evicted++;
        }
        decoded_bits[bit] = (evicted > REPEATS / 2) ? 1 : 0;
    }

    uint8_t decoded[PAYLOAD_BYTES] = {0};
    for (size_t bit = 0; bit < nbits; bit++) {
        decoded[bit / 8] = (uint8_t)((decoded[bit / 8] << 1) | decoded_bits[bit]);
    }

    printf("CPU-cache timing PoC (local x86-64 process pair)\n");
    printf("CPU affinity: receiver=%d sender=%d\n", cpu, cpu);
    printf("Calibration: warm median=%llu cycles; evicted median=%llu cycles; threshold=%llu\n",
           (unsigned long long)warm_median,
           (unsigned long long)cold_median,
           (unsigned long long)threshold);
    printf("Raw reload timings (cycles), one row per bit; 1=evicted, 0=warm:\n");
    for (size_t bit = 0; bit < nbits; bit++) {
        printf("bit %02zu decoded=%u timings=", bit, decoded_bits[bit]);
        for (size_t repeat = 0; repeat < REPEATS; repeat++) {
            printf("%s%llu", repeat ? "," : "",
                   (unsigned long long)timings[bit][repeat]);
        }
        putchar('\n');
    }
    printf("Decoded bytes from timed reload: %02x%02x\n", decoded[0], decoded[1]);
    fflush(stdout);
    write_all(report_fd, decoded_bits, nbits);
    close(report_fd);
    _exit(0);
}

static int fill_random(uint8_t *data, size_t length) {
    size_t received = 0;
    while (received < length) {
        ssize_t n = getrandom(data + received, length - received, 0);
        if (n < 0 && errno == EINTR) continue;
        if (n <= 0) return -1;
        received += (size_t)n;
    }
    return 0;
}

static size_t encode_bits(const uint8_t *payload, uint8_t *bits) {
    for (size_t bit = 0; bit < PAYLOAD_BITS; bit++) {
        bits[bit] = (payload[bit / 8] >> (7 - (bit % 8))) & 1U;
    }
    return PAYLOAD_BITS;
}

int main(void) {
    long page_size = sysconf(_SC_PAGESIZE);
    if (page_size < CACHE_LINE_BYTES) {
        fprintf(stderr, "unsupported page size\n");
        return 2;
    }
    size_t map_size = (size_t)page_size;
    void *payload_map = mmap(NULL, map_size, PROT_READ | PROT_WRITE,
                             MAP_SHARED | MAP_ANONYMOUS, -1, 0);
    void *sync_map = mmap(NULL, map_size, PROT_READ | PROT_WRITE,
                          MAP_SHARED | MAP_ANONYMOUS, -1, 0);
    if (payload_map == MAP_FAILED || sync_map == MAP_FAILED) {
        perror("mmap");
        return 2;
    }
    probe_line = (volatile uint8_t *)payload_map;
    *probe_line = 0;
    _mm_mfence();
    if (mprotect(payload_map, map_size, PROT_READ) != 0) {
        perror("mprotect payload read-only");
        return 2;
    }
    sync_state_shared = (struct sync_state *)sync_map;
    atomic_init(&sync_state_shared->ready, 0);
    atomic_init(&sync_state_shared->done, 0);
    if (!atomic_is_lock_free(&sync_state_shared->ready) ||
        !atomic_is_lock_free(&sync_state_shared->done)) {
        fprintf(stderr, "lock-free shared atomics are required\n");
        return 2;
    }

    int report_pipe[2];
    if (pipe(report_pipe) != 0) {
        perror("pipe");
        return 2;
    }
    int cpu = choose_cpu();
    pid_t receiver = fork();
    if (receiver < 0) {
        perror("fork receiver");
        return 2;
    }
    if (receiver == 0) {
        close(report_pipe[0]);
        return receiver_child(cpu, PAYLOAD_BITS, report_pipe[1]);
    }

    close(report_pipe[1]);
    uint8_t payload[PAYLOAD_BYTES];
    if (fill_random(payload, sizeof(payload)) != 0) {
        perror("getrandom");
        kill(receiver, SIGTERM);
        waitpid(receiver, NULL, 0);
        close(report_pipe[0]);
        return 2;
    }
    uint8_t bits[PAYLOAD_BITS];
    size_t nbits = encode_bits(payload, bits);

    pid_t sender = fork();
    if (sender < 0) {
        perror("fork sender");
        kill(receiver, SIGTERM);
        waitpid(receiver, NULL, 0);
        close(report_pipe[0]);
        return 2;
    }
    if (sender == 0) {
        close(report_pipe[0]);
        return sender_child(cpu, bits, nbits);
    }

    uint8_t decoded_bits[PAYLOAD_BITS];
    size_t received = 0;
    while (received < nbits) {
        ssize_t n = read(report_pipe[0], decoded_bits + received, nbits - received);
        if (n < 0 && errno == EINTR) continue;
        if (n <= 0) break;
        received += (size_t)n;
    }
    close(report_pipe[0]);

    int sender_status = 0;
    int receiver_status = 0;
    waitpid(sender, &sender_status, 0);
    waitpid(receiver, &receiver_status, 0);

    if (received != nbits || !WIFEXITED(sender_status) ||
        WEXITSTATUS(sender_status) != 0 || !WIFEXITED(receiver_status) ||
        WEXITSTATUS(receiver_status) != 0) {
        fprintf(stderr, "sender/receiver process failed\n");
        return 1;
    }

    size_t errors = 0;
    for (size_t bit = 0; bit < nbits; bit++) {
        if (decoded_bits[bit] != bits[bit]) errors++;
    }
    printf("Sender payload: %02x%02x; bit errors: %zu/%zu\n",
           payload[0], payload[1], errors, nbits);

    munmap(payload_map, map_size);
    munmap(sync_map, map_size);
    return errors == 0 ? 0 : 1;
}
