Skip to content
pi-c Artifact [607becd117]
Login

Artifact [607becd117]

Artifact 607becd11770007f12d92e41fc3bb042d93c8bc244754cb8b14876f2a12fa528:


/* Exact-capacity tests for the parsers and decoders that fill a caller's buffer. A sanitizer only
 * sees a write that happens, and most tests hand these functions generous stack buffers, where an
 * off-by-one lands in slack nobody watches. Here each output goes to a heap buffer of exactly the
 * size it is documented to need, so a single byte more is an ASan report, and, where the function
 * takes a capacity, to one byte less, which it must refuse (or cut) without touching memory beyond.
 * Built with the dev sanitizers: `make test-capacity`. Each case names the function it covers. */
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "cred.h"
#include "http.h"
#include "image.h"
#include "keyhealth.h"
#include "noise.h"
#include "oauth.h"
#include "sqlar.h"
#include "sqlite3.h"
#include "sse.h"
#include "webpush.h"

/* A heap buffer of exactly N bytes (never 0), filled so a short write shows. */
static unsigned char *hb(size_t n) {
    unsigned char *p = malloc(n ? n : 1);
    assert(p);
    memset(p, 0xa5, n ? n : 1);
    return p;
}

static void seq(unsigned char *b, size_t n, unsigned char from) {
    for (size_t i = 0; i < n; i++) {
        b[i] = (unsigned char)(from + i);
    }
}

/* ---- noise: the handshakes ---------------------------------------------------------- */

#define PAY1 "twenty bytes of data"
#define PAY2 "reply: seventeen+"

typedef struct {
    pic_noise_keypair pic, phone, pre;
    unsigned char prologue[4], bind[7];
} keys;

static void keys_make(keys *k) {
    unsigned char b[32];
    seq(b, 32, 0x01);
    assert(pic_noise_keypair_make(&k->pic, b) == 0);
    seq(b, 32, 0x21);
    assert(pic_noise_keypair_make(&k->phone, b) == 0);
    seq(b, 32, 0xd1);
    assert(pic_noise_keypair_make(&k->pre, b) == 0);
    memcpy(k->prologue, "pro!", 4);
    memcpy(k->bind, "bind-id", 7);
}

static void pair(const keys *k, pic_noise_hs *I, pic_noise_hs *R) {
    pic_noise_hs_init(I, 1, &k->phone, k->pic.pub, NULL, k->prologue, sizeof k->prologue);
    pic_noise_hs_init(R, 0, &k->pic, NULL, NULL, k->prologue, sizeof k->prologue);
}

/* A message 1 (into M, *MN bytes) with I left after it, and R left after reading it. */
static void through1(const keys *k, pic_noise_hs *I, pic_noise_hs *R, unsigned char *m, size_t *mn) {
    unsigned char pl[64];
    size_t n;
    pair(k, I, R);
    assert(pic_noise_write1(I, PAY1, strlen(PAY1), m, 1024, mn) == 0);
    assert(pic_noise_read1(R, m, *mn, pl, sizeof pl, &n) == 0);
}

static void noise_ik(void) {
    keys k;
    pic_noise_hs I, R;
    unsigned char big[1024], m1[1024], m2[1024], *out;
    size_t m1n, m2n, n, p1 = strlen(PAY1), p2 = strlen(PAY2);
    keys_make(&k);

    /* pic_noise_write1: e, s, tag, the payload and its tag: exactly that, and one byte less refused */
    pair(&k, &I, &R);
    assert(pic_noise_write1(&I, PAY1, p1, big, sizeof big, &m1n) == 0);
    pair(&k, &I, &R);
    out = hb(m1n);
    assert(pic_noise_write1(&I, PAY1, p1, out, m1n, &n) == 0 && n == m1n);
    free(out);
    pair(&k, &I, &R);
    out = hb(m1n - 1);
    assert(pic_noise_write1(&I, PAY1, p1, out, m1n - 1, &n) == -1);
    free(out);
    pair(&k, &I, &R);
    out = hb(0);
    assert(pic_noise_write1(&I, "", 0, out, 0, &n) == -1);
    free(out);

    /* pic_noise_read1: the payload only: exactly its length, and one byte less refused */
    through1(&k, &I, &R, m1, &m1n);
    pair(&k, &I, &R);
    assert(pic_noise_write1(&I, PAY1, p1, m1, sizeof m1, &m1n) == 0);
    out = hb(p1);
    assert(pic_noise_read1(&R, m1, m1n, out, p1, &n) == 0 && n == p1 && memcmp(out, PAY1, p1) == 0);
    free(out);
    pair(&k, &I, &R);
    assert(pic_noise_write1(&I, PAY1, p1, m1, sizeof m1, &m1n) == 0);
    out = hb(p1 - 1);
    assert(pic_noise_read1(&R, m1, m1n, out, p1 - 1, &n) == -1);
    free(out);
    pair(&k, &I, &R);
    assert(pic_noise_write1(&I, "", 0, m1, sizeof m1, &m1n) == 0); /* an empty payload into nothing */
    out = hb(0);
    assert(pic_noise_read1(&R, m1, m1n, out, 0, &n) == 0 && n == 0);
    free(out);

    /* pic_noise_write2 */
    through1(&k, &I, &R, m1, &m1n);
    assert(pic_noise_write2(&R, PAY2, p2, big, sizeof big, &m2n) == 0);
    through1(&k, &I, &R, m1, &m1n);
    out = hb(m2n);
    assert(pic_noise_write2(&R, PAY2, p2, out, m2n, &n) == 0 && n == m2n);
    free(out);
    through1(&k, &I, &R, m1, &m1n);
    out = hb(m2n - 1);
    assert(pic_noise_write2(&R, PAY2, p2, out, m2n - 1, &n) == -1);
    free(out);

    /* pic_noise_read2 */
    through1(&k, &I, &R, m1, &m1n);
    assert(pic_noise_write2(&R, PAY2, p2, m2, sizeof m2, &m2n) == 0);
    out = hb(p2);
    assert(pic_noise_read2(&I, m2, m2n, out, p2, &n) == 0 && n == p2 && memcmp(out, PAY2, p2) == 0);
    free(out);
    through1(&k, &I, &R, m1, &m1n);
    assert(pic_noise_write2(&R, PAY2, p2, m2, sizeof m2, &m2n) == 0);
    out = hb(p2 - 1);
    assert(pic_noise_read2(&I, m2, m2n, out, p2 - 1, &n) == -1);
    free(out);
    puts("ok pic_noise_write1, read1, write2, read2 at their exact capacity");
}

