cybersecurity · intermediate · ~15 min

Parse an access log status code

Field-skipping on quasi-structured text.

Challenge

Extract the HTTP status code from a Common Log Format access-log line.

Task

Implement int log_status_code(const char *line) that returns the HTTP status code from a CLF line — the integer that appears right after the closing " of the quoted request. No main — the grader calls it.

A typical line looks like:

127.0.0.1 - frank [10/Oct/2000:13:55:36 -0700] "GET /apache_pb.gif HTTP/1.0" 200 2326

Input

line: a NUL-terminated log line (may be malformed).

Output

The status code as an int, or -1 if the line is malformed (no quoted request, or no numeric code after it).

Example

... "GET / HTTP/1.0" 200 1234   ->   200
... "GET /x HTTP/1.1" 404 0     ->   404
"not a real log line"           ->   -1
... "GET / HTTP/1.0" - 1234     ->   -1   (non-numeric code)

Edge cases

  • A line with no " characters, or with a non-numeric status field, returns -1.

Rules

  • Locate the second ", skip spaces, then parse the run of digits.

Input format

A NUL-terminated access-log line (may be malformed).

Output format

The HTTP status code as an int, or -1 if malformed.

Constraints

Locate the second double-quote, skip spaces, then parse the digits.

Starter code

int log_status_code(const char *line) {
    /* TODO */
    return -1;
}

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