networking · intermediate · ~20 min
Strict header-parsing pattern with name validation.
An HTTP Cookie header is one line of semicolon-separated pairs: name1=value1; name2=value2; name3=value3. Look up one cookie by name and copy out its value.
Implement int find_cookie(const char *header, const char *name, char *out_value, int cap) that finds the cookie named name in header and copies its value into out_value.
Behaviour:
;.name exactly (case-sensitive, whole name only — not as a substring).out_value, NUL-terminated.header: the Cookie header line.name: the cookie name to look up.out_value, cap: destination buffer and its capacity.Returns 1 if the cookie was found (with its value written to out_value), or 0 if not found or on a rejected input.
find_cookie("session=abc123; theme=dark", "session", out, cap) -> 1, out="abc123"
find_cookie("session=abc123; theme=dark", "lang", out, cap) -> 0
find_cookie("subsession=x", "session", out, cap) -> 0 (no substring match)
session=) returns 1 with out_value empty.0) if name itself contains any of: =, ;, \r, \n, or space.Every web server, every WAF, every analytics tag needs to read Cookie headers. Doing it strictly catches malformed cookies that smuggle attacks.
The Cookie header line (header), the cookie name to find (name), and an output buffer (out_value) with capacity (cap).
Returns 1 if found (value written to out_value), or 0 if absent or on rejected input.
Match the whole name only (no substring match). Reject a name containing '=', ';', CR, LF, or space.
int find_cookie(const char *header, const char *name, char *out_value, int cap) { /* TODO */ (void)header; (void)name; (void)out_value; (void)cap; return 0; }
Using strstr — matches bar=x inside foobar=x. Use word-boundary matching.
Empty header. Cookie with empty value (name=;). Multiple instances (use first).
O(strlen).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.