Skip to content
pi-c Artifact [c21c79aad4]
Login

Artifact [c21c79aad4]

Artifact c21c79aad47dc9349ce781e0e41215fa16ced9c29d8b886b62b537966d6565f3:


/* HTTP/1.1 response parser tests. Every case is also fed byte by byte. */
#include <arpa/inet.h>
#include <assert.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <unistd.h>

#include "http.h"
#include "net.h"

typedef struct {
    char body[1024];
    size_t len;
} sink;

static int collect(void *ctx, const char *bytes, size_t n) {
    sink *s = ctx;
    assert(s->len + n < sizeof s->body);
    memcpy(s->body + s->len, bytes, n);
    s->len += n;
    s->body[s->len] = '\0';
    return 0;
}

static int head_count(void *ctx, const pic_http_resp *r) {
    (void)r;
    ++*(int *)ctx;
    return 0;
}

/* want_rc: 0 complete, -1 malformed (during feed or at end). */
static void check(const char *in, size_t n, int want_rc, int want_status, const char *want_body, const char *want_err) {
    for (int bytewise = 0; bytewise < 2; bytewise++) {
        pic_http_resp r;
        sink s;
        int rc = 0;
        memset(&s, 0, sizeof s);
        pic_http_resp_init(&r, collect, &s);
        if (bytewise) {
            for (size_t i = 0; i < n && rc == 0; i++) {
                rc = pic_http_feed(&r, in + i, 1);
            }
        } else {
            rc = pic_http_feed(&r, in, n);
        }
        if (rc == 0) {
            rc = pic_http_end(&r);
        }
        if (rc != want_rc || (want_rc == 0 && (r.status != want_status || strcmp(s.body, want_body) != 0)) ||
            (want_err && !strstr(r.err, want_err))) {
            fprintf(stderr, "case %.50s (bytewise=%d): rc=%d status=%d body=[%s] err=[%s]\n", in, bytewise, rc, r.status,
                    s.body, r.err);
            assert(0);
        }
    }
}

#define OK(in, status, body) check(in, sizeof(in) - 1, 0, status, body, NULL)
#define BAD(in, err) check(in, sizeof(in) - 1, -1, 0, "", err)

