From 5de4fd071e9f2702ffaa695b72f50dc06c1d1e4c Mon Sep 17 00:00:00 2001 From: Nick Krichevsky Date: Sat, 8 Sep 2018 23:53:54 -0400 Subject: [PATCH] Implement parse_request_line --- server/request_handling.c | 50 +++++++++++++++++++++++++++++++++++++++ server/request_handling.h | 12 ++++++++++ 2 files changed, 62 insertions(+) create mode 100644 server/request_handling.h diff --git a/server/request_handling.c b/server/request_handling.c index 9ecc96e..b9ef99e 100644 --- a/server/request_handling.c +++ b/server/request_handling.c @@ -1,4 +1,6 @@ +#include "request_handling.h" #include +#include /** * Identical to strcpy, but strips a trailing '\r\n' @@ -28,3 +30,51 @@ static char *strcpy_no_crlf(char *dest, const char *src) { return dest; } + +/** + * Parse a request line into a request_line + * + * @param line The line to parse. + * @param parsed_line A pointer to a request_line. Values must be freed by caller. + * + * @return -1 if malformed, 0 if well formed. + */ +int parse_request_line(const char *line, struct request_line *parsed_line) { + int line_size = strlen(line) + 1; + char *raw_line = malloc(line_size * sizeof(char)); + strcpy(raw_line, line); + + char *method = strtok(raw_line, " "); + if (method == NULL) { + free(raw_line); + return -1; + } + int method_size = strlen(method) + 1; + parsed_line->method = malloc(method_size * sizeof(char)); + strcpy_no_crlf(parsed_line->method, method); + + char *uri = strtok(NULL, " "); + if (uri == NULL) { + free(raw_line); + free(parsed_line->method); + return -1; + } + int uri_size = strlen(uri) + 1; + parsed_line->uri = malloc(uri_size * sizeof(char)); + strcpy_no_crlf(parsed_line->uri, uri); + + char *http_version = strtok(NULL, " "); + if (http_version == NULL) { + free(raw_line); + free(parsed_line->method); + free(parsed_line->uri); + return -1; + } + int version_size = strlen(http_version) + 1; + parsed_line->http_version = malloc(version_size * sizeof(char)); + strcpy_no_crlf(parsed_line->http_version, http_version); + + free(raw_line); + + return 0; +} diff --git a/server/request_handling.h b/server/request_handling.h new file mode 100644 index 0000000..9032bbf --- /dev/null +++ b/server/request_handling.h @@ -0,0 +1,12 @@ +#ifndef REQUEST_HANDLING_H +#define REQUEST_HANDLING_H + +struct request_line { + char *http_version; + char *method; + char *uri; +}; + +int parse_request_line(const char *line, struct request_line *parsed_line); + +#endif