CGI for C++ applications

Source Code

The hard part about this example is doing anything demonstrable with C++. So we'll do something very silly in just printing our HTTP output into the log file. For the kcgi inclusion, we'll need all the usual header files.

#include <sys/types.h> /* size_t, ssize_t */
#include <stdarg.h> /* va_list */
#include <stddef.h> /* NULL */
#include <stdint.h> /* int64_t */
#include <kcgi.h>

Next, we'll need our C++ bits. This is make-work, but serves to illustrate…

#include <iostream>

Now let's just jump directly into our main function. It will do nothing more than print Hello, world! to the browser. But it will also emit Said hello! into the error log. See your web server configuration for where this will appear. It's usually in the error.log file. On OpenBSD's default server, it's often in /var/www/logs/error.log.

int 
main(void) {
    enum kcgi_err	  er;
    struct kreq	  r;
    const char *const pages[1] = { "index" };

    /* Set up our main HTTP context. */

    er = khttp_parse(&r, NULL, 0, pages, 1, 0);
    if (KCGI_OK != er)
        return 0;
    khttp_head(&r, kresps[KRESP_STATUS], 
        "%s", khttps[KHTTP_200]);
    khttp_head(&r, kresps[KRESP_CONTENT_TYPE], 
        "%s", kmimetypes[r.mime]);
    khttp_body(&r);
    khttp_puts(&r, "Hello, world!\n");
    std::cerr << "Said hello!";
    khttp_free(&r);
    return 0;
}

Nothing to it—looks like any of our C examples. The difference is that we've used some C++ code to emit Said hello! to the error log. The next part is how we can compile this code. For that, we'll need to use a C++ compiler instead of the C compiler we've been using to date. For the sake of argument, let's assume that the kcgi headers are libraries are installed in the system directories. However, mostly they'll need -L/usr/local/lib and -I/usr/local/include.

% c++ -W -Wall -Wextra -c -o tutorial5.o tutorial5.cc
% c++ -static -W -Wall -Wextra -o tutorial5 tutorial5.cc -lkcgi -lz

Or just… (and noting again the -static, which we need by being in our file-system jail)

% c++ -static -W -Wall -Wextra -o tutorial5 tutorial5.cc -lkcgi -lz

Now you can install your compiled CGI script just like any CGI script. See Getting Started with CGI in C for these steps in detail. All of these steps work for FastCGI, of course. Enjoy! (On non-OpenBSD systems, you'll probably need to use sudo instead of doas.)

% doas install -m 0555 tutorial5 /var/www/cgi-bin