CHAPTER 8HOW CGULL WORKS21

CHAPTER 8How cgull Works

There is less to cgull than the earlier chapters might suggest: a C file of about five hundred lines, a JavaScript file of about two hundred, and a command that runs the compiler. This chapter describes how they fit together, for the curious and for anyone who wants to change them.

8.1 CGI

The Common Gateway Interface is how web servers ran programs in the 1990s. For each request the server started the program, passed it the request's details in environment variables and its body on standard input, and sent back whatever the program wrote to standard output: headers, a blank line, and the body. A CGI program in C needs nothing but getenv and printf:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    printf("Content-Type: text/plain\r\n\r\n");
    printf("You asked for %s\n", getenv("PATH_INFO"));
    return 0;
}

A cgull program is a CGI program. cg_run reads the request from the environment, finds the handler, and at the end writes the response to standard output, CGI-style, with a Status: line first. The library is a convenient way to write such a program; underneath, it is the same arrangement.

CGI fell out of favour because starting a process per request was slow. Starting a WebAssembly instance is not, which is what makes the old arrangement work again.

8.2 The Request Going In

The Worker turns each request into these environment variables, along with the Worker's string variables and secrets:

VariableValue
REQUEST_METHODThe method, e.g. GET
REQUEST_URIThe path and query string, still encoded
PATH_INFOThe path, decoded
QUERY_STRINGThe query string, without the ?, still encoded
SCRIPT_NAMEEmpty: the program is the whole site
CONTENT_TYPEThe body's type, if any
CONTENT_LENGTHThe body's length, if there is a body
HTTP_NAMEEach request header, its name in capitals with - as _: HTTP_USER_AGENT
REMOTE_ADDRThe visitor's IP address
SERVER_NAME, SERVER_PORTThe host name and port the request was sent to
HTTPSon or off
SERVER_PROTOCOLHTTP/1.1
GATEWAY_INTERFACECGI/1.1
SERVER_SOFTWAREcgull

If a Worker variable has the same name as one of these, the request's value wins. The body is given to the program as standard input.

8.3 The Shim

The JavaScript side, shim.js, compiles the module once, when the Worker starts, and makes a new instance of it for each request. The module is built for WASI, the WebAssembly System Interface, which gives C's standard library the calls it needs from an operating system. The shim provides only those a CGI program uses:

WASI callWhat the shim does
environ_get, environ_sizes_getGive the program the variables above
fd_readReads the request body, on file descriptor 0
fd_writeCollects standard output (the response) and standard error (the logs)
fd_fdstat_getSays descriptors 0 to 2 are character devices
clock_time_getGives Date.now()
random_getFills a buffer from crypto.getRandomValues
proc_exitEnds the program
args_get, fd_close, fd_seek, fd_prestat_getReport no arguments, no seeking, and no directories

Any other call the module imports gets ENOSYS, "function not implemented", which the standard library turns into an ordinary error such as fopen returning NULL. When the program has finished, the shim splits its output at the first blank line, turns the Status: line into the response's status and the rest into its headers, and returns the remainder as the body. A trap, an exit status other than 0, or output without a blank line gives a 500.

The Worker itself, build/worker.js, is a few lines: it passes each request, and the Worker's string variables, to the shim.

8.4 Native Builds

Because the program is plain CGI, it doesn't need the shim at all. cgull build --native compiles it for the machine you're on, as build/app, and that program runs under any web server that speaks CGI, or on its own:

$ REQUEST_METHOD=GET REQUEST_URI=/hello/you ./build/app
Status: 200 OK
Content-Type: text/html; charset=utf-8

<h1>Hello, you!</h1>

The real use of this is debugging. A native build can run under gdb, or be built with the sanitizers, which catch out-of-bounds accesses and undefined behaviour that WebAssembly would let pass:

"cgull": { "cflags": ["-fsanitize=address,undefined", "-g"] }

Remove the sanitizer flags again before deploying, since wasi-sdk does not support them. cgull run --native sends a request to the native program through the same code that parses the WebAssembly one's output, so the two can be compared. cgull's own tests do exactly that, running every case both ways.

8.5 What Comes Next

A cgull program can't yet make requests of its own, or use Cloudflare's storage. Both need the program to wait for JavaScript promises, and WebAssembly can now do that: JavaScript Promise Integration, WebAssembly.Suspending, lets a call from WebAssembly suspend the instance until a promise settles, and Workers support it. The plan is for calls like these to look as ordinary as everything else:

const char *page = cg_fetch("https://example.com/");
const char *name = cg_kv_get("USERS", id);

Responses may also be streamed one day, rather than kept until the handler returns, and forms with file uploads parsed.

Set in Tinos and Courier Prime. Served by a C program on Cloudflare Workers, cgull 0.1.0. Source on GitHub, BSD licensed.