static void noise_prekey(void) {
    keys k;
    pic_noise_hs I, R;
    unsigned char big[1024], m[1024], *out;
    size_t mn, used, n, pn = strlen(PAY1);
    keys_make(&k);
#define PK_PAIR()                                                                                        \
    do {                                                                                                 \
        pic_noise_hs_init_prekey(&I, 1, &k.phone, k.pic.pub, k.prologue, sizeof k.prologue);           \
        pic_noise_hs_init_prekey(&R, 0, &k.pic, NULL, k.prologue, sizeof k.prologue);                  \
    } while (0)
    PK_PAIR();
    assert(pic_noise_write1_prekey(&I, k.pre.pub, k.bind, sizeof k.bind, PAY1, pn, big, sizeof big, &mn) == 0);
    /* pic_noise_write1_prekey */
    PK_PAIR();
    out = hb(mn);
    assert(pic_noise_write1_prekey(&I, k.pre.pub, k.bind, sizeof k.bind, PAY1, pn, out, mn, &n) == 0 && n == mn);
    free(out);
    PK_PAIR();
    out = hb(mn - 1);
    assert(pic_noise_write1_prekey(&I, k.pre.pub, k.bind, sizeof k.bind, PAY1, pn, out, mn - 1, &n) == -1);
    free(out);
    /* pic_noise_read1_begin on a message that is exactly its head, and finish into the payload alone */
    PK_PAIR();
    assert(pic_noise_write1_prekey(&I, k.pre.pub, k.bind, sizeof k.bind, PAY1, pn, m, sizeof m, &mn) == 0);
    {
        unsigned char *exact = hb(mn); /* the message in a buffer of its own length */
        memcpy(exact, m, mn);
        assert(pic_noise_read1_begin(&R, exact, mn, &used) == 0);
        out = hb(pn);
        assert(pic_noise_read1_finish(&R, exact + used, mn - used, &k.pre, k.bind, sizeof k.bind, out, pn, &n) == 0 &&
               n == pn && memcmp(out, PAY1, pn) == 0);
        free(out);
        PK_PAIR();
        assert(pic_noise_write1_prekey(&I, k.pre.pub, k.bind, sizeof k.bind, PAY1, pn, m, sizeof m, &mn) == 0);
        memcpy(exact, m, mn);
        assert(pic_noise_read1_begin(&R, exact, mn, &used) == 0);
        out = hb(pn - 1);
        assert(pic_noise_read1_finish(&R, exact + used, mn - used, &k.pre, k.bind, sizeof k.bind, out, pn - 1, &n) == -1);
        free(out);
        free(exact);
    }
    puts("ok pic_noise_write1_prekey, read1_begin, read1_finish at their exact capacity");
}

/* ---- noise: the transport ------------------------------------------------------------- */

