3

I am having a bit of trouble using strtok with strcmp.

//Handles the header sent by the browser
char* handleHeader(char *header){
        //Method given by browser (will only take GET, POST, and HEAD)
        char *method,*path, *httpVer;

        method = (char*)malloc(strlen(header)+1);
        strcpy(method,header);
        method = strtok(method," ");


        path = strtok(NULL," ");
        httpVer = strtok(NULL, " ");
        printf("\nMethod: %s\nPath: %s\nHTTP: %s\n",method,path,httpVer);


        printf("\nc1: %d\nc2: %d\n",strcmp(httpVer,"HTTP/1.0"),strcmp(httpVer,"HTTP/1.1"));

        if(!(!strcmp(httpVer,"HTTP/1.0") || (!strcmp(httpVer,"HTTP/1.1")))){
                printf("\ngive a 400 error\n");
                return "400 foo";
        }


        if(!strcmp(method,"GET")){
                //char *path = strtok(NULL," ");

                //If they request the root file, change the path to index.html
                if(!strcmp(path,"/")){
                        path = (char*)malloc(strlen(BASE_DIR) + strlen("/index.html")+1);
                        strcpy(path,"/index.html");
                }
                 return readPage(path,2);
        }
}

If I give it the following header

GET / HTTP/1.0

I get this output:

Method: GET
Path: /
HTTP: HTTP/1.0


c1: 1
c2: -1

give a 400 error

As you can see, strtok() parses the string properly, but the values c1, and c2 dont seem to make sense (c1 should return 0, but instead it returns 1).

Whats going on here?

4

4 回答 4

6

I'm guessing that you're not giving it this:

GET / HTTP/1.0

but rather this:

GET / HTTP/1.0\n

or possibly this:

GET / HTTP/1.0\r\n

Looking at your code, there should be one blank line between the "HTTP" output line and the "c1" line, but you have two, implying that the "HTTP" value itself contains a newline.

Output some quotes around the values - I bet you see this:

HTTP: "HTTP/1.0
"
于 2009-09-19T20:09:14.043 回答
2

正如您从输出中的空白行中看到的那样(正如一些人已经说过的那样),您的HTTP/1.0. 你可以解决这个问题。

但是你为什么要用 C 写一个新的 HTTP 请求解析器呢?这是2009年!那里已经有很多它们,其中一些甚至是正确的,许多是自由许可的。即使出于某种原因您确实需要编写自己的语言,您也应该使用一种安全的语言(Python、Java、Lua、C#、Perl 等),这样如果您在计数字符时犯了一个微不足道的错误,您就不会结束你的程序中有一个很大的安全漏洞。(即使你不得不使用 C,strtok也是一个特别令人震惊的 C 函数。)

于 2009-09-19T21:09:56.070 回答
1

From your output it looks like there may be a '/n' at the end of the HTTP/1.0 string? Richie is too fast for me ;)

Try trimming/removing any white space on the input string before you tokenize it.

于 2009-09-19T20:12:47.720 回答
-1

Try using

strncmp(httpVer, "HTTP/1.0", 8)

so that you ignore trailing whitespace.

于 2009-09-19T20:12:31.733 回答