summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorcflip <cflip@cflip.net>2023-06-01 09:38:51 -0600
committercflip <cflip@cflip.net>2023-06-01 09:47:02 -0600
commit02a542644617f65cf7285f0facebc827fd036b45 (patch)
treee5888f4c3d70ae46f55b7c17d74f1f14fb455b80
parent40b66da398695590f82594bb92fd824bfdb44836 (diff)
Parse query string from HTTP requests
-rw-r--r--http.c45
-rw-r--r--http.h1
2 files changed, 39 insertions, 7 deletions
diff --git a/http.c b/http.c
index 41a0435..fb536c8 100644
--- a/http.c
+++ b/http.c
@@ -8,18 +8,47 @@
struct http_request http_parse_request(const char *reqstr)
{
- struct http_request req;
char uribuf[CFWS_MAXURI];
- size_t urilen;
+ size_t urilen = 0, query_len = 0;
+ const char *counter;
+
+ struct http_request req;
+ req.method = HTTP_METHOD_GET;
+ req.uri = NULL;
+ req.query_str = NULL;
- sscanf(reqstr, "GET %s HTTP/1.1", uribuf);
+ /* TODO: Support other request methods such as POST */
+ if (strncmp(reqstr, "GET ", 4) != 0) {
+ fprintf(stderr, "Unhandled request type: %s\n", reqstr);
+ return req;
+ }
- /* TODO: Support other method types, notably POST */
- req.method = HTTP_METHOD_GET;
+ counter = reqstr + 4;
+ while (*counter != ' ' && *counter != '?' && *counter != 0
+ && urilen < CFWS_MAXURI) {
+ uribuf[urilen++] = *counter;
+ ++counter;
+ }
- urilen = strlen(uribuf);
req.uri = malloc(urilen + 1);
- memcpy(req.uri, uribuf, urilen + 1);
+ memcpy(req.uri, uribuf, urilen);
+ req.uri[urilen] = '\0';
+
+ /* Parse the query string if one exists. */
+ if (*counter == '?') {
+ /* Skip the question mark at the beginning. */
+ counter++;
+
+ while (*counter != ' ' && *counter != 0
+ && query_len < CFWS_MAXURI) {
+ uribuf[query_len++] = *counter;
+ ++counter;
+ }
+
+ req.query_str = malloc(query_len + 1);
+ memcpy(req.query_str, uribuf, query_len);
+ req.query_str[query_len] = '\0';
+ }
/* TODO: Parse request headers */
@@ -29,6 +58,8 @@ struct http_request http_parse_request(const char *reqstr)
void http_free_request(struct http_request *req)
{
free(req->uri);
+ if (req->query_str)
+ free(req->query_str);
}
static const char *response_msg[2] = {
diff --git a/http.h b/http.h
index 3cdc062..89576f6 100644
--- a/http.h
+++ b/http.h
@@ -18,6 +18,7 @@ enum http_res_code {
struct http_request {
int method;
char *uri;
+ char *query_str;
};
struct http_request http_parse_request(const char *);