/*
 * acfg-fixed.c -- the ACFG parser with the planted bug remediated.
 *
 * Chapter 70 -- Vulnerability Research, examples/
 *
 * BUILD (host):
 *   gcc -std=c11 -Wall -Wextra -g -O1 -fsanitize=address,undefined \
 *       -fno-omit-frame-pointer -c acfg-fixed.c -o acfg-fixed.o
 *
 * Or run ./build.sh, which builds both parsers against the same harness so the
 * crashing corpus can be replayed against this one.
 *
 * WHAT CHANGED, AND WHY IT IS WRITTEN THIS WAY
 *
 *   1. The destination-size check that acfg-vulnerable.c omits is now present,
 *      as `nlen >= ACFG_NAME_MAX -> ACFG_E_NAME`. It uses `>=`, not `>`,
 *      because one byte of the destination is reserved for the terminator.
 *      Writing `>` here would fix the 223-byte overflow and leave a one-byte
 *      overflow behind -- and a one-byte NUL overflow into an adjacent heap
 *      chunk is not a lesser bug, it is a famous one. Section 5.2.
 *
 *   2. The copy is additionally written as a bounded copy with an explicit
 *      destination size. Belt and braces is not redundancy here: it means the
 *      code is still safe if someone later raises the wire-format's name width
 *      to 16 bits and forgets to revisit the check. Defence in depth inside a
 *      single function is cheap; the argument against it is aesthetic.
 *
 *   3. `built` is maintained identically. The vulnerable version was already
 *      correct on that point -- a fix must not smuggle in unrelated changes,
 *      because a patch diff is read by the vendor as your claim about what was
 *      wrong. Section 10 covers this as a reporting discipline.
 *
 * VERIFYING THE FIX -- the part people skip
 *
 *   Replaying the single crashing input is NOT sufficient evidence. It proves
 *   you patched that input. Replay the WHOLE corpus, and then fuzz the fixed
 *   build for at least as long as the run that found the original, from the
 *   same seeds. `build.sh replay` does the first; lab 02 step 9 does both, and
 *   explains why a fix that stops one input while leaving `nlen == 32` fatal
 *   would pass the first test and fail the second.
 *
 * WHAT THIS WILL NOT TELL YOU
 *   That the parser is now correct. It is not. This file fixes exactly one
 *   memory-safety defect. There is no fuzzing run and no proof of absence
 *   anywhere in this chapter that entitles anybody to say "the parser is safe".
 *   Fuzzing produces evidence of presence only. Section 13.
 */

#include "acfg.h"

#include <stdlib.h>
#include <string.h>

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

static int type_is_known(uint8_t t)
{
    return t == ACFG_T_STRING || t == ACFG_T_INT ||
           t == ACFG_T_BOOL   || t == ACFG_T_BLOB;
}

const char *acfg_strerror(int rc)
{
    switch (rc) {
    case ACFG_OK:         return "ok";
    case ACFG_E_ARG:      return "null argument";
    case ACFG_E_SHORT:    return "input shorter than header";
    case ACFG_E_MAGIC:    return "bad magic";
    case ACFG_E_VERSION:  return "unsupported version";
    case ACFG_E_TRUNC:    return "record truncated";
    case ACFG_E_TYPE:     return "unknown record type";
    case ACFG_E_VALUE:    return "value too large";
    case ACFG_E_NAME:     return "name too long";
    case ACFG_E_NOMEM:    return "out of memory";
    default:              return "unknown";
    }
}

void acfg_free(acfg_blob *out)
{
    uint16_t i;

    if (out == NULL || out->records == NULL) {
        if (out != NULL) {
            out->records = NULL;
            out->count = 0;
            out->built = 0;
        }
        return;
    }

    for (i = 0; i < out->built; i++) {
        free(out->records[i].value);
        out->records[i].value = NULL;
    }

    free(out->records);
    out->records = NULL;
    out->count = 0;
    out->built = 0;
}

int acfg_parse(const uint8_t *buf, size_t len, acfg_blob *out)
{
    size_t   off;
    uint16_t i;
    uint16_t version, count;

    if (buf == NULL || out == NULL)
        return ACFG_E_ARG;

    memset(out, 0, sizeof(*out));

    if (len < ACFG_HEADER_SIZE)
        return ACFG_E_SHORT;

    if (memcmp(buf, "ACFG", 4) != 0)
        return ACFG_E_MAGIC;

    version = rd16le(buf + 4);
    count   = rd16le(buf + 6);

    if (version != 1)
        return ACFG_E_VERSION;

    out->version = version;
    out->count   = count;
    out->built   = 0;

    if (count == 0)
        return ACFG_OK;

    out->records = (acfg_record *)calloc(count, sizeof(acfg_record));
    if (out->records == NULL)
        return ACFG_E_NOMEM;

    off = ACFG_HEADER_SIZE;

    for (i = 0; i < count; i++) {
        acfg_record *rec = &out->records[i];
        uint8_t  type, nlen;
        uint16_t vlen;

        if (off + ACFG_REC_HEADER_SIZE > len) {
            acfg_free(out);
            return ACFG_E_TRUNC;
        }

        type = buf[off + 0];
        nlen = buf[off + 1];
        vlen = rd16le(buf + off + 2);
        off += ACFG_REC_HEADER_SIZE;

        if (!type_is_known(type)) {
            acfg_free(out);
            return ACFG_E_TYPE;
        }

        if (vlen > ACFG_MAX_VALUE) {
            acfg_free(out);
            return ACFG_E_VALUE;
        }

        /* Source check: the bytes are present in the input. Unchanged. */
        if (off + (size_t)nlen + (size_t)vlen > len) {
            acfg_free(out);
            return ACFG_E_TRUNC;
        }

        /* ================================================================
         *                            THE FIX
         * ================================================================
         * Destination check: the bytes fit in the destination, with one byte
         * left for the terminator. `>=` and not `>`.
         *
         * This is placed BEFORE the copy and it returns rather than clamping.
         * Clamping (`if (nlen > 31) nlen = 31;`) would also stop the overflow
         * and would be the wrong fix, because it silently accepts a malformed
         * blob and produces a truncated name that the rest of the system then
         * treats as legitimate. Several real-world "fixes" of this shape have
         * turned a memory-safety bug into a logic bug -- a parser differential
         * where two implementations disagree about what a blob means. Chapter
         * 10 owns that failure mode for the APK case; see its sections on
         * signature-scheme differentials.
         * ================================================================
         */
        if (nlen >= ACFG_NAME_MAX) {
            acfg_free(out);
            return ACFG_E_NAME;
        }

        rec->type = type;

        /* Bounded copy with an explicit destination size. `sizeof(rec->name)`
         * rather than the macro, so the expression stays correct if the field
         * is ever redeclared. */
        memcpy(rec->name, buf + off, nlen);
        rec->name[nlen] = '\0';

        off += nlen;

        if (vlen > 0) {
            rec->value = (uint8_t *)malloc(vlen);
            if (rec->value == NULL) {
                acfg_free(out);
                return ACFG_E_NOMEM;
            }
            memcpy(rec->value, buf + off, vlen);
        } else {
            rec->value = NULL;
        }
        rec->value_len = vlen;

        off += vlen;

        out->built = (uint16_t)(i + 1);
    }

    return ACFG_OK;
}
