cybersecurity · intermediate · ~15 min

Parse an http/https URL safely

Practise parsing a foundational structure that's a popular attack surface.

Challenge

Parse a simple http/https URL into its parts, defaulting the port and rejecting malformed input.

The grader supplies this struct (do not redefine it):

typedef struct {
    char scheme[8];   // "http" or "https"
    char host[128];   // hostname (no port)
    int  port;        // 80/443 by default
    char path[256];   // "/" if not present
} url_t;

Task

Implement int parse_http_url(const char *url, url_t *out) that fills out from a URL of the form scheme://host[:port][/path]. No main — the grader calls it.

Input

  • url: the URL string to parse.
  • out: a url_t to populate.

Output

Returns 0 on success (with out filled), or -1 on failure. Defaults: port 80 for http, 443 for https; path "/" when none is present.

Example

"http://example.com/path"   ->   scheme="http",  host="example.com", port=80,   path="/path"
"https://api.example.org/v1" ->  scheme="https", port=443, path="/v1"
"http://host:8080/"          ->  port=8080
"ftp://x/y"                  ->  -1   (bad scheme)
"http://x:abc/"             ->  -1   (bad port)

Edge cases

  • Reject schemes other than http/https, hosts longer than 127 chars, and non-numeric or out-of-range ports.
  • A URL with no path gets path "/".

Rules

  • Find the :// separator, then parse host, optional :port, optional /path. Bound every copy to its destination size.

Input format

A URL string and a url_t out struct to populate.

Output format

0 with out filled on success, -1 on failure; port and path default when absent.

Constraints

Only http/https; host <= 127 chars; valid port; bound every copy; do not redefine url_t.

Starter code

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

int parse_http_url(const char *url, url_t *out) {
    /* TODO */
    return -1;
}

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