English
Data path
How an accepted connection gets to an outgoing one and how data flows over it.
text
inbound (protocol module, its own shard)
│ Metadata + Stream | PacketConn
▼
Dispatch::route_stream / route_packet / connect modules/system/dispatch
│ tracker.register → tokio task on the same shard
▼
route(): fake-ip → enrich → rule walk ── Sniff ──► ours-sniff (peek/read)
│ └─ Resolve ─► Dns::lookup
▼ Decision
Routing::outbound → Outbound::resolve_group (group freeze)
│ tracker.routed
▼
Outbound::connect_stream / connect_packet → Dialer (ours_api::dial, ours-mod-dial) → detour | socket
▼
ours-relay: relay_stream (copy/splice) | relay_packet (Moved)Inbound
An inbound (the ours_api::Inbound trait, crates/api/src/adapter.rs) is started by the kernel on every shard (Inbound::start, see Runtime): listening sockets of one reuseport group. An accepted connection is handed, before the protocol is parsed, to the least loaded shard (ours_runtime::balance) and lives on it until close. The inbound parses its own protocol, fills in Metadata (crates/api/src/session.rs: id, inbound tag and type, network, source, destination, user in Learned) and hands it to the dispatcher:
route_stream(stream, metadata)— a TCP-like stream;route_packet(conn, metadata, idle)— a packet stream with an idle timeout (by defaultUDP_TIMEOUT= 300 s, sing-boxudp_timeout);connect(metadata)— route and connect, but return the stream to the caller without relay (an HTTP proxy with several requests on one connection);inject(tag, stream, source)— hand a stream to the inbound namedtag(an inbound'sdetour), without a socket;inject_packet(tag, conn, source)— the same for a packet flow.
An inbound that reads the packets of all clients from one socket (tproxy, shadowsocks, direct) splits them into streams through ours_relay::udpnat::UdpNat (crates/relay/src/udpnat.rs): the first packet from a source opens a stream (push returns a new PacketConn, which the inbound passes to route_packet), the following ones go to its queue. udp_mapping decides whether the destination is part of the stream key, udp_filtering — who may reply, udp_nat_max (by default ours_api::options::UDP_NAT_MAX = 4096) bounds the table: a new stream evicts the one that has been silent the longest.
A transport with sessions (accept_session: HTTP/2 in grpc, http, xhttp) hands the inbound the session's streams one by one, and vless/trojan serve each with its own task on the shard where the session driver is running at that moment (Connection::shard, balance::spawn_at). The session driver is started with balance::spawn_movable and may move from a saturated shard to a free one (runtime.stream_placement, Runtime); the same holds for the client. An HTTP/2 stream (ours_h2::Stream) is Send: the session state is behind a Mutex, wakeups are tokio Wakers that work across executor threads; received DATA are slices of the driver's pooled buffers, which the relay frees on its own shard, and they return to the cache of the driver's shard.
Dispatcher
The only implementation is the dispatch module (modules/system/dispatch/src/lib.rs, module description). It holds ArcSwap<Routing> — a snapshot of what to route by (rules, outbounds by tag, final, reload policies, DNS, Host, inbounds by tag); reload replaces the snapshot as a whole.
For every connection:
tracker.register— an entry in the tracker before the task is started (the task's abort handle goes straight into the entry). Until the connection is routed, reload and statistics do not see it.translate_fake_ip— a fake destination address is replaced with the domain it was issued for; an unknown fake address closes the connection. Withreverse_mappingthe domain of a real address is looked up.enrich— the process and neighbour (MAC, hostname) lookups are done only if the rules need them (Rules::needs); the process is looked up only for a local source.- The rule walk:
step(crates/route-api/src/walk.rs) walks the rules up to an action that needs connection data:Step::Sniff—sniff_with: for a TCP socket the data is only peeked at (peek), so that it stays in the socket for splice; other streams are read and the data is put back in front (Prefixed), packets accumulate in a queue (Queued). The default timeout is 300 ms;Step::Resolve—Dns::lookupof the destination domain for the following rules;route-optionschange the metadata (address/port override,udp_timeout, reload policy, network strategy) and the walk continues;route,reject,hijack-dnsend it; with no decision —Decision::Default(route.finalor the first outbound).
Routing::outboundtakes the outbound by tag and callsOutbound::resolve_group: a group (modules/routing/group, group) returnsPinned— its choice, frozen for this connection (nested groups — recursively).tracker.routed— the connection is shown in the tracker with its outbound. If during sniffingRoutingchanged or a rule-set was updated (thegenerationcounter), the walk is repeated on the new snapshot with what has already been sniffed.
hijack-dns hands the connection to the DNS module (Dns::exchange): a stream — length-prefixed queries, packets — one at a time. In the tracker such a connection is attributed to the service outbound dns-out. reject (block) closes a stream with a reset (RST), drop — without RST; reply is not supported for TCP and UDP: the stream is closed without RST and an error is logged.
Outbound and dial
Outbound::connect_stream/connect_packet is implemented by the protocol module. It opens sockets through an ours_api::dial::Dialer that the dial module builds (ours_mod_dial::Dialer, modules/system/dial/src/lib.rs, dial) — the single place for detour, netns, bind, routing_mark, network strategy:
- with
detourthe connection is handed to an outbound fromDialTable(the tag table of the current configuration, replaced on reload); detour loops are caught by a stack of tags in a task-local; - without
detouraddresses are resolved throughDnsCell(the DNS of the current configuration); addresses from DNS are tried with Happy Eyeballs v2 (connect_staggered: families alternate, each attempt starts after the fallback delay or when the previous one fails), a given IP — one after another (connect_serial); interfaces are chosen byHostaccording to the network strategy, with a deferred fallback.
For a packet stream whose destination was changed by routing (fake-ip, override), the dispatcher wraps the client side in Translated: replies reach the client "from" the address it sent to.
UDP-over-TCP (crates/uot) is the sing v1/v2 framing for protocols that carry packets in a stream to a magic destination; used by the socks inbound/outbound.
Relay
ours-relay (crates/relay/src/lib.rs):
relay_stream— both directions in one task; each is copied through a pooled buffer (a buffer is taken only when there is data) until both ends are sockets the process does not need to look into (TCP, kTLS, the protocol has finished framing,Stream::Spliced); from then on —splicein the kernel. Each end states the buffer form it reads or writes in now (Splice::read_form/write_form,ReadForm/WriteForminours-net-sys), and one table in the relay (route) picks the path for the pair. How each form is copied is in ours-relay;relay_packet— packets in both directions until an error oridlewithout packets. The outbound side isMoved: reload may send a new outbound throughRedirect(ours-tracker), and the stream opens a connection through it and continues, keeping the NAT entry and the client.
The UDP stream timeout: udp.timeout from a rule (udp_timeout in the options), otherwise the sing-box timeout for the protocol (sniffed or guessed from the port), but no more than idle from the inbound (walk::udp_timeout).
Tracker
ours-tracker (crates/tracker/src/lib.rs) is the table of live connections, split into stripes by id so that shards do not fight over one lock. An entry holds the metadata, the outbound, the task's abort handle and, for packet streams, Redirect. An entry is removed when its Tracked (or the Guard of connect) is dropped. Reload walks the tracker (Dispatcher::reconsider) — see Reload. The dispatcher publishes the tracker as a service (Arc<Tracker>); it is read by the Admin API (Monitor, counters, rule traces).