static void noise_transport(void) {
    pic_noise_transport s, r;
    unsigned char sid[PIC_NOISE_SID], up[32], down[32], *data, *rec, *out;
    size_t sizes[] = {0, 1, 100, PIC_NOISE_CHUNK - 1, PIC_NOISE_CHUNK}, n;
    int flag, gap;
    seq(sid, sizeof sid, 1);
    seq(up, 32, 40);
    seq(down, 32, 80);
    pic_noise_transport_init(&s, 0, sid, up, down);
    pic_noise_transport_init(&r, 1, sid, up, down);
    data = hb(PIC_NOISE_CHUNK + 1);
    seq(data, PIC_NOISE_CHUNK + 1, 7);
    for (size_t i = 0; i < sizeof sizes / sizeof sizes[0]; i++) {
        /* pic_noise_record: 1 + sid + counter + flag + data + tag, no more */
        size_t want = 1 + PIC_NOISE_SID + 8 + 1 + sizes[i] + PIC_NOISE_TAG;
        rec = hb(want);
        assert(pic_noise_record(&s, 1, data, sizes[i], rec) == want);
        /* pic_noise_open_record: into PIC_NOISE_CHUNK exactly */
        out = hb(PIC_NOISE_CHUNK);
        assert(pic_noise_open_record(&r, rec, want, &flag, out, &n, &gap) == 0 && flag == 1 && n == sizes[i] &&
               memcmp(out, data, n) == 0);
        free(out);
        free(rec);
    }
    /* a longer chunk is cut to PIC_NOISE_CHUNK, still inside the documented record size */
    rec = hb(PIC_NOISE_RECORD_CAP);
    assert(pic_noise_record(&s, 0, data, PIC_NOISE_CHUNK + 1, rec) == PIC_NOISE_RECORD_CAP);
    out = hb(PIC_NOISE_CHUNK);
    assert(pic_noise_open_record(&r, rec, PIC_NOISE_RECORD_CAP, &flag, out, &n, &gap) == 0 && n == PIC_NOISE_CHUNK);
    free(out);
    /* one byte over the largest record is refused, read from a buffer of exactly that length */
    free(rec);
    rec = hb(PIC_NOISE_RECORD_CAP + 1);
    out = hb(PIC_NOISE_CHUNK);
    assert(pic_noise_open_record(&r, rec, PIC_NOISE_RECORD_CAP + 1, &flag, out, &n, &gap) == -1);
    free(out);
    free(rec);
    free(data);
    puts("ok pic_noise_record and pic_noise_open_record at the largest record");
}

static void noise_small(void) {
    unsigned char sid[PIC_NOISE_SID], msg[40], *out, *in, mb[16], pub[PIC_NOISE_PUB], ps[32], tok[32], sig[64];
    unsigned char back[16], pub2[PIC_NOISE_PUB], ps2[32];
    uint64_t exp;
    pic_noise_keypair kp;
    size_t n;
    seq(sid, sizeof sid, 1);
    seq(msg, sizeof msg, 9);
    /* pic_noise_head: 1 + sid + message */
    for (size_t len = 0; len <= sizeof msg; len += 20) {
        out = hb(1 + PIC_NOISE_SID + len);
        assert(pic_noise_head(PIC_NOISE_REC_M1, sid, msg, len, out) == 1 + PIC_NOISE_SID + len);
        free(out);
    }
    /* pic_noise_offer and pic_noise_offer_read: PIC_NOISE_OFFER bytes */
    seq(mb, 16, 1);
    seq(ps, 32, 50);
    seq(tok, 32, 3);
    seq(sig, 32, 3);
    assert(pic_noise_keypair_make(&kp, tok) == 0);
    memcpy(pub, kp.pub, sizeof pub);
    out = hb(PIC_NOISE_OFFER);
    pic_noise_offer(mb, pub, ps, 1800000000u, out);
    in = hb(PIC_NOISE_OFFER);
    memcpy(in, out, PIC_NOISE_OFFER);
    assert(pic_noise_offer_read(in, PIC_NOISE_OFFER, back, pub2, ps2, &exp) == 0 && exp == 1800000000u);
    free(out);
    free(in);
    /* pic_noise_es256: 64 bytes */
    {
        unsigned char *s64 = hb(64);
        assert(pic_noise_es256(tok, "header.claims", s64) == 0);
        free(s64);
    }
    /* pic_noise_webpush: LEN + 103 bytes */
    for (size_t len = 0; len <= 200; len += 100) {
        unsigned char salt[16], auth[16], *pt = hb(len + 1), *body = hb(len + 103);
        pic_noise_keypair as, ua;
        seq(salt, 16, 1);
        seq(auth, 16, 2);
        seq(tok, 32, 11);
        assert(pic_noise_keypair_make(&as, tok) == 0);
        seq(tok, 32, 61);
        assert(pic_noise_keypair_make(&ua, tok) == 0);
        n = pic_noise_webpush(&as, salt, ua.pub, auth, pt, len, body);
        assert(n == len + 103);
        free(pt);
        free(body);
    }
    puts("ok pic_noise_head, offer, offer_read, es256 and webpush at their exact sizes");
}

/* ---- base64 ---------------------------------------------------------------------------- */

