Skip to content
systemcoding.dev
Networking

Write an Incremental Parser for Streaming Protocols

Build a resumable state-machine parser in C that takes a protocol in any chunking, so TCP segmentation never breaks framing, and test it at every split offset.

9 min read
Summarize in AI
Flat illustration of network packets crossing between two hosts, with the C, Wireshark and Linux logos.

TCP does not preserve message boundaries. A sender that writes one 100-byte message may be read as 100 bytes, as 1 byte followed by 99, or as that message glued to the front of the next one. A parser that calls recv once and expects a whole frame will work on loopback and fail in production. The fix is an incremental parser: a small state machine that you feed whatever bytes arrived, which remembers where it stopped and resumes on the next call. This post builds one in C17 for a length-prefixed protocol, shows the invariants that make it correct, and tests it by splitting the input at every possible offset. The code is portable and the reasoning applies to any streaming protocol, from a custom binary format to the line-oriented text of SMTP.

The protocol

To keep the focus on the technique, use a simple framed protocol. Each message is a 2-byte big-endian length followed by that many payload bytes, up to a maximum of 1024. A message of length 5 carrying hello is the seven bytes 00 05 68 65 6c 6c 6f. The stream is just these messages back to back.

The two cases that break naive parsers are visible immediately. The 2-byte length itself can be split across two reads, with one byte in each. And the payload can arrive in any number of pieces. The parser has to handle both without ever blocking and without copying more than it must.

State, not a buffer of everything

One approach is to append every received byte to a growing buffer and re-scan from the start each time. It is easy to write, and it is quadratic in the worst case, because a slow sender that trickles one byte at a time forces a re-scan of everything received so far. It also needs an unbounded buffer unless you add a cap.

The incremental approach keeps a small amount of state and consumes each byte exactly once. Here the state is which field you are in, how many bytes of it you have collected, and the payload buffer so far.

frame_parser.hc
#ifndef FRAME_PARSER_H
#define FRAME_PARSER_H

#include <stddef.h>
#include <stdint.h>

#define FRAME_MAX 1024

enum frame_state {
    FRAME_LEN_HI,    /* waiting for the high length byte */
    FRAME_LEN_LO,    /* waiting for the low length byte */
    FRAME_PAYLOAD,   /* collecting payload bytes */
    FRAME_ERROR      /* a protocol violation; the stream is unusable */
};

struct frame_parser {
    enum frame_state state;
    uint16_t length;
    uint16_t filled;
    uint8_t payload[FRAME_MAX];
};

typedef void (*frame_cb)(const uint8_t *payload, uint16_t len, void *ctx);

void frame_parser_init(struct frame_parser *p);

/* Consumes all n bytes. Returns 0 on success, -1 after a protocol error. */
int frame_parser_feed(struct frame_parser *p, const uint8_t *data, size_t n,
                      frame_cb cb, void *ctx);

#endif

Three design decisions are visible in the interface. feed takes a callback rather than returning a frame, because one chunk of input can contain several complete messages, or none. It consumes all the bytes it is given, so the caller never has to track a leftover offset. And it returns an error rather than aborting, because a hostile peer controls the input and a bad length must close that one connection and nothing else.

The state machine

Each byte moves the parser one step. The switch handles one byte at a time, which keeps the logic obvious. A faster version would copy runs of payload bytes with memcpy, and the next section does exactly that.

frame_parser.cc
#include "frame_parser.h"
#include <string.h>

void frame_parser_init(struct frame_parser *p)
{
    p->state = FRAME_LEN_HI;
    p->length = 0;
    p->filled = 0;
}

int frame_parser_feed(struct frame_parser *p, const uint8_t *data, size_t n,
                      frame_cb cb, void *ctx)
{
    size_t i = 0;

    while (i < n) {
        switch (p->state) {
        case FRAME_LEN_HI:
            p->length = (uint16_t)(data[i++] << 8);
            p->state = FRAME_LEN_LO;
            break;

        case FRAME_LEN_LO:
            p->length |= data[i++];
            if (p->length > FRAME_MAX) {
                p->state = FRAME_ERROR;
                return -1;
            }
            p->filled = 0;
            if (p->length == 0) {
                cb(p->payload, 0, ctx);
                p->state = FRAME_LEN_HI;
            } else {
                p->state = FRAME_PAYLOAD;
            }
            break;

        case FRAME_PAYLOAD: {
            size_t want = (size_t)p->length - p->filled;
            size_t have = n - i;
            size_t take = want < have ? want : have;

            memcpy(p->payload + p->filled, data + i, take);
            p->filled += (uint16_t)take;
            i += take;

            if (p->filled == p->length) {
                cb(p->payload, p->length, ctx);
                p->state = FRAME_LEN_HI;
            }
            break;
        }

        case FRAME_ERROR:
            return -1;
        }
    }
    return 0;
}

The payload case takes min(want, have) bytes in one memcpy. That is the whole trick for speed: states that carry bulk data copy runs, and states that carry a single control byte go one at a time. The length check happens the instant the second length byte arrives, before any payload is accepted, so a peer cannot make the parser buffer more than FRAME_MAX bytes. The parser has a fixed size and never calls malloc.

Zero-length messages are legal in this protocol, and the code handles them without entering FRAME_PAYLOAD. If it did enter that state with length == 0, the next byte it read would be misinterpreted as payload. Boundary values such as 0 and the maximum are where parsers fail, so each gets a test below.

Test by splitting at every offset

The property that defines correctness is simple: feeding the stream in any chunking must produce the same messages as feeding it all at once. You can check this exhaustively for a small input by splitting it at every offset, and then feeding it one byte at a time.

