如何在 CGI 中处理 POST 请求中的内容长度为 0?

How to handle 0 Content length in POST request in CGI?

在我的 CGI 应用程序中,当我传递 0 内容长度 POST 请求时,会发生一些事情。这是我的代码:

char* len_ = getenv("CONTENT_LENGTH");
char* type_ = getenv("REQUEST_METHOD");
if(len_ != NULL)
{
    // The code crashes somewhere here
    long int len = strtol(len_, NULL, 10);
    char* postdata = (char*)malloc(len + 1);
    if (!postdata) { exit(EXIT_FAILURE); }
    //fgets(postdata, len + 1, stdin);
    string temp = "";
    fstream ff;
    string fileName = string(XML_DATA_DIRECTORY) + string("data.xml");
    ff.open(fileName.c_str(), ios::in | ios::out | ios::trunc);
    // ff.open(fileName.c_str());

    if(ff)
    {
        // Modified: To handle new line in the Xml request
        while(fgets(postdata, len + 1, stdin) != NULL)
        {
            temp.append(postdata);
        }
        ff << temp;
    }
    else
    {
        // Error on the ifstream
    }
    ff.close();
    //free(postdata);
}
else
{
    // No Data
}

我使用 FireFox 的 Http-Requester 插件测试我的应用程序,当我传递一个没有数据的 POST 请求时,应用程序似乎进入了一个循环并且没有响应。如果我传递 GET 请求,代码工作正常,因为 len_ 变为 NULL 并退出 if 语句。如果我用数据传递 POST 请求,它工作正常并且很好地接收数据并保存它。

我无法弄清楚的情况是 POST 和 CONTENT_LENGTH = 0。如何计算这种情况?我试过 strlen(len_) 但没有成功。感谢您的帮助。

检查是否getenv returns NULL,例如:

char* len_;
long int len;

len_ = getenv("CONTENT_LENGTH");
if (len_ && sscanf(len_, "%ld", &len) == 1) {
   if (len > 0) {
      ...
   }
}

请注意(正如@Deduplicator 所指出的)最好将 len 声明为 unsigned longsize_t,因为 CONTENT_LENGTH(发送的字节数客户)总是积极的。