static void b64(void) {
    unsigned char raw[64], *dec;
    char *enc, big[256];
    for (size_t n = 0; n <= 50; n++) {
        size_t el;
        long dn;
        seq(raw, n, 0xf0);
        /* pic_b64u_enc: its length and a NUL, no padding */
        el = (n * 4 + 2) / 3;
        enc = (char *)hb(el + 1);
        assert(pic_b64u_enc(raw, n, enc) == el && enc[el] == '\0');
        memcpy(big, enc, el + 1);
        free(enc);
        /* pic_b64u_dec: exactly n bytes, and one byte less refused */
        dec = hb(n);
        assert(pic_b64u_dec(big, el, dec, n) == (long)n && memcmp(dec, raw, n) == 0);
        free(dec);
        if (n) {
            dec = hb(n - 1);
            assert(pic_b64u_dec(big, el, dec, n - 1) == -1);
            free(dec);
        }
        /* pic_base64_encode: 4 * ((n + 2) / 3) + 1 bytes with padding */
        el = 4 * ((n + 2) / 3);
        enc = (char *)hb(el + 1);
        assert(pic_base64_encode(raw, n, enc) == el && enc[el] == '\0');
        memcpy(big, enc, el + 1);
        free(enc);
        /* pic_base64_decode has no capacity argument: it must write only the n bytes it returns,
         * padded or not, though the header promises 3 * (len / 4) + 3 */
        dec = hb(n);
        dn = (long)pic_base64_decode(big, el, dec);
        assert(dn == (long)n && memcmp(dec, raw, n) == 0);
        free(dec);
        dec = hb(n);
        while (el && big[el - 1] == '=') {
            el--;
        }
        dn = (long)pic_base64_decode(big, el, dec);
        assert(dn == (long)n && memcmp(dec, raw, n) == 0);
        free(dec);
    }
    puts("ok pic_b64u_enc, pic_b64u_dec, pic_base64_encode and pic_base64_decode at their exact sizes");
}


/* ---- web push ----------------------------------------------------------------------------- */

static void webpush(void) {
    unsigned char priv[PIC_WEBPUSH_PRIV], auth[PIC_WEBPUSH_AUTH];
    char *out, big[512];
    int n, m;
    seq(priv, sizeof priv, 3);
    seq(auth, sizeof auth, 9);
    /* pic_webpush_origin: its length and a NUL, and one byte less is refused */
    {
        static const char *const urls[] = {"https://push.example.com/send/abc", "https://push.example.com:8443/x",
                                           "http://127.0.0.1:8080/p"};
        for (size_t i = 0; i < sizeof urls / sizeof urls[0]; i++) {
            n = pic_webpush_origin(urls[i], big, sizeof big);
            assert(n > 0);
            out = (char *)hb((size_t)n + 1);
            assert(pic_webpush_origin(urls[i], out, (size_t)n + 1) == n && out[n] == '\0');
            free(out);
            out = (char *)hb((size_t)n);
            assert(pic_webpush_origin(urls[i], out, (size_t)n) == -1);
            free(out);
        }
    }
    /* pic_webpush_authorization: the whole header value; claims of the largest size allowed */
    {
        char aud[513], sub[513];
        memset(aud, 'a', 512);
        aud[512] = '\0';
        memset(sub, 's', 512);
        sub[512] = '\0';
        for (int big_claims = 0; big_claims < 2; big_claims++) {
            const char *a = big_claims ? aud : "https://push.example.com", *b = big_claims ? sub : "mailto:[email protected]";
            char *ref = malloc(4096);
            assert(ref);
            n = pic_webpush_authorization(priv, a, 1800000000, b, ref, 4096);
            assert(n > 0);
            free(ref);
            out = (char *)hb((size_t)n + 1);
            m = pic_webpush_authorization(priv, a, 1800000000, b, out, (size_t)n + 1);
            assert(m == n && out[n] == '\0');
            free(out);
            out = (char *)hb((size_t)n);
            assert(pic_webpush_authorization(priv, a, 1800000000, b, out, (size_t)n) == -1);
            free(out);
        }
    }
    /* pic_webpush_topic: PIC_WEBPUSH_TOPIC bytes, 22 characters and the NUL */
    out = (char *)hb(PIC_WEBPUSH_TOPIC);
    pic_webpush_topic(auth, "session-one", out);
    assert(strlen(out) == PIC_WEBPUSH_TOPIC - 1);
    free(out);
    puts("ok pic_webpush_origin, pic_webpush_authorization and pic_webpush_topic at their exact sizes");
}

/* ---- server-sent events ------------------------------------------------------------------- */

static int sse_count;
static size_t sse_last;

static int sse_on(void *ctx, const char *event, const char *data, size_t n) {
    (void)ctx;
    (void)event;
    assert(strlen(data) == n);
    sse_count++;
    sse_last = n;
    return 0;
}

/* Feeds TEXT from a buffer of exactly its length. */
static int sse_feed_exact(pic_sse *p, const char *text) {
    size_t n = strlen(text);
    char *b = (char *)hb(n);
    int rc;
    memcpy(b, text, n);
    rc = pic_sse_feed(p, b, n);
    free(b);
    return rc;
}

