Rust tokio crate (R1)
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.
The Rust hook for services on tokio. It is a small crate, vbxtrace-hook, vendored into the service directory next to a copy of vulnboxd's hook core, so the service builds with no network. Using it takes one changed line where the server starts and a wrapper around each place a handler starts a process, connects out or opens a file. It then reports which request each of those belongs to. Rust has no runtime hook point an environment variable could reach: generics are monomorphised and the binary has no stable symbols. So unlike the interpreted runtimes, Rust's only way in is a source change, and the hub shows it as a full diff for you to approve.
The same crate also serves the runtimes off tokio (async-std/tide, smol, may, glommio, monoio, plain threads): see R2.
Covers
| Versions (tested in a sample) | |
|---|---|
| Rust | 1.85 or newer (the vendored core is edition 2024); samples built with the current stable |
| Architectures | x86_64 and aarch64; glibc and musl; static or dynamic binaries (samples: x86_64, musl) |
| tokio | 1.x (feature tokio; wrappers: tokio-process, tokio-fs, tokio-net) — 1.53 |
| axum | 0.7 (axum07), 0.8 (axum08): axum::serve with any make service — 0.7.9, 0.8.9 |
| hyper | 1.x (hyper1): own accept loops, hyper-util's auto::Builder, TowerToHyperService — 1.12; 0.14 (hyper014): make_service_fn — 0.14.32 |
| warp | 0.3 (through hyper 0.14, hyper014) — 0.3.7; 0.4 (through hyper 1, hyper1 + Trace) — not sampled |
| actix-web | 4.x (actix-web4) — 4.17 |
| Rocket | 0.5 (rocket05) — 0.5.1 |
| poem | 3.x (poem) — 3.1 |
| Salvo | 1.x, TCP listeners (salvo) — 1.0 |
| tonic | 0.12–0.14 gRPC servers (tonic) — 0.14 (0.12 and 0.13 build against the same API but are not sampled) |
| Any tower service | Trace / TraceLayer (http1 + tower-service / tower; http 0.2: http02) |
| Raw tokio TCP servers | ConnInfo::from_tokio + session / begin |
| std | Command, File/OpenOptions, TcpStream/UdpSocket, thread::spawn wrappers (always on) |
Each integration is a cargo feature. Every third-party dependency is optional, has its default features off and accepts the widest version range that works. So a service compiles only what it uses, and the hook adds no crate its lockfile does not already have. The offline test (below) checks exactly that.
What the kernel already links without this hook: nothing, for tokio. Tasks move between worker threads and one thread runs many requests' tasks in turn, so the sensor's "one client socket per thread" rule never applies. Parts of a service that run thread-per-connection on plain std threads are linked by the kernel alone (see R2).
How it gets in
From a registry (local development, or a build with network; the same release as the hook directory): cargo add vbxtrace-hook@1.0.0 --features axum08 (crates.io; one feature per integration); see Local development.
Source change. The hub proposes a diff that you review. It goes out like a rule push, and the service rebuilds in the normal deploy flow. Every proposal has these steps:
Copy the hook directory's
rust/(/usr/local/lib/vulnboxd/trace/ruston the vulnbox) into the service asvendor/vbxtrace. It holds two crates:vbxtrace-hook(the binding) andvbxtrace(the core: the USDT probes,no_std, no dependencies). Each is a workspace root of its own, so it builds wherever it is put.Add the dependency, with the features for what the service uses:
diff[dependencies] axum = "0.8" tokio = { version = "1", features = ["full"] } +vbxtrace-hook = { path = "vendor/vbxtrace/vbxtrace-hook", features = ["axum08", "tokio-fs", "tokio-process"] }If the service's
Cargo.tomlhas a[workspace]table, the proposal adds the vendored crates to its excludes (exclude = ["vendor/vbxtrace"]). Otherwise cargo stops with "multiple workspace roots found".Change the line that starts the server (per framework, below).
Replace the calls whose effects should be linked with the hook's wrappers (What it records), and the spawns whose work should keep the request (Context following).
Make sure the Dockerfile copies
vendor/beforecargo build. A Dockerfile that copies onlyCargo.toml,Cargo.lockandsrc/first, for layer caching, getsCOPY vendor/vbxtrace vendor/vbxtraceadded.
The build needs no network: the hook brings no new crates. A service whose build environment is offline usually vendors its crates.io dependencies already (cargo vendor into some directory and .cargo/config.toml); that keeps working unchanged. The repository's test applies each example diff (axum, actix-web, Rocket, tonic, warp, poem, Salvo, and R2's tide) to a fixture service that vendors its crates. It then builds the fixture's own Dockerfile with podman build --network none and cargo build --offline, and checks the binary for the probes (hooks/rust/r1/tests/offline-build.sh).
The server line, per framework
axum 0.7 / 0.8: wrap whatever is passed to axum::serve:
- axum::serve(listener, app).await.unwrap();
+ axum::serve(listener, vbxtrace_hook::axum::trace(app)).await.unwrap();The same holds for app.into_make_service() and app.into_make_service_with_connect_info::<C>(). The app's own connect info, layers and state stay as they are. axum creates a service per accepted connection from the make service, and the wrapper makes it a Trace for that connection.
actix-web 4: a middleware, plus a connection callback that remembers each connection:
- HttpServer::new(|| App::new().service(run))
+ HttpServer::new(|| App::new().wrap(vbxtrace_hook::actix::Trace).service(run))
+ .on_connect(vbxtrace_hook::actix::on_connect)
.bind(("0.0.0.0", 8000))?An existing on_connect(f) becomes on_connect(vbxtrace_hook::actix::on_connect_with(f)). Put the wrap last (outermost).
hyper 1 (own accept loop):
let (stream, _) = listener.accept().await?;
+ let conn = vbxtrace_hook::ConnInfo::from_tokio(&stream);
let io = TokioIo::new(stream);
tokio::spawn(async move {
- http1::Builder::new().serve_connection(io, service_fn(handler)).await
+ let svc = vbxtrace_hook::Trace::with_conn(service_fn(handler), conn);
+ http1::Builder::new().serve_connection(io, svc).await
});hyper 0.14 and warp 0.3: warp::serve(routes).run(addr) has no per-connection hook. The proposal replaces it with what warp::serve does inside: hyper's Server with a make_service_fn that wraps each connection's service:
let make = hyper::service::make_service_fn(move |conn: &AddrStream| {
let svc = vbxtrace_hook::hyper014::trace(warp::service(routes.clone()), conn.local_addr(), conn.remote_addr());
async move { Ok::<_, std::convert::Infallible>(svc) }
});
hyper::Server::bind(&addr).serve(make).await?;warp already depends on hyper 0.14 with these features, so the added hyper line brings nothing new.
tonic 0.12–0.14: a layer, plus the hook's incoming stream, which tells the layer each request's connection:
- Server::builder()
- .add_service(health)
- .serve("0.0.0.0:50051".parse().unwrap())
+ let listener = tokio::net::TcpListener::bind("0.0.0.0:50051").await.unwrap();
+ Server::builder()
+ .layer(vbxtrace_hook::tonic::TraceLayer)
+ .add_service(health)
+ .serve_with_incoming(vbxtrace_hook::tonic::incoming(listener))Handlers still get request.remote_addr() and local_addr(), because the layer puts tonic's own TcpConnectInfo into each request as well. The incoming stream sets TCP_NODELAY like tonic's default; a builder's own tcp_nodelay/tcp_keepalive setting moves to incoming(listener).nodelay(..).
Rocket 0.5: a fairing, and the routes' handlers wrapped so they run in the request's context:
- rocket::build().mount("/", routes![note])
+ rocket::build()
+ .attach(vbxtrace_hook::rocket::Trace)
+ .mount("/", vbxtrace_hook::rocket::traced(routes![note]))Rocket never shows the hook a connection, so a request's index is only known when each connection carries one request: with keep_alive = 0 (Rocket.toml, ROCKET_KEEP_ALIVE=0 or Config) every index is 0. With keep-alive on, requests are reported with the index unknown. The sensor then links them only through other exact facts, never by guessing. The proposal mentions ROCKET_KEEP_ALIVE=0 as an optional extra: it changes connection reuse, not responses.
poem 3: a listener wrapper and a middleware:
- let app = Route::new().at("/note/:id", get(note));
- Server::new(TcpListener::bind("0.0.0.0:3000")).run(app).await
+ let app = Route::new().at("/note/:id", get(note)).with(vbxtrace_hook::poem::Trace);
+ Server::new(vbxtrace_hook::poem::TracedListener(TcpListener::bind("0.0.0.0:3000"))).run(app).awaitSalvo 1: an acceptor wrapper, and a hoop on the Service (not a Router, so it also sees requests that match no route):
- Server::new(acceptor).serve(router).await;
+ let service = Service::new(router).hoop(vbxtrace_hook::salvo::Trace);
+ Server::new(vbxtrace_hook::salvo::TracedAcceptor(acceptor)).serve(service).await;poem and Salvo hand requests no connection identity either. So the wrapper registers each accepted connection under its local port and peer address until the connection's IO is dropped, and the middleware looks the request's own addresses up. No two open connections share that key, so the lookup is exact.
Raw tokio TCP servers:
let (sock, _) = listener.accept().await?;
- tokio::spawn(handle(sock));
+ let conn = vbxtrace_hook::ConnInfo::from_tokio(&sock);
+ tokio::spawn(conn.session(handle(sock)));session makes the whole connection one request (index 0, protocol raw). A server that speaks a message protocol can call conn.begin(Protocol::Http1) per message instead and run the handling in request.bind(fut).
The hub proposes R1 when it finds a Cargo.toml/Cargo.lock with tokio and one of axum, hyper, warp, actix-web, rocket, poem, salvo or tonic; a Rust build stage (FROM rust:…, clux/muslrust, cargo-chef); or a cargo command. Templates: hooks/rust/r1/proposals/*.toml, with example diffs (*.diff) that apply to the fixtures in hooks/rust/r1/tests/offline/.
What it records
| Event | Emitted from | Join key |
|---|---|---|
request_begin / request_end | the framework integration (above), or ConnInfo::begin / Request::end by hand | the accepted socket's local port and peer, and the request's index on the connection |
spawned | CommandExt::spawn_traced / status_traced / output_traced (tokio and std), process::note_spawned(pid) | child pid |
connected | tokio::net::connect, net::connect / connect_timeout / connect_udp / send_to_udp, net::note_connected(&socket, transport) for a socket a library connected | the socket's local port |
opened | tokio::fs::{open, create, read, read_to_string, write, OpenOptions}, fs::{…} (std), fs::note_opened(&file, flags) | pid + fd |
context_enter / context_exit | tokio::spawn_blocking, thread::spawn / spawn_with / spawn_scoped / wrap, scope(..), CommandExt::output_traced (std) | the thread, while it works for one request |
Details:
- Requests. The protocol is
grpc(by content type),http2/http3(by version),websocket(anUpgrade: websocketrequest), elsehttp1;rawfor sessions. A request ends with the response's status when the handler's future returns the response head (0 if it errors without one, or is dropped). - Request index. A
ConnInfoper accepted connection counts its requests. It counts even while no tracer is attached (one atomic add per request), so a tracer that attaches in the middle of a keep-alive connection still gets exact indexes. HTTP/2 streams are numbered in the order hyper hands them to the service. Where no index can be known exactly (Rocket with keep-alive), the hook passesREQUEST_INDEX_UNKNOWN(shown asrequest_index=unknown) instead of guessing. - Addresses are read from the accepted socket (getsockname/getpeername) at the first request that is traced, not per connection. axum 0.7 hides its socket, so there the local address is read when a connection is accepted while a tracer is attached; a connection accepted before that counts its requests but traces none.
- open(2) flags. std's and tokio's
OpenOptionsdo not tell which flags they pass. The hook's drop-inOpenOptionsrecords every setting and computes the flags exactly as std does on Linux,O_CLOEXECincluded:File::createis0x80241,File::open0x80000. - std
Command::output()picks its stdio defaults internally and hides the child, sooutput_tracedcannot see the pid. Instead it marks the thread as working for the request (context_enter/context_exit) while it blocks, and the sensor links the child forked from that thread. tokio'soutput()is reimplemented exactly (stdout and stderr piped, spawn, thenwait_with_output), so it reportsspawnedwith the pid. - Events outside a request (context 0) are not emitted.
Context following
The current request lives in a thread-local word. It is set around every poll of a future bound to the request and restored afterwards (also when the polled code panics). This is how tokio::task_local! works inside, but it works the same on every executor and on plain threads. The framework integrations bind the handler's future. Everything the handler awaits inline is followed with no further change.
New tasks and threads only carry the context through the hook's helpers:
| Instead of | Use |
|---|---|
tokio::spawn(fut) | vbxtrace_hook::tokio::spawn(fut) |
tokio::task::spawn_local(fut) | vbxtrace_hook::tokio::spawn_local(fut) |
tokio::task::spawn_blocking(f) | vbxtrace_hook::tokio::spawn_blocking(f) (adds context_enter/exit on the pool thread) |
join_set.spawn(fut) | join_set.spawn_traced(fut) (vbxtrace_hook::tokio::JoinSetExt) |
actix_web::rt::spawn(fut), any executor's spawn | spawn(vbxtrace_hook::bind(fut)) |
web::block(f), rayon, a thread pool | vbxtrace_hook::thread::wrap(f) |
std::thread::spawn(f) | vbxtrace_hook::thread::spawn(f) |
A task spawned plainly runs without the request. What it does is then not linked, but never linked to the wrong request. handoff is not needed, because the child task carries the same context id.
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
.probessection. 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_totalcounts it). Linking with-C link-arg=-Wl,-z,separate-loadable-segments(inRUSTFLAGSor.cargo/config.toml) avoids it. - Unwrapped calls are not linked. In an async runtime, a
std::fs::File::openthat is not wrapped happens on a thread that serves many requests, so the sensor cannot tell whose it was. Libraries that open their own connections (database pools, HTTP clients such as reqwest or sqlx) neednote_connected(&socket, ..)where the socket is visible, or stay unlinked. Crates that run their own runtime (reqwest's blocking client) carry no context. - Streaming bodies. A request ends when the response head is ready; a body streamed after that (SSE, file downloads) runs outside the request's context.
- Rocket with keep-alive: unknown request index (above). Rocket's catchers (404, 500) run outside the request's context; their requests still begin and end.
- Salvo: TCP listeners only; TLS (rustls, openssl, native-tls) and QUIC acceptors are not wrapped. Salvo 0.x is not supported (its connection API changed in every release).
- tonic: one request per RPC. A bidirectional stream's messages are not separate requests. The status is the HTTP status (200); the gRPC status travels in the trailers.
- poem 1.x/2.x and axum ≤ 0.6 are not integrated. axum 0.6 can be served through hyper 0.14 with
hyper014::trace. panic = "abort": the guard cannot catch a panic inside the hook (there are none on purpose); a panic aborts as any panic in the service would.- Rust older than 1.85 cannot build the vendored core (edition 2024).
Safety
- Every wrapper calls exactly the function it replaces, with the same arguments, and returns its result untouched. Wrapped futures are polled as they are: the hook adds a thread-local swap around each poll and nothing else.
- The hook's own work runs in a guard that catches panics (
catch_unwind). After 5 internal errors the hook switches itself off for the process. Your code never runs inside the guard, so its panics pass through untouched. - Chaos testing (
VBXTRACE_CHAOS=1) makes every guarded call fail withresume_unwind. That unwinds without calling the panic hook, so a service's panic hook and stderr never see it. - While no tracer is attached, each hook point checks the core's semaphores (eight loads) and does nothing else, except the per-connection request count described above.
VBXTRACE=0in the environment switches the hook off at start, including the counting.- Compatibility glue runs whether or not a tracer is attached: tonic's
TcpConnectInfostays in each request; the Rocket/poem/Salvo wrappers forward every IO call. - Tested: every sample service (axum 0.7 and 0.8, actix-web, hyper 1, warp/hyper 0.14, tonic, Rocket, poem, Salvo, raw tokio) runs with the recording core and must produce its golden event sequence. It also runs with every hook call failing (chaos) and without the hook (the service before the proposal), and the responses must be byte-identical. Overhead has not been measured yet.
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. Reverting removes vendor/vbxtrace, the dependency line and the wrapper calls, and the service rebuilds as before.
Troubleshooting
- Are the probes there? The probes are compiled into the service's binary:
readelf -n target/release/<service> | grep -A3 vbxtracelists them, andsudo bpftrace -l 'usdt:/proc/<pid>/exe:vbxtrace:*'shows them in the running service. - Is the hook on?
vbxtrace_hook::installed()is false afterVBXTRACE=0or 5 internal errors;vbxtrace_hook::active()is true only while a tracer is attached. - Requests show
request_index=unknown. Rocket with keep-alive (see above). - No
request_beginat all. The server line is not wrapped, or (poem, Salvo, actix) only one of the two changes was made: the listener/acceptor/on_connectpart and the middleware part are both needed. - No
spawned/connected/openedfor a request. The call is not wrapped, or it runs in a task spawned without the hook'sspawn. - "multiple workspace roots found": the service is a workspace; exclude
vendor/vbxtrace. - "no matching package named … found" with
--offline: an integration feature was turned on for a framework the service does not use; enable only the features the proposal lists. - Which links did a flow get? The hub shows each link's method; this package's are
hook:R1.