int main(void) {
    /* Chunked, with extensions, mixed-case hex and trailers. */
    OK("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\nContent-Type: text/event-stream\r\n\r\n"
       "5\r\nhello\r\nA;ext=1\r\n, world!!!\r\n0\r\nX-Trailer: y\r\n\r\n",
       200, "hello, world!!!");
    /* Content-Length, bare-LF lines, an interim 100 response first. */
    OK("HTTP/1.1 100 Continue\r\n\r\nHTTP/1.1 401 Unauthorized\ncontent-length: 4\n\nnope", 401, "nope");
    /* Body until the connection ends. */
    OK("HTTP/1.0 200 OK\r\n\r\nall of it", 200, "all of it");
    /* No body for 204; duplicate equal lengths are fine. */
    OK("HTTP/1.1 204 No Content\r\n\r\n", 204, "");
    OK("HTTP/1.1 200 OK\r\nContent-Length: 2\r\nContent-Length: 2\r\n\r\nok", 200, "ok");
    /* Headers captured. */
    {
        const char in[] = "HTTP/1.1 429 Too Many\r\nRetry-After:  7 \r\nrequest-id: req_1\r\nContent-Length: 0\r\n\r\n";
        pic_http_resp r;
        pic_http_resp_init(&r, NULL, NULL);
        assert(pic_http_feed(&r, in, sizeof in - 1) == 0 && pic_http_done(&r));
        assert(r.status == 429 && strcmp(r.retry_after, "7") == 0 && strcmp(r.request_id, "req_1") == 0);
        assert(r.ratelimit[0] == '\0');
    }
    /* Rate-limit headers, Anthropic's and the x-ratelimit family, kept as lines. */
    {
        const char in[] = "HTTP/1.1 429 Too Many\r\nAnthropic-RateLimit-Tokens-Reset: 2026-11-22T15:45:00Z\r\n"
                          "x-ratelimit-remaining-requests:  0 \r\nx-other: 1\r\nContent-Length: 0\r\n\r\n";
        pic_http_resp r;
        pic_http_resp_init(&r, NULL, NULL);
        assert(pic_http_feed(&r, in, sizeof in - 1) == 0 && pic_http_done(&r));
        assert(strcmp(r.ratelimit, "anthropic-ratelimit-tokens-reset: 2026-11-22T15:45:00Z\n"
                                   "x-ratelimit-remaining-requests: 0\n") == 0);
    }
    { /* remote control's relay: whether the lane's reader is connected */
        const char in[] = "HTTP/1.1 204 No Content\r\npic-peer: 1\r\n\r\n";
        pic_http_resp r;
        pic_http_resp_init(&r, NULL, NULL);
        assert(pic_http_feed(&r, in, sizeof in - 1) == 0 && pic_http_done(&r));
        assert(r.status == 204 && strcmp(r.peer, "1") == 0);
    }
    { /* on_head: once, at the final response's headers, before any body byte (a quiet stream is up) */
        const char in[] = "HTTP/1.1 100 Continue\r\n\r\nHTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\n\r\n";
        pic_http_resp r;
        sink s;
        int heads = 0;
        memset(&s, 0, sizeof s);
        pic_http_resp_init(&r, collect, &s);
        r.on_head = head_count;
        r.ctx = &heads;
        assert(pic_http_feed(&r, in, sizeof in - 1) == 0);
        assert(heads == 1 && r.status == 200 && !r.body_started);
    }

    /* Smuggling and corruption guards. */
    BAD("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\nContent-Length: 3\r\n\r\n", "both chunked");
    BAD("HTTP/1.1 200 OK\r\nTransfer-Encoding: gzip, chunked\r\n\r\n", "transfer encoding");
    BAD("HTTP/1.1 200 OK\r\nContent-Encoding: gzip\r\n\r\n", "compressed");
    BAD("HTTP/1.1 200 OK\r\nContent-Length: 2\r\nContent-Length: 3\r\n\r\n", "conflicting");
    BAD("HTTP/1.1 200 OK\r\nContent-Length: 1x\r\n\r\n", "content length");
    BAD("HTTP/1.1 200 OK\r\nX: a\r\n folded\r\n\r\n", "folded");
    BAD("HTTP/1.1 200 OK\r\nBad Name: a\r\n\r\n", "header name");
    BAD("HTTP/2 200\r\n\r\n", "status line");
    BAD("HTTP/1.1 20 OK\r\n\r\n", "status line");
    BAD("HTTP/1.1 101 Switching\r\n\r\n", "protocol switch");
    /* Chunk framing. */
    BAD("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\nz\r\n", "chunk size");
    BAD("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n2\r\nabc\r\n", "longer than its size");
    BAD("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\nFFFFFFFFFFFFFFFFF\r\n", "overflows");
    /* Truncation at every kind of boundary is an error at the end. */
    BAD("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhel", "ended before");
    BAD("HTTP/1.1 200 OK\r\nContent-Length: 9\r\n\r\nshort", "ended before");
    BAD("HTTP/1.1 200 OK\r\nContent-Le", "ended before");
    /* Nothing may follow a complete response. */
    BAD("HTTP/1.1 200 OK\r\nContent-Length: 1\r\n\r\nab", "after the end");
    /* Header size cap. */
    {
        static char big[70000];
        size_t n;
        memcpy(big, "HTTP/1.1 200 OK\r\n", 17);
        n = 17;
        while (n + 20 < sizeof big - 4) {
            memcpy(big + n, "X-Pad: aaaaaaaaaaa\r\n", 20);
            n += 20;
        }
        check(big, n, -1, 0, "", "exceed");
    }
    /* The built-in roots load: PIC_CA=builtin skips the system bundles, and a
     * TLS connection then fails at the network (nothing listens on port 9),
     * not at the certificates. */
    {
        char err[256];
        pic_net *n;
        (void)setenv("PIC_CA", "builtin", 1);
        n = pic_net_new(err, sizeof err);
        if (!n || pic_net_connect(n, "127.0.0.1", 9, 1, 2, 2) == 0 || strstr(pic_net_error(n), "certificate") ||
            strstr(pic_net_error(n), "bundle")) {
            fprintf(stderr, "builtin roots: %s\n", n ? pic_net_error(n) : err);
            return 1;
        }
        pic_net_free(n);
        (void)unsetenv("PIC_CA");
    }
    /* A TLS failure at the network names the step once, then the cause whole: the cause is
     * copied out before the message is written over it. */
    {
        char err[256];
        pic_net *n;
        struct sockaddr_in a;
        socklen_t alen = sizeof a;
        int l = socket(AF_INET, SOCK_STREAM, 0), status = 0;
        pid_t kid;
        memset(&a, 0, sizeof a);
        a.sin_family = AF_INET;
        a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
        assert(l >= 0 && bind(l, (struct sockaddr *)&a, sizeof a) == 0 && listen(l, 1) == 0 &&
               getsockname(l, (struct sockaddr *)&a, &alen) == 0);
        kid = fork();
        assert(kid >= 0);
        if (kid == 0) { /* takes the connection and closes it before any TLS */
            int c = accept(l, NULL, NULL);
            char b[64];
            if (c >= 0) {
                (void)read(c, b, sizeof b);
                close(c);
            }
            _exit(0);
        }
        close(l);
        n = pic_net_new(err, sizeof err);
        assert(n && pic_net_connect(n, "127.0.0.1", ntohs(a.sin_port), 1, 5, 5) == -1);
        if (strcmp(pic_net_error(n), "the TLS handshake: the server closed the connection") != 0 &&
            strcmp(pic_net_error(n), "the TLS handshake: recv: Connection reset by peer") != 0) {
            fprintf(stderr, "tls failure: \"%s\"\n", pic_net_error(n));
            return 1;
        }
        pic_net_free(n);
        (void)waitpid(kid, &status, 0);
    }
    puts("http: all cases pass, whole and byte by byte");
    return 0;
}