Skip to content

Haskell, OCaml, Julia, R, Scala Native (C4) ​

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 sheets have the steps by hand.

C4 is for services written in Haskell (Warp/WAI: Servant, Yesod, Scotty), OCaml (cohttp, Dream), Julia (HTTP.jl, Oxygen, Genie), R (plumber) and Scala Native. None of these runtimes can load a hook from outside, so the hook gets in by a source change: you copy a small binding into the service, wrap the server or router in it with one or two lines, and add a read-only mount of the hook directory to the compose entry. At run time the binding loads vulnboxd's core library from /opt/vbxtrace. Without the mount, or with VBXTRACE=0, the binding does nothing.

The Haskell, OCaml, R and Scala Native bindings compile the guarded C binding vbxhook.c of package C1 into the service and call it through each language's C FFI. The safety rules therefore live in one place. Julia's binding is pure Julia and needs no C compiler.

Covers ​

Versions
Haskell, GHC8.10 and later (tested: 9.10.3)
Warp / WAIwarp 3.3 and later, wai 3.2 (tested: warp 3.4.15, wai 3.2.5, network 3.2.9)
Servant, Yesod, Scotty, Spockevery version that produces a WAI Application on Warp
OCaml4.14 and later (tested: 5.3)
cohttp-lwt-unix5 and 6 (tested: 6.2.1, lwt 6.1.2, conduit-lwt-unix 8.0.0)
Dream1.0 alphas (tested: the opam release on the ocaml/opam 5.3 image)
Lwt / Eiocontext helpers: Lwt 5.7 and later, Eio 1.x
Julia1.11 and later, because the binding needs Base.ScopedValues (tested: 1.12.7)
HTTP.jl1.x (tested: 1.10.19); Oxygen and Genie run on it
R / plumberR 4.1 and later, plumber 1.x on httpuv (tested: R 4.5.1, plumber 1.3.0, httpuv 1.6.16, processx 3.8.6)
Scala Native0.5 with Scala 3 (tested: 0.5.8, Scala 3.3.7); servers on java.net.ServerSocket

What the kernel already links without this hook. A server that forks a process per connection, or runs one OS thread per connection (a Scala Native ServerSocket server with a thread per connection, for example), is linked exactly by the kernel. There the hook adds only request boundaries on keep-alive connections. Everything else on this page multiplexes many requests over a few OS threads, so the kernel cannot tell which request a syscall was made for:

  • GHC's green threads.
  • Lwt and Eio fibers.
  • Julia tasks.

plumber is a special case. R runs every handler on its main thread, one request at a time, but httpuv does the socket I/O on a second thread. The hook supplies the request boundaries and the exact peer.

How it gets in ​

On a developer machine: no registry package; copy the files from the hook directory that vulnboxctl hooks install-local puts in ~/.local/share/vulnboxd/trace, as below; see Local development.

Every language uses the same compose change, a read-only mount of the hook directory:

diff
 services:
   <service>:
+    volumes:
+      - /usr/local/lib/vulnboxd/trace:/opt/vbxtrace:ro

That is the whole compose change; no environment variable is needed. (The Haskell, OCaml, R and Scala Native bindings, through vbxhook.c, also take the file named by VBXTRACE_LIB first, ignored in setuid and file-capability binaries, and, only with VBXTRACE_DEV=1, a library in ~/.local/share/vulnboxd/trace that belongs to root or the user and nobody else can write, for local development. Julia loads /opt/vbxtrace only.) The source change differs per language. For each one, the files to copy come from the hook directory on the vulnbox (/usr/local/lib/vulnboxd/trace/, also visible as /opt/vbxtrace/ inside a container that has the mount). The C sources are always:

  • native/c/vbxhook.c
  • native/c/vbxhook.h
  • include/vbxtrace.h

The hub's proposals and their example diffs are in hooks/native/c4/proposals/.

Haskell (Warp, Servant, Yesod) ​

  1. Copy native/haskell/vbxtrace/ to <service>/vendor/vbxtrace/, and the three C files into vendor/vbxtrace/cbits/.
  2. Add vendor/vbxtrace to cabal.project (or the packages: of stack.yaml), and vbxtrace to the executable's build-depends.
  3. Wrap the application:
diff
 import Network.Wai.Handler.Warp (defaultSettings, runSettings, setPort)
+import VBXTrace.Wai (newVbx, vbxMiddleware, vbxSettings)

 main :: IO ()
-main = runSettings (setPort 8080 defaultSettings) app
+main = do
+  vbx <- newVbx 8080
+  runSettings (vbxSettings vbx (setPort 8080 defaultSettings)) (vbxMiddleware vbx app)

For Servant, Yesod and Scotty, wrap the WAI application they produce in the same way:

  • Servant: vbxMiddleware vbx (serve api server)
  • Yesod: toWaiApp site >>= runSettings settings . vbxMiddleware vbx
  • Scotty: scottyApp

vbxSettings keeps any setOnOpen / setOnClose you already have. On glibc older than 2.34, add extra-libraries: dl to vbxtrace.cabal. musl and current glibc need nothing.

OCaml (cohttp, Dream) ​

  1. Copy native/ocaml/vbxtrace/ to <service>/vendor/vbxtrace/, and the three C files into vendor/vbxtrace/src/. dune picks the library up from the vendored directory.
  2. cohttp-lwt-unix: add vbxtrace.cohttp-lwt-unix to the executable's libraries and replace Server.make:
diff
-  (Cohttp_lwt_unix.Server.create ~mode:(`TCP (`Port 8080)) (Cohttp_lwt_unix.Server.make ~callback ()))
+  (Cohttp_lwt_unix.Server.create ~mode:(`TCP (`Port 8080)) (Vbxtrace_cohttp_lwt_unix.make ~callback ()))

If you build the server with your own conn_closed, use let callback, conn_closed = Vbxtrace_cohttp_lwt_unix.wrap ~conn_closed callback.

  1. Dream: add vbxtrace.dream and put the middleware first, before anything that rewrites Dream.client:
diff
 let () =
   Dream.run ~port:8080
+  @@ Vbxtrace_dream.middleware ~port:8080
   @@ Dream.router [ ... ]

The optional libraries vbxtrace.lwt, vbxtrace.eio, vbxtrace.cohttp-lwt-unix and vbxtrace.dream build only when their dependencies are installed. The core library vbxtrace needs nothing beyond unix, and it uses plain external stubs, not ctypes.

Julia (HTTP.jl, Oxygen, Genie) ​

  1. Copy native/julia/VBXTrace.jl and native/julia/VBXTraceHTTP.jl to <service>/vbxtrace/. No C files and no compiler are needed.
  2. Serve through the stream middleware:
diff
 using HTTP
+include("vbxtrace/VBXTrace.jl")
+include("vbxtrace/VBXTraceHTTP.jl")
 ...
-HTTP.serve(handler, "0.0.0.0", 8080)
+HTTP.serve(VBXTraceHTTP.middleware(HTTP.streamhandler(handler)), "0.0.0.0", 8080; stream = true)

Stream handlers (HTTP.Stream -> nothing) are wrapped directly: VBXTraceHTTP.middleware(stream_handler). Oxygen and Genie build an HTTP.jl handler. Hand their router to HTTP.serve as above (Oxygen: Oxygen.router / serve(; handler)), so the middleware sits at the stream level, where the connection is visible.

R (plumber) ​

  1. Copy native/r/vbxtrace.R and native/r/vbxtrace_r.c to <service>/vbxtrace/, together with the three C files.
  2. Build the shim in the image. The R images ship a compiler.
  3. Pass the router through vbx_plumber():
diff
 # Dockerfile
+RUN cd vbxtrace && PKG_CPPFLAGS=-I. R CMD SHLIB -o vbxtrace_r.so vbxtrace_r.c vbxhook.c

 # entrypoint.R
 library(plumber)
+source("vbxtrace/vbxtrace.R")
+vbx_load("vbxtrace/vbxtrace_r.so")
-pr("plumber.R") |> pr_run(host = "0.0.0.0", port = 8000)
+pr("plumber.R") |> vbx_plumber() |> pr_run(host = "0.0.0.0", port = 8000)

Scala Native ​

  1. Copy native/scala-native/src/main/scala/vbxtrace/ into the service's src/main/scala/, and the three C files into src/main/resources/scala-native/. The Scala Native sbt plugin compiles C files found there.
  2. Wrap the request handling. For a ServerSocket server with a thread per connection:
diff
+import vbxtrace.VBXTrace
 ...
   while hasRequest(s) do
-    handle(s)
+    val ctx = VBXTrace.begin(s.getLocalPort, s.getInetAddress.getHostAddress, s.getPort, index)
+    val status = handle(s)
+    VBXTrace.end(ctx, status)
     index += 1

On glibc older than 2.34, add nativeConfig ~= (_.withLinkingOptions(_ :+ "-ldl")).

When the hub proposes it ​

The hub proposes each variant when it detects one of these:

LanguageFilesImageDependencies
Haskell*.cabal, cabal.project, stack.yaml, package.yamlhaskell:, fpco/stack-buildwarp, wai, servant-server, yesod, scotty, Spock
OCamldune-project, dune, *.opamocaml/opamcohttp-lwt-unix, cohttp-eio, dream, lwt, eio
JuliaProject.toml, Manifest.toml, *.jljulia:HTTP, Oxygen, Genie
Rplumber.R, entrypoint.R, DESCRIPTION, renv.lockrocker/, r-base, rstudio/plumberplumber, httpuv
Scala Nativebuild.sbt, project/plugins.sbt, build.millsbtscala/scala-sbtsbt-scala-native, snunit

The Julia and R proposals also match the service's command line: julia for Julia, and Rscript or plumb( for R.

Building against the static archive instead ​

Compiled with -DVBXHOOK_STATIC and linked against libvbxtrace-<arch>.a, vbxhook puts the probes into the service binary itself and needs no mount. This applies to the cabal, dune, R and Scala Native builds; see C1's vbxhook.h.

What it records ​

The join keys are always:

  • request_begin / request_end: the accepted socket's local port, peer address and port, and the request index on the connection.
  • spawned: the child pid.
  • connected: the outgoing socket's local port.
  • opened: pid + fd.

Haskell ​

EventEmitted fromExactness
request_begin / request_endvbxMiddleware, around the WAI application; ends with the status of the response passed to respond, after Warp sent it (0 if the application threw)peer = remoteHost; local port = the port given to newVbx. Request index: Warp reports every accepted connection to setOnOpen / setOnClose by peer address. Among the live connections of one listener, the peer address and port are unique, so a counter reset on open and dropped on close is exact. HTTP/2 streams count in the order Warp starts them, with protocol http2.
spawnedspawnedHandle (vbxContext req) ph (System.Process getPid); call it before waitForProcesschild pid
connectedconnectedSocket ctx sock (network withFdSocket)from the socket
openedopened ctx fd (openFlags mode flags) after System.Posix.IO.openFdopenFlags rebuilds exactly what unix ≥ 2.8 passes to open(2), from base's own O_* constants. Flags without a constant there (nofollow, cloexec, directory, sync) give "unknown".

OCaml ​

EventEmitted fromExactness
request_begin / request_end (cohttp-lwt-unix)Vbxtrace_cohttp_lwt_unix, around the callback; ends when the callback's promise resolves, with the response status (cohttp then writes the response)local port and peer from the accepted fd (Conduit_lwt_unix.TCP {fd}). Request index: cohttp creates a fresh Cohttp.Connection.t per accepted connection and passes it to conn_closed, so the per-connection counter is exact. cohttp 6 marks the module deprecated, but the server still provides the identity.
request_begin / request_end (Dream)Vbxtrace_dream.middleware ~portpeer = Dream.client (the socket peer, as long as nothing rewrote it before the middleware); local port = the given port. Request index: unknown. Dream gives handlers no connection identity and no close notification, so the index is reported as VBX_REQUEST_INDEX_UNKNOWN instead of a guess.
spawnedVbxtrace.spawned ctx pid (Unix.create_process, Lwt_process #pid; Vbxtrace_lwt.spawned p)child pid
connectedVbxtrace.connected_fd ctx fd (Unix.connect; Lwt_unix.unix_file_descr; Vbxtrace_lwt.connected)from the socket
openedVbxtrace.openfile ctx path flags perm (or Vbxtrace_lwt.openfile)Vbxtrace.open_flags maps Unix.open_flag lists through the system's own O_* constants, exactly as Unix.openfile does. Keep-exec is the default, and O_CLOEXEC appears only if listed.

Julia ​

EventEmitted fromExactness
request_begin / request_endVBXTraceHTTP.middleware, around the stream handler; ends with stream.message.response.status after the handler returned, by which time HTTP.jl has written the responselocal port and peer from the connection's TCPSocket (getsockname / getpeername). Request index: HTTP.jl keeps one HTTP.Connection object per accepted connection and reuses it for every request on it, so a counter per connection object (a WeakKeyDict) is exact.
spawnedVBXTrace.spawned(p) for p = run(cmd; wait = false)getpid(p)
connectedVBXTrace.connected(sock) after Sockets.connectfrom the socket
openedVBXTrace.open(path, mode) (wraps Base.open)Julia always opens with O_CLOEXEC, so "w" is O_WRONLY|O_CREAT|O_TRUNC|O_CLOEXEC = 0x80241 (checked with strace). Unknown modes give "unknown".

R ​

EventEmitted fromExactness
request_begin / request_endvbx_plumber(): the preroute hook opens the request; postserialize closes it, or postroute when a handler returns the response object itself (plumber then skips serialization). Ends with res$status.peer = httpuv's REMOTE_ADDR / REMOTE_PORT; local port = SERVER_PORT. Request index: unknown. httpuv tells R neither which connection a request came on nor when one closes, so a count keyed by the peer would be wrong once a client port is reused.
spawnedvbx_spawned(p$get_pid()) (processx; sys::exec_background returns the pid as well)child pid. system() / system2() hide the pid; the kernel still sees R's main thread fork inside the request.
connected, openedvbx_connected(...) / vbx_opened(fd, flags) only when the caller knows the keysbase R's socketConnection() and file() expose no fd. What R's main thread does between request_begin and request_end belongs to that request, because plumber runs one at a time.

Scala Native ​

EventEmitted fromExactness
request_begin / request_endVBXTrace.begin(...) / VBXTrace.end(ctx, status) around your handlerlocal port, peer and peer port from java.net.Socket. The request index is a counter owned by the connection's thread, so it is exact. With a raw fd, use VBXTrace.beginFd(fd, index).
spawnedVBXTrace.spawned(ctx, p.pid()) (ProcessBuilder)child pid
connectedVBXTrace.connected(ctx, sock.getLocalPort, ip, port) or connectedFd(ctx, fd)from the socket
openedVBXTrace.opened(ctx, fd, flags) after posix fcntl.openthe flags you passed

No C4 binding emits handoff or context_enter / context_exit; see below.

Context following ​

Every event a C4 binding emits carries its context id explicitly, and none of the joins depends on which OS thread made a call. So context following means making the id available to the code that spawns, connects or opens. Handoff is never needed. In GHC, Lwt, Eio and Julia, the OS thread carries no meaning anyway: lightweight threads move between OS threads, and many share one. For the same reason, the thread-current slot of vbxhook (vbxh_current) is offered only to Scala Native.

LanguageMechanismFollows automaticallyPass by hand
Haskellthe WAI request vault (vbxContext req, key ctxKey)everything that has the Requestthreads started with forkIO / async: capture the Ctx (a Word64) in the closure, e.g. let ctx = vbxContext req in forkIO (... spawnedHandle ctx ph ...)
OCaml + Lwtan Lwt.key (Vbxtrace_lwt.current ()), set with Lwt.with_value by the cohttp and Dream wrappersevery promise and callback created inside the request: bind, Lwt.async, Lwt.pick, Lwt_unix I/OLwt_preemptive.detach, Thread.create: read current () first and pass the value in
OCaml + Eioa fiber key (Vbxtrace_eio.with_ctx, current ())fibers forked inside: Fiber.fork, Fiber.both, Fiber.all, switch childrenDomain_manager.run, executor pools, Eio_unix.run_in_systhread
Juliaa ScopedValue (VBXTrace.CTX, VBXTrace.current()), bound with @with by the middlewareevery task started inside the request, on any thread: @async, Threads.@spawn, @sync, Channel producersa worker task started before the request that receives work over a Channel: send current() with the work and call the helpers with ctx, or run it in VBXTrace.with_ctx(ctx) do ... end
Rone variable (vbx_current()), exact because plumber runs one request at a time; also req$.vbx_ctxthe whole handlerpromises / future handlers: read req$.vbx_ctx; future and callr workers are separate processes, which the kernel links by fork
Scala Nativethe Long; optionally vbxhook's per-thread slot (VBXTrace.setCurrent / current)the connection's threadFutures / executors: pass the value. If the work must show up as the request's on another OS thread, use handoff + enter / exit

Example (Haskell): a handler that starts a worker thread.

haskell
handler req respond = do
  let ctx = vbxContext req
  _ <- forkIO $ do
    (_, _, _, ph) <- createProcess (proc "/usr/bin/convert" args)
    spawnedHandle ctx ph            -- still linked to the request
    void (waitForProcess ph)
  respond (responseLBS status202 [] "")

Known gaps ​

  • Request index unknown on plumber and Dream. Neither tells the application which connection a request came on. The binding sends VBX_REQUEST_INDEX_UNKNOWN, and the sensor joins those requests by peer and time. Requests on a keep-alive connection are still told apart by their boundaries. Prefer cohttp over Dream where the exact index matters.

  • TLS and Unix sockets. The cohttp wrapper handles TCP flows only. Julia's middleware needs a TCPSocket at the top of the connection, which SSLContext is not. Warp-TLS works, because remoteHost is still the socket's peer.

  • Status timing. cohttp and Dream end the request when the handler's promise resolves. A streamed body is written after request_end, and the kernel still attributes those writes to the connection.

  • Requests that fail. A plumber request whose handler raises an R error reaches no hook, so it gets no request_end. The sensor closes it at the next request_begin on the thread.

  • Calls without a helper. These are linked only by the kernel:

    • R: base R file() / socketConnection() and system().
    • Haskell: readFile / withFile. Use openFd + opened where it matters.
    • Julia: libraries that open files or sockets inside C code.

    Under green threads and fibers, the kernel's own link is ambiguous while several requests run at once.

  • cohttp-eio. Only the Eio context helper ships. A ready wrapper for cohttp-eio is not included yet; vbxtrace_eio.ml shows how to open a request from the connection's fd.

  • Scala Native frameworks. The sample uses java.net.ServerSocket. snunit runs behind NGINX Unit, which owns the connections, and http4s-ember on Scala Native runs on Cats Effect fibers (use IOLocal for the context). Neither has a ready wrapper.

  • Julia before 1.11 has no Base.ScopedValues. Use the ScopedValues.jl package and edit the using line, or upgrade.

Safety ​

  • One guard implementation. Every call goes through vbxhook's gate:

    • Nothing happens unless the core library loaded from /opt/vbxtrace and vbx_v1_enabled() reports a tracer. This check comes before anything else.
    • VBXTRACE=0 at the first call switches the binding off for the process.
    • Internal errors (an unreadable socket address, an unparsable peer) are counted, and the fifth switches the binding off.
    • vbxhook saves and restores errno and never blocks or allocates.

    Julia's binding repeats exactly these rules in Julia (including VBXTRACE_CHAOS), with every core call inside try / catch.

  • Nothing escapes into the service.

    • Haskell: the FFI calls are unsafe ccalls that cannot throw. The process and socket helpers catch every exception.
    • OCaml: the stubs are [@@noalloc] and raise nothing.
    • R: wraps every .Call in tryCatch, and the shim never raises an R error.
    • Scala Native: wraps every extern call in try.
    • The middlewares rethrow the application's own exceptions unchanged, and never change requests or responses. Haskell adds one vault entry; Julia binds a scoped value.
  • Bookkeeping while no tracer is attached. The exact request counters (Haskell, Julia) are kept as long as the binding is not off for good, so indexes stay right when a tracer attaches mid-connection. That costs one map update per request.

  • Chaos-tested. Every sample runs with VBXTRACE_CHAOS=1, which makes every core call fail inside the guard. Its responses are compared byte for byte with the normal run and with a build containing no hook code at all.

Sampleeventschaosbaseline
haskell-warp13 events matchresponses byte-identical (581 bytes)byte-identical
ocaml-cohttp13 events matchbyte-identical (488 bytes)byte-identical
ocaml-dream13 events match (index unknown)byte-identical (368 bytes)byte-identical
julia-http13 events matchbyte-identical (461 bytes)byte-identical
r-plumber11 events match (index unknown, no fd for file/connect)byte-identical (368 bytes)byte-identical
scala-native-socket13 events matchbyte-identical (368 bytes)byte-identical

Overhead (p99 with the hook loaded and the sensor detached, and attached) has not been measured yet. It will be added in the measurement phase.

Turning it off ​

Set VBXTRACE=0 in the service's environment and restart it, or revert the change that added the hook; vulnboxd's rollback covers a hook that breaks a service.

To remove the hook completely:

  1. Undo the middleware lines.
  2. Delete the vendored directory: vendor/vbxtrace (Haskell, OCaml), vbxtrace/ (Julia, R), or src/main/scala/vbxtrace plus the three C files under src/main/resources/scala-native/ (Scala Native).
  3. Drop the /opt/vbxtrace mount.

Removing only the mount also switches the hook off: the binding finds no core and stays inactive.

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.

  • Is the hook loaded? The core is loaded on the first request, not at startup. After one request, grep libvbxtrace /proc/<pid>/maps shows the library. If it is missing:

    • the mount is absent;
    • VBXTRACE=0 is set;
    • the binary is fully static: build with -DVBXHOOK_STATIC and the archive instead (not Julia).

    Inside the service, the binding reports how many internal errors it has counted (5 or more means off): VBXTrace.errors (Haskell), Vbxtrace.errors () (OCaml), VBXTrace.errors() (Julia), .Call("vbxr_errors") (R), VBXTrace.errors (Scala Native).

  • Which links did a flow get? The hub shows each link's method; this package's are hook:c4.

  • No events from Warp. vbxSettings was not applied to the settings Warp actually runs with, so the middleware sees connections it was never told about and stays silent rather than guess. Pass the settings through vbxSettings and wrap the application with the same vbx.

  • No events from cohttp. The server listens on TLS or a Unix socket, or Server.make was not replaced (check that Vbxtrace_cohttp_lwt_unix is linked).

  • Julia: events but no request_end status. The handler threw. HTTP.jl answered with a 500 of its own, and the binding reports status 0.

  • R: vbx_load() returns FALSE. The shim was not built (no vbxtrace_r.so), it was built without vbxhook.c, or VBXTRACE=0 is set.

  • Builds fail on dlopen. On glibc older than 2.34, link -ldl: cabal extra-libraries: dl, dune (c_library_flags -ldl), R PKG_LIBS=-ldl, Scala Native linking options.