私は C でサーバーを書くことについて学ぼうとしていますが、私を本当に混乱させるものに出くわしました。私はいくつかのコードを理解しようとしています(私のものではありません)。parse
私はそれのほとんどを理解しています...この関数のこの1つの重要な要素を除いて.
具体的にはstrsep()
、以下のコードでどのように機能していますか?
strsep()
文字列内で停止するポイント(トークン?)を見つけて、最後を切り落とし、残りを新しい変数に格納すると思いました。リクエストライン内でを見つけるmethod
など:method = strsep(copyofLine, " ");
これは私には理にかなっています。
ただし、これがどのように機能するかわかりません:
//put request-target in abs_path
abs_path = strsep(copyofLine, "]" + 1);
]
HTTP 要求行にがあるのはなぜですか?
そしてここにも:
HTTP_version = strsep(copyofLine, "\\");
バックスラッシュがあるのはなぜですか?説明してください。
以下は完全な機能です。ありがとうございました。
/**
* 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;
}