static void sse(void) {
    pic_sse p;
    char line[200], name[80];
    /* data_cap: an event's data, with a newline after each line, fills data_cap bytes exactly */
    assert(pic_sse_init(&p, 128, 16, sse_on, NULL) == 0);
    sse_count = 0;
    assert(sse_feed_exact(&p, "data: 123456789012345\n\n") == 0 && sse_count == 1 && sse_last == 15);
    assert(sse_feed_exact(&p, "data: 1234567890123456\n\n") == -1); /* 16 bytes and its LF: one over */
    pic_sse_free(&p);
    assert(pic_sse_init(&p, 128, 16, sse_on, NULL) == 0);
    assert(sse_feed_exact(&p, "data: 1234567\ndata: 1234567\n\n") == 0 && sse_last == 15); /* 8 + 8 = 16 with the LFs */
    pic_sse_free(&p);
    /* line_cap: a line of exactly that many bytes, and one more */
    assert(pic_sse_init(&p, 32, 64, sse_on, NULL) == 0);
    memset(line, 'x', 32);
    line[32] = '\n';
    line[33] = '\0';
    assert(sse_feed_exact(&p, line) == 0);
    memset(line, 'x', 33);
    line[33] = '\n';
    line[34] = '\0';
    assert(sse_feed_exact(&p, line) == -1);
    pic_sse_free(&p);
    /* the event name and the id fields hold 63 characters and a NUL */
    assert(pic_sse_init(&p, 256, 64, sse_on, NULL) == 0);
    (void)snprintf(name, sizeof name, "event: %.63s\ndata: x\n\n", "nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn");
    assert(sse_feed_exact(&p, name) == 0);
    (void)snprintf(name, sizeof name, "event: %.64s\ndata: x\n\n", "nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn");
    assert(sse_feed_exact(&p, name) == -1);
    pic_sse_free(&p);
    assert(pic_sse_init(&p, 256, 64, sse_on, NULL) == 0);
    (void)snprintf(name, sizeof name, "id: %.63s\n", "iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii");
    assert(sse_feed_exact(&p, name) == 0 && strlen(p.last_id) == 63);
    (void)snprintf(name, sizeof name, "id: %.64s\n", "iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii");
    assert(sse_feed_exact(&p, name) == 0 && strlen(p.last_id) == 63); /* too long: kept as it was */
    pic_sse_free(&p);
    puts("ok pic_sse_feed at the exact line, data, event and id capacities");
}

/* ---- sqlar ----------------------------------------------------------------------------------- */

static void sqlar(void) {
    sqlite3 *db;
    sqlite3_stmt *q;
    size_t sizes[] = {0, 1, 100, 4096, 70000};
    assert(sqlite3_open(":memory:", &db) == SQLITE_OK);
    assert(pic_sqlar_register(db) == 0);
    for (size_t i = 0; i < sizeof sizes / sizeof sizes[0]; i++) {
        size_t n = sizes[i];
        unsigned char *raw = hb(n), *packed;
        const void *blob;
        int bn;
        memset(raw, 'z', n);
        for (size_t k = 0; k < n; k += 7) {
            raw[k] = (unsigned char)k;
        }
        assert(sqlite3_prepare_v2(db, "SELECT sqlar_compress(?1)", -1, &q, NULL) == SQLITE_OK);
        sqlite3_bind_blob64(q, 1, raw, n, SQLITE_STATIC);
        assert(sqlite3_step(q) == SQLITE_ROW);
        bn = sqlite3_column_bytes(q, 0);
        blob = sqlite3_column_blob(q, 0);
        packed = hb((size_t)bn);
        if (bn) {
            memcpy(packed, blob, (size_t)bn);
        }
        sqlite3_finalize(q);
        /* sqlar_uncompress(Y, SZ): exactly SZ bytes out; a wrong SZ either way is an error, not a
         * write beyond (SZ one short makes inflate stop early, one long leaves bytes unfilled) */
        for (int delta = -1; delta <= 1; delta++) {
            long long sz = (long long)n + delta;
            if (sz < 0 || (bn == (int)n && delta != 0 && sz != bn && 0)) {
                continue;
            }
            assert(sqlite3_prepare_v2(db, "SELECT sqlar_uncompress(?1, ?2)", -1, &q, NULL) == SQLITE_OK);
            sqlite3_bind_blob64(q, 1, packed, (size_t)bn, SQLITE_STATIC);
            sqlite3_bind_int64(q, 2, sz);
            if (delta == 0) {
                assert(sqlite3_step(q) == SQLITE_ROW && sqlite3_column_bytes(q, 0) == (int)n &&
                       (n == 0 || memcmp(sqlite3_column_blob(q, 0), raw, n) == 0));
            } else if (bn != (int)n) { /* compressed: a size that is not its own is corrupt */
                assert(sqlite3_step(q) == SQLITE_ERROR);
            } else {
                (void)sqlite3_step(q); /* stored raw: the data comes back as it is whatever SZ says */
            }
            sqlite3_finalize(q);
        }
        free(packed);
        free(raw);
    }
    sqlite3_close(db);
    puts("ok sqlar_compress and sqlar_uncompress at the exact original size");
}

/* ---- the HTTP response parser ---------------------------------------------------------------- */

static int http_sink(void *ctx, const char *bytes, size_t n) {
    (void)ctx;
    (void)bytes;
    (void)n;
    return 0;
}

/* A response whose HEADER (name) has a value of LEN bytes, in a buffer of exactly its length,
 * fed whole and then one byte at a time. FIELD is a view of one of the fixed fields. */
