Skip to content
pi-c Artifact [5735cadc92]
Login

Artifact [5735cadc92]

Artifact 5735cadc92816fc4583caca46d367757ad2b836e750f8267707dea03fc151037:


/* libFuzzer target: HTTP/1.1 response parser. The outcome, status and body
 * must not depend on how the bytes are chunked. */
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "http.h"

int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size);

/* The parser needs no network; these satisfy pic_http_post's references. */
int pic_net_connect(pic_net *n, const char *host, int port, int tls, int idle_seconds, int deadline_seconds) {
    (void)n, (void)host, (void)port, (void)tls, (void)idle_seconds, (void)deadline_seconds;
    return -1;
}
int pic_net_write(pic_net *n, const void *bytes, size_t len) {
    (void)n, (void)bytes, (void)len;
    return -1;
}
long pic_net_read(pic_net *n, void *bytes, size_t cap) {
    (void)n, (void)bytes, (void)cap;
    return -1;
}
void pic_net_close(pic_net *n) { (void)n; }
const char *pic_net_error(const pic_net *n) {
    (void)n;
    return "";
}

typedef struct {
    char *body;
    size_t len, cap;
} sink;

static int collect(void *ctx, const char *bytes, size_t n) {
    sink *s = ctx;
    if (s->len + n > s->cap) {
        s->cap = (s->len + n) * 2;
        s->body = realloc(s->body, s->cap);
        if (!s->body) {
            abort();
        }
    }
    memcpy(s->body + s->len, bytes, n);
    s->len += n;
    return 0;
}

static int run(const char *bytes, size_t n, size_t chunk, sink *s, int *status) {
    pic_http_resp r;
    int rc = 0;
    pic_http_resp_init(&r, collect, s);
    for (size_t i = 0; i < n && rc == 0; i += chunk) {
        rc = pic_http_feed(&r, bytes + i, n - i < chunk ? n - i : chunk);
    }
    if (rc == 0) {
        rc = pic_http_end(&r);
    }
    *status = r.status;
    return rc;
}

int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
    sink a = {NULL, 0, 0}, b = {NULL, 0, 0};
    int sa, sb, ra, rb;
    if (size == 0) {
        return 0;
    }
    ra = run((const char *)data + 1, size - 1, size, &a, &sa);
    rb = run((const char *)data + 1, size - 1, (size_t)(data[0] % 16) + 1, &b, &sb);
    if (ra != rb || (ra == 0 && (sa != sb || a.len != b.len || (a.len && memcmp(a.body, b.body, a.len) != 0)))) {
        fprintf(stderr, "chunking changed the result: rc %d/%d status %d/%d body %zu/%zu\n", ra, rb, sa, sb, a.len,
                b.len);
        abort();
    }
    free(a.body);
    free(b.body);
    return 0;
}