cybersecurity · intermediate · ~15 min · safe pentest lab

Parse an HTTP request line

Practise defensive parsing of a real protocol from sample text.

Challenge

Parse an HTTP request line into its three fields — network code is mostly parsing, and bounds-checking each field as you copy is what prevents buffer-overflow CVEs.

Task

Implement int parse_request_line(const char *line, http_req_t *out) that parses METHOD PATH VERSION\r\n into the struct:

typedef struct { char method[8]; char path[256]; char version[16]; } http_req_t;

Input

  • line: a NUL-terminated request line of the form METHOD PATH VERSION\r\n. The grader passes fixed strings.
  • out: the struct to fill on success.

Output

Returns int: 0 on success (filling out), -1 on malformed input.

Example

"GET /index.html HTTP/1.1\r\n"   ->   0, method="GET", path="/index.html", version="HTTP/1.1"
"GET /\r\n"                       ->   -1   (only two fields)
"REALLYLONGMETHOD / HTTP/1.1\r\n" ->   -1   (method overflows)

Edge cases

  • Empty input returns -1.
  • Each field must fit its destination (method <= 7, path <= 255, version <= 15 bytes excluding the NUL).

Rules

  • Tokens are separated by single spaces.
  • Strip the trailing \r\n. Reject (return -1) rather than truncate any field that would overflow.

Input format

A NUL-terminated request line METHOD PATH VERSION\r\n and an output http_req_t pointer.

Output format

An int: 0 on success with out filled, -1 on malformed input.

Constraints

Single-space separators; reject any field that would overflow its bounded buffer.

Starter code

#include <stdio.h>
#include <string.h>

int parse_request_line(const char *line, http_req_t *out) {
    /* TODO */
    return -1;
}

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