static void http_field(const char *name, size_t len, size_t fieldcap, char *(*field)(pic_http_resp *)) {
    static pic_http_resp r;
    size_t want = len < fieldcap ? len : fieldcap - 1;
    for (int bytewise = 0; bytewise < 2; bytewise++) {
        char *head = malloc(64 + strlen(name) + len), *b;
        size_t hn, n;
        assert(head);
        hn = (size_t)snprintf(head, 64 + strlen(name), "HTTP/1.1 204 No Content\r\n%s: ", name);
        memset(head + hn, 'v', len);
        memcpy(head + hn + len, "\r\n\r\n", 4);
        n = hn + len + 4;
        b = (char *)hb(n);
        memcpy(b, head, n);
        free(head);
        pic_http_resp_init(&r, http_sink, NULL);
        r.want = "x-want";
        if (bytewise) {
            for (size_t i = 0; i < n; i++) {
                assert(pic_http_feed(&r, b + i, 1) == 0);
            }
        } else {
            assert(pic_http_feed(&r, b, n) == 0);
        }
        free(b);
        assert(strlen(field(&r)) == want);
        assert(r.status == 204);
    }
}

static char *f_retry(pic_http_resp *r) { return r->retry_after; }
static char *f_reqid(pic_http_resp *r) { return r->request_id; }
static char *f_ctype(pic_http_resp *r) { return r->content_type; }
static char *f_etag(pic_http_resp *r) { return r->etag; }
static char *f_lastmod(pic_http_resp *r) { return r->last_modified; }
static char *f_peer(pic_http_resp *r) { return r->peer; }
static char *f_wanted(pic_http_resp *r) { return r->wanted; }

static void http(void) {
    static const struct {
        const char *name;
        size_t cap;
        char *(*field)(pic_http_resp *);
    } f[] = {{"Retry-After", sizeof((pic_http_resp *)0)->retry_after, f_retry},
             {"request-id", sizeof((pic_http_resp *)0)->request_id, f_reqid},
             {"Content-Type", sizeof((pic_http_resp *)0)->content_type, f_ctype},
             {"ETag", sizeof((pic_http_resp *)0)->etag, f_etag},
             {"Last-Modified", sizeof((pic_http_resp *)0)->last_modified, f_lastmod},
             {"Pic-Peer", sizeof((pic_http_resp *)0)->peer, f_peer},
             {"X-Want", sizeof((pic_http_resp *)0)->wanted, f_wanted}};
    for (size_t i = 0; i < sizeof f / sizeof f[0]; i++) {
        /* a value one short of the field, exactly the field, one over: always a NUL inside it */
        http_field(f[i].name, f[i].cap - 2, f[i].cap, f[i].field);
        http_field(f[i].name, f[i].cap - 1, f[i].cap, f[i].field);
        http_field(f[i].name, f[i].cap, f[i].cap, f[i].field);
        http_field(f[i].name, f[i].cap + 1, f[i].cap, f[i].field);
    }
    /* the rate-limit lines: filled to the last byte that fits, then one more header dropped whole */
    {
        static pic_http_resp r;
        char *msg = malloc(4096), *b;
        size_t n = 0, total;
        int k = 0;
        assert(msg);
        n += (size_t)snprintf(msg + n, 4096 - n, "HTTP/1.1 204 No Content\r\n");
        while (n < 3500) {
            n += (size_t)snprintf(msg + n, 4096 - n, "X-RateLimit-%02d: %0*d\r\n", k, 60 + (k % 7), k);
            k++;
        }
        n += (size_t)snprintf(msg + n, 4096 - n, "\r\n");
        total = n;
        b = (char *)hb(total);
        memcpy(b, msg, total);
        free(msg);
        pic_http_resp_init(&r, http_sink, NULL);
        assert(pic_http_feed(&r, b, total) == 0 && strlen(r.ratelimit) < sizeof r.ratelimit);
        free(b);
    }
    /* a header line of exactly the line buffer's size, and one more */
    {
        static pic_http_resp r;
        size_t room = sizeof r.line, n;
        char *b;
        for (int over = 0; over < 2; over++) {
            size_t vlen = room - (sizeof "X-Long: " - 1) + (size_t)over;
            n = sizeof "HTTP/1.1 204 No Content\r\n" - 1 + (sizeof "X-Long: " - 1) + vlen + 4;
            b = (char *)hb(n);
            memcpy(b, "HTTP/1.1 204 No Content\r\nX-Long: ", sizeof "HTTP/1.1 204 No Content\r\nX-Long: " - 1);
            memset(b + n - vlen - 4, 'w', vlen);
            memcpy(b + n - 4, "\r\n\r\n", 4);
            pic_http_resp_init(&r, http_sink, NULL);
            (void)pic_http_feed(&r, b, n); /* either answer: no byte past the line buffer */
            free(b);
        }
    }
    puts("ok pic_http_feed's header fields and line buffer at their exact sizes");
}

/* ---- images ------------------------------------------------------------------------------------ */