test_parser.cc
#include "frame_parser.h"
#include <stdio.h>
#include <string.h>

struct collected {
    int count;
    char text[8][16];
};

static void collect(const uint8_t *payload, uint16_t len, void *ctx)
{
    struct collected *c = ctx;
    if (c->count < 8 && len < sizeof c->text[0]) {
        memcpy(c->text[c->count], payload, len);
        c->text[c->count][len] = '\0';
    }
    c->count++;
}

static int run(const uint8_t *stream, size_t n, size_t split,
               struct collected *out)
{
    struct frame_parser p;
    memset(out, 0, sizeof *out);
    frame_parser_init(&p);

    if (frame_parser_feed(&p, stream, split, collect, out) < 0)
        return -1;
    return frame_parser_feed(&p, stream + split, n - split, collect, out);
}

int main(void)
{
    /* "hello", an empty frame, then "ok" */
    const uint8_t stream[] = {
        0x00, 0x05, 'h', 'e', 'l', 'l', 'o',
        0x00, 0x00,
        0x00, 0x02, 'o', 'k'
    };
    size_t n = sizeof stream;
    int bad = 0;

    for (size_t split = 0; split <= n; split++) {
        struct collected c;
        if (run(stream, n, split, &c) < 0 || c.count != 3 ||
            strcmp(c.text[0], "hello") != 0 || c.text[1][0] != '\0' ||
            strcmp(c.text[2], "ok") != 0) {
            printf("split %zu: FAILED\n", split);
            bad++;
        }
    }
    printf("%zu splits tried, %d failed\n", n + 1, bad);

    struct collected c;
    struct frame_parser p;
    const uint8_t oversized[] = { 0x04, 0x01 };   /* length 1025 */
    frame_parser_init(&p);
    int rc = frame_parser_feed(&p, oversized, sizeof oversized, collect, &c);
    printf("oversized length returns %d\n", rc);
    return bad != 0;
}
Text
14 splits tried, 0 failed
oversized length returns -1

The stream is 13 bytes, so there are 14 split positions from 0 to 13, which is what the first line reports. Splits at 1, 8 and 10 land in the middle of a length field, and splits at 3 to 6 land in the middle of a payload, so the test covers both hazards. Feeding the whole stream in one call is the split at 13. Extending the loop to feed one byte at a time is a good further exercise, and a fuzzer such as libFuzzer can generate random streams and random chunkings far beyond what you will write by hand.

Applying it to a socket

On a real connection the loop is: recv into a small buffer, pass exactly the bytes received to frame_parser_feed, and close the connection if it returns -1. The parser needs no knowledge of how many bytes recv returned beyond the count you pass, and no knowledge of how the sender chunked them.

reader_loop.cc
#include "frame_parser.h"
#include <sys/socket.h>
#include <unistd.h>

void read_loop(int fd, frame_cb cb, void *ctx)
{
    struct frame_parser p;
    uint8_t chunk[512];

    frame_parser_init(&p);
    for (;;) {
        ssize_t n = recv(fd, chunk, sizeof chunk, 0);
        if (n <= 0)
            break;                       /* EOF or error: stop */
        if (frame_parser_feed(&p, chunk, (size_t)n, cb, ctx) < 0)
            break;                       /* protocol error: drop the peer */
    }
    close(fd);
}

A chunk size of 512 is arbitrary and independent of the frame size, which is the point: correctness no longer depends on how recv slices the stream.

What changes for text protocols

The same structure handles line-oriented protocols such as SMTP or Redis's inline commands. The states become "collecting a line" and "seen a carriage return", and the length cap becomes a maximum line length, which RFC 5321 sets to 512 bytes for an SMTP command line. The principles do not change. Consume each byte once, keep the state in a struct, bound every buffer, and treat any violation as a reason to close the connection.

Backpressure and what the parser must not do

An incremental parser answers "what do these bytes mean", and it should stay out of every other decision. It should not decide how much to read from the socket, because that is flow control and belongs to the caller. It should not block, sleep or allocate on the hot path, and it should not call back into code that can close the connection while the parser is still iterating over the chunk it was given. If the callback needs to tear down the connection, have it set a flag and let the loop check that flag after feed returns, otherwise the parser's struct may be freed in the middle of its own loop.

A related decision is how much work one feed call may do. A single 512-byte chunk can contain hundreds of tiny frames, and a callback that does real work for each can starve other connections in an event loop. A common compromise is to let the callback queue the frame for later handling and keep feed cheap, with a limit on how many frames may sit unprocessed. When that limit is reached, stop reading from that socket, which pushes the pressure back to the sender through TCP's own window. That is backpressure, and it only works if the parsing layer does not hide an unbounded queue of its own.

Finally, decide up front what a protocol error means for the stream. In this format a bad length leaves the parser unable to find the next frame boundary, so the only safe response is to drop the connection. The FRAME_ERROR state is sticky for that reason: once reached, every later byte is refused, and a caller that ignores the return value still cannot get a frame out of a corrupt stream.

Where this approach costs you

State machines are verbose. Every new field adds states, and a format with nested, optional or variable-length parts, such as TLS records or HTTP chunked bodies, grows a long switch that is easy to get wrong. Parser generators, or a parsing library such as nom in Rust, trade that verbosity for a description closer to the grammar. The state-machine form is still the right thing to understand first, because those tools produce the same structure.

Share

Keep reading

Flat illustration of a microcontroller wired to an LED and a sensor, with the Bluetooth, Nordic Semiconductor and Arm logos.
Embedded

Create a Custom BLE GATT Service on nRF52

Define a custom 128-bit GATT service on nRF52 with Zephyr: characteristic properties, read and write callbacks, notifications through the CCC and MTU limits.

9 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.