My parse function works for the root directory, but for subsequent requests for, say, cat.jpg, the memcpy function seems to copy an extra \220 into both requesttarget and HTTPversion (so, for instance, the HTTPversion string would read "HTTP/1.1\220" instead of simply "HTTP/1.1"). I can't figure out why this is. Here is the code for the parse function.
bool parse(const char* line, char* abs_path, char* query)
{
char* method = NULL;
char* requesttarget = NULL;
char* HTTPversion = NULL;
char* position = strchr(line, ' ');
method = malloc(strlen(line) - strlen(position));
strncpy(method, line, strlen(line) - strlen(position));
//check if method is GET
if(strcmp(method, "GET") != 0)
{
//respond 405 Method Not Allowed
error(405);
return false;
}
//check for more than one space after method
char* space = " ";
if(strcmp(position + 1, space) == 0)
{
error(501);
free(method);
return false;
}
char* position1 = strchr((position + 1), ' ');
requesttarget = malloc(strlen(position) - strlen(position1) - 1);
memcpy(requesttarget, (position + 1), (strlen(position) - strlen(position1) - 1));
//break up requesttarget into absolute path and query
char* questionmark = strchr(requesttarget, '?');
if(questionmark != NULL)
{
strncpy(abs_path, requesttarget, strlen(requesttarget) - strlen(questionmark));
strcpy(query, questionmark);
}
else if(questionmark == NULL)
{
strcpy(abs_path, requesttarget);
query[0] = '\0';
}
//check that request target begins with /
if(requesttarget[0] != '/')
{
free(method);
//respond with 501 Not Implemented
error(501);
free(requesttarget);
free(method);
return false;
}
//check that request target does not contain "
if(strchr(requesttarget, '"') != NULL)
{
free(method);
//respond with 400 Bad Request
error(400);
free(requesttarget);
return false;
}
if(strcmp(position1 + 1, " ") == 0)
{
error(501);
free(requesttarget);
free(method);
return false;
}
HTTPversion = malloc(strlen(position1) - strlen("\r\n") - 1);
memcpy(HTTPversion, position1 + 1, strlen(position1) - strlen("\r\n") - 1);
size_t n = 8;
if(strncmp(HTTPversion, "HTTP/1.1", n) != 0)
{
//respond 505 HTTP Version Not Supported
error(505);
free(requesttarget);
free(method);
free(HTTPversion);
return false;
}
free(requesttarget);
free(method);
free(HTTPversion);
return true;
}