static void image(void) {
    static const unsigned char png[] = {0x89, 'P', 'N', 'G', 13, 10, 26, 10, 0, 0, 0, 13, 'I', 'H', 'D', 'R', 0, 0, 0, 1, 0, 0, 0,
                                        1, 8, 6, 0, 0, 0, 0x1f, 0x15, 0xc4, 0x89, 0, 0, 0, 13, 'I', 'D', 'A', 'T', 0x78, 0x9c, 0x63,
                                        0, 1, 0, 0, 5, 0, 1, 0x0d, 0x0a, 0x2d, 0xb4, 0, 0, 0, 0, 'I', 'E', 'N', 'D', 0xae, 0x42, 0x60, 0x82};
    static const unsigned char gif[] = "GIF89a\x01\x00\x01\x00\x80\x00\x00\x00\x00\x00\xff\xff\xff,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;";
    static const unsigned char jpeg[] = {0xff, 0xd8, 0xff, 0xc0, 0, 11, 8, 0, 16, 0, 32, 1, 1, 0x11, 0, 0xff, 0xd9};
    static const unsigned char webp_x[] = {'R', 'I', 'F', 'F', 22, 0, 0, 0, 'W', 'E', 'B', 'P', 'V', 'P', '8', 'X', 10, 0, 0, 0,
                                           0, 0, 0, 0, 1, 0, 0, 2, 0, 0};
    static const unsigned char webp_l[] = {'R', 'I', 'F', 'F', 22, 0, 0, 0, 'W', 'E', 'B', 'P', 'V', 'P', '8', 'L', 10, 0, 0, 0,
                                           0x2f, 1, 0, 0, 0, 0, 0, 0, 0, 0};
    static const unsigned char webp_s[] = {'R', 'I', 'F', 'F', 22, 0, 0, 0, 'W', 'E', 'B', 'P', 'V', 'P', '8', ' ', 10, 0, 0, 0,
                                           0, 0, 0, 0x9d, 0x01, 0x2a, 3, 0, 4, 0};
    static const unsigned char bmp[] = {'B', 'M', 58, 0, 0, 0, 0, 0, 0, 0, 54, 0, 0, 0, 40, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0,
                                        24, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    struct {
        const char *name;
        const unsigned char *b;
        size_t n;
    } fx[] = {{"png", png, sizeof png},       {"gif", gif, sizeof gif - 1},    {"jpeg", jpeg, sizeof jpeg},
              {"webp VP8X", webp_x, sizeof webp_x}, {"webp VP8L", webp_l, sizeof webp_l}, {"webp VP8", webp_s, sizeof webp_s},
              {"bmp", bmp, sizeof bmp}};
    for (size_t i = 0; i < sizeof fx / sizeof fx[0]; i++) {
        /* pic_image_sniff and pic_image_inspect read every prefix of a real header from a buffer
         * of exactly that length: a read past the end is a report */
        for (size_t len = 0; len <= fx[i].n; len++) {
            unsigned char *b = hb(len);
            pic_image img;
            char *why = (char *)hb(160);
            if (len) {
                memcpy(b, fx[i].b, len);
            }
            (void)pic_image_sniff(b, len);
            memset(&img, 0, sizeof img);
            img.data = b;
            img.len = len;
            (void)pic_image_inspect(&img, NULL, why, 160);
            free(why);
            free(b);
        }
        /* the whole header must be understood */
        {
            unsigned char *b = hb(fx[i].n);
            pic_image img;
            char *why = (char *)hb(160);
            memcpy(b, fx[i].b, fx[i].n);
            memset(&img, 0, sizeof img);
            img.data = b;
            img.len = fx[i].n;
            assert(pic_image_sniff(b, fx[i].n) != NULL);
            if (strcmp(fx[i].name, "bmp") != 0) {
                assert(pic_image_inspect(&img, NULL, why, 160) == PIC_IMAGE_OK && img.width > 0 && img.height > 0);
            }
            free(why);
            free(b);
        }
    }
    /* the reason: a buffer of exactly its length (message and NUL), and cut where it is shorter */
    {
        unsigned char *b = hb(sizeof png);
        pic_image img;
        char probe[200], *why;
        size_t need;
        memcpy(b, png, sizeof png);
        memset(&img, 0, sizeof img);
        img.data = b;
        img.len = sizeof png;
        assert(pic_image_inspect(&img, "image/jpeg", probe, sizeof probe) == PIC_IMAGE_MISMATCH);
        need = strlen(probe) + 1;
        for (size_t cap = 1; cap <= need; cap++) {
            why = (char *)hb(cap);
            assert(pic_image_inspect(&img, "image/jpeg", why, cap) == PIC_IMAGE_MISMATCH);
            assert(strlen(why) == (cap < need ? cap - 1 : need - 1));
            free(why);
        }
        img.width = img.height = 9000; /* too large: pic_image_fit's reason, in a buffer of its exact size */
        assert(pic_image_fit(&img, probe, sizeof probe) == PIC_IMAGE_TOO_LARGE);
        need = strlen(probe) + 1;
        why = (char *)hb(need);
        assert(pic_image_fit(&img, why, need) == PIC_IMAGE_TOO_LARGE && strlen(why) == need - 1);
        free(why);
        free(b);
    }
    puts("ok pic_image_sniff, pic_image_inspect and pic_image_fit on exact-length buffers");
}

/* ---- credentials and key health ------------------------------------------------------------------ */

static void cred(void) {
    unsigned char key[PIC_CRED_KEY], *pt, *box, *back, salt[16], *dk;
    char *out;
    size_t sizes[] = {0, 1, 15, 16, 17, 200}, n;
    seq(key, sizeof key, 1);
    seq(salt, sizeof salt, 5);
    for (size_t i = 0; i < sizeof sizes / sizeof sizes[0]; i++) {
        n = sizes[i];
        pt = hb(n);
        seq(pt, n, 100);
        /* pic_cred_seal: N + PIC_CRED_OVERHEAD bytes; pic_cred_open: N bytes back */
        box = hb(n + PIC_CRED_OVERHEAD);
        assert(pic_cred_seal(key, "aad", pt, n, box) == 0);
        back = hb(n);
        assert(pic_cred_open(key, "aad", box, n + PIC_CRED_OVERHEAD, back) == 0 && (n == 0 || memcmp(back, pt, n) == 0));
        free(back);
        free(box);
        free(pt);
    }
    /* a sealed row shorter than its overhead is refused, read from a buffer of exactly that length */
    for (n = 0; n < PIC_CRED_OVERHEAD; n++) {
        box = hb(n);
        back = hb(1);
        assert(pic_cred_open(key, "aad", box, n, back) == -1);
        free(back);
        free(box);
    }
    /* pic_cred_kdf: the 32 bytes of a key */
    dk = hb(PIC_CRED_KEY);
    pic_cred_kdf("pass", 4, salt, sizeof salt, 2, dk);
    free(dk);
    /* pic_cred_trim: at most CAP - 1 bytes and a NUL: exactly the trimmed length + 1, and cut below it */
    {
        const char *in = " \t sk-the-key-text \r\n";
        size_t want = strlen("sk-the-key-text");
        for (size_t cap = 1; cap <= want + 3; cap++) {
            size_t got;
            out = (char *)hb(cap);
            got = pic_cred_trim(in, out, cap);
            assert(got == (cap > want ? want : cap - 1) && strlen(out) == got);
            free(out);
        }
    }
    /* pic_oauth_random: (4 * BYTES + 2) / 3 characters and a NUL */
    for (size_t bytes = 0; bytes <= 96; bytes += 8) {
        size_t cap = (bytes * 4 + 2) / 3 + 1;
        out = (char *)hb(cap);
        assert(pic_oauth_random(out, cap, bytes) == 0 && strlen(out) == cap - 1);
        free(out);
        out = (char *)hb(cap - 1);
        assert(pic_oauth_random(out, cap - 1, bytes) == -1);
        free(out);
    }
    out = (char *)hb(200);
    assert(pic_oauth_random(out, 200, 97) == -1);
    free(out);
    /* pic_oauth_pkce: two 64-byte arrays, 43 characters and a NUL each */
    {
        char *v = (char *)hb(64), *c = (char *)hb(64);
        assert(pic_oauth_pkce(v, c) == 0 && strlen(v) == 43 && strlen(c) == 43);
        free(v);
        free(c);
    }
    puts("ok pic_cred_seal, open, kdf, trim, pic_oauth_random and pkce at their exact sizes");
}

static void keyhealth(void) {
    pic_key_health h;
    long long now = 1795000000000LL;
    char probe[512], *out;
    pic_keyhealth_classify("anthropic", 429, "{}", "", "", "900", now, &h);
    /* a reason cut to its field, whatever the body says */
    {
        char body[700], msg[400];
        memset(msg, 'm', sizeof msg - 1);
        msg[sizeof msg - 1] = '\0';
        (void)snprintf(body, sizeof body, "{\"error\":{\"type\":\"x\",\"message\":\"%s\"}}", msg);
        pic_keyhealth_classify("openai", 500, body, msg, "", "", now, &h);
        assert(strlen(h.reason) < sizeof h.reason);
    }
    pic_keyhealth_classify("anthropic", 429, "{}", "", "", "900", now, &h);
    for (int which = 0; which < 5; which++) {
        size_t need;
        for (int state = 0; state < 2; state++) {
            if (state) {
                pic_keyhealth_classify("anthropic", 402, "{}", "plain words", "", "", now, &h);
            } else {
                pic_keyhealth_classify("anthropic", 429, "{}", "slow down", "", "900", now, &h);
            }
#define FMT(buf, cap)                                                                                   \
    (which == 0   ? pic_keyhealth_until(h.until_ms ? h.until_ms : now + 600000, now, buf, cap)        \
     : which == 1 ? pic_keyhealth_phrase(&h, now, buf, cap)                                             \
     : which == 2 ? pic_keyhealth_alert(&h, now, buf, cap)                                              \
     : which == 3 ? pic_keyhealth_message("anthropic", "main", &h, now, buf, cap)                       \
                  : pic_keyhealth_headline("anthropic", "main", &h, now, buf, cap))
            FMT(probe, sizeof probe);
            need = strlen(probe) + 1;
            out = (char *)hb(need);
            FMT(out, need);
            assert(strlen(out) == need - 1);
            free(out);
            if (need > 1) {
                out = (char *)hb(need - 1);
                FMT(out, need - 1);
                assert(strlen(out) == need - 2);
                free(out);
            }
        }
    }
    puts("ok the key-health sentences (until, phrase, alert, message, headline) at their exact sizes");
}

int main(void) {
    noise_ik();
    noise_prekey();
    noise_transport();
    noise_small();
    b64();
    webpush();
    sse();
    sqlar();
    http();
    image();
    cred();
    keyhealth();
    puts("ok capacity");
    return 0;
}