Errors when retrieving request body in Mongoose WebServer

281 Views Asked by At

I'm working with an old version of mongoose (open source web server) in C, which did not provide native access to the requests payload. In order to support POST and PUT requests, I manually modified it: after mongoose reads the headers, I check if Content-Length is set and, if so, I read again from the socket for Content-Lenght characters.

    findCL = strstr(conn->buf, "Content-Length:");
    if (findCL)
    {
        // skip "Content-Length:" string
        findCL += 15 * sizeof(char);
        findCLEnd = (char*)strchr(findCL, delimiter);
        sizeLen = findCLEnd - findCL;
        strncpy(CLSize, findCL, sizeLen);
        CLSize[sizeLen] = '\0';

        size = strtoll(CLSize, NULL, 10);

        if (size > 0)
        {
            conn->content_len = read_request(NULL, conn->client.sock, conn->ssl,
                conn->buf, conn->buf_size, &conn->data_len);
            conn->content_len = size;
            perror("recv");
            body = (char*)malloc(sizeof(char) * (size + 1));
            strncpy(body, conn->buf + conn->request_len, size);
            body[size] = '\0';
        }
    }

So far so good, even if the code is not that beautiful it does the dirty job. Problem is, while in debug the code works fine, but when the code runs as a simple background process the body is not parsed correctly: sometimes the resulting body is truncated, some other times it is just empty. It seems that the problem is caused by the fast queries from the clients.

1

There are 1 best solutions below

0
phagio On

Not a real answer, but that's how I solved. The web server module started as a Mongoose web server; I ported it to Civetweb some months ago, hoping that the latest versions of the project also supported the parsing of the body. It was not so, and I had to implement it manually. After some times I discovered that Civetweb had issues in serving Javascript files to IE8 browsers (for some mysterious reason). I reverted to Mongoose and all worked, except the body parsing, which brought to the code above and the subsequent errors. I finally solved by reverting back to Civetweb, stable version 1.9.1, keeping the manual body parsing procedure. This solved both the truncated requests body and the truncated served javascript files. Probably the first version of Civetweb was a not-so-stable beta, although I wonder how did it manage to work for months.

I still haven't checked the diffs between the two versions, but I expect it to be something related to maximum response sizes depending on platform or request headers or whatever else.