* fix(ebpf): key the IPv6 new-flow budget by /64 * fix(ebpf): match IPv6 fragments on address and identification only * fix(ebpf): record an expiry hint only after the ring accepts it * refactor(core): size UDP commit batch buffers by request count * test(core): drop tests that pass without their change and widen deadline margins * docs(datapath): describe the /64 budget, IPv6 fragment keys and hint recording * docs(agents): restore the ActivateDirect grace and dead-outbound health invariants * docs(datapath): state the per-CPU ceiling of the new-flow budget * fix(ebpf): keep the IPv6 new-flow budget per source address * docs(datapath): per-address IPv6 budget, accurate map ceiling, hint cost and UDP health wording
74 KiB
AGENTS.md — honk
Agent guide to understanding, building, testing, and modifying honk. Repository layout/conventions last verified against the tree on 2026-08-09.
Re-read it when a conversation grows long or context is trimmed: a rule read once is not a rule in force. Never substitute memory or resemblance for evidence.
Task routing
| Doing | Read first |
|---|---|
| any change | this file; also .agents/skills/honk-change/SKILL.md (the loop every PR here follows) |
honk-config, honk-tool, doc/*/reference, dialect.md, or a core/outbound consumer of Config, Node, derive_id, group filters, DNS routing |
.agents/rules/configuration.md; skill honk-config-change |
real-kernel or eBPF work, crates/honk-ebpf*, crates/honk-core/src/ebpf/, mock-eBPF development |
.agents/rules/real-ebpf.md; skill honk-real-ebpf-tests |
| placing or finding tests, benchmarks | .agents/rules/test-locations.md |
| releases, CI workflows | .agents/rules/release.md; skill honk-release |
| deployment, security-sensitive paths | .agents/rules/deployment.md, .agents/rules/security.md |
| REALITY / xtls interop verification against live servers | .agents/rules/maintainer-lab.md (the maintainer's lab; not required for contributions) |
Maintaining this guide: a rule that binds every change goes in this file; a subsystem's reference goes in its .agents/rules/ file, in the section it belongs to. A new rules file gets a row in the routing table, and every file the table sends the reader to must exist. .agents/tools/ describes the one-time extraction and is not re-run on later edits. The CI mechanical review drops its documentation reminder when either AGENTS.md or .agents/rules/ changes alongside code.
Project overview
honk is a Rust transparent-proxy engine for Linux, inspired by dae (eBPF datapath and configuration surface) and sing-box (outbound groups, multi-protocol dialers, Clash-compatible API). It is not a line-for-line port of either: the kernel path uses TC hooks with a restricted native-BPF routing policy compiled from userspace, while the userspace outbound/control stack follows sing-box-oriented designs.
honk-coreintercepts via TC redirect and userspace proxy relay. Ambiguous LAN UDP uses default-on NFQUEUE 320 when prerequisites pass (global.nfqueue_enable: falsedisables; see.agents/rules/configuration.md). Its owned nftables table/chain installs no globaliptablesTPROXY rules.honk-configprovides shared types/parsers for original dae{ section { ... } }, the primary and only documented config syntax.- Status: experimental alpha (
v0.0.1-alpha). Expect breaking changes. - License: GPL-3.0-only. Repository: https://github.com/daeuniverse/honk
- Docs:
README.md/README.zh.md(bilingual overview, feature checklist, TODO list); matchingdoc/en//doc/zh/trees underdoc/, indexed by bilingualdoc/README.md. Each hasconfiguration.md,design/(overview/datapath/routing/nfqueue/control-plane/dns/outbound/groups),reference/(global/nodes/groups/routing/dns/subscription/experimental/api/cli), andoperations/runbooks. Lab benchmark tooling, evidence, and bilingual docs live only onbench.
Repository layout
.
├── Cargo.toml / Cargo.lock # Workspace manifest (release + release-musl profiles)
├── Justfile # Day-to-day dev tasks (build, test, run, debug via clash API, cleanup)
├── README.md / README.zh.md # Bilingual project overview
├── AGENTS.md # This file
├── .agents/ # rules/ (subsystem reference), skills/ (task skills), tools/ (the split scripts); see Task routing
├── LICENSE # GPL-3.0-only
├── config.dae # Full-featured example config (production-leaning)
├── config.min.dae # Minimal example (good for --mock-ebpf dev)
├── example.dae # Annotated example (Chinese comments)
├── doc/ # en/ + zh/ doc trees: guide, design/, reference/, operations/
├── ci/ # zigcc/zigcxx: zig cc/c++ wrappers for cross builds (strip CMake's clang-style --target from boring-sys ASM rules + rustc's aarch64 errata linker args; used by build-musl and the release workflow); zig-bindgen-env: derive BINDGEN_EXTRA_CLANG_ARGS from `zig cc -E -v` for cross bindgen
├── .github/workflows/ # release.yml: tag-triggered test + cross-build + GitHub Release
└── crates/
├── honk-config # Config schema + dae-syntax parser + share links (workspace member)
├── honk-ebpf-common # no_std shared eBPF/userspace types (workspace member)
├── honk-nfqueue # Raw-netlink NFQUEUE 320 + owned nftables table/chain (workspace member)
├── honk-outbound # Proxy handlers, groups, health checks (workspace member)
├── honk-core # eBPF proxy engine, library + `honk-core` binary (workspace member)
├── honk-tool # `honk-tool` CLI toolbox: `sub` subscription/node probing (workspace member)
└── honk-ebpf # Kernel eBPF programs (EXCLUDED from workspace, own Cargo.lock)
Notable absences (referenced by older docs but not in this tree): Makefile, scripts/, Dockerfile, docker-compose.yml, plan.md, run_tests.sh, test-honk.sh, log/, and the vendored reference checkouts (honk/, outbound/, sing-box/ — these paths are .gitignored). The old run / deploy / docker* recipes were removed with those missing files; use run-debug, run-dae, and deploy-vyos. test-routing and its dependent test-netns share one complete disposable-VM gate; prepare its toolchain, objects and environment through honk-real-ebpf-tests rather than attaching root-cgroup hooks on a shared host.
Technology stack
- Language: Rust, edition 2024 (workspace-wide, including the eBPF crate).
- Async runtime: Tokio (
full). - Allocator: default-on
mimallocfeature makes mimalloc global in shippedhonk-core; musl malloc is slow under contention. Aligned 1 GiB arenas decommit purged pages, but fragment-pinned worker heaps linger. Linuxmain.rsdisables process transparent huge pages before Tokio, builds the runtime explicitly, and dispatches the top-level future onto a worker. Each owning worker's park callback runsmi_collect(true): OS-thread-local 60s cooldown, delayed first collection. A bounded periodic rendezvous, only when every other worker is idle, wakes owners parked after cross-thread frees so that callback can purge their heaps.HONK_MI_COLLECT_SECS=0installs neither hook nor rendezvous. Startup also lowers mimalloc v3's 1000 mspurge_delayto 100 ms throughmi_option_set_default, so an operator'sMIMALLOC_PURGE_DELAYstill wins; the Rust binding has no constant for the option, hence the local index. Clash/logs(clash_api/logs.rs) skips formatting without subscribers; its unfiltered tracing layer would otherwise allocate aStringper sub-level datapath event. Default logs silencequinn::endpoint(logging.rs::QUIET_TARGET): its driver-death ERROR accompanies carrier loss under probe/warm transports (e.g. SYNACK-watchdog kills) and duplicates the failure honk reports with its own context, so it is lifecycle noise. A completed nonzero-timeout packet-backed endpoint close stops Quinn drivers before adapter workers and emits none; zero-timeout close and parent-owner teardown keep their existing order. ValidRUST_LOGoverrides console/file filtering until a nativelog.levelPATCH, which the next activation reverts; Clash/logsand native/api/v1/logsalways exclude this target. - eBPF: userspace aya 0.14 (optional
ebpffeature inhonk-core); kernel sideaya-ebpf0.2 targetingbpfel-unknown-none(nightly +-Zbuild-std=core+bpf-linker). - NFQUEUE:
honk-nfqueueuses rawNETLINK_NETFILTERfor one fixed queue and its nftables transaction; no libnetfilter_queue/libmnl/libnftnl or firewall subprocess. - HTTP APIs: axum 0.8 + tower-http 0.7. Default-on
clash-apienables WebSockets; independent opt-innative-api(build with--features native-apiornative-ui; release builds include it) owns Hyper HTTP/1.1 and observation, config, probe, DNS, lifecycle and source-owned management, with its listener disabled until configured. Native limits: 64 connections, 5s headers, 30s read-idle deadline only while no request is in flight (end of body until response resolves), 30s stalled-write deadline, 5s joined HTTP shutdown; one 1s sampler. Accept errors log and retry (100ms backoff on EMFILE/ENFILE/ENOBUFS/ENOMEM); a failed connection task is logged, not fatal. Flow recorder 1024/64 steps/8 MiB including snapshots, terminal 300s, evicting the oldest ended record before any live one; flow snapshots 8/30s. Node snapshots 8/30s/4 MiB. SSE 512 events/60s/16 clients/64 queue/15s heartbeat; events and logs both resume ready → replay → live. Native catalog group IDs are process-stable; config group UUIDs andcreated_atsurvive same-name reload, not rename. Per-network Selector and automatic-policy pin/clear, source-owned Group PATCH, synchronous main-source node/provider create/delete and verified-geodata operations are enabled; native runtime_mode and full kernel transparency remain gated. Default-offnative-uiembeds pinned real doona assets without fonts: packaging obtains the distribution pinned in.github/ci/pins.envthroughci/fetch-doona.sh, andbuild.rsembedsHONK_DOONA_DIR, including its notices; no vendored asset tree or runtime fetch.alive/observations.rsretains qualified actual probe facts independently of legacy routing liveness; never infer fresh native health from restored/synthetic/derived collections. Config/auth:.agents/rules/configuration.md,.agents/rules/security.md.native_api/server.rsowns HTTP/sampler shutdown;auth.rsowns one tracked blocking credential job and sessions, with storage/request children. Close auth admission before the five-second HTTP grace, then join real KDF/SQLite work even after request cancellation. Signed ready checkpoints remain distinct from evicted event cursors. Catalog snapshots, DNS responses and DNS log pages mask listener-secret display values before bounded serialization, without changing IDs or cursor bindings. - QUIC: quinn 0.11 (TUIC/Juicity/Hysteria2 outbounds, DoQ/DoH3 DNS);
h3/h3-quinnfor DoH3 only — Hysteria2 ships its own minimal HTTP/3+QPACK layer. Core opts into h3's third-party-backend error visibility so DNS can distinguish typed endpoint loss from deterministic H3 response errors without parsing text. Keep that version-sensitive inspection private indns/transport/quic.rs; upgrades must retain its failure-scope regression. - TLS: boring 5.2.0 + tokio-boring 5.2.0 for proxy/DNS TCP TLS and QUIC via custom
quinn_proto::cryptoinhonk-outbound/src/quic/boring.rs; webpki-root-certs CA roots. rustls supplies loopback wire interop tests and preserves the existing platform-verifier policy for HTTP downloads only. boring-sys builds BoringSSL from source withcmake, C compiler,libclang(bindgen). Pin all three Boring crates to 5.2.0; patch boring-sys tohttps://github.com/Glassyiris/boring-sys, revision3beb573b65ecaa69b7eefe3c2fecd074b97facd2, branchboring-sys-5.2. The fork adds REALITY-requiredSSL_set1_client_x25519_private_keyandSSL_set_client_hello_fixup_cb. Rebase it before upgrading the stack. - Persistence: rusqlite 0.40 (
bundled) for the state db (state.rs,<data_dir>/state/honk.db): the--store dbrevisions (native_api/store/db.rs), the runtime-state cache tables (state/cache.rs), subscription bodies (subscription/store.rs), the password-mode administrator (native_api/auth.rs) and the geodata sources (native_api/geodata/sources.rs); each except the revisions and the geodata sources imports its pre-state-db file once. - Serialization: serde, toml 1, serde_json, serde_yaml.
- Logging: tracing + tracing-subscriber (
env-filter,json); alsolog. - HTTP downloads: marked TCP or a routed tunnel + Hyper HTTP/1 + tokio-rustls/platform verifier for subscriptions, geodata and external UI downloads (one GET in
marked_http); reqwest 0.13 supplies URL types and API test clients. Keep platform CA roots and SAN validation, redirect credential stripping, proxy authentication precedence, body caps and cancellation-owned connection drivers. - Error handling: anyhow + thiserror 2.
- Misc: socket2, ipnet, aho-corasick, lru, dashmap, parking_lot, h2 0.4 (urltest probes + DoH), tokio-tungstenite (WS transport), zip (external-UI download only), libsystemd (only
sd_notify), nix (POSIX/Linux syscall wrappers), aes-gcm/chacha20poly1305/blake3/sha1/sha2/hmac/hkdf/md-5. - Dev/test: tempfile, tokio-test, rcgen 0.14, tokio-tungstenite, criterion 0.8 (DNS and UDP benchmarks).
See design docs.
Native flow complete means source evidence through that flow's executed frontier, not success or global transparency. Preserve actual route/DNS/group/transport/session outcomes and generation/attempt/lookup lineage; never reconstruct kernel execution or historical membership from current state. Capture loss, ambiguity and essential redaction remain explicit partial evidence. Keep recorder snapshots and frozen kernel dictionaries within the shared byte budget. Async observation scopes borrow caller-pinned operations to avoid multiplying future state; preserve cancellation/drop ordering before terminal cleanup, rather than increasing thread stacks or adding per-layer boxes.
Engine-side observation (flows, rules, catalog identity, DnsRecorder, Observation/owner) lives in crate::observe; native_api holds only the HTTP projection. Without native-api, observation hooks compile as zero-cost inert twins (observe/inert.rs). honk-outbound features flow-observation and owned-tasks are enabled by honk-core native-api.
observe/dns/history.rs owns bounded client DNS retention inside DnsRecorder; native_api/dns/log.rs reads a lock-held view for cursor/filter handling, listener-secret masking and JSON projection.
observe/flows/producer.rs owns FlowGuard mutations, callbacks and shared selection projection; observe/flows/record.rs owns wire models, including DNS inputs; native_api/flows.rs only maps them to HTTP. DNS scopes retain lookup/catalog authority rather than becoming a generic projection owner. native_api/config/http.rs owns source HTTP adapters; the coordinator awaits durable promotion before advancing its queue.
native_api/settings.rs owns independent flow/log/DNS-log demand, stream leases and the existing maintenance/grace transition; passive events alone do not enable diagnostic recording. control/reload/fingerprint.rs owns same-name config group identity normalization; connection_tracker.rs owns shared close completion. control/cache.rs::StateTick retains its join across cancellation and waits beyond the ten-second warning for real blocking maintenance. mode.rs::DatapathFlagsPublication participates in the existing reload publication order documented in doc/en/design/control-plane.md; no new lock edges are implied. Real-backend cleanup() releases its receive-trace fallback before the BPF object, not at backend Drop.
Kernel witness admission uses DATAPATH_FLAG_TRACE_ENABLED in the existing composed flags, reconciled by the existing native sampler and terminal shutdown. Convergence is a subsequent tick, not a hard one-second bound; missing pre-enable evidence stays explicit. Preserve admitted operation capture after demand changes and never clear retained sidecars/dictionaries just to turn recording off. native_api/events.rs caches one first-filter frame per immutable record and charges its possible frame/cache-cell reservation within the unchanged 2 MiB retained-ring budget; other filters, signed checkpoints and epoch/reset boundaries remain independent.
native_api/events/http.rs owns event query/cursor parsing, Accept negotiation and HTTP stream responses shared with logs; replay, signing, subscriptions and frame-budget accounting remain in native_api/events.rs.
Outbound source ownership: proxy/{error,packet,outbound,registry}.rs retain the public proxy facade; Shadowsocks owns aead2022/stream, and VLESS owns feature-only handler/encryption plus cool/mux backends. Shared UoT, transport and REALITY stay outside VLESS. QUIC owns path_health, flow_control, metrics, endpoint, client, stream and boring; the public quic_boring facade remains supported. AnyTLS uses padding/writer/overflow plus the shared uot non-connect transport. Score budget owns currency/in-flight accounting, evaluation owns the shared bounded serving pool, comparison/store owns bounded observations, comparison owns timed pair evidence, verification owns the single optional-work dispatch walk and readonly reporting, and evidence/ranking/feedback own outcomes and ordinary decisions; ranking/dispatch owns stateful selection entry points, reservations and reporting. Named node provenance and borrowed cell stamps keep parent-incarnation/effective-fence rules shared without merging failure time with reload invalidation. Comparison and validation regression topics use nested test modules. Alive uses health/urltest, and SessionPool uses maintenance/speculative; common state stays at each ancestor to avoid widening fields. Normal builds without rprx allocate no VLESS pools/carrier semaphores; cfg(test) retains backend-only unit coverage, never handler registration.
Shared gRPC lives in proxy/transport/grpc.rs: h2 owns HTTP/2 and connection-wide HPACK with a 64 KiB response-header limit and its default 4 KiB dynamic table. The returned stream owns the driver/socket; split readers and writers share stable driver wakeups. At most one 16 KiB application message is queued, and flush waits for both its ownership release and physical I/O flush, including after peer window reductions. Preserve buffered payload before terminal read errors, retained read outcomes, request half-close, and graceful GOAWAY for an admitted stream; never replay application bytes.
XHTTP is a node-owned H2 transport in proxy/transport/xhttp/ (browser, preparation, request, response, runtime, session, stream, upload); requests without a configured User-Agent carry Xray's Chrome fetch() headers; gRPC and XHTTP share the H2 byte-queue tracking in proxy/transport/h2_io.rs, and runtime/pooled.rs owns the pooled-session lifecycle dispatch (AnyTLS, VLESS, XHTTP). Per node generation there are 128 logical flows and, per peer (upload, plus a GET-only download peer from download settings), at most two reusable carriers (a draining carrier may overlap its replacement), 128 request slots per carrier, 16 KiB streaming writes, and 256 KiB stream / 4 MiB connection receive windows; each packet-up flow has at most eight outstanding POST responses, and only VLESS holds the process carrier permit. Each carrier retains up to 2048 locally reset requests (16 admission windows) for h2's default one-second in-flight-frame grace period and keeps its bounded default lifetime budget of 1024 protocol-error resets. A speculative UDP candidate publishes its carrier only at winner commit, whatever the multiplex path; a draining carrier still publishes drain-only. stream-up shutdown completes once the request END_STREAM is flushed while its response keeps draining, and any later status or reset still fails the flow. Never replay application bytes after HEADERS acceptance.
Score keeps business reliability separate from event-timed performance and configured-probe cohorts; never add overlapping global/family/exact completions. Live accepted progress must not multiply terminal outcomes or re-add final byte totals. Neutral cells stay in bounded LRUs to preserve in-flight incarnations and trial recency; admitted business reporters survive reload, but probe baselines are invalidated and old probe publication is fenced. TCP establishment orchestration stays in control/connection/tcp.rs, dial/admission in tcp/dial.rs; one Score replacement shares the original deadline and recorded final-edge provenance, never display-chain authorization or application replay. Score tests belong under group/score/tests/.
UDP establishment orchestration stays in control/connection/udp.rs, candidate preparation and shared-source path selection in udp/dial.rs; endpoint/driver publication and the first application send remain in the initializer.
URLTest's fresh retry deadline preserves any admitted original Score identity; an unbegun primary has no continuation, while actual admission refusals remain terminal.
Every pool-bound pending Score attempt, including ordinary retries, must still belong to each captured group/network pool at begin. Missing or departed membership cancels pending work and refunds reservations before any stale/unscored path. Unbound stale observation factories may proceed unscored only without a reserved token; preserve their identity and publish no current currency/evidence. Never downgrade invalid optional work into a free challenger dial. Continuations cannot earn in a new group/network/family; sources.recovery counts all continuations, including DNS fallback, UI redirects and subscription redirects. Reload refunds pending work but retains started in-flight suppression until settlement/TTL. DNS lifecycle admission is synchronous; only physical-dial admission may wait before I/O.
QUIC node provenance belongs to actual proxy-carrier owners, never every quinn::ConnectionError; packet-backed DNS endpoints preserve their adapter's terminal cause separately from end-to-end DNS errors. Project it only onto typed endpoint loss, not buffered reset/EOF, remote close or malformed H3 responses; address retry aggregation must retain the cause. H2 stream/user errors and active-session AnyTLS TCP SYNACK timeouts are target/flow-scoped; silent-session/UoT service faults remain node-scoped. VMess zero-byte response-header EOF stays ambiguous I/O, while partial/malformed headers retain carrier provenance. XUDP END|ERROR closes a shared multi-target source and has no single-target attribution.
Score verification reports scoped empirical observations, not a statistical error guarantee or optimality certificate. The same evaluator identifies availability/response gaps, schedules bounded real-flow validation and publishes readonly pairwise response relations; missing transfer creates no work and waits for actual offered load. Keep practical equivalence, provisional forwarding and observed usability separate; there is no group-wide comparison claim. Relations expire with their response metric; API reads cannot spend validation budgets or mutate counters.
Score trial suppression requires an actual ordinary escape to a different leaf, not merely a failure/ineligibility reason label. Configured health feedback carries the real restart-required probe interval into immutable cohort identity; keep four-report qualification, cadence-aware checked retention and weaker-side freshness without widening business windows or adding probes. Common response targets qualify before the canonical cap, independent of measured values; directional metrics use that same cohort. Partial matched-target coverage may still inform promotion and relations but must keep the response gap pending.
Readonly relations are independent of completion-dependent switching margins and the action heuristic's millisecond floor: they read the selection's original promotion pairs and classify only a fresh qualified response with the inclusive symmetric 10% band. Reliability, directional and holding protections belong to ordinary selection, not relations.
Score owns one bounded serving pool per group/network, shared by all parent routes and targets. Demand-sized k = 1 + ⌊D/128⌋ within 3–25 is additionally capped by ⌈√n⌉ + 1 (minimum 3); D is original business projected to the evidence half-life, q = 16. All ordinary, first-choice, escape, recovery and optional picks stay in-pool; no k + 1 winner override. Bootstrap reserves the ordinary first-choice winner within k, and reranking prioritizes ordinary eligibility before utility/probe ties so unqualified peers cannot displace the only usable service. Three node-wide failures or authoritative health exclusion can replace a member inside the same capacity. Preserve absent direct members; immediate subgroup names (not configurable UUIDs) identify representative slots and replacements cannot accumulate stale leaves. Selector Apply must reach its chosen child even when Peek has no visible member. Captured ordinary-pool obligations are checked again at begin, including after reload; only that owner's explicit final is exempt. Already-begun work continues, while a new retry must revalidate membership. Readonly uses committed members or a temporary cold projection and cannot mutate them. A rotation member selected for ordinary service trades places with a ranked member without changing membership; its replacement gets a fresh rotation interval. TCP/UDP remain separate, and active connections can retain retired members. Keep borrowed group-key lookups on the admission path, original budgets, normal rotation and no-substitute recovery.
Full child resolution may withdraw its retained via slot when the chosen path has no eligible candidate; retry-only omissions cannot. IPv4-before-final preflight derives temporary pool membership through the same path under current authority, without committing pools, counters or work. Public Peek remains committed-only after initialization.
Optional work has one dispatch walk, shared with the readonly question/action/wait: evaluated challengers with an open question (recovery, availability, a pair when ordinary selection could compare them but the selection's original pair lacks a fresh non-partial business response of the scope newer than its degradation, qualification), untrained first, then most progress toward that question, then least recently selected. Each member has at most one unanswered trial per open question and target (qualification counts across targets); except for recovery, a member is dispatched only while its completions plus unfinished work stay below the selection's completions, so cold exploration starts after the selection's first completion. Configured probes never settle a pair question; there is no joint alignment across challengers. A budget refusal ends the walk, an in-flight refusal tries the next member, and recency advances only when attributed work is admitted at begin.
Trial settlement preserves historical cost/outcome counters after reload, but only currently configured (group, node) members contribute policy yield. Removed members cannot pause or accelerate replacement funding; retained members may contribute across authority changes.
Out-of-pool members receive no new ordinary or optional selections. Previously reserved policy work retains its token, identity and TTL checks but must also revalidate current serving membership before begin. Probe baselines remain available, while comparison-cell admission normally follows the evaluation set, with exceptions for up to four recent Apply winners and initial/no-initialized-set collection. Recent failure exclusion removes an ineligible member from pending validation; exclusion is not measured equivalence. Response degradation compares only the same exact target; aggregate comparisons reopen on carrier pressure, not mixed-target spikes.
Observed availability uses four distinct targeted Traffic reporters with eligible RX after setup/TX per uninterrupted cell cohort, not terminal completions. Cell epochs and per-reporter/per-cell credits fence failure, reload, silence of at least 60 seconds and incarnation replacement; clones, repeated RX and settlement cannot multiply credits. Neutral settlement may flush eligible RX only at its actual event time. First post-failure RX clears exploration delay for funded half-open work; four own-cell post-failure reporters clear its hard episode and grant current recovery qualification without resetting numeric history. Availability alone never grants cold/reload-only qualification, and another target's aggregate recovery cannot supply exact credits.
Shared-source replies may precede sender-task TX bookkeeping. Only the first successfully accepted positive send may reconcile that reporter's already delivered RX at or after its serialized send start and setup completion; capture start after source-gate waits, preserve actual RX time and all cell fences, and never turn queued/failed/retired sends or ordinary TX-only callbacks into receive evidence.
TCP copy/splice relay errors retain socket-side provenance and their original I/O cause. Only client-side disconnects (ConnectionReset, ConnectionAborted, BrokenPipe, NotConnected, UnexpectedEof, TimedOut, HostUnreachable, NetworkUnreachable) settle Score as cancellation: preserve factual RX and prior failures, never grant success or clear backoff. The same upstream errors, protocol errors, and unclassified local failures keep their existing failure treatment; connection-error telemetry remains unchanged. Never infer Score neutrality from log severity or error kind alone.
Score ordinary incumbent protection is separate from verification. Keep first-choice utility and immediate escape from ineligibility/unresolved failure inside the shared serving pool. Target failures retain numeric outcomes but mutate only exact hard state; typed node/carrier faults and unknown pre-setup/targetless failures remain node-conservative. Dependent cells inherit node incarnation, failure time and shared-source episode highwater; late fanout counts flows without refencing a recovered episode. Probe failures invalidate only their current slot, unrelated target failures never invalidate probes. Preserve typed causes through shared writer closure, child fanout, cancellation cleanup and QUIC-stall classification. RX recovery respects failure/reload and started-cell fences; publication is event-driven and capped at once per second per reporter. Ordinary cold qualification still needs four effective completions, and historical reliability/hold maturity use actual decayed counts without overlapping sums. Healthy promotion compares every eligible challenger in the evaluation set against the fixed incumbent, using eight canonical equal-weight common targets and 15-second blocks expiring at start+60s; pair results are indexed by node, never found by a member-by-store scan. Currency obeys spent + reserved <= B + E, where each original start adds 1/q to E with q = 16, or q = 8 while the group/network's decayed original business (five-minute half-life) implies at least 2 flows/s and the scope has ≥3 recent trial outcomes (ten-minute half-life, decayed weight > 2.5) at ≥80% success; target refusals are not yield outcomes and reload forgets yield. Behind an observed-usable selection, scopes under 20% recent success pause optional trials (≥2 recent failures wait for decay, one allows a single trial in flight; a ledger refusal like exhausted credit: each refused candidate counts as budgetBlocked and reads as a budget wait, an in-flight member reads inFlight; exploration continues without a usable selection, recovery unaffected). B is frozen and earned credit caps at eight; node-work spends before DNS/admission, begun cancellation never refunds, retries/nested recounting never mint credit. Keep readonly relations distinct from promotion, and logical memory distinct from RSS. ordinarySwitch excludes first choice/trials/Peek and is distinct from switchFlap. No per-packet logs or exported target identities.
Score carrier pressure is advisory node-to-proxy evidence, never business outcome, target performance or ordinary UDP loss. Runtime-owner weak binding and active-authority/publication-time fences own admission. Physical TCP uses length-checked borrowed TCP_INFO with event-driven one-second gating; QUIC reuses its existing monitor after confirmation/publication and resets peer/counter baselines. Shared carriers publish sustained episodes, not one event per logical flow. Health-filter family is not socket identity; hints reopen node-scoped questions only for carrier-backed networks, excluding native Shadowsocks UDP and unobserved raw SOCKS/direct paths. Preserve validation budgets, backoff, utility, qualification, pool liveness, Vision Direct and terminal/health semantics. carrierPressure and carrierValidation are readonly diagnostic counters, not loss rates.
carrierRttPressure and carrierLossPressure count the reason at fresh-hint admission; a combined episode increments both but only one carrierPressure. Duplicate/stale hints add no cause counts. These are overlapping diagnostics, not transport identities, packet loss rates or additional business failures.
Build and test commands
Rust workspace
cargo check
cargo build --release # whole workspace (needs cmake + C compiler + libclang for boring-sys)
cargo build --release -p honk-core # engine (default features: clash-api, mimalloc, rprx; mock eBPF)
cargo test --all # full suite (see current validation guidance below)
The root rust-toolchain.toml pins the host compiler; crates/honk-ebpf/rust-toolchain.toml pins the eBPF compiler and components. Real-eBPF and standalone eBPF builds: .agents/rules/real-ebpf.md. CI and releases consume the same files: .agents/rules/release.md.
Justfile (preferred for day-to-day dev)
| Recipe | Purpose |
|---|---|
build / check / lint / fmt / fmt-check |
cargo build --release / check / clippy --all --all-targets --features honk-core/native-ui,honk-core/udp-bench -- -D warnings / fmt --all / fmt --all -- --check |
test-routing |
Complete pre-provisioned floor-kernel VM gate, including compiled routing goldens and failed-publication preservation; prerequisites in honk-real-ebpf-tests |
test / test-ci / test-core / test-config / test-ebpf |
Test suites (test = full workspace; test-ci = nextest CI profile with honk-core/native-ui, per-test timeouts and JUnit; test-core = core + outbound unit/integration tests; test-config = config unit/integration tests; test-ebpf = honk-ebpf-common only) |
test-netns |
Depends on test-routing, sharing its single disposable-VM run of routing, real NFQUEUE/eBPF, ownership, lifecycle and exact SO_MARK tests |
outbound-ci / outbound-ci-e2e |
honk-outbound gate (ci/outbound-ci.sh: fmt + clippy + honk-config & honk-outbound suites; ...-e2e adds live hy2 e2e via HONK_HY2_SERVER=) — run after every outbound change |
dns-ci |
DNS subsystem gate (ci/dns-ci.sh: fmt + clippy + honk-config + honk-core dns/control + honk-outbound suites) — run after every DNS-path change |
build-core / build-core-ebpf |
honk-core with ebpf feature |
build-musl / build-musl-embedded-ui |
Static musl build (x86_64-unknown-linux-musl, for VyOS/Debian) via the ci/zigcc/ci/zigcxx zig wrappers + link-self-contained=no (needs zig 0.14+); takes a features argument (default ebpf,native-api); -embedded-ui fetches the pinned doona unless HONK_DOONA_DIR is set and builds ebpf,native-ui |
build-ebpf |
eBPF object standalone (nightly, bpfel-unknown-none) — warns when RUSTFLAGS is set (it overrides the crate's --btf rustflags) and verifies the object actually has .BTF (aya refuses BTF-less objects) |
run-debug |
Build with ebpf, clean previous state, run with config.dae + external object |
run-dae |
Run with config.dae + --mock-ebpf |
debug-status / debug-config / debug-alive / debug-stats / watch-debug |
Query the clash HTTP API on :9090 (/version, /configs, /proxies, /group/{n}/delay, /stats, /connections) |
bpf-progs / bpf-maps |
Inspect loaded BPF programs and pinned maps |
deploy-vyos HOST=... |
musl build + scp to a VyOS router |
clean / clean-all |
cargo clean / stop honk-core, remove dae0/daens, ephemeral BPF pins and policy routes while preserving UDP_DECISION_SEQUENCE |
cycle |
clean-all + build-core |
watch-core |
cargo watch rebuild |
Removed run / deploy / docker* recipes called absent scripts/debug-local.sh / scripts/deploy-gateway.sh / Dockerfile / docker-compose.yml (Repository layout).
outbound-ci runs all-target Clippy and crate test suites in separate rprx-off and rprx-on invocations; the config suite runs once. The weekly/manual public-vless-loopback lane separately runs the two public ignored vless_udp official-peer cases, the ignored official Vision uplink Direct case and the ignored shared-source sing-box matrix with pinned executables, not the legacy external-mask test.
Current validation guidance
Do not treat dated pass counts as repository status; use current command output and CI. just test-routing and just test-netns use the same complete pre-provisioned disposable-VM gate. The routing-test object, toolchain and VM environment must be prepared as documented in honk-real-ebpf-tests; do not substitute host execution or spoof VM markers.
just test-ci requires cargo-nextest and selects .config/nextest.toml's ci profile: no retries, a three-minute per-test timeout and no fail-fast. JUnit is written to target/nextest/ci/junit.xml; CI uploads it on failure. Plain cargo test remains supported.
env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY \
cargo test --workspace --no-fail-fast
cargo clippy --workspace --all-targets --features honk-core/udp-bench -- -D warnings
Group-policy/scorer changes should run cargo test -p honk-config group_policy, cargo test -p honk-outbound group::score, and focused core Score/Clash tests before the workspace gate (Score needs no feature flag).
For UDP, run focused honk-outbound SOCKS5/group, honk-nfqueue parser/verdict/rule,
and honk-core control/NFQUEUE/token-transition/endpoint/reload/warm-up/Clash /stats
tests before the workspace gate. Held-packet changes also require just test-netns:
only the ignored root NFQUEUE test proves real nftables/queue/verdict semantics,
not the unprivileged suite. Deployment A/B needs real eBPF/netns/upstreams and the
bench lab harness. TLS backends and the HTTP-download exception: Technology stack.
routing::tests::test_geosite_* need geosite.dat/geoip.dat. Both tests call use_repo_geo_assets(), which points DAE_LOCATION_ASSET at the checkout root, so files at the top of the checkout are the quickest local setup; otherwise the loader falls through the documented geo asset search order, which is how CI's /etc/dae install works, and the tests fail for a reason unrelated to the change under test.
Unset HTTP_PROXY/HTTPS_PROXY/ALL_PROXY so HTTP clients do not proxy loopback fetches.
The maintainer's REALITY interop lab: .agents/rules/maintainer-lab.md (not required for contributions).
The documented sing-box 1.12 / MetaCubeX-uTLS 1.8.0 REALITY lab peer buffers
8192 bytes of target TLS records including framing; this is server-version-specific,
not a universal honk certificate limit. Earlier dl.google.com / www.microsoft.com
size observations are historical, not a maintained target allowlist.
Code style guidelines
- Rust source files do not carry SPDX/copyright headers; licensing and attribution live in the root
README.md/LICENSE. - Comment discipline (feat/analyze-dns): readable code; comments explain "why", never "what". Allow module
//!purpose/non-obvious architecture, public-item///, and short rationale/invariant/wire-format/upstream-parity/past-bug comments. Narrating/restating code is a defect. Ordinary logic should have near-zero comments (seecrates/honk-core/src/dns/runtime.rs); prefer descriptive names/small functions. Before closing each work phase, review touched comments and delete/rewrite stale behavior descriptions; stale comments are defects. - Commits:
type(scope): one short imperative line—feat|fix|refactor|perf|test|docs|style|bench(<area>), no body, no markdown. Each commit stands alone and leaves the tree building; multi-part work is more commits, and fixups are squashed before pushing rather than pushed. - PR bodies: English, one short paragraph under each of
## Problem,## How I fixed itand## Verified, in that order: what is wrong, what changed, what was checked — not the reasoning that led there. Link long evidence; do not paste it. - Prefer
anyhow::Resultfor application/binary code andthiserrorfor library error types. - Use
tracingmacros for logging; prefer structured fields (info!(network = "tcp", outbound = %name, ...)). Levels follow frequency × actionability: ERROR only when configured function is lost until an operator acts (committed-degraded activation, process exit, permanent subsystem death, invariant breach); WARN once per entered degraded state (fallback, ceiling, node/group unavailable, rejected candidate with the old config intact); INFO for low-rate lifecycle, operator outcomes and recovery; DEBUG for single connection/request/query outcomes and periodic maintenance. Log a failure once, at the layer that owns its stats/Score/recovery; repeat a persisting state at DEBUG, not per tick. A failure that repeats per query with no episode boundary (DNS SERVFAIL, singleflight saturation) useslogging::warn_throttled!: WARN at most every 10 s per site. Native/api/v1/logs, Clash/logsand the console all receive these levels. - Use
tokioasync/await andtokio::select!for long-lived loops. - Kernel/userspace structs belong in
honk-ebpf-common; follow its stable#[repr(C)]layout and coordinatedhonk-ebpf/honk-coremap-writer change rules. - Follow
cargo fmt --alland keepjust lint(all targets withhonk-core/native-ui,honk-core/udp-bench) andcargo clippy --workspace --all-targets --no-default-features --features honk-core/udp-bench -- -D warningsclean. - Claims need their line. A consequence stated in a PR or an issue names the code producing it, or is narrowed until it can; say what you did not check. Line numbers come from
origin/main, not your working tree. - Read to the end of the path before describing a defect. The trigger, the consequence, and the absence of a thing are each bounded by code you have not opened yet: the callee, the caller, the consumer that clamps the value, the search that would have settled it.
- Fix where the paths converge, not where you first saw the failure: a guard on one loader leaves its siblings failing open.
- A check that could not run did not pass. If a gate is missing, errors, or produces no output, say so; empty output reads exactly like a clean run.
- Stop before touching an area
CONTRIBUTING.mdreserves, before anything leaves the machine, and before discarding work someone else may want; otherwise continue. - Match the surrounding file's idioms; make minimal, scoped changes (no opportunistic cleanups).
- Documentation language: code comments and
doc/en/docs are English; user docs are bilingual (README.zh.md,doc/zh/) — update both when you change documented behavior.
Testing instructions
- A new test must fail without the change. Remove the production hunk, run it, read the failure; a test that passes either way is not evidence. Read what already covers the behaviour first — several deliberate oddities here are pinned by one test. A deletion needs no test of its own.
- Say which gates you ran and which you did not. Running a subset is fine; reporting no limits after running a subset is not.
cargo test --all: unprivileged default workspace unit/integration suites using mock eBPF/loopback where appropriate.just test-routingand dependentjust test-netnsshare the full isolated floor-kernel VM gate, including routing goldens, failed-publication preservation, real NFQUEUE/eBPF and guarded root-cgroup fixtures.- Test locations:
.agents/rules/test-locations.md. - Older standalone netns/podman scripts mentioned in stale docs are absent; use the supported
just test-netnsgate above.
Notes for agents
Configuration contracts (settings, dialect, honk-tool): .agents/rules/configuration.md. Deployment and security-sensitive paths: .agents/rules/deployment.md, .agents/rules/security.md.
Shared eBPF/honk-core constants and #[repr(C)] structs in #![no_std]; aya is non-BPF-only for Pod impls. Layouts and map key sizes must agree: change types/constants together in this crate, honk-ebpf, and honk-core map writers.
- Choose commands for the owning crate: workspace
cargoskipshonk-ebpf, which has separateCargo.lockand nightly-only target. - Change eBPF map layouts, state transitions, marks and statistics keys together in
honk-ebpf-common,honk-ebpf,honk-coreand theirhonk-nfqueue/honk-toolconsumers; preserve theUDP_DECISION_SEQUENCEABI and cross-restart token uniqueness. - Invariants: IPv4 flows are stored as
::ffff:<ipv4>(network byte order) everywhere; all wire structs are#[repr(C)].DnsCacheEntryandDomainKeydo not exist (domain routing usesDomainRouting; DNS caching is purely userspace). ABI assertions and focused token/state tests protect the live layouts. Userspace has noPARAMstatic; only the kernel'sGlobal<DaeParam>is configured throughEbpfLoader::override_global. Preserve the legacy 12-byte raw-token ABI across cleanup/restart; startup validates without rewriting. At generation boundaries, eBPF stays sticky-exhausted until fenced userspace rotation. Ring events prompt detection; locked periodic reads are the lossless backstop. One synchronous private map-in-map grace barrier drains pre-fence non-sleepable readers; canonical tuple fences exclude new accesses. Rotation requires an empty candidate-through-3 suffix across conn state, handoff, redirect andRetirementFence.decision_token, never its operation owner. Follow NFQUEUE terminal ordering and fencing; preserve partial deletion counts, both operation/release errors and fatal fencing of unresolved ownership. Complete scans end at terminalENOENT, and admitted cleanup must remain joined after warnings.ActivateDirectis the sole grace-free terminal commit: an in-placeEXIST|F_LOCKupdate of frozenDirectArmedstate that requires both auxiliaries to be absent.ArmDirect,ActivateProxyandBlockkeep the fence and one grace per batch; never let a reclaim reach an element a pre-fence reader may still hold. Preserve backend write lock → correlator cell lock order and drop the backend lock before endpoint kernel handoff. Commit leases and their original deadlines remain owned across caller cancellation.FlowMapValue<T>adds a native lock at offset 0 and payload at offset 8 to conn/redirect/handoff maps (stored sizes 80/48/80; payloads 72/40/72 bytes). These tuple elements are never replaced or physically deleted by the kernel: Linux can recycle them before an RCU reader ends. Take coherent locked snapshots/projections, compare captured identity during locked mutation, and call no helper under lock except unlock.flow.rsandauxiliary.rsown these boundaries. Engine snapshots use locked reads; external CLI tuple enumeration requires bucket-protected locked batches without unsafe singleton fallback.honk-core'sebpf/map_snapshot.rsowns the one userspaceBPF_MAP_LOOKUP_BATCHcursor/count traversal for the engine and CLI; adapters keep typing, capability and fallback policy. Validate actual map BTF wrappers; preserve the 12-byte UDP allocator. Preserve the shared nonwrapping TCP/UDP incarnation domain, forward-SYN-only publication and accepted-child proof before routing, pinning or cleanup; TCP ownership defines the classification rules. Exact native pins belong to each accepted guard, not the tuple's latest occupant, and janitor rechecks them under backend write ownership.honk_tcp_passiveis a required root-cgroupsock_opslink; startup and listener publication fail without it, and a legacy flags=0 program already holding that cgroup's slot refuses startup. It acts only onPASSIVE_ESTABLISHED_CBfor sockets whose netns cookie equalsTCP_DAENS_NETNS_COOKIE(fromSO_NETNS_COOKIEof a daens socket; zero disables), takes the ISN asrcv_nxt - 1, and under the existing locks validates tuple, ISN,ORIGINAL_INTERCEPT, conn/handoff/redirect incarnation agreement and handoff age, but not Active (TC marks Closing on a FIN/RST it can see before, or on, the handshake-completing segment), before onebpf_sk_storage_get(F_CREATE)of the completeTcpSocketBinding. It always returns 1 and counts storage failure. Keep it stack-only with family-separated#[inline(never)]constant-offset ctx reads built from per-word volatile loads (a merged copy ofremote_ip6failed the 6.12 verifier). TCP ownership needs no kernel BTF, ftrace,bpf_probe_read*in mandatory TC programs, or built-in IPv6; external raw BTF stays mandatory at startup (loader target BTF, pname/receive-trace offsets), and receive tracing still needs in-kernel BTF/ftrace and degrades without them. Owned daens disables and verifies cookies, migration and Fast Open; only the absent optionaltcp_syncookieskey is tolerated, never inspection/write/verification failure. Failed unpublished UDP claims retain their actual token asAborted, never mutate completed states, and retire matching auxiliaries before conn state. Only actual conn-deletion evidence authorizes exact endpoint retirement, including partial progress before an error. Stateless auxiliary refresh may overwrite only token/incarnation0/0; unknown-peer fallback grants neither renewal nor attribution. Keep NFQUEUE cold reconstruction under backend-owned admission checks; see datapath ownership. Occupancy calibration requires a complete traversal and fresh counters; telemetry failure must not stop sweeping or relax pressure. Cleanup and admission-pressure publication errors remain fatal; janitor policy owns cadence and thresholds. - UDP transport invariant: ordinary production endpoints use
PacketTransport; source-shared protocols use core-owned source transports with endpoint send views and one receiver: concrete VLESS XUDP/Mux.Cool, Hysteria2 and TUIC arms, and one genericSharedarm for everyMultiTargetTransport(Shadowsocks, Juicity, SOCKS5, Trojan, AnyTLS, VLESS UoT v2 and H2MUX), selected through the protocol registry's shared-source slot. Tunnel handlers frame datagrams directly: Trojan, native VLESS UDP, AnyTLS and VLESS UoT v2 (non-connect, address per packet), VLESS H2MUX (PacketAddr), VLESS XUDP/Mux.Cool, Shadowsocks, TUIC/Hysteria2, and Juicity. Direct and SOCKS5 hide raw sockets behind the same contract; no loopback bridges remain.UdpEndpointPoolretires dead transports rather than black-holing flows. The core source index is keyed by reused runtime identity, normalized client, protocol/UDP path, andActualPeerorRewriteTo(original destination). It owns one logical protocol association, one receiver, and multiple endpoint send views per scope; the full(client, destination)endpoint map remains authoritative for routing, decision token, and per-flow Score. An occupied wrong-owner,Initializing, orRetiringentry is a drop, never a foreign reply. Only an absentActualPeerkey may use foreign-reply delivery, without per-flow Score; domain rewrites stay pinned to their original destination. Source ownership and joined shutdown of every non-VLESS protocol work withoutrprx; only VLESS alternatives require it.MultiTargetTransportassociations carry every destination of one client source on one logical association (one SS2022 session with a single session ID, packet counter and replay windows; one Juicity stream; one SOCKS5 control connection and relay; one Trojan associate stream; one non-connect UoT v2 or H2MUX PacketAddr stream) and return the server-reported real peer fromrecv_packet: IPv4-mapped peers are IPv4, a domain source is accepted only as the captured domain and port, any other domain is dropped without DNS (stream protocols consume the frame whole), and an unknown address type stays terminal; undecodable or unprojectable Shadowsocks datagrams still drop only themselves. A per-packet destination name is sent only when it is exactly the name the association was dialed by, otherwise the numeric target (Shadowsocks, SOCKS5, Trojan, AnyTLS, VLESS UoT/H2MUX; Juicity forwards the supplied name and has no real-peer evidence): real servers (sing-box) fix the destination form by the first packet and drop the association on a mismatched spelling.send_packetandsend_toshare one unboxed helper;confirmedreaches the transport only on a view's first send andadmittedmeans the datagram reached the wire path or writer queue; a send that times out beforeadmittedis packet-local congestion whatever the carrier, until the source's uplink stall limit below. Partial-frame timeouts of reliable-stream carriers (Trojan, Juicity, AnyTLS) stay terminal for the whole source, and a frame write cancelled halfway (for example by a retired view) poisons the Trojan, Juicity, UoT and H2MUX stream (FramePoison) so the next send fails with the typedFrameInterruptedinstead of extending a torn frame; core retires the source neutrally when a retired view caused the tear. A native UDP size refusal (EMSGSIZE) is a typed localInvalidSizerejection, not a transport failure.source.send_gateis the outer lock and backends hold only leaf locks beneath it, never calling core; the last view's endpoint permit stays held until the source receiver exits or another view binds. Explicit VLESSnativestays unshareable, and Auto keeps native UDP on 53/443 without Vision because Single XUDP measured about half the goodput and 1.9-3.3× the CPU per MB. The VLESS source ID is a runtime-lazy private keyed hash. Reusing a runtime and replacing only a carrier preserves it; replacing/restarting the runtime changes it. This preserves honk's per-source semantics, not Xray's global-ID identity or collision-free NAT. Hy2 Session IDs and TUIC association IDs belong to their actual QUIC connection; physical connection reuse does not merge distinct source associations. Late local callbacks are owner/token fenced, and no cancelled or ambiguous packet is replayed automatically. Hy2/TUIC retain concrete reply peers in the existing bounded reassembly entries; TUIC continuationNonewaits for fragment zero, including out-of-order arrival. Known captured domain/port projection is distinct from a foreign IP and never starts DNS. Keep TUIC zero-length datagrams and Hy2's existing empty-inbound rejection. Source QUIC tokens start only after the send gate but stay driver-owned through timeout classification; dropping a timed-out send future must not substitute token failure for timeout. Gate waits consume the existing deadline. Preserve datagram versus stream cancellation/congestion and keep VLESS-only empty-first/poisoned-child rules local. Capture terminal per-flow Score before synchronous health callbacks; shared-sourceDataUdphealth belongs to the source, so an unreplied view cannot demote an already-replied source. Preserve health-neutral policy/size/capacity rejection, packet-local congestion, idle-after-reply, retirement and shutdown; an uninterrupted 30 s run of unadmitted deadlines is a transport failure, QUIC retains its own path-health classification, andPacketRejection::Capacitystays terminal through wrappers, DNS retries and CLI projection.SharedErrorpreserves the causal chain for all waiters on DNS and reusable-session initialization. Terminal packet refusal must survive outer route retries, name-family aggregation, and fallible health/URLTest resolver hooks; never replace it with system/bootstrap DNS or a default probe target. Preserve ordinary-error and configured-literal fallback behavior. Authoritative and cold URLTest UDP preparation return genericPreparedUdpTransport<T>values. Only the selected value's fallible commit may publish and return itsArc<T>; losing/dropped preparations roll back. They share one absolutemax(10s, 4 × connect_timeout)deadline, including winner commit. Policy is checked at actual candidate admission; rejection terminates and drains without sibling/direct fallback. Deadline expiry drains started preparations; cancellation and never-started candidates are health-neutral, while completed transport failures still count. Endpoint publication and the separately bounded first send follow successful commit. resolve_group_filters: case-sensitivename(...)and dae-compatiblesubtag(...), supporting exact/keyword:/regex:.&&ANDs predicates with!negation; separatefilter:lines OR them.subtagmapsNode.subscription_idto current subscription tag. Rebuild filtered membership after refresh so stable IDs cannot retain stale provenance. Include all nodes only with neither node filters nor sub-groups.src/node.rs—Nodehas only shared identity/endpoint/provenance plus typedOutboundConfig; use variant accessors for protocols.src/node/vless.rsexclusively ownsVlessConfig,VlessUdpEncoding,VlessMultiplex,VlessUdpMux,Udp443Policy, normalization, path selection, and combination validation.src/node/protocol.rsowns the other protocol configs and shared TLS/stream/QUIC options.src/node/validation.rsowns intrinsic and collection admission. Sole serde adaptersrc/node/wire.rspreserves the compatibility flat TOML/YAML/JSON shape without becoming a second VLESS model.parser/diagnostics.rsattaches current node-entry source, line and ordinal to both share-link warnings and returned typed errors. Node tags must not be used as schema-field locations for these diagnostics.Node::derive_id()is the sole identity source: UUID v5 over normalized protocol credentials and dial shape. VLESS identity includesnetwork, UDP encoding, multiplex policy/concurrency, UDP/443 policy, transport, REALITY/flow, and encryption; changing these may change the ID. Assign after normalization at every construction entry.Node::default()returns nil, rejected by the runtime registry;Config::validaterejects ID collisions and unsupported protocol combinations. VLESS UDP permission comes only fromnetwork; encoding (Auto|Native|Xudp|UotV2) and multiplexing (Off|H2|Xray) are independent. Xray TCP and UDP concurrency normalize to1..=128; zero TCP means 8, negative disables TCP mux, zero XUDP follows TCP, negative uses the protocol UDP path, and positive XUDP uses a separate pool. Its UDP/443 policy isReject|Skip|Allow: reject applies even when no mux pool exists, skip returns to protocol framing and the Vision gate, and allow bypasses Vision's port-443 denial only for an actual UDP mux path. H2 padding is an H2 property. Vision always rejects TCP multiplexing, including with Encryption; UDP-only Xray multiplexing is legal. Without Encryption, Vision requires raw TCP with TLS 1.3 or REALITY. With Encryption, Direct in either direction removes only the AEAD layer and preserves the outer transport and random-XOR layer (XrayXorConnskip rule). Random-mode Direct copies at most the existing 8 KiB plaintext chunk per write; native Direct adds no wire-copy buffer. Encryption may use direct or Xray-mux paths but not H2 or UoT framing. Never infer a retry or replay from a failed combination. Vision pads the uplink and removes downstream padding; each switches independently. The dial sends the request with an empty long-padded first frame. Uplink application-data termination follows the complete TLS record boundary (handler/stream/tls.rs), carrying Direct only after a TLS 1.3 ServerHello with cipher 0x1301–0x1304 and a codec direct writer. Non-TLS/malformed input, early application data without an eligible ServerHello and undecided inspection-budget exhaustion use End instead. After uplink Direct the TLS/REALITY write half is marked closed (no alert, KeyUpdate ack or close_notify reaches the raw uplink); downstream Direct first drains decoded SSL plaintext. Unencrypted TLS/REALITY carriers (VisionSplice) lend their socket to the bidirectional splice engine once both directions are Direct, nothing is buffered and 256 KiB moved (relay/vision.rs); pipe setup failure or an unavailable/policy-denied probe before any bytes are staged resumes the same stream, one attempt per connection. Shared REALITY intent/key presence is resolved byTlsOptions::effective_reality_public_key; node admission and outbound parsing must not turn missing or blank keys with REALITY intent into ordinary TLS/plaintext.- VLESS runtime/pool ownership lives in
honk-outbound/src/runtime/vless.rsandproxy/vless/{handler,mux,cool}.rs; the control plane owns source sharing inhonk-core/src/control/udp_endpoint/source.rs. One process VLESS-carrier semaphore, carved from the startup FD partition before UDP endpoints and shared across reload and DNS forks, is authoritative. Its permits cover actual carrier I/O through active, provisional, draining, and idle task teardown. H2 keeps its own two-carrier/128-concurrent-stream bound and has no 128-open lifetime; Mux.Cool has no per-node two-carrier cap, admits at most the configured positive concurrency capped at 128 per carrier, and rolls a carrier after 128 issued IDs. The existing maintenance pass reaps unretained idle VLESS carriers; do not add a protocol timer. Resolve warm retention and runtime reuse byWarmRequirement::SessionorWarmRequirement::Udp; a runtime selected only by UDP Xray mux remains eligible for bare TCP use. Pool waiters register capacity notifications before checking availability. Detached attachment returns its first pool-owned stream permit; all releases, carrier publications, backend close/drain transitions and closed-carrier pruning notify waiters, including non-reserving warm offers. Bind each backend to its owning pool notification before publication or detached attachment. Source send start/completion, matching retirement intent, and endpoint/source-view retirement publication share the existing source-state mutex. Release transition guards before pool retirement or unavailable-health callbacks; never hold them across await. Positive availability reports retain their admission fence. Source retirement publishes its Score disposition with admission closure. The common endpoint Score finalizer preserves that disposition for bound views; never-bound or previously retired views retain their local result. Snapshot source state before reporting, without holding it across Score callbacks. - Before behavior changes, read
doc/en/design/overview.mdand subsystem siblings indoc/en/design/, plus config guide/referencedoc/en/configuration.md/doc/en/reference/. Update bothdoc/en/anddoc/zh/for behavior changes. - If you add or remove workspace crates, update this file and the root
Cargo.toml[workspace] memberslist. - README authorship disclosure: the maintainer focuses on eBPF; most userspace subsystems were largely AI-authored with partial review. Review userspace changes accordingly.
Runtime invariants (do not break)
- Bypass mark: initialize the process-wide effective
global.so_mark_from_daebefore network I/O (zero means default0x100; restart-required; validation rejects0xc8000000because daens routes TPROXY-marked listener replies locally). Dials/probes/DNS/bootstrap/HTTP/QUIC sockets and transparent listeners use that exact value. Nonzero direct rule marks userule_mark | CLASSIFIED_MARK, never OR the global value; Linuxip rulemust mask with0x3fffffff. WAN bypass accepts exact configured marks or classified-without-pending marks, not arbitrary bit0x100. Clear inherited listener marks on accepted TCP sockets. Non-DNS local-socket probing recognizes honk viamark == PARAM.dae_socket_mark; unmarked transparent listeners look like local services. Host-netnsdns.bindingress stays unmarked, not an exemption from LAN port-53 policy. Exact configured marks bypass LAN TCP/UDP policy too, including LAN-bound loopback. Bootstrap fallback uses/etc/hostsand marked DNS to the first numeric/etc/resolv.confnameserver, never unmarked libc NSS. - Anyfrom UDP replies: never reply from a transparent TPROXY listener; preserve original-destination addressing and keep client-only fallback free of outbound attribution or conn-renewal authority. UDP arriving from
dae0must not create reverse conn state; see reply ownership. - Netns discipline: stay in host netns, creating/serving
dns.bindthere. Enterdaensonly via scoped synchronousdaens::with_daens_netns; never.awaitinside because setns is per-thread. Save/proc/thread-self/ns/netunder a process-wide mutex; restore on every exit; failed restore aborts, preventing stranded workers originating dials in daens. Socket creation testsdaens::DAENS_READYset bydaens::setup_daens_namespace, never compat bind-mount existence. Unmount only this instance's tmpfs/bind-mount; deletedae0by creation-recorded ifindex, leaving same-named replacements alone. - Datapath admission: require all hooks, including
dae0_ingressin WAN-only mode, listener FD publication and receive-loop/NFQUEUE readiness before admission, and close admission before listener teardown. Drop only owned TCX links and preserve pass-through versus mark-owning finality. - NFQUEUE readiness and ownership: ordinary UDP staging and fragmented LAN UDP53 controller/raw delivery require ready queue ownership. Clear readiness, complete the synchronous kernel grace barrier, reclaim Preparing/Pending in fenced batches, then publish a fresh routing descriptor generation. Failed quiescence forbids READY until a complete fence succeeds.
ROUTING_GENERATION_SEQUENCEis a core-owned single-value persistent pin, separate from unchangedUDP_DECISION_SEQUENCE; reserve nonwrapping 20-bit values before publication/fences and preserve across cleanup/restart. Never reset it while host fragment queues may retain old carriers. No recompilation for descriptor-only fences. - Fragmented LAN UDP53: only first fragments needing controller/raw delivery defer to host native reassembly and queue 320; native direct-must/block/exact bypass retain their actions. Disabled/unready queues drop required fragments. DNS queue events use route/generation carriers, never ordinary token cleanup or conn-state. Admission epoch, receipt deadline and generation checks precede confirmed
NF_DROP; publish DNS/raw work only afterward. Validate UDP checksums with kernel partial-checksum metadata, reject identified bad payloads per packet, and retain fatal queue/envelope/verdict errors. Existing redirect tracking supplies anyfrom replies. TCP fragments are outside this path. - Token-checked terminal state: require token agreement across skb mark, conn state, handoff, redirect track, verdict cell, lease, endpoint/tombstone, backend transition. Direct marked
NF_ACCEPTfollowsArmDirect, which requiresPendingand retains the token through activation; activate only after every verdict succeeds.ActivateProxypublishes the final outbound and mark while retaining the provisional redirect track. Armed followers append only verdict guards, discarding payload without slow/endpoint admission. Proxy publishes before canonical dial/send. Stale cleanup fences the exact tuple, waits pre-fence readers, then revalidates; never overwrite/delete newer incarnations. - NFQUEUE lifecycle: fence readiness → quiesce stagers → reject ingress → drain all admitted work, including commits → detach producers → close queue → delete the owned table last; reload retains the joined commit pump. Ownership ambiguity stays fatal/fenced; preserve the allocator pin and the rollback-safe rotation rule.
- must/block are final: a matching configured
mustrule is terminal; Clash mode override never overridesblockormustresults. - Fail-closed on dead outbounds: preserve the health-gating exceptions, never introducing an implicit
directfallback or letting health bypass selected policy. Selector TCP/UDP must not substitute an unchosen sibling or bypass a chosen empty subgroup; the sole-leaf TCP recovery attempt follows the current Selector path. New flows routed to a dead outbound areTC_ACT_SHOTon LAN ingress and WAN egress. Only fresh TCP SYN publication is health-gated: established and cached/retransmitted TCP survive health changes, while UDP is gated per packet except native-direct offload and committed token-bound LANProxyredirects. TCP and UDP port 53 are exempt. Ordinary LAN TCP/UDP:53evaluates traffic policy even when an exact or wildcard local DNS listener exists; local-socket precedence applies only to non-53 destinations.mustsuppresses sniff-driven rerouting and preserves the selected direct/block/group action, not a blanket bypass. Do not synthesize interface-address routing rules or a replacement kernel allowlist; retain interface observation for topology/ECS/health. Gateway-native routing is explicit user configuration. Network events clear stale probe cooldowns and schedule immediate checks; other dead nodes stay closed until fresh success verifies recovery. - eBPF connectivity pushes are group-OR plus the sole-TCP-leaf exception: publish OR of reachable leaf states, including explicit nested
finaledges, into every affected ancestor group alive slot, with the last-resort exception above. One dead member must neverTC_ACT_SHOTan entire multi-leaf group. GroupManager owns nested final resolution; ordinary member lists remain separate from final-aware health, warm and Score reachability. Never substitute an unchosen Selector sibling or bypass a terminal protocol refusal. - Internal traffic is never proxied: own-link
169.254.0.0/16,fd00:686f:6e6b::/64. Broadcast/multicast passes through eBPF:dst_is_special()(crates/honk-ebpf/src/transport.rs) early-exits L2 broadcast/multicast MAC, 255.255.255.255, 224.0.0.0/4, 0.0.0.0, ff00::/8 in lan_ingress/lan_egress/wan_egress. DHCP/mDNS/SSDP never enter routing/conntrack; otherwise OpenWrt LAN DHCP breaks. Preserve non-DNS LAN local-socket precedence, including the TCP pure-SYN probe skip; destination 53 must not take that early return. - Reserved outbound indices:
0 Direct | 1 Block | 2+ user groups | 0xFC MustRules | 0xFD ControlPlaneRouting | 0xFE OR | 0xFF AND.