Question

I'm writing an http server for my school project, and I'm trying to execute a CGI script. The following code successfully executes the cgi program, and the output of the program is sent to the browser, but there's something wrong with the way I'm sending POSTed data. Here's what I've got:

    int p[2];
    pipe(p);

    int pid = fork();

    if (pid == 0) {
        close(p[1]);

        dup2(p[0], STDIN_FILENO);
        dup2(socket, STDOUT_FILENO);

        execve(path.c_str(), {}, (char**) &env[0]);
    } else {
        close(p[0]);

        string body = req->getBody();
        write(p[1], body.c_str(), body.size());

        close(socket);
    }

If I understand CGI correctly I just need to set an HTTP_CONTENT_LENGTH environment variable (which I'm doing) and send the request body to stdin. Am I using pipe, dup2, and write the correct way to do that?

When posting to my test PHP script, the $_POST array is empty. When posting to my test perl script, it simply never sends any response or finishes running; I assume it's waiting for more stdin. If there's nothing obviously wrong with my piping and dup2ing, I'll post some compilable test code that illustrates the problem.

Thank you!

Was it helpful?

Solution

The piping and dup2ing is all OK; my problem was my CGI environment variable. The winning environment variable is CONTENT_LENGTH, not prefixed with HTTP_.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top