Implement parse_request_line
parent
16668c0707
commit
5de4fd071e
|
@ -1,4 +1,6 @@
|
|||
#include "request_handling.h"
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
|
|
|
@ -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
|
Loading…
Reference in New Issue