CGIServer

(edited 2023.07.24 by gsz)

The story

This is one of those "how hard could it be" projects. I was messing around a lot with CGI scripts on one of my projects. I built a log viewer and lister in bash, but also started to realize, that I could use it to automate each and every one of my tasks via CGI. I am still amazed by the elegance how it works and reuses existing technologies and techniques like enviornment variables, stdin, stdout etc. It is an elegant and mainly stable solution. By design it eliminates memory leaks, since new processes are created for each request. Elegant, simple, usable? Yes. Effective? Not really. Do I care? No.

So I developed a nice fetish to CGI as technology, and was messing around with it. What I find interesting however is, that NGinx doesn't support it. Now I could have go around that and install Apache or Lighttpd, but I wasn't as fluent with container technologies as I am now (well, I hadn't any clue about it) so I told to myself: why not to create one from scratch? So I did.

The project can be found here

The implementation

I used Java. I know, not the sharpest tool for such a task, but hey. If you have a hammer...

It uses plain old ServerSocket to listen to requests and a thread pool of handlers. It forks a new process for each request, sets the environment variables based on the HTTP reuqest headers and executes the script. It copies the HTTP body to stdin and then copies the stdout as the HTTP response. When I say copies, I mean streams. So nothing big is stored in memory, only the buffers.

It runs well with just a low amount of memory (16 MB is fine, 32MB better).

It needs some configuration, but after that, it runs well.

There are no magic in the implementation. The only one present however is, that if no script is present in the request, the CGI Server will try and guess for index and execute that script. This is a feature out of necessity, and I am not a fan of it. It should be at least configurable, but it is what it is for now. I will improve on this one later on.

Enjoy.