0

我正在尝试学习用 C 编写服务器,但遇到了一些让我非常困惑的事情。我一直在尝试理解一些代码(不是我的)。我了解其中的大部分内容...除了此parse功能中的一个关键元素。

具体来说,如何strsep()在下面的代码中工作?

我认为这会strsep()找到一个点(令牌?),在该点中停止在一个字符串中,然后切断结尾,将剩余部分存储在一个新变量中。例如在请求行中查找methodmethod = 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;
}
4

0 回答 0