Skip to content

C / C++ (C1) ​

Ready

The hub recognises the services this package fits and proposes the compose part of the change, if any; the source change stays by hand, with the steps and examples in the proposal's review. Nothing changes until a player approves it (Hook proposals). The cheat sheet has the steps by hand.

For C and C++ services. Most of them need no hook at all: forking servers (inetd, xinetd, socat fork, tcpserver, pre-fork) and thread-per-connection servers are linked exactly by the kernel. Event-loop servers (hand-rolled epoll, libevent, libev, libuv, Boost.Asio/Beast, Seastar, Drogon, Crow, Pistache, cpp-httplib, civetweb, mongoose) serve many requests on one thread. For those, the hook is a source change: a small guarded C binding, vbxhook, is vendored into the service, and a few lines go around the request handler. C1's vbxhook is also the binding that every other native package (C2, C3, C4) calls through its C FFI.

Covers ​

Versions
CompilersGCC ≥ 4.9, Clang ≥ 3.5 (C99 / C++11 or later)
C librariesglibc ≥ 2.17, musl ≥ 1.1 (Alpine); fully static binaries with the static archive
Hand-rolled loopsepoll, poll, select, io_uring (see Known gaps)
Event librarieslibevent 2.1 (evhttp, bufferevent), libev 4, libuv 1.x, mongoose 7, civetweb 1.1x
C++ frameworks (C++17)Boost.Asio / Beast (Boost ≥ 1.70; full handler-trait forwarding from 1.80) and standalone Asio, cpp-httplib (tested 0.18), Crow ≥ 1.3, Drogon (tested 1.9), Pistache (tested 0.0.5), Seastar (tested 22.11 git 2025-03; POSIX stack)

The library integrations table lists each library's helper header and sample.

What the kernel already links without this hook:

Server modelLinked byHook adds
process per connection (inetd/xinetd/socat fork/tcpserver/fork after accept)process lineage + the inherited socketrequest boundaries on keep-alive connections
pre-fork (each worker accepts and serves one connection at a time)the worker holds exactly one client socketrequest boundaries
thread per connection (pthread_create after accept, civetweb, cpp-httplib's pool with one connection per worker)the thread holds exactly one client socket ("unambiguous ownership")request boundaries; jobs handed to other threads (handoff)
single-threaded event loop, or a few loop threads with many connections eachnothing per requesteverything

How it gets in ​

From a registry (local development, or a build with network; the same release as the hook directory): CMake FetchContent of vbxtrace-c-1.0.0.tar.gz from the release page (targets vbxtrace::hook, vbxtrace::hook_static), or the Conan recipe / vcpkg port next to it; see Local development.

Source change, in one of two variants. The hub proposes it with a full diff.

Default: vendored vbxhook + the core from the read-only mount ​

  1. Copy native/c/vbxhook.h, vbxhook.c, vbxhook.hpp (and any integrations/vbxhook_<lib>.h* you use) plus include/vbxtrace.h from /usr/local/lib/vulnboxd/trace/ into the service's vendor/vbxtrace/. A/D build environments often have no internet; the vendored files need nothing else.
  2. Compile vendor/vbxtrace/vbxhook.c with the service and add -Ivendor/vbxtrace. On glibc older than 2.34, add -ldl.
  3. Wrap the request handler and report what the service does (see What it records).
  4. Mount the hook directory read-only. At the first call, vbxhook loads /opt/vbxtrace/libvbxtrace-$(uname -m).so. Without the mount it stays off. (In full, it looks for the core in this order: the file named by VBXTRACE_LIB, then /opt/vbxtrace/libvbxtrace-<arch>.so (the mount), then, only with VBXTRACE_DEV=1 and only when the directory and the library belong to root or the user and nobody else can write them, ~/.local/share/vulnboxd/trace (or $XDG_DATA_HOME/vulnboxd/trace) for local development. A setuid or file-capability binary ignores VBXTRACE_LIB and VBXTRACE_DEV.)
diff
 services:
   <service>:
+    volumes:
+      - /usr/local/lib/vulnboxd/trace:/opt/vbxtrace:ro
diff
 CFLAGS ?= -O2 -Wall
+CFLAGS += -Ivendor/vbxtrace
-service: main.c
-	$(CC) $(CFLAGS) -o $@ main.c
+service: main.c vendor/vbxtrace/vbxhook.c
+	$(CC) $(CFLAGS) -o $@ main.c vendor/vbxtrace/vbxhook.c -ldl
diff
+#include "vbxhook.h"
 struct conn {
     int fd;
+    uint32_t requests;              /* request index on this connection */
 ...
-        status = handle(path, c->fd);
+        uint64_t ctx = vbxh_begin_fd(c->fd, c->requests++, VBXH_PROTO_HTTP1);
+        status = handle(ctx, path, c->fd);
+        vbxh_end(ctx, (uint16_t)status);
 ...
         pid_t pid = fork();
         ...
+        vbxh_spawned(ctx, pid);

With CMake: target_sources(service PRIVATE vendor/vbxtrace/vbxhook.c), target_include_directories(service PRIVATE vendor/vbxtrace), target_link_libraries(service PRIVATE ${CMAKE_DL_LIBS}). With Meson: add the file to the sources and dependency('dl', required: false).

Static: the core linked in (no mount) ​

For fully static binaries (-static, scratch or distroless-static images), or when a mount is unwanted: also vendor libvbxtrace-<arch>.a, compile vbxhook.c with -DVBXHOOK_STATIC, and link the archive. The probes then sit in the service binary itself. The sensor finds them there, as it does for Rust and Go binaries.

diff
-CFLAGS ?= -O2 -Wall
+ARCH := $(shell uname -m)
+CFLAGS ?= -O2 -Wall -Ivendor/vbxtrace -DVBXHOOK_STATIC
-	$(CC) $(CFLAGS) -static -o $@ main.c
+	$(CC) $(CFLAGS) -static -o $@ main.c vendor/vbxtrace/vbxhook.c vendor/vbxtrace/libvbxtrace-$(ARCH).a

The archive carries Rust's core. Linking two Rust static libraries into one program can clash, so if the service already links one, use the default variant.

Detection. The hub proposes C1 when it finds Makefile, CMakeLists.txt, meson.build, *.c/*.cpp sources or a binary without other runtime markers, and the sources show an event loop: epoll_wait, poll, select, event_base_dispatch, ev_run, uv_run, io_context::run, mg_mgr_poll, framework includes. It does not propose a hook for forking or thread-per-connection services. Templates: hooks/native/c1/proposals/ (c-generic, c-static, one per library).

What it records ​

EventCallEmitted fromJoin key
request_beginvbxh_begin_fd(fd, index, proto)where the service has parsed a request head (or accepted a raw session: VBXH_PROTO_RAW, index 0)local port + peer address/port from getsockname/getpeername on fd; request index
vbxh_begin_str(local_port, "ip", port, index, proto)frameworks that only give the peer as textas above
request_endvbxh_end(ctx, status)after the response is complete (or the session closes)context id
spawnedvbxh_spawned(ctx, pid)after fork/vfork/posix_spawn/popen (pid via your own fork)child pid
connectedvbxh_connected_fd(ctx, sock)after a successful connect (UDP: after the first sendto)the socket's local port (transport from SO_TYPE)
openedvbxh_opened(ctx, fd, flags)after open/openat/fopen (fileno)pid + fd
handoffchild = vbxh_handoff(ctx)before queueing work to a thread poolboth context ids
context_enter/exitvbxh_enter(child) / vbxh_exit(child)around the job on the worker threadthe thread

request_index is the 0-based number of the request on that accepted connection. Keep a counter in your per-connection state and pass conn->requests++. The library helper headers do this for you.

API ​

c
int      vbxh_init(void);        /* optional: load early (before threads); returns 1 if usable */
int      vbxh_active(void);      /* tracer attached? skip costly key gathering otherwise */
uint64_t vbxh_begin_fd(int fd, uint32_t request_index, uint8_t protocol);
uint64_t vbxh_begin(uint16_t local_port, const uint8_t *peer, size_t peer_len, uint16_t peer_port,
                    uint32_t request_index, uint8_t protocol);
uint64_t vbxh_begin_str(uint16_t local_port, const char *peer_ip, uint16_t peer_port,
                        uint32_t request_index, uint8_t protocol);
void     vbxh_end(uint64_t ctx, uint16_t status);
void     vbxh_spawned(uint64_t ctx, int32_t child_pid);
void     vbxh_connected_fd(uint64_t ctx, int fd);
void     vbxh_connected(uint64_t ctx, uint16_t local_port, const uint8_t *peer, size_t peer_len,
                        uint16_t peer_port, uint8_t transport);
void     vbxh_connected_str(uint64_t ctx, uint16_t local_port, const char *peer_ip, uint16_t peer_port,
                            uint8_t transport);
void     vbxh_opened(uint64_t ctx, int32_t fd, uint32_t flags);
uint64_t vbxh_handoff(uint64_t parent);
void     vbxh_enter(uint64_t ctx);
void     vbxh_exit(uint64_t ctx);
uint64_t vbxh_current(void);
void     vbxh_set_current(uint64_t ctx);
int      vbxh_errors(void);

Every function accepts ctx = 0 and then does nothing. While no tracer is attached, vbxh_begin* returns 0, so the rest of the request costs one comparison per call. Protocol constants: VBXH_PROTO_RAW, _HTTP1, _HTTP2, _GRPC, _WEBSOCKET, _HTTP3. Transports: VBXH_TRANSPORT_TCP, _UDP, _UNIX. Peer text accepts 1.2.3.4, ::1, ::ffff:1.2.3.4, [::1] and fe80::1%eth0.

C++ (vbxhook.hpp, header-only, no exceptions, no allocation):

cpp
vbxhook::Request req(fd, conn.requests++, VBXH_PROTO_HTTP1);  // request_begin
req.status(404);                                                // request_end on scope exit
vbxhook::Scope cur(req.ctx());       // thread-current context for this block
vbxhook::Enter job(child_ctx);       // context_enter/exit around a pool job
uint64_t ctx = req.release();        // async response: end later with vbxh_end(ctx, status)

Library integrations ​

For the common libraries, a helper header in native/c/integrations/ does the per-connection bookkeeping. Vendor the whole integrations/ directory next to vbxhook.h/vbxhook.c/vbxhook.hpp, so that each header's #include "../vbxhook.h" resolves. Each header is self-contained: it documents its integration lines, how it derives the keys, and its gaps at the top of the file. It changes nothing in the library's behaviour: it reads fields, or installs callbacks only into slots the service doesn't use. The C++ headers are C++17, header-only, noexcept throughout, and never let an exception escape.

LibraryHeaderRequest index fromRequest endSample (image)
hand-rolled epoll/poll/selectvbxhook.hyour per-connection counteryour vbxh_endepoll, threads, forking, static (alpine:3.22)
libevent 2.1 (evhttp, bufferevent)vbxhook_libevent.hper-evhttp_connection side table, cleaned by a close callbackevhttp's on-complete callbacklibevent (alpine, libevent 2.1.13)
libev 4vbxhook_libev.hstruct vbxh_ev_conn in your client structyour vbxh_endlibev (alpine, libev 4.33)
libuv 1.xvbxhook_libuv.hstruct vbxh_uv_conn in your client structyour vbxh_end in the uv_write callbacklibuv (alpine, libuv 1.51)
Mongoose 7vbxhook_mongoose.hper-connection side table keyed by mg_connection + c->idwhen Mongoose has the whole response queuedmongoose (alpine, Mongoose 7.20)
CivetWeb 1.xvbxhook_civetweb.hthread-local, reset in init_connectionend_request callbackcivetweb (alpine, CivetWeb 1.16)
Boost.Asio / Asio (raw TCP)vbxhook_asio.hppvbxhook::asio::Connection in your sessionyour finish()asio (alpine, Boost 1.84)
Boost.Beastvbxhook_asio.hppvbxhook::asio::Connection in your sessionfinish() in the async_write handlerbeast (alpine, Boost 1.84)
cpp-httplibvbxhook_httplib.hppthread-local, reset per connection task (wrapped new_task_queue)the loggerhttplib (debian:trixie-slim, 0.18.7)
Crowvbxhook_crow.hppmiddleware context that survives Crow's per-request resetafter_handlecrow (alpine, Crow 1.3.5 + asio 1.28)
Drogonvbxhook_drogon.hppper-I/O-thread table keyed by the address 4-tuple, reset by the new-connection advicepre-sending advicedrogon (debian:trixie-slim, Drogon 1.9.0)
Pistachevbxhook_pistache.hppa counter in the Tcp::Peer's data map~Request, with the status the writer sentpistache (debian:trixie-slim, Pistache 0.0.5)
Seastar (own accept loop)vbxhook_seastar.hppvbxhook::seastar::Connection in your connection objectyour finish()seastar (alpine, Seastar 22.11 git 2025-03-03)
Seastar httpdvbxhook_seastar.hppunknown (VBXH_REQUEST_INDEX_UNKNOWN)~Requestseastar-httpd (same image)

Every integration has a proposal template plus an example diff in hooks/native/c1/proposals/<name>.toml / .diff. In all of them, ctx is the request's context id, and the effects are reported the same way: vbxh_spawned(ctx, pid) after fork/posix_spawn, vbxh_opened(ctx, fd, flags) after open, and vbxh_connected_fd(ctx, sock) after connect.

libevent (evhttp, bufferevent) ​

c
#include "integrations/vbxhook_libevent.h"

static void on_request(struct evhttp_request *req, void *arg) {
    uint64_t ctx = vbxh_evhttp_begin(req);   /* first line of the gencb and of every evhttp_set_cb handler */
    ...                                      /* evhttp_send_reply now or later */
}
  • Keys: local port and peer come from the connection's bufferevent fd. The request index is counted per evhttp_connection in a small per-thread side table (vbxhook_conntab.h). The entry is created on the connection's first request, stamped with fd + peer port (so a reused connection object never inherits a count), and removed by a close callback installed at that moment.
  • End: automatic. evhttp's on-complete callback fires once the whole response is written, with evhttp_request_get_response_code. If the connection closes first, the request ends with status 0.
  • Deferred handlers that only have the request use vbxh_evhttp_ctx(req). After bufferevent_socket_connect, call vbxh_bev_connected(ctx, bev).
  • Raw bufferevent servers: call vbxh_bev_begin(bev, index, VBXH_PROTO_RAW) per session (or per command, with your own counter).
  • Gaps: a service that sets its own close callback on server connections replaces the hook's. Only table clean-up is lost; the stamp keeps counts exact. Call vbxh_evhttp_closed(evcon) from yours to keep the table tidy. A service with its own on-complete callback calls vbxh_evhttp_complete(req) from it. Otherwise the request ends at the next request or at close, with status 0. VBXH_EVHTTP_NO_CALLBACKS installs neither callback. Event bases are single-threaded, and the table is per thread and static to the including source file, so make all calls from one file.

libev ​

c
#include "integrations/vbxhook_libev.h"
struct client { ev_io io; struct vbxh_ev_conn vbx; /* zeroed on accept */ ... };

uint64_t ctx = vbxh_ev_begin(&c->vbx, &c->io, VBXH_PROTO_HTTP1);   /* per parsed request */
...
vbxh_end(ctx, status);                                             /* once the response is written */

libev only delivers readiness, so the service owns parsing. Index exactness depends on two things: the struct is zeroed on accept (calloc/memset/VBXH_EV_CONN_INIT), and every request calls vbxh_ev_begin. For ev_child watchers, call vbxh_ev_spawned(ctx, &w).

libuv ​

c
#include "integrations/vbxhook_libuv.h"
struct client { uv_tcp_t tcp; struct vbxh_uv_conn vbx; ... };

uint64_t ctx = vbxh_uv_begin(&c->vbx, (uv_stream_t *)&c->tcp, VBXH_PROTO_HTTP1);
/* keep ctx with the write request; in the uv_write callback: */ vbxh_end(ctx, status);

libuv-shaped helpers report effects:

  • vbxh_uv_spawned(ctx, &proc) after uv_spawn
  • vbxh_uv_opened(ctx, &req, flags) after uv_fs_open (sync, or in its callback)
  • vbxh_uv_connected(ctx, (uv_handle_t *)&sock) in a successful uv_tcp_connect callback, or after the first uv_udp_send

Context does not follow uv_queue_work. Take job->ctx = vbxh_handoff(ctx) before queueing, and bracket the work callback with vbxh_enter/vbxh_exit. Async uv_fs_* calls need no handoff: the opened event is linked by the fd.

Mongoose 7 ​

c
#include "integrations/vbxhook_mongoose.h"
VBXH_MG_HANDLER(fn_vbx, fn)                          /* wraps the unchanged handler fn */
mg_http_listen(&mgr, "http://0.0.0.0:8000", fn_vbx, NULL);
  • Context: inside fn, vbxh_current() is the request's context while the MG_EV_HTTP_MSG handler runs, and vbxh_mg_ctx(c) returns it until the response is queued. Without the macro, call vbxh_mg_before first and vbxh_mg_after last in the handler.
  • Index: a per-thread side table keyed by the mg_connection pointer, stamped with c->id, and freed on MG_EV_CLOSE. Mongoose doesn't parse a pipelined request before the previous response is complete, so the count is exact.
  • End: when c->is_resp clears (after mg_http_reply, mg_http_serve_*, or the last chunk). The status is parsed from the queued status line.
  • Gaps: TLS connections with deferred replies end with status 0. Builds without BSD sockets (MG_ENABLE_SOCKET == 0: built-in TCP/IP, lwIP, RTOS) emit nothing.

CivetWeb ​

c
#include "integrations/vbxhook_civetweb.h"
callbacks.begin_request = ...;            /* the service's own, if any */
vbxh_civetweb_callbacks(&callbacks);      /* after them, before mg_start/mg_start2 */

The service's init_connection/begin_request/end_request callbacks keep working: the hook calls them from its wrappers and returns their results unchanged. CivetWeb runs each connection on one worker thread. A thread-local counter is reset in init_connection and advanced in end_request, which CivetWeb calls after every handled request. Begin is in begin_request; end is in end_request, with CivetWeb's status. Handlers use vbxh_current(). CivetWeb is thread-per-connection, so the kernel already links a handler's syscalls. The hook adds the request boundaries.

Boost.Asio / Asio (raw TCP and custom protocols) ​

cpp
#include "integrations/vbxhook_asio.hpp"      // after the Asio headers; boost::asio or standalone ::asio
class session : public std::enable_shared_from_this<session> {
    tcp::socket socket_;
    vbxhook::asio::Connection vbx_;            // one per accepted connection
    vbxhook::Request req_;                     // the request (or raw session) in flight
    void start() {
        req_ = vbx_.session(socket_);          // raw session: protocol raw, request_index 0
        net::async_read_until(socket_, buf_, '\n',
            vbxhook::asio::bind_context(req_.ctx(), [self = shared_from_this()](auto ec, std::size_t n) { ... }));
    }
    // ... in the final write completion: req_.finish();
};
  • Keys: local port and peer come from getsockname/getpeername on socket.native_handle(). native_fd() also unwraps layered streams through lowest_layer(). For request/response protocols, vbx_.begin(socket, proto) counts requests per connection.
  • Context: Asio runs every completion handler from io_context::run(), so nothing follows an async chain by itself. Either use req_.ctx() (the session object is captured by every handler anyway), or wrap a handler with vbxhook::asio::bind_context(ctx, h). The wrapper makes ctx current while the handler runs, and forwards the handler's associated executor, allocator and cancellation slot (through the associator trait on Asio ≥ 1.24 / Boost ≥ 1.80; older versions get executor and allocator only). Work posted to another io_context or thread pool needs vbxh_handoff + vbxhook::Enter.
  • Outgoing sockets: call vbxhook::asio::connected(ctx, socket) in the connect completion.

Boost.Beast ​

The Asio header again, with one request per http::async_read:

cpp
void on_read() {                                            // http::async_read succeeded
    vreq_ = vbx_.begin(stream_.socket(), VBXH_PROTO_HTTP1); // request_begin; ends the previous Request
    ... build res_ ...
    vreq_.status(res_.result_int());
    http::async_write(stream_, res_, [self = shared_from_this()](beast::error_code ec, std::size_t) {
        self->vreq_.finish();                               // request_end
        ...
    });
}

Beast parses one request at a time per stream, so the session's counter is exact. The sample hands /handoff to a net::thread_pool with vbxh_handoff + vbxhook::Enter.

cpp-httplib ​

cpp
#include <httplib.h>
#include "integrations/vbxhook_httplib.hpp"
...
vbxhook::httplib::install(svr);   // after the routes and any new_task_queue assignment, before listen()
  • Index: cpp-httplib runs each accepted connection as one task of the queue that Server::new_task_queue returns (the default ThreadPool). That task serves all of the connection's keep-alive requests synchronously on the worker thread. install() wraps new_task_queue so that each connection task first resets a thread-local counter. The index is the number of responses the logger has seen on the connection so far. The logger also runs for 400/414/500 responses that cpp-httplib makes itself, so requests rejected before routing still count.
  • Begin and end: begin is in the pre-routing handler (with req.local_port, req.remote_addr, req.remote_port), and the request becomes the thread's current context. End is in the logger, with res.status. Handlers use vbxh_current().
  • Own handlers: install() takes over the pre-routing handler and the logger. A service with its own passes them: install(svr, my_pre_routing, my_logger).
  • Gaps: a new_task_queue assigned after install() isn't wrapped. Its requests are reported with request_index unknown. Requests rejected before routing get no begin/end, but they still count.

Crow ​

cpp
#include "crow.h"
#include "integrations/vbxhook_crow.hpp"
crow::App<vbxhook::crow::Middleware> app;      // was crow::SimpleApp; the middleware goes FIRST in the list
...
app.port(8080);
vbxhook::crow::set_port(app);                  // Crow's request has no local address
app.run();
// in a handler taking `const crow::request &req`:  uint64_t ctx = vbxhook::crow::ctx(app, req);
  • Index: Crow keeps one middleware context object per connection, and resets it for every request by assigning a freshly constructed one. The hook's context type deliberately keeps its per-connection fields (counter, peer) across that assignment. The counter therefore lives exactly as long as the connection, and a new connection constructs a new context. The counter advances in after_handle, which Crow calls once for every request that reaches routing, including its own 404 for unknown paths.
  • Begin and end: begin is in before_handle, with req.remote_ip_address/req.remote_port (needs Crow ≥ 1.3); end is in after_handle, with res.code.
  • Context: the thread-current slot is not set. Crow handlers may complete later via res.end(), so "the handler returned" is never visible to the middleware.
  • Gaps: Crow answers unknown paths without a catch-all route right after the request line, before filling in the peer, and calls only after_handle. The hook then emits begin+end at that point, using the peer remembered from an earlier request on the connection. On a connection's first request, nothing is emitted, but the counter still advances. HTTP/1.1 requests without Host are answered 400 without calling any middleware, so they aren't counted. That's undetectable, and real clients always send Host. WebSocket upgrades have no request_end. Unix-socket listeners emit nothing.

Drogon ​

cpp
#include <drogon/drogon.h>
#include "integrations/vbxhook_drogon.hpp"
vbxhook::drogon::install();                    // before drogon::app().run()
// in handlers/controllers/filters:  uint64_t ctx = vbxhook::drogon::ctx(req);
  • Advices: install() registers a new-connection advice, a synchronous advice (always returns nullptr, never answers) and a pre-sending advice. They coexist with the service's own advices.
  • Index: Drogon's public API exposes no connection behind a request, and its connection context slot belongs to Drogon's parser. What it does give is a new-connection advice with (peer, local), called on the connection's I/O thread before any of its requests. A live TCP connection is identified exactly by that 4-tuple. Per I/O thread, the hook keeps "4-tuple → requests so far": the new-connection advice (re)sets the entry, and the synchronous advice (called once per parsed request, in order, on the same thread) takes the index. A reused 4-tuple is necessarily a new connection, so it is reset, never inherited.
  • End: the pre-sending advice, with resp->statusCode(). It covers every response, including Drogon's own 404/405 and static files. The context travels in req->attributes().
  • Context: the thread-current slot is not set, because handlers answer through callbacks or coroutines.
  • Gaps: Drogon doesn't report closed connections, so the table is capped per I/O thread (VBXHOOK_DROGON_MAX_CONNS, default 65536) and emptied when full. Requests on connections it no longer knows, or that were accepted before a tracer attached, are reported with request_index unknown; peer and ports stay exact. A request whose response is never sent gets no request_end. Requests Drogon rejects while parsing (400/413) are not counted, and those usually close the connection.

Pistache ​

cpp
#include "integrations/vbxhook_pistache.hpp"
void onRequest(const Http::Request &request, Http::ResponseWriter response) override {
    vbxhook::pistache::Request vbx(request, response);   // request_begin; request_end when vbx goes
    ...                                                  // vbx.ctx() (also vbxh_current() while vbx lives)
    response.send(Http::Code::Ok, "...");
}
  • Index and keys: a counter stored in the Tcp::Peer's data map (key vbxtrace), Pistache's per-connection object, created on the connection's first request. The peer comes from the peer's fd.
  • End: in the destructor, with getResponseCode() if the writer sent a response, else 0. A handler that moves the writer and answers later calls vbx.release(), and vbxh_end(ctx, code) itself.
  • Gaps: requests Pistache answers itself (malformed 400, 408 timeouts) never reach onRequest, so they aren't counted. Pistache 0.0.5 answers Connection: Close unless the client sends Connection: keep-alive, so with most simple clients every connection carries one request (the sample shows that).

Seastar ​

Seastar sockets hide their fd, so the keys come from Seastar's own socket addresses. These are exact on the POSIX network stack. The native (DPDK) stack and Unix sockets emit nothing.

cpp
#include "integrations/vbxhook_seastar.hpp"
// own accept loop, raw session:
c->req = vbxhook::seastar::session(c->sock);                 // ... c->req.finish();
// own accept loop, request/response protocol:
c->req = c->vbx.begin(c->sock, VBXH_PROTO_HTTP1);            // vbxhook::seastar::Connection vbx;
// a continuation that should see vbxh_current():
.then(vbxhook::seastar::bind(c->req.ctx(), [c] { ... }))
// seastar::connect() result:
vbxhook::seastar::connected(ctx, sock);
  • seastar::httpd: handlers get the request (get_client_address(), get_server_address()), but nothing identifies the connection, and httpd::connection has no hook. vbxhook::seastar::begin_http(*req) therefore reports the exact peer and local port with request_index unknown. Before returning the reply, set vbx.status(vbxhook::seastar::status_of(*rep)). In asynchronous handlers, move vbx into the continuation that completes the reply. Paths without a handler are answered by httpd with no handler call; the sample adds a default handler.
  • Context: a request is a chain of continuations interleaved with other requests on the same reactor thread, so pass ctx along or wrap single continuations with bind. smp::submit_to, seastar::thread and alien threads need a handoff.
  • Gaps: seastar::experimental::spawn_process hides the pid and open_file_dma hides the fd, so neither can be reported. The kernel side still sees the syscalls, just not linked to the request.

Context following ​

C has no runtime context, so the service passes ctx along. Two helpers cover the common shapes:

  • Explicit: thread ctx through the handler (handle(ctx, …)). This is the most robust option and what the proposals do.
  • Thread-current slot: vbxh_set_current(ctx) at request start, vbxh_current() deep inside (vbxhook::Scope in C++). This is right for code that handles one request at a time on a thread: a sequential loop, a thread per connection, a worker running one job. In an event loop, a request whose handling spans several callbacks must store ctx in its per-connection/per-request object instead: bufferevent ctx, uv_handle_t.data, mg_connection.data, an Asio handler's captured state.
  • Thread pools: before queueing a job, child = vbxh_handoff(ctx) and pass child with it. On the worker, vbxh_enter(child) … vbxh_exit(child). The kernel then attributes the worker thread's syscalls in between to the request.
  • fork(): the binding (and the core) are inherited by the child. A forking server's child can call vbxh_begin_fd directly (sample forking). Context ids are unique per process. Every child starts from the parent's counter, so the sensor keys contexts by (pid, ctx).

Known gaps ​

  • Processes started after the sensor attached, with the probes in the binary. The kernel switches the probes on in such a process through a counter on the file page that holds the .probes section. When the linker put that page into two LOAD segments (lld can, sharing it with the read-only-after-relocation data), the kernel's increment lands in the wrong mapping, so the sensor raises the counter itself in the process's own writable mapping (vulnboxd_sensor_usdt_semaphores_raised_total counts it). Linking with -Wl,-z,separate-loadable-segments avoids it, as the shipped libvbxtrace-<arch>.so does.
  • io_uring: accepts, connects and opens submitted through io_uring don't pass the syscall tracepoints. vbxh_connected_fd/vbxh_opened reports from the completion still give exact joins (pid + fd, local port). Spawns are unaffected.
  • Library-internal I/O: database client libraries (libpq, libmysqlclient, hiredis) connect inside their own code. Call vbxh_connected_fd(ctx, PQsocket(conn)) (or redisContext->fd) after the connect returns. Async clients that connect in the background need that call in their connect callback.
  • Static archive in the harness: the recording build of the core exists only as a shared library, so the static sample runs only in baseline mode. Its events are those of epoll.
  • dlopen in static binaries: the default variant needs a dynamically linked libc. Fully static binaries must use -DVBXHOOK_STATIC.
  • popen/system: the child pid is not available. Use fork+exec or posix_spawn where the link matters. Otherwise the kernel still links the child to the thread, which is exact only when the thread is unambiguous.

Safety ​

  • Nothing happens without a tracer: every call checks that the binding is loaded and not disabled and that vbx_v1_enabled() reports a tracer, before doing anything else.
  • Internal errors are counted: a core without a symbol, getsockname/getpeername failing on the fd you passed, an unparsable peer text. After 5, the binding switches itself off for the process. VBXTRACE=0 at the first call keeps it off. A missing /opt/vbxtrace mount is not an error. The binding simply stays off.
  • No side effects: errno is preserved. No allocation, no locks, no signals, no threads, no I/O except getsockname/getpeername/getsockopt(SO_TYPE) on the descriptor you pass. Initialisation is a single atomic compare-and-swap. A thread racing it sees "off" for that one call instead of waiting. The C++ library headers add small framework-shaped bookkeeping on top. cpp-httplib wraps one std::function per connection. Drogon keeps a per-I/O-thread unordered_map entry per connection and a request attribute. Pistache stores one shared_ptr counter per connection. All of this happens only while a tracer is attached (except the httplib wrapper), is guarded by try/catch, and never throws into the service.
  • Chaos test: with VBXTRACE_CHAOS=1, every call into the core counts as a failure inside the guard. The samples' responses are byte-identical with the hook failing, with it working and without it, and the chaos runs record no events.

Sample results (x86_64; hooks/run-samples.sh native --package C1, correctness modes: events against golden.events, chaos and baseline responses byte-identical to the events run). Overhead is measured in a later, dedicated performance phase on a quiet host:

SampleWhateventschaos / baseline
epollhand-rolled epoll loop, /handoff to a thread18 recorded events matchresponses byte-identical (289 bytes)
threadsthread per connection18 recorded events matchresponses byte-identical (289 bytes)
forkingfork per connection (contexts keyed by pid)18 recorded events matchresponses byte-identical (289 bytes)
static-DVBXHOOK_STATIC + static archive— (no recording static core)baseline ran
libeventevhttp, libevent 2.1.1313 recorded events matchresponses byte-identical (369 bytes)
libevlibev 4.3313 recorded events matchresponses byte-identical (239 bytes)
libuvlibuv 1.51, /handoff via uv_queue_work18 recorded events matchresponses byte-identical (289 bytes)
mongooseMongoose 7.2013 recorded events matchresponses byte-identical (287 bytes)
civetwebCivetWeb 1.1613 recorded events matchresponses byte-identical (239 bytes)
asioBoost.Asio 1.84, raw TCP sessions (drive raw)11 recorded events matchresponses byte-identical (30 bytes)
beastBoost.Beast 1.84, /handoff via net::thread_pool18 recorded events matchresponses byte-identical (445 bytes)
httplibcpp-httplib 0.18.7 (debian:trixie-slim)18 recorded events matchresponses byte-identical (618 bytes)
crowCrow 1.3.5 + asio 1.2818 recorded events matchresponses byte-identical (588 bytes)
drogonDrogon 1.9.0, 2 I/O threads (debian:trixie-slim)18 recorded events matchresponses byte-identical (1228 bytes)
pistachePistache 0.0.5 (debian:trixie-slim); its Connection: Close puts /missing on a second connection18 recorded events matchresponses byte-identical (403 bytes)
seastarSeastar 22.11 (git 2025-03-03), raw TCP sessions (drive raw)11 recorded events matchresponses byte-identical (30 bytes)
seastar-httpdseastar::httpd, request_index=unknown13 recorded events matchresponses byte-identical (484 bytes)

All samples run on alpine:3.22 (musl) unless noted. The libevent, libev, mongoose, civetweb and seastar-httpd samples serve the script without /handoff. The raw samples report status=0.

Turning it off ​

Set VBXTRACE=0 in the service's environment and restart it. The vendored code then does nothing at all. To remove the hook, revert the change that added it; vulnboxd's rollback covers a hook that breaks a service. Removing only the /opt/vbxtrace mount also switches the default variant off.

Troubleshooting ​

  • Are the probes there? readelf -n /usr/local/lib/vulnboxd/trace/libvbxtrace-x86_64.so lists them; sudo bpftrace -l 'usdt:/usr/local/lib/vulnboxd/trace/libvbxtrace-x86_64.so:*' too. With the static variant, run the same commands on the service binary.
  • Is the hook loaded? grep vbxtrace /proc/<pid>/maps shows the core mapped (default variant) once the first request has been handled, or after vbxh_init(). If it is missing, check the mount and that VBXTRACE is not 0.
  • The hook switched itself off. vbxh_errors() returns 5 or more. The usual cause is passing a descriptor that is not a socket to vbxh_begin_fd/vbxh_connected_fd, such as a listening socket instead of the accepted one, or an fd that was already closed.
  • Which links did a flow get? The hub shows each link's method; this package's are hook:c1.
  • Linking fails with duplicate Rust symbols (static variant): the service links another Rust static library. Use the default variant.