I am trying to learn about writing servers in C and have come across something that is really confusing me. I have been trying to understand some code (not mine). I understand most of it...except this one crucial element in this parse
function.
Specifically, how is strsep()
working in the code below?
I thought that strsep()
finds a point (token?) in which to stop within a string and then chops the end off, storing the remainder within a new variable. Such as finding the method
within the requestline: method = strsep(copyofLine, " ");
This makes sense to me here.
However I don't understand how it works with this:
//put request-target in abs_path
abs_path = strsep(copyofLine, "]" + 1);
Why would there be a ]
in an HTTP request line?
and also here:
HTTP_version = strsep(copyofLine, "\\");
Why would there be a backwards slash? Please explain.
Below is the full function. Thank you.
/**
* Parses a request-line, storing its absolute-path at abs_path
* and its query string at query, both of which are assumed
* to be at least of length LimitRequestLine + 1.
*/
bool parse(const char* line, char* abs_path, char* query)
{
//allocate memory for copy of line
char** copyofLine = malloc(sizeof(char**));
//copy line into new variable
strcpy(*copyofLine, line);
//allocate memory for method and copy actual method into it
char* method = malloc(sizeof(char*));
method = strsep(copyofLine, " ");
//if method is not get, respond to browser with error 405 and return false
if (strcasecmp(method, "GET") != 0) {
error(405);
return false;
}
//put request-target in abs_path
abs_path = strsep(copyofLine, "]" + 1);
//if request-target does not begin with /, respond with 501 and return false
if (abs_path[0] != '/') {
error(501);
return false;
}
char* HTTP_version = malloc(sizeof(char*));
HTTP_version = strsep(copyofLine, "\\");
if(strcasecmp(HTTP_version, "HTTP/1.1") != 0) {
error(505);
return false;
}
//if request-target contains a "", respond with error 400 and return false
char* c = abs_path;
if (strchr("\"", *c)) {
error(400);
return false;
}
//allocate memory for copy of abs_patg
char** copyofAbs_path = malloc(sizeof(char**));
//copy line into new variable
strcpy(*copyofAbs_path, abs_path);
for (int i = 0, n = strlen(*copyofAbs_path); i < n; i++) {
for (int j = 0, m = strlen(*copyofAbs_path) - i; j < m; j++) {
if (*copyofAbs_path[i] == '/' && *copyofAbs_path[i+1] == '?') query[j] = *copyofAbs_path[i+2];
if (*copyofAbs_path[i] == '/' && *copyofAbs_path[i+1] != '?') query[j] = *copyofAbs_path[i+1];
// if (strlen(query)) < 1) query = "";
if (query[j] == '\0') break;
}
}
free(HTTP_version);
free(c);
free(method);
free(copyofLine);
free(copyofAbs_path);
return false;
}