| Line | Branch | Exec | Source |
|---|---|---|---|
| 1 | #include "http_parser.h" | ||
| 2 | #include <string.h> | ||
| 3 | #include <ctype.h> | ||
| 4 | |||
| 5 | 3 | int parse_http_request(char *buffer, size_t len, HttpRequest *req) { | |
| 6 | 3 | char *cursor = buffer; | |
| 7 | 3 | char *end = buffer + len; | |
| 8 | char *line_end; | ||
| 9 | |||
| 10 | // Parse the Request-Line: METHOD SP PATH SP VERSION CRLF | ||
| 11 | 3 | line_end = strstr(cursor, "\r\n"); | |
| 12 |
1/2✗ Branch 0 not taken.
✓ Branch 1 taken 3 times.
|
3 | if (!line_end) return -1; |
| 13 | 3 | *line_end = '\0'; | |
| 14 | |||
| 15 | // Extract the method | ||
| 16 | 3 | char *method = cursor; | |
| 17 | 3 | char *space = strchr(method, ' '); | |
| 18 |
2/2✓ Branch 0 taken 1 times.
✓ Branch 1 taken 2 times.
|
3 | if (!space) return -1; |
| 19 | 2 | *space = '\0'; | |
| 20 | 2 | req->method = method; | |
| 21 | |||
| 22 | // Extract the path | ||
| 23 | 2 | char *path = space + 1; | |
| 24 | 2 | space = strchr(path, ' '); | |
| 25 |
1/2✗ Branch 0 not taken.
✓ Branch 1 taken 2 times.
|
2 | if (!space) return -1; |
| 26 | 2 | *space = '\0'; | |
| 27 | 2 | req->path = path; | |
| 28 | |||
| 29 | // The rest is the HTTP version | ||
| 30 | 2 | char *version = space + 1; | |
| 31 | 2 | req->version = version; | |
| 32 | |||
| 33 | // Move the cursor past the CRLF | ||
| 34 | 2 | cursor = line_end + 2; | |
| 35 | |||
| 36 | // Parse headers | ||
| 37 | 2 | req->header_count = 0; | |
| 38 |
3/6✓ Branch 0 taken 2 times.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✓ Branch 3 taken 2 times.
✗ Branch 4 not taken.
✓ Branch 5 taken 2 times.
|
2 | while (cursor < end && !(cursor[0] == '\r' && cursor[1] == '\n')) { |
| 39 | ✗ | line_end = strstr(cursor, "\r\n"); | |
| 40 | ✗ | if (!line_end) break; | |
| 41 | ✗ | *line_end = '\0'; | |
| 42 | |||
| 43 | // Find the ':' separator | ||
| 44 | ✗ | char *colon = strchr(cursor, ':'); | |
| 45 | ✗ | if (!colon) return -1; | |
| 46 | ✗ | *colon = '\0'; | |
| 47 | ✗ | char *field = cursor; | |
| 48 | ✗ | char *value = colon + 1; | |
| 49 | |||
| 50 | // Remove any leading spaces in the value | ||
| 51 | ✗ | while (*value && isspace((unsigned char)*value)) value++; | |
| 52 | |||
| 53 | ✗ | if (req->header_count < MAX_HEADERS) { | |
| 54 | ✗ | req->headers[req->header_count].field = field; | |
| 55 | ✗ | req->headers[req->header_count].value = value; | |
| 56 | ✗ | req->header_count++; | |
| 57 | } | ||
| 58 | // Otherwise, you might decide to ignore extra headers | ||
| 59 | |||
| 60 | ✗ | cursor = line_end + 2; | |
| 61 | } | ||
| 62 | |||
| 63 | // The parser has also read the empty line separating headers and body | ||
| 64 | 2 | return 0; | |
| 65 | } | ||
| 66 |