networking · intermediate · ~25 min

Decode an HTTP/1.1 chunked body

Strict chunked-encoding parser; refuse permissive variants.

Challenge

Decode a chunked body into a flat buffer.

Implement int decode_chunked(const char *in, int in_len, char *out, int cap, int *out_len).

Format: repeating HEX_SIZE CRLF DATA CRLF, terminated by 0 CRLF CRLF. Reject anything not strictly matching the grammar (trailing garbage on the size line, missing CRLF, etc.).

Return 1 on success (and *out_len set), 0 on any parse error.

Why this matters

The chunked-encoding parser is the smuggling-vector surface. Writing one correctly — strict, bounded — is the defensive baseline.

Input format

Bytes + length + output buffer + cap.

Output format

0/1 + decoded length.

Constraints

Refuse non-hex chars, refuse out-of-range size, refuse if would overflow cap.

Starter code

#include <stddef.h>
int decode_chunked(const char *in, int in_len, char *out, int cap, int *out_len) { /* TODO */ (void)in; (void)in_len; (void)out; (void)cap; (void)out_len; return 0; }

Common mistakes

Accepting whitespace before/after the size. Accepting non-hex chars.

Edge cases to handle

Empty body (just 0\r\n\r\n). Single chunk. Multiple chunks. Chunk size with leading 0x.

Complexity

O(in_len).

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.