CGI
CGI (Common Gateway Interface) is a convention for running a program per HTTP request. The web server sets environment variables, writes the body to stdin, and sends the program's stdout back as the response.
Detailed Explanation
Before application servers, a C program became a web handler by being an executable in cgi-bin. The server spawned it, filled REQUEST_METHOD, QUERY_STRING, CONTENT_LENGTH, PATH_INFO, and others, and connected the sockets to the process's stdio. The program printed headers, a blank line, then a body:
Content-Type: text/plain\r\n
\r\n
hello
That is still a useful mental model. FastCGI and every later "worker process" design are CGI with a persistent process. Servlets and net/http handlers are CGI with a function call instead of exec. When you write a tiny C tool that a reverse proxy launches, you are doing CGI even if you never say the word.
The C details are hostile. QUERY_STRING is not decoded. %20 is still %20 until you decode it, and decoding must reject overlong forms and %00. CONTENT_LENGTH is a string; atoi on a missing or huge value is a buffer overflow if you then malloc and fread that many bytes from stdin. Environment variables are not authenticated input; they are request data.
A CGI process starts and exits per request in classic CGI, so leaks vanish and a crash is one request. That is also why it is slow. FastCGI keeps the process, so now you have leaks, threads, and a state machine again.
Do not write new production apps as classic CGI. Do learn the I/O map: request metadata in the environment, body on stdin, response on stdout, diagnostics on stderr. That map still describes how a language talks to a web server at the lowest level.
Code Examples
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
const char *method = getenv("REQUEST_METHOD");
const char *qs = getenv("QUERY_STRING");
if (method == NULL) {
method = "GET";
}
fputs("Content-Type: text/plain\r\n\r\n", stdout);
printf("method=%s query=%s\n", method, qs ? qs : "");
return 0;
}#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
static int read_body(char *buf, size_t cap)
{
const char *cl = getenv("CONTENT_LENGTH");
if (cl == NULL) {
return 0;
}
errno = 0;
char *end = NULL;
unsigned long n = strtoul(cl, &end, 10);
if (errno != 0 || end == cl || n >= cap) {
return -1;
}
size_t got = fread(buf, 1, (size_t)n, stdin);
buf[got] = '\0';
return (int)got;
}Common Gotchas
Headers must end with a blank line
a missing blank line makes the server treat your body as more headers.
Classic CGI is a new process per request
`static` locals do not persist, and that is a feature.
Trusting `CONTENT_LENGTH` as a `size_t` without a bound allocates attacker-contr
Trusting `CONTENT_LENGTH` as a `size_t` without a bound allocates attacker-controlled sizes
`QUERY_STRING` needs URL-decoding and still needs escaping before you put it in
`QUERY_STRING` needs URL-decoding and still needs escaping before you put it in HTML or SQL