LmCast :: Stay tuned in

Kcgi – minimal CGI and FastCGI library for C/C++

Recorded: Oct. 14, 2026, 6:09 a.m.

Original Summarized

kcgi | minimal CGI and FastCGI library for C/C++

BSD.lv tools for BCHS:
kcgi,
sqlbox,
ort

kcgi
–

minimal CGI and FastCGI library for C/C++

Version

1.0.1

kcgi is an
open source
CGI and FastCGI library for C/C++ web applications. It is minimal,
secure, and auditable. To start, install the
library. Then read the deployment and
usage guides.

Hide source comments

Show source comments

The following echoes Hello, World! as an HTTP response to a
CGI request.

#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>

int main(void) {
struct kreq r;
const char *page = "index";
if (khttp_parse(&r, NULL, 0, &page, 1, 0) != KCGI_OK)
return 1;
khttp_head(&r, kresps[KRESP_STATUS],
"%s", khttps[KHTTP_200]);
khttp_head(&r, kresps[KRESP_CONTENT_TYPE],
"%s", kmimetypes[KMIME_TEXT_PLAIN]);
khttp_body(&r);
khttp_puts(&r, "Hello, world!");
khttp_free(&r);
return 0;
}
#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>

int main(void) {
struct kreq r;
const char *page = "index";

/*
* Parse the HTTP environment.
* We only know a single page, "index", which is also
* the default page if none is supplied.
* (We don't validate any input fields.)
*/

if (khttp_parse(&r, NULL, 0, &page, 1, 0) != KCGI_OK)
return 1;

/*
* Ordinarily, here I'd switch on the method (OPTIONS, etc.,
* defined in the method variable) then switch on which
* page was requested (page variable).
* But for brevity's sake, just output a response: HTTP 200.
*/

khttp_head(&r, kresps[KRESP_STATUS],
"%s", khttps[KHTTP_200]);

/*
* Show content-type unilaterally as text/plain.
* This would usually be set from r.mime.
*/

khttp_head(&r, kresps[KRESP_CONTENT_TYPE],
"%s", kmimetypes[KMIME_TEXT_PLAIN]);

/* No more HTTP headers: start the HTTP document body. */

khttp_body(&r);

/*
* We can put any content below here: JSON, HTML, etc.
* Usually we'd switch on our MIME type.
* However, we're just going to put the literal string as noted…
*/

khttp_puts(&r, "Hello, world!");

/* Flush the document and free resources. */

khttp_free(&r);
return 0;
}

For fuller examples, see sample.c (C and
CGI), samplepp.cc (C++ and CGI),
sample-fcgi.c (C and FastCGI), or
jump to the Documentation section.

kcgi supports many features: auto-compression, handling of
all HTTP input operations (query strings, cookies, page bodies,
multipart) with validation, authentication, configurable output
caching, request debugging, formatted writers (JSON, XML, etc.) and
so on. Its strongest differentiating feature is using sandboxing
and process separation for handling the untrusted input path.

current release

Version 1.0.1:
2025-11-17

Hot-fix 1.0.0 with proper naming of Mac OS X
shared libraries, which use a different
convention of version suffix than other
Unix-like systems.

(release archive)

installation

First, check if kcgi isn't already packaged
for your system, such as with
pkg_add kcgi (OpenBSD),
pkg install kcgi (FreeBSD),
brew install kcgi (brew),
pacman -S kcgi (Arch Linux),
and so on. If so, install using that system.

If not, kcgi has been built and run on
GNU/Linux (musl and glibc),
OpenBSD,
NetBSD,
FreeBSD),
Solaris,
OmniOS, and
Mac OS X
(only Mojave and newer!) on i386, amd64, powerpc, arm64, and
sparc64.
Download kcgi.tgz and verify the
archive with
kcgi.tgz.sha512.
To run bleeding-edge code between releases, the
repository is on
GitHub.
In both cases, build and install instructions may be
found on the repository page.

The only hard build-time dependency is BSD make
(bmake on Linux)
and zlib.
If you're running the regression tests (see
Testing), you'll also need
libcurl.

deployment

To use kcgi, you'll need a web server
capable of running CGI or FastCGI.
Apache,
nginx, and OpenBSD's
httpd(8)
have all been used extensively, with the latter two natively over
FastCGI and via the slowcgi wrapper.

To compile kcgi applications, use the
package configuration. Linking is similarly normative.

% cc `pkg-config --cflags kcgi` -c yourprog.c
% cc yourprog.o `pkg-config --libs kcgi`

Well-deployed web servers, such as the default
OpenBSD server, by default are
deployed within a
chroot(2). If this
is the case, you'll need to statically link your binary (or pull all
shared libraries into the shadow root).

% cc -static yourprog.o `pkg-config --static --libs kcgi`

FastCGI applications may either be started directly by the web
server (which is popular with
Apache) or externally
given a socket and kfcgi(8) (this method
is normative for OpenBSD's
httpd(8) and suggested
for the security precautions taken by the wrapper).

documentation

The kcgi manpages, starting with
kcgi(3), are the canonical source of
documentation. The following is a list of all manpages:

kcgi.3

kcgi_buf_printf.3

kcgi_buf_putc.3

kcgi_buf_puts.3

kcgi_buf_write.3

kcgi_strerror.3

kcgi_writer_disable.3

kcgi_writer_free.3

kcgi_writer_get.3

kcgi_writer_putc.3

kcgi_writer_puts.3

kcgi_writer_write.3

kcgihtml.3

kcgijson.3

kcgiregress.3

kcgixml.3

kfcgi.8

khtml_attr.3

khtml_close.3

khtml_closeelem.3

khtml_closeto.3

khtml_double.3

khtml_elem.3

khtml_elemat.3

khtml_entity.3

khtml_int.3

khtml_ncr.3

khtml_open.3

khtml_printf.3

khtml_putc.3

khtml_puts.3

khtml_write.3

khttp_body.3

khttp_datetime2epoch.3

khttp_epoch2datetime.3

khttp_epoch2str.3

khttp_epoch2tms.3

khttp_fcgi_free.3

khttp_fcgi_getfd.3

khttp_fcgi_init.3

khttp_fcgi_parse.3

khttp_fcgi_test.3

khttp_free.3

khttp_head.3

khttp_parse.3

khttp_printf.3

khttp_putc.3

khttp_puts.3

khttp_template.3

khttp_templatex.3

khttp_urlabs.3

khttp_urldecode.3

khttp_urlencode.3

khttp_urlpart.3

khttp_write.3

khttpbasic_validate.3

khttpdigest_validate.3

kjson_array_close.3

kjson_array_open.3

kjson_close.3

kjson_obj_close.3

kjson_obj_open.3

kjson_open.3

kjson_putbool.3

kjson_putdouble.3

kjson_putint.3

kjson_putnull.3

kjson_putstring.3

kjson_string_close.3

kjson_string_open.3

kjson_string_write.3

kmalloc.3

kutil_invalidate.3

kutil_log.3

kutil_openlog.3

kvalid_string.3

kxml_close.3

kxml_open.3

kxml_pop.3

kxml_popall.3

kxml_prologue.3

kxml_push.3

kxml_pushnull.3

kxml_putc.3

kxml_puts.3

kxml_write.3

Alternatively, the following are introductory materials to the
system:

Getting Started with CGI in C


This tutorial describes a typical CGI example using kcgi.
In it, I'll process HTML form input with two named fields, string (a non-empty, unbounded string) and
integer, a signed 64-bit integer.
I'll then output the input within a simple HTML page.
The tutorial will be laid out in code snippets, which I'll put together at the end.
I'll then follow with compilation instructions.

Getting and Setting CGI Cookies in C


Cookies are an integral part of any web application.
In this tutorial, I'll describe how to use the HTTP header functionality in kcgi to set,
recognise, and store cookies.

FastCGI Deployments


FastCGI allows for much higher throughput by running web applications as daemons.
In this tutorial, I'll describe how to deploy a simple FastCGI application using kfcgi(8).

Custom Validation


Applications often need to validate more then doubles, integers, or strings included in
kvalid_string(3).
In this tutorial, I'll provide some examples on how to override the validation function.

Using Pages


The tutorial gives an overview of the basic path handling provided by kcgi, and then shows and discusses
relevant code snippets.

CGI for C++ applications

kcgi supports C++ callers just as easily as C.
In this brief tutorial I'll take you through compiling a C++ application that uses the kcgi
library.

Best practises for pledge(2) security


Let's set the record straight for securing kcgi CGI and FastCGI applications with pledge(2).
This is focussed on secure OpenBSD deployments.

CORS and kcgi


This article isn't about CORS (cross-origin resource sharing) but
rather the enumerations and functions available in
kcgi(3) to handle CORS requests.

In addition to these resources, the following conference sessions
have referenced kcgi.


Dzonsons, Kristaps.
Role-based Access Control in BCHS Web Applications.
Proceedings of
AsiaBSDCon, Tokyo,
Japan, March 2018.
(Slides,
video.)
paper.)


Dzonsons, Kristaps.
Secure BSD Web Applications in C: Practical Strategies.
Proceedings of
AsiaBSDCon, Tokyo,
Japan, March 2017.
(Slides.)


Dzonsons, Kristaps.
Secure BSD Web Application Development in C.
Proceedings of
AsiaBSDCon,
Tokyo, Japan, March 2016.
(Slides.)


Dzonsons, Kristaps.
kcgi: securing CGI applications in C.
Proceedings of
AsiaBSDCon,
Tokyo, Japan, March 2015.
(Slides,
paper.)

And the following relate to extending standards:

Dzonsons, Kristaps.
FastCGI Extensions for Management Control.
March 2016.

implementation details

The bulk of kcgi's CGI handling lies in
khttp_parse(3), which fully parses
the HTTP request. Application developers must invoke this function
before all others. For FastCGI, this function is split between
khttp_fcgi_init(3), which
initialises context; and
khttp_fcgi_parse(3), which
receives new parsed requests. In either case, requests must be
freed by
khttp_free(3).

All functions isolate the parsing and validation of untrusted
network data within a sandboxed child process. Sandboxes
limit the environment available to a process, so exploitable errors
in the parsing process (or validation with third-party libraries)
cannot touch the system environment. This parsed data is returned
to the parent process over a socket. In the following, the HTTP
parser and input validator manage a single HTTP request,
while connection delegator accepts new HTTP requests and
passes them along.

This method of sandboxing the untrusted parsing process follows
OpenSSH, and requires special
handling for each operating system:

seccomp(2)
(Linux)

This requires a seccomp-enabled Linux kernel and a
recognised hardware architecture. It is supplemented by
setrlimit(2) limiting.

pledge(2)
(OpenBSD)

This will only work on OpenBSD >5.8.

sandbox_init(3)
(Apple OSX)

This uses the sandboxing profile for pure computation
as provided in Mac OS X Leopard and later. This is
supplemented by resource limiting via
setrlimit(2).

capsicum(4)
(FreeBSD)

Uses the capabilities facility on
FreeBSD 10 and later.
This is supplemented by resource limiting with
setrlimit(2).

Since validation occurs within the sandbox, special care must be
taken that validation routines don't access the environment (e.g.,
by opening files, network connections, etc.), as the child
might be abruptly killed by the sandbox facility.
(Not all sandboxes do this.) If required, this kind of validation
can take place after the parse validation sequence.

The connection delegator is similar, but has different sandboxing
rules, as it must manage an open socket connection and respond to
new requests.

testing

kcgi is shipped with a fully automated
testing framework executed with make regress. To test
your own applications, use the
kcgiregress(3) library.
This framework acts as a mini-webserver, listening on a local port,
translating an HTTP document into a minimal CGI request, and passing
the request to a kcgi CGI client. For
internal tests, test requests are constructed with
libcurl.
The binding local port is fixed: if you plan on running the
regression suite, you may need to tweak its access port.

The testing framework is used by the GitHub
Actions
to make sure that all commits pass the regression tests on all
supported systems (including with compiler sanitisation).

Another testing framework exists for use with the
American fuzzy lop.
To use this, you'll need to compile the make afl target
with your compiler of choice, e.g., make clean, then
make afl CC=afl-gcc. Then run the
afl-fuzz tool on the afl-multipart,
afl-plain, and afl-urlencoded binaries
using the test cases (and dictionaries, for the first) provided.

performance

Security comes at a price—but not a stiff price. By design,
kcgi incurs overhead in three ways: first,
spawning a child to process the untrusted network data; second,
enacting the sandbox framework; and third, passing parsed pairs back
to the parent context. In the case of running CGI scripts,
kcgi performance is bound to the operating
system's ability to spawn and reap processes.
For FastCGI, the bottleneck becomes the transfer of data.

©
Kristaps Dzonsons

The kcgi library provides a minimal, secure, and auditable framework for implementing CGI and FastCGI for C and C++ web applications. The library features numerous functionalities, including auto-compression, validation, authentication, configurable output caching, request debugging, formatted data writers like JSON and XML, and crucially, a strong implementation of sandboxing and process separation for handling untrusted input.

The core operation of kcgi relies on functions such as khttp_parse, which handles the full parsing of the HTTP request, and specific functions for managing HTTP headers and body output. The library supports various interaction points, including handling query strings, cookies, and multipart data, all of which undergo validation. A significant architectural feature is the use of sandboxing and process separation to manage the untrusted input path. This is achieved by running the parsing and validation routines within a sandboxed child process, which limits the environment available to the process, thereby mitigating potential security risks arising from exploitable errors in parsing or third-party validation routines. This sandboxing approach, inspired by OpenSSH, requires specific handling depending on the operating system and the chosen sandboxing mechanism, such as seccomp(2) on Linux, pledge(2) on OpenBSD, sandbox_init(3) on macOS, and capsicum(4) on FreeBSD, often supplemented by resource limiting via setrlimit(2).

The library supports both traditional CGI execution and high-throughput FastCGI deployment. For FastCGI, the mechanism involves functions like khttp_fcgi_init and khttp_fcgi_parse, which manage the initialization and reception of new requests, respectively. The framework allocates responsibility between the HTTP parser and the connection delegator to manage requests and pass parsed data back to the parent context. While validation occurs within the sandbox, developers must ensure that validation routines do not access system resources, as the child process might be abruptly terminated by the sandbox facility.

Deployment requires a compatible web server, such as Apache, nginx, or OpenBSD's httpd(8), which can operate the applications directly via CGI or, more efficiently, through FastCGI. FastCGI applications can be launched as daemons or communicate externally via sockets using kfcgi(8), a method suggested for heightened security.

The kcgi documentation provides comprehensive resources, including manpages detailing functions for HTTP manipulation, JSON and XML handling, and input validation. Tutorials cover practical applications, such as processing HTML form input, managing cookies, and deploying FastCGI. Furthermore, the library includes a testing framework, kcgiregress(3), which functions as a mini-webserver to translate HTTP documents into CGI requests, allowing for internal stress testing. This framework also supports fuzzing tools to test security robustness against multipart, plain, and URL-encoded inputs.

Performance considerations reflect the security design; overhead is introduced by spawning child processes, establishing sandbox frameworks, and transferring parsed data back to the parent. For CGI execution, performance is largely dictated by the operating system's capabilities in process management. For FastCGI, the bottleneck tends to be the data transfer efficiency. The library was developed by Kristaps Dzonsons.