Links, connectors and net types
Source files: 66 · checked against Etemenanki 46c12e4 · katana v6.0.0
Etemenanki/concepts/src/link.rsEtemenanki/concepts/src/net.rsEtemenanki/concepts/src/sniff.rsEtemenanki/concepts/src/relay.rsEtemenanki/concepts/src/core.rsEtemenanki/concepts/src/runtime.rsEtemenanki/concepts/src/client.rsEtemenanki/concepts/tests/runtime.rsEtemenanki/concepts/tests/client.rsEtemenanki/environment/src/dial/mod.rsEtemenanki/environment/src/routing.rsEtemenanki/environment/tests/integration/udp.rsEtemenanki/environment/tests/unit/routing.rsEtemenanki/protocols/src/flow.rsEtemenanki/protocols/src/core/mod.rsEtemenanki/protocols/src/sniff/mod.rsEtemenanki/protocols/src/socks/handshake.rsEtemenanki/protocols/src/socks/server.rsEtemenanki/protocols/src/socks/protocol.rsEtemenanki/protocols/src/socks/udp_link.rsEtemenanki/protocols/src/http/core.rsEtemenanki/protocols/src/trojan/core.rsEtemenanki/protocols/src/ss_legacy/core.rsEtemenanki/protocols/src/ss_2022/core.rsEtemenanki/protocols/src/vless/core.rsEtemenanki/protocols/src/vmess/core.rsEtemenanki/protocols/src/mux/demux.rsEtemenanki/protocols/src/hysteria/server/inbound.rsEtemenanki/protocols/src/anytls/core.rsEtemenanki/protocols/src/anytls/client/mod.rsEtemenanki/protocols/src/anytls/client/datagram.rsEtemenanki/protocols/src/sss/core.rsEtemenanki/protocols/src/sss/client.rsEtemenanki/protocols/src/sss/server.rsEtemenanki/protocols/src/transports/connect.rsEtemenanki/protocols/tests/support/pipeline.rsEtemenanki/protocols/tests/pipeline/transports.rsEtemenanki/protocols/tests/pipeline/socks.rsEtemenanki/protocols/tests/unit/socks/server.rsEtemenanki/protocols/tests/unit/socks/protocol.rsEtemenanki/protocols/tests/unit/http/core.rsEtemenanki/protocols/tests/unit/sniff/tls.rsEtemenanki/protocols/tests/unit/sniff/http.rsEtemenanki/protocols/tests/unit/sniff/mod.rsEtemenanki/supervisor/src/connector.rsEtemenanki/supervisor/src/topology/flow.rsEtemenanki/supervisor/src/topology/router.rsEtemenanki/supervisor/src/topology/plane.rsEtemenanki/supervisor/src/topology/outbound/mod.rsEtemenanki/supervisor/src/topology/outbound/freedom.rsEtemenanki/supervisor/src/topology/outbound/proxy.rsEtemenanki/supervisor/src/topology/outbound/udp_fanout.rsEtemenanki/supervisor/src/topology/outbound/dns.rsEtemenanki/supervisor/src/track/mod.rsEtemenanki/supervisor/src/track/metered.rsEtemenanki/supervisor/src/entity/id.rsEtemenanki/supervisor/src/entity/session.rsEtemenanki/supervisor/tests/unit/router.rsEtemenanki/supervisor/tests/unit/plane.rsEtemenanki/supervisor/tests/unit/session.rsEtemenanki/supervisor/tests/unit/track.rsEtemenanki/supervisor/tests/hot_swap.rsEtemenanki/supervisor/tests/tracking.rsEtemenanki/app/tests/integration/e2e_sniff.rskatana/tests/unit/e2e.rskatana/tests/unit/runtime.rs
Every crate that depends on etemenanki-concepts (2.1.2 at this revision) speaks one small, shared vocabulary. link.rs says what an outbound is and how one is dialed. net.rs says what an address and a user are. sniff.rs says what sniffing found. relay.rs holds two byte-copy futures for paths with no protocol in between. None of these modules resolves names, applies socket policy or routes. They fix the shapes that the server runtime, the client runtime, the dialers, the protocol cores and the supervisor plug into. etemenanki-app, the FFI and katana all run their connections through the supervisor, so they meet these types only through the supervisor’s implementations. katana 6 implements none of the traits on this page itself.
This page is for contributors who add a protocol, an outbound kind or a connector, or who change how the runtime treats links. It gives each type with its exact signature, says who implements it and who consumes it at 46c12e4, and ties every rule to the mechanism that enforces it and the test that pins it.
Responsibilities
Section titled “Responsibilities”| Module | Defines | Leaves to others |
|---|---|---|
concepts/src/link.rs |
DatagramLink, UdpOutbound, Outbound<S, D>, Connector, SocketConnector, SocketTarget, NoStream, NoDatagram |
Socket options, connect timeouts and DNS. The dialers in etemenanki-environment and the supervisor’s outbounds own those. |
concepts/src/net.rs |
UserAuthorization, NetworkUser<T>, DialNetwork, Remote, Destination |
Resolution. A Destination may name a domain, and whoever reaches it decides how to resolve it. |
concepts/src/sniff.rs |
SniffedProtocol, SniffedBehavior, Sniffer |
The sniffers (TlsSniffer, HttpSniffer), their byte budget and deadline. They live in protocols/src/sniff/. |
concepts/src/relay.rs |
UnidirectionalConnection, BidirectionalConnection, Relayed |
Timeouts and accounting. A caller wraps the future. |
Flow<T> in protocols/src/flow.rs is not part of the concepts crate. It appears on this page because it is the Target every server core in etemenanki-protocols hands its connector, and so it is where the net and sniff types meet:
pub struct Flow<T> { pub destination: Destination, pub user: NetworkUser<T>, /// What sniffing recovered from the flow's first bytes, when the inbound /// sniffs and the destination named only an IP. pub sniffed: Option<SniffedBehavior>, /// The client's address, when the inbound knows it. pub source: Option<IpAddr>,}
impl<T> Flow<T> { pub fn new(destination: Destination, user: NetworkUser<T>, source: Option<IpAddr>) -> Self; pub fn toward(&self, destination: Destination) -> Self;}
impl<T> Clone for Flow<T>;impl<T> fmt::Debug for Flow<T>;Clone and Debug are written out, so neither puts a bound on T. Flow::new starts with sniffed: None. For a UDP flow, destination is the first packet’s; later packets carry their own address through Effect::SendTo. The supervisor fixes T once for everything it serves: supervisor/src/topology/flow.rs → pub type Flow = etemenanki_protocols::flow::Flow<Principal>.
Who implements what
Section titled “Who implements what”| Crate | Implements | Consumes |
|---|---|---|
etemenanki-concepts |
DatagramLink for UdpSocket, UdpOutbound, NoDatagram and ProxyClientRuntime over a datagram codec. Connector for SocketConnector, for every matching closure, and for ProxyClientConnector. AsyncRead and AsyncWrite for NoStream. |
ProxyServerRuntime and ProxyClientRuntime drive links and call connectors. |
etemenanki-environment |
Connector<DialTarget> and Connector<SocketTarget> for Dialer; DatagramLink for DualStackUdp. |
Nothing on this page beyond the types it implements. |
etemenanki-protocols |
Connector<Destination> for TransportConnector and for sss’s SssConnector<C>, which wraps another; Connector<Flow<T>> for WgConnector, Hy2Connector and AnyTlsConnector; DatagramLink for SocksUdpLink<S>, WgDatagramLink, Hy2DatagramLink, AnyTlsDatagram (outbound role) and TunUdpLink, QuicDatagrams (transport role). |
Every server core names Flow<T> as its Target. The SOCKS inbound drives a Connector and a DatagramLink itself and uses BidirectionalConnection, as does an sss inbound’s fallback relay. |
etemenanki-supervisor |
Connector<Flow> for AppConnector and FreedomConnector; DatagramLink for ResolvingUdp, FanOutLink, OutboundDatagram, BlackholeLink, DnsUdpLink and MeteredDatagram<D>. |
It hands AppConnector to every runtime and to the SOCKS driver, and reads Principal out of NetworkUser::user_data. |
| katana 6 | Nothing in src/. Its tests define three connectors, TcpConnector, DirectConnector and RelayedConnector, in tests/unit/e2e.rs, and wrap TcpConnector in an SssConnector for their sss client. |
Destination, DialNetwork and Remote, which its lowering builds for the outbound servers in the spec it hands the supervisor (see Lowering inbounds and outbounds). |
How the pieces compose
Section titled “How the pieces compose”A server core decides what to open. The runtime asks a Connector to open it and gets back an Outbound: either a byte stream or a DatagramLink. From then on the runtime moves bytes between the core and that link.
flowchart LR wire["client transport"] --> rt["ProxyServerRuntime"] rt -- "Event" --> core["ProxyCoreDecode"] core -- "Effect::Open, target = Flow" --> rt sn["Sniffer result: SniffedBehavior"] -.-> |"Flow.sniffed"| core rt -- "Connector::connect(target)" --> conn["Connector"] conn -- "Outbound::Stream" --> s["AsyncRead + AsyncWrite + Unpin"] conn -- "Outbound::Datagram" --> d["DatagramLink, Addr = Destination"] s --> dest["destination or upstream"] d --> dest
The module docs of link.rs put it this way: the same traits serve both roles. A server core’s Connector dials real sockets, and a client core’s hands over the plaintext endpoint the application already holds. The traits therefore recur one level down. ProxyClientConnector is a Connector whose outbounds are ProxyClientRuntimes, and each of those dials its upstream through another Connector, TransportConnector. For a TCP flow routed to a proxy outbound, the dial futures of three connectors are polled in the connection’s task: the supervisor’s AppConnector, the outbound’s ProxyClientConnector (held inside ProxyClient), and its TransportConnector. An sss outbound adds a fourth between the last two, the SssConnector that wraps the transport in sss’s transform chains.
| Layer | Implementor | Target |
Stream / Datagram |
|---|---|---|---|
| Routing, for every inbound the supervisor serves | supervisor/src/connector.rs → AppConnector |
Flow (Flow<Principal>) |
Metered<OutboundStream> / FanOutLink |
| Direct outbound | supervisor/src/topology/outbound/freedom.rs → FreedomConnector |
Flow |
TcpStream / ResolvingUdp |
| Proxy outbound | concepts/src/client.rs → ProxyClientConnector, wrapped by supervisor/src/topology/outbound/proxy.rs → ProxyClient |
whatever its Make closure takes: the supervisor’s Flow |
ProxyClientRuntime<BUF, S, C> / ProxyClientRuntime<BUF, D, C>, where C is TransportConnector, or SssConnector<TransportConnector> for sss |
| sss’s transform chains | protocols/src/sss/client.rs → SssConnector<C> |
Destination |
TransformStream<C::Stream> / NoDatagram |
| Upstream dial | protocols/src/transports/connect.rs → TransportConnector |
Destination |
TransportStream / NoDatagram |
| Tunnel outbounds | protocols/src/wireguard/connector.rs → WgConnector, protocols/src/hysteria/connector.rs → Hy2Connector |
Flow<T> |
WgStream / WgDatagramLink, Hy2Stream / Hy2DatagramLink |
| AnyTLS outbound | protocols/src/anytls/client/mod.rs → AnyTlsConnector, with its pool of sessions |
Flow<T> |
AnyTlsStream / AnyTlsDatagram |
| Host sockets | environment/src/dial/mod.rs → Dialer |
DialTarget or SocketTarget |
TcpStream / DualStackUdp or UdpOutbound |
| Reference and tests | concepts/src/link.rs → SocketConnector, any closure, and the test connectors |
anything | anything |
The link stack the supervisor hands a runtime
Section titled “The link stack the supervisor hands a runtime”The supervisor’s outbound handler, supervisor/src/topology/outbound/mod.rs → Outbound, is not a Connector. One handler serves every flow routed to it, so its two entry points take &self and return boxed futures of closed types:
pub type StreamFuture = Pin<Box<dyn Future<Output = io::Result<OutboundStream>> + Send>>;pub type DatagramFuture = Pin<Box<dyn Future<Output = io::Result<OutboundDatagram>> + Send>>;
impl Outbound { pub fn connect_stream(&self, flow: Flow) -> StreamFuture; pub fn connect_datagram(&self, flow: Flow) -> DatagramFuture;}Each variant’s own link is put into one of two closed types: OutboundStream (Tcp, Proxy for any boxed ProxyClientRuntime, AnyTlsStream or DnsTcpStream, Wg, Hy2, Blackhole) or OutboundDatagram, a newtype over Box<dyn DatagramLink<Addr = Destination> + Send>. Target::connect_stream and Target::connect_datagram in supervisor/src/topology/plane.rs resolve a balancer to its member and return that plain OutboundStream or OutboundDatagram. AppConnector wraps a stream in Metered, which counts it as one flow; once that flow is killed, every later call on it, poll_shutdown included, fails with ConnectionAborted (the flow was killed). A UDP flow never reaches an outbound directly: it becomes a FanOutLink, which opens one sub-link per outbound version and wraps each in MeteredDatagram, the datagram counterpart of Metered. For a speed-limited user, Metered and MeteredDatagram also wait out the user’s debt before each read, write, send or receive, so either can return Pending for that reason alone.
A drain uses the same kill. When a drain policy closes an outbound version, Target::close_flows(&Tracker) sets the target’s drained flag and kills, through Tracker::kill_where, every flow whose outbound() is that version’s OutboundId. A flow still dialing then is not registered yet, so AppConnector::connect and FanOutLink, right after metering a new link, call target.close_if_drained(entry), which kills the flow when the flag is set. Either way the flow fails with the flow was killed. Supervisor::close_rerouted, which a front end may call after a route change, kills the same way, through Tracker::kill_where: every flow the current plane would send to another outbound than the one carrying it. The resolver’s own streams (RoutedDialer in supervisor/src/topology/outbound/dns.rs) are plain OutboundStreams, not metered, so neither reaches them.
Among the outbounds built on ProxyClient, the SOCKS outbound’s UDP side is the one datagram path that does not go through ProxyClientConnector: SocksOutbound::connect_datagram dials a control stream with TransportConnector::dial and runs SocksUdpLink::associate over it, binding the relay socket with UdpDialer::bind(AddressFamily::of(relay)). The client runtime page covers that path and the client runtime buffer sizes of each proxy outbound.
flowchart LR ac["AppConnector"] -- "TCP flow" --> m["Metered"] m --> os["OutboundStream"] os --> sl["TcpStream, ProxyClientRuntime, WgStream, Hy2Stream, AnyTlsStream, DnsTcpStream, Blackhole"] ac -- "UDP flow" --> fo["FanOutLink"] fo -- "one sub-link per OutboundId" --> md["MeteredDatagram"] md --> od["OutboundDatagram"] od --> dl["ResolvingUdp, ProxyClientRuntime, SocksUdpLink, WgDatagramLink, Hy2DatagramLink, AnyTlsDatagram, DnsUdpLink, BlackholeLink"]
Every layer implements the same trait as the layer below it: AsyncRead + AsyncWrite + Unpin for streams, DatagramLink<Addr = Destination> for datagrams. The runtime sees one link per key and does not know how many wrappers it holds.
FanOutLink routes each packet as self.flow.toward(to) on the plane that is current for that packet. It resolves a balancer to a member with resolve(prefer), preferring the member an earlier packet of the same route was sent through (the via a sub-link is filed under), so an association does not hop between members packet by packet. It keys its sub-links by OutboundId, never by a target’s address, which a freed and rebuilt outbound could reuse. Its poll_recv_from starts where the last receive stopped (next), so every sub-link gets a turn, and a newly opened sub-link wakes a receive parked on the link (recv_waker).
The routing plane page covers the plane and its targets, the outbounds page covers Outbound and FanOutLink, and the tracking page covers Metered, pacing and how a drain kills flows.
AppConnector::connect
Section titled “AppConnector::connect”AppConnector is the one connector the supervisor hands out. supervisor/src/serve.rs builds one per session from the plane cell, a FlowContext, the flow tracker and the session. The serving page covers what a session is on each transport. The SOCKS driver gets its connector through charging_datagrams(), so a UDP association’s payload counts toward the session’s wire bytes. Some connectors carry no session, for example a TUN device’s: a device admits no users, so there is nobody to close its flows for.
#[derive(Clone)]pub struct AppConnector { plane: PlaneCell, ctx: FlowContext, tracker: Tracker, session: Option<Arc<Session>>, charge_datagrams: bool,}
impl AppConnector { pub(crate) fn new( plane: PlaneCell, ctx: FlowContext, tracker: Tracker, session: Option<Arc<Session>>, ) -> Self; pub(crate) fn charging_datagrams(self) -> Self; /// The peer the listener captured, if it has one to give. pub fn source(&self) -> Option<IpAddr>; /// The session the flows belong to, if any. pub fn session(&self) -> Option<&Arc<Session>>;}
impl Connector<Flow> for AppConnector { type Stream = Metered<OutboundStream>; type Datagram = FanOutLink; type Future = ConnectFuture; // Pin<Box<dyn Future<Output = …> + Send>>}
/// What a FanOutLink files its sub-links under.#[derive(Clone)]pub(crate) struct FlowScope { pub tracker: Tracker, pub session: Option<SessionId>, /// The session's wire, when the sub-links' payload counts toward it. pub charge: Option<Arc<Wire>>,}Only the supervisor can build an AppConnector (new is pub(crate)); serve.rs reads the peer address and the session’s wire counter back through source() and session(). The context is supervisor/src/topology/flow.rs → FlowContext, the inbound tag and the client’s address: the peer the listener captured at accept, or, on a TCP inbound that reads a PROXY protocol v2 header, the client address the header names, or, on a WebSocket inbound that reads a real-IP header, the client that header names on a connection from a proxy in the trusted networks:
#[derive(Clone, Debug)]pub struct FlowContext { pub inbound_tag: CompactString, pub source: Option<IpAddr>,}Both fields exist only because a route rule can match on them: without them, RouteMatch::InboundTag and RouteMatch::SourceCidr would be rules that never fire. A flow’s own source (a QUIC client, a TUN host) wins over the listener’s.
connect(flow) runs these steps synchronously and returns a boxed future:
- With a session, it calls
Session::admit(&flow.user.user_data)(supervisor/src/entity/session.rs). A session whose token is cancelled refuses withPermissionDeniedthe session was closed. The first flow binds the session to itsPrincipal; once a session is bound,admitchecks only its token and itsboundflag. A principal that was revoked before the bind is refused withPermissionDeniedthe user was removed before the session opened a flow, and the session’s token is cancelled first. So is a first flow that would take its user past their device limit (UserSpec::device_limit): when the session’s source IP is not one the user’s bound sessions already come from, and those come from as many IPs as the limit,admitcancels the token and refuses withPermissionDeniedthe user's sessions already come from as many IPs as their device limit. On a refusal, the future resolves to that error. The users and sessions page covers admission. - For
flow.destination.network == DialNetwork::Udp, it builds aFanOutLinkover the plane cell, the context, the flow and aFlowScope(the tracker, the session id and, only whencharge_datagramsis set, the session’sWire). It returnsOutbound::Datagram(link)without dialing anything. - Otherwise it loads the plane once and routes the flow with
plane.route(&flow, &ctx).Plane::routehands every flow to port 53 (DNS_PORT) to the DNS service target when the plane has one, and otherwise decides by the route table (Plane::route_upstream, which the resolver’s own flows use directly).AppConnectorthen resolves a balancer to its member now (routed.target.resolve(None)), recordsFlowMeta::of(...), and startstarget.connect_stream(flow). The future awaits the dial, wraps the stream withtracker.meter_stream(meta, stream), and then callstarget.close_if_drained(stream.entry()), so a flow whose version a drain closed during the dial is killed as soon as it is registered. A balancer whose member is itself a balancer, which validation rules out, fails the open withbalancer member {id} is itself a balancer.
Because the plane is loaded once per connect, a route change reaches the next flow and does not re-route a flow already open.
DatagramLink
Section titled “DatagramLink”pub trait DatagramLink: Unpin { type Addr;
fn poll_send_to( &mut self, cx: &mut Context<'_>, buf: &[u8], to: &Self::Addr, ) -> Poll<io::Result<usize>>;
fn poll_recv_from( &mut self, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll<io::Result<Self::Addr>>;}A datagram link is packet-oriented. One poll_send_to is one datagram to to, and one poll_recv_from is one datagram from the address it returns. There is no end of stream, no flush and no shutdown, so nothing above a link flushes it: a link that writes its packets into a stream must flush that stream itself, as ProxyClientRuntime does after each packet it sends. The methods take &mut self rather than Pin<&mut Self>, and the trait requires Unpin:
- The server runtime stores outbounds by value in a
BTreeMapkeyed by the core’sKey, and the map moves them when it rebalances.Unpinmakes that sound, and the module docs oflink.rsgive it as the reason for the bound. - The trait stays object safe once
Addris fixed.supervisor/src/topology/outbound/proxy.rs→OutboundDatagramwraps aBox<dyn DatagramLink<Addr = Destination> + Send>, so every protocol’s datagram link fits one type.
Addr is what a packet is addressed by, and it decides which of two roles a link can play:
| Role | Required Addr |
Enforced by | Implementors |
|---|---|---|---|
Outbound, behind a Connector |
Destination |
Conn::Datagram: DatagramLink<Addr = Destination> on the ProxyServerRuntime impls that poll it, including its Future and Stream impls |
concepts: UdpOutbound, NoDatagram, ProxyClientRuntime over a datagram codec. environment: DualStackUdp. protocols: SocksUdpLink<S>, WgDatagramLink, Hy2DatagramLink, AnyTlsDatagram. supervisor: ResolvingUdp, FanOutLink, OutboundDatagram, BlackholeLink, DnsUdpLink, MeteredDatagram<D>. |
Transport, the client side of a runtime built with over_datagrams |
the core’s TransportAddr |
D: DatagramLink<Addr = Core::TransportAddr> on ProxyServerRuntime::over_datagrams |
TunUdpLink (SocketAddr, protocols/src/tun/udp.rs, one runtime per TUN client source), QuicDatagrams ((), protocols/src/hysteria/server/datagrams.rs, the datagrams of one Hysteria 2 QUIC connection), UdpSocket (SocketAddr, used by the concepts tests), TinyQuic ((), a test link in concepts/tests/runtime.rs) |
MeteredDatagram<D> is the one generic wrapper: it implements DatagramLink<Addr = Destination> for any inner DatagramLink<Addr = Destination>.
The two bounds, as the runtime writes them:
impl<const BUF_SIZE: usize, Core, D, Conn> ProxyServerRuntime<BUF_SIZE, Core, DatagramTransport<D>, Conn, ProxyRunsQuiet>where Core: ProxyCoreDecode, D: DatagramLink<Addr = Core::TransportAddr>, Conn: Connector<Core::Target>,{ pub fn over_datagrams(link: D, core: Core, connector: Conn) -> Self;}
impl<const BUF_SIZE: usize, Core, Trans, Conn> Future for ProxyServerRuntime<BUF_SIZE, Core, Trans, Conn, ProxyRunsQuiet>where Core: ProxyCoreDecode, Trans: Transport<Addr = Core::TransportAddr>, Conn: Connector<Core::Target>, Conn::Datagram: DatagramLink<Addr = Destination>,{ type Output = Result<Traffic, RuntimeError<Core::Error>>;}In the transport role the runtime sees the link through DatagramTransport<D>, whose Transport::poll_send refuses a write without a peer with InvalidInput (a datagram transport needs a peer per packet), and whose poll_flush and poll_shutdown complete at once. The runtime reads such a transport one packet at a time and checks each read: a Transport whose DATAGRAM is true but which yields a stream read or an end of stream ends the runtime with RuntimeError::Transport carrying InvalidData datagram transport delivered a stream read. DatagramTransport itself only ever yields packets.
What each result means to the runtime
Section titled “What each result means to the runtime”The runtime reads a link’s results differently in the two roles. A link author needs to know which result keeps the link alive:
| Call and result | As an outbound | As a transport |
|---|---|---|
poll_send_to → Pending |
The packet is not sent yet. The runtime polls an outbound link with its key’s KeyWaker; the link registers that waker, which wakes the task, and the runtime retries the send on a later poll. |
The packet stays staged and is sent on a later poll. |
poll_send_to → Ready(Ok(n)) |
The effect is done and n counts toward Traffic::outbound_tx. A short count is not retried. |
The packet is done and its staged length counts toward Traffic::transport_tx. |
poll_send_to → Ready(Err(e)) |
The packet is dropped and the key stays live. The core receives Event::SendFailed { key, to, error }. |
The packet is dropped, uncounted, and the core receives Event::TransportSendFailed { to, error }. The runtime keeps running. |
poll_recv_from → Ready(Ok(from)) |
Event::Datagram { key, from, data }, one whole packet; its length counts toward Traffic::outbound_rx. |
Event::TransportDatagram { from, data }, one whole packet, to be consumed whole. |
poll_recv_from → Ready(Err(e)) |
The key is removed and the core receives Event::OutboundError { key, error }. |
Fatal: the runtime ends with RuntimeError::Transport. |
The runtime hands a datagram outbound a buffer of at most datagram_limit() bytes: the core’s MAX_DATAGRAM (default 4096), capped at BUF_SIZE - STAGING_RESERVE. It hands a datagram transport a buffer of at most MAX_DATAGRAM capped at BUF_SIZE. The server runtime page covers when a datagram outbound is polled and the rest of the scheduling.
A datagram link has no end of stream. A zero-length Ok from poll_recv_from is a zero-length datagram: the runtime delivers it as an Event::Datagram with an empty data, and never marks the outbound’s read side closed. A datagram outbound stays in the map until an error removes it or the core closes it.
Refusing a packet and dropping one
Section titled “Refusing a packet and dropping one”A link that returns an error lets the core decide what to do with the key. A link that drops a packet on purpose returns Ready(Ok(buf.len())) from a send, or skips the packet on a receive and reads the next one, and the core never hears of it. The workspace’s links use both:
| Link | Returns an error | Drops silently |
|---|---|---|
UdpOutbound |
A Remote::Domain target: Unsupported, a plain UDP outbound cannot resolve a domain. Socket errors. |
Never. |
DualStackUdp |
A Remote::Domain target: Unsupported, udp: a plain dual-stack link cannot resolve a domain. Socket errors. The dialers page covers how it picks a socket. |
Never. |
ResolvingUdp |
Socket errors. | On send: a domain target that does not resolve, logged as freedom: dropping a datagram to an unresolvable {to:?} at debug level. |
BlackholeLink |
Never. | Every packet. Its poll_recv_from is always Pending. |
DnsUdpLink |
Never. | On send: a query past MAX_PENDING (64) in flight, logged as dns service: 64 queries in flight, dropping one. A message that does not decode as a query: the send accepts it, and the DNS service logs dns service: dropping an undecodable query: {e} and never answers it. Both logs are at debug level. Every other query is answered later. |
FanOutLink |
Never, from either method. | On send: a packet whose sub-link could not be opened, logged at debug level as udp fan-out: opening {id} failed: {e}. The outbounds page covers its sub-links. |
MeteredDatagram<D> |
After its flow is killed, by a caller or by a drain of its outbound version, from both methods: ConnectionAborted, the flow was killed. |
What the inner link drops. |
SocksUdpLink<S> |
Once the control connection has ended: BrokenPipe, socks: the control connection closed. A read error on the control stream, returned once. Socket send and receive errors. |
On receive: datagrams from any address but the relay, and relay datagrams that do not parse. |
ProxyClientRuntime over a datagram codec |
On send: InvalidInput frame larger than the client runtime's buffer for a packet that, with the codec’s reserve, does not fit even the empty staging buffer; codec errors as InvalidData; InvalidInput codec refused a packet that fits its reserve; upstream write and flush errors. On receive: codec errors as InvalidData; codec opened an impossible frame; InvalidData upstream frame larger than the client runtime's buffer; UnexpectedEof upstream closed inside a frame; and UnexpectedEof once the upstream has ended the flow. |
On receive: frames that open without a source address. On send, under SssDatagram: a packet longer than the stream’s U, logged at debug level. |
AnyTlsDatagram |
On send: InvalidInput for a packet that, with its header, does not fit one stream packet (anytls: datagram too large for UDP-over-TCP), or whose peer domain is too long to encode (anytls: the datagram's domain is too long); stream errors. On receive: a reply address that does not parse; InvalidData uot: reply larger than a packet; UnexpectedEof anytls: the server ended the UDP stream; stream errors. |
Never. |
FanOutLink never returns an error, so a UDP key backed by it never receives Event::SendFailed or Event::OutboundError. SocksUdpLink::associate runs before a link exists, so its handshake errors are the connector’s, not the link’s; the client runtime page lists them, together with the rest of the client runtime’s errors.
The UdpSocket impl
Section titled “The UdpSocket impl”impl DatagramLink for UdpSocket { type Addr = SocketAddr; // poll_send_to -> UdpSocket::poll_send_to(self, cx, buf, *to) // poll_recv_from -> UdpSocket::poll_recv_from(self, cx, buf)}The bare tokio socket forwards to its inherent methods. Its Addr is SocketAddr, so it fits only the transport role: one socket serving many peers, each named by a concrete address. It cannot be a connector’s Datagram type under the server runtime, because the runtime requires Addr = Destination there.
UdpOutbound
Section titled “UdpOutbound”pub struct UdpOutbound(pub UdpSocket);
impl DatagramLink for UdpOutbound { type Addr = Destination;}UdpOutbound is the same socket in the outbound role. poll_send_to calls Destination::socket_addr():
- For
Remote::IpAddr, it sends to that address. - For
Remote::Domain, it returnsErrorKind::Unsupportedwith the texta plain UDP outbound cannot resolve a domain. The runtime turns that intoEvent::SendFailed, and the key stays live.
poll_recv_from wraps the peer’s SocketAddr in Destination::udp, so Event::Datagram’s from is always an IP for this link.
The refusal is by design. The type’s doc comment says so: a link that resolves belongs to the application, which has the resolver. Resolution is policy (which resolver answers, which address family a destination may use), and environment/src/dial/udp.rs → DualStackUdp makes the same choice. The link that resolves is supervisor/src/topology/outbound/freedom.rs → ResolvingUdp. It wraps a DualStackUdp, and for a Remote::Domain target it resolves the name with the freedom outbound’s Resolver under its AddressFamilyStrategy (destination_to_socketaddrs). The outbounds page describes ResolvingUdp in full, including which resolver a freedom outbound is given.
Outside tests, only the two Connector<SocketTarget> impls construct a UdpOutbound: SocketConnector’s and Dialer’s. Nothing in the workspace calls either outside tests, and no supervisor outbound uses UdpOutbound. In tests, the closure connectors of concepts/tests/runtime.rs and protocols/tests/support/pipeline.rs → FreedomConnector build one. That test connector is a Connector<Flow<()>> with Datagram = UdpOutbound: for a Udp flow it binds a socket on 127.0.0.1:0, and for any other flow it connects over TCP to an IP destination and refuses a domain with Unsupported domain.
Outbound<S, D>
Section titled “Outbound<S, D>”pub enum Outbound<S, D> { Stream(S), Datagram(D),}Outbound<S, D> is a dialed outbound. The connector picks the variant, not the caller. AppConnector returns Datagram for a flow whose destination.network is DialNetwork::Udp, without dialing anything, and Stream otherwise. Consumers that expect one kind reject the other explicitly:
| Consumer | Receives | Result |
|---|---|---|
ProxyServerRuntime, applying Effect::Forward or Effect::ForwardHeld |
a datagram outbound | RuntimeError::WrongLinkKind (stream effect on a datagram outbound or vice versa), which ends the connection |
ProxyServerRuntime, applying Effect::SendTo or Effect::SendToHeld |
a stream outbound | RuntimeError::WrongLinkKind |
ProxyServerRuntime, applying Effect::Shutdown |
a datagram outbound | not an error: the effect completes at once without calling the link, and the link stays open |
ProxyClientRuntime, dialing the upstream wire |
Outbound::Datagram |
ErrorKind::Unsupported (proxy client runtime needs a stream to the upstream, got a datagram socket) and the wire goes Down |
protocols/src/socks/server.rs, a CONNECT |
Outbound::Datagram |
ErrorKind::Unsupported (socks: a CONNECT was answered with a datagram link) |
protocols/src/socks/server.rs, a UDP ASSOCIATE |
Outbound::Stream |
ErrorKind::Unsupported (socks: an association was answered with a stream) |
supervisor/src/topology/outbound/proxy.rs → proxy_stream |
Outbound::Datagram |
ErrorKind::Other (a TCP flow was dialed as datagrams) |
supervisor/src/topology/outbound/proxy.rs → proxy_datagram |
Outbound::Stream |
ErrorKind::Other (a UDP flow was dialed as a stream) |
Outbound::connect_stream, for Freedom, Wireguard, Hysteria2 and Anytls |
Outbound::Datagram from the inner connector |
ErrorKind::Other: freedom dialed a TCP flow as UDP, wireguard dialed a TCP flow as UDP, hysteria2 dialed a TCP flow as UDP, anytls dialed a TCP flow as UDP |
Outbound::connect_datagram, for the same four |
Outbound::Stream from the inner connector |
ErrorKind::Other: freedom dialed a UDP flow as TCP, wireguard dialed a UDP flow as TCP, hysteria2 dialed a UDP flow as TCP, anytls dialed a UDP flow as TCP |
A protocol that has only one kind refuses the other before any dial. Outbound::connect_datagram answers Http, Shadowsocks and Ss2022 with ErrorKind::Unsupported: http carries no datagrams, shadowsocks carries no datagrams and shadowsocks-2022 carries no datagrams. Under a FanOutLink, that error is an open that failed, so the packet is dropped.
The enum is also used as a plain “one of two kinds” type. ProxyClientConnector’s Make closure returns Outbound<S, D> where S and D are codecs, not links: it picks the stream codec or the datagram codec for a flow. The supervisor’s Make is Box<dyn FnMut(Flow) -> link::Outbound<S, D> + Send>, and a protocol with no datagram codec uses NoUdp = NoCodec<Destination, io::Error> for D. Because supervisor/src/topology/outbound/mod.rs has its own type named Outbound, that module imports the concepts module and writes this one as link::Outbound. katana’s tests/unit/e2e.rs does the same.
Connector
Section titled “Connector”pub trait Connector<Target> { type Stream: AsyncRead + AsyncWrite + Unpin; type Datagram: DatagramLink; type Future: Future<Output = io::Result<Outbound<Self::Stream, Self::Datagram>>>;
fn connect(&mut self, target: Target) -> Self::Future;}A Connector turns a Target into an Outbound. Under a server runtime, Target is the core’s ProxyCoreDecode::Target, which is Flow<T> for every core in etemenanki-protocols and Flow<Principal> wherever the supervisor serves. Under a client runtime, it is the codec’s ProxyCoreEncodeHandshake::Target: the upstream server, a Destination in the supervisor.
Properties of the trait that shape the code around it:
connecttakes&mut self, so a connector may keep state between dials. The server runtime owns its connector by value and calls it synchronously while it applies anEffect::Open.ProxyClientRuntime::newborrows the connector (connector: &mut Conn) only for the call that creates the dial future, andProxyClientConnectorkeeps its inner connector as a field and lends&mut self.dialerto eachnew.- The supervisor’s
Outboundhandler is shared by every flow routed to it and only has&self. It meets the&mut selfreceiver in two ways.FreedomConnector,WgConnector,Hy2ConnectorandAnyTlsConnectorareClone, and each dial clones the connector and connects on the clone.ProxyClientkeeps itsProxyClientConnectorbehind aparking_lot::Mutex(inner: Mutex<ProxyClientConnector<BUF, Make<S, D>, C, Destination>>, whereCdefaults toTransportConnector), andProxyClient::connect(&self, flow: Flow) -> ProxyClientConnecting<BUF, S, D, C>holds the lock only while the innerconnectbuilds the dial future. Futurehas noUnpinorSendbound. Both runtimes box it once per open:LinkState::Connecting(Pin<Box<F>>)in the server runtime andWire::Connecting(Pin<Box<F>>)in the client runtime. A connector may therefore return an unnamedasynctype or astd::future::Ready. Every production connector exceptProxyClientConnectorreturnsPin<Box<dyn Future<Output = …> + Send>>(AppConnector,FreedomConnector,TransportConnector,SssConnector,WgConnector,Hy2Connector,AnyTlsConnector, bothDialerimpls andSocketConnector), so that the runtime holding it can be spawned.ProxyClientConnectorreturns the named futureProxyClientConnecting, which resolves when the upstream is dialed and the codec’s handshake is done, or with the first error.connectitself cannot fail. Every failure is the future’s output, even one the connector knows about at once:AppConnectorreturns an admission refusal asBox::pin(async move { Err(e) }).- The future’s error is the outbound’s failure. The server runtime removes the key, drops every effect still queued for it (
forget_key), and deliversEvent::ConnectFailed { key, error }. - The key is the core’s to choose. An
Effect::Openthat reuses a live key ends the runtime withRuntimeError::DuplicateKey(open reuses a live outbound key), and an effect that names a key with no slot ends it withRuntimeError::UnknownKey(effect targets an unknown outbound key). The server runtime page lists the otherRuntimeErrorvariants.
The blanket impl for closures
Section titled “The blanket impl for closures”impl<Target, F, Fut, S, D> Connector<Target> for Fwhere F: FnMut(Target) -> Fut, Fut: Future<Output = io::Result<Outbound<S, D>>>, S: AsyncRead + AsyncWrite + Unpin, D: DatagramLink,{ type Stream = S; type Datagram = D; type Future = Fut;}Any FnMut(Target) -> Fut whose future yields io::Result<Outbound<S, D>> is a connector, so a test never needs to name a type. That includes plain functions (a fn item is FnMut) and, through the standard library’s FnMut impl for &mut F, a mutable borrow of a closure. The concepts tests use closures and plain functions:
fn udp_connector(_: ()) -> Ready<io::Result<Outbound<NoStream, UdpOutbound>>>fn dialer(dials: Dials) -> impl FnMut(String) -> DialFuturedialer hands out prepared duplex streams in order and refuses the target "fail" with ConnectionRefused (refused by test). dial_failure_surfaces_on_first_use in concepts/tests/client.rs uses a closure dial as the connector and passes &mut dial because ProxyClientRuntime::new takes connector: &mut Conn.
katana’s tests build stream-only connectors as named types in tests/unit/e2e.rs, all with Datagram = NoDatagram:
TcpConnector, aConnector<Destination>, dials an IP destination over plain TCP and refuses a domain witha test dials addresses only. It is the connector of the VMess and VLESS test clients (vmess_client,vmess_client_to,vless_client), whichtests/unit/runtime.rsreuses, the VLESS one throughvless_roundtrip.DirectConnector, aConnector<Flow<()>>, dials a flow’s destination throughTcpConnector. It serves the upstream VLESS server thatproxy_outbound_relays_and_meterstunnels through.RelayedConnector, aConnector<Destination>holding an IPv4 client address, dials likeTcpConnectorand then writes a PROXY protocol v2 header naming that client before anything else. It is the connector ofrelayed_vmess_client, which katana’s end-to-end tests use to reach the node as different clients.
SocketConnector and SocketTarget
Section titled “SocketConnector and SocketTarget”#[derive(Debug, Clone, Copy, Default)]pub struct SocketConnector;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum SocketTarget { Tcp(SocketAddr), Udp { ipv6: bool, },}
impl Connector<SocketTarget> for SocketConnector { type Stream = TcpStream; type Datagram = UdpOutbound; type Future = Pin<Box<dyn Future<Output = io::Result<Outbound<TcpStream, UdpOutbound>>> + Send>>;}SocketConnector is the dependency-free reference connector:
SocketTarget::Tcp(addr)runsTcpStream::connect(addr).SocketTarget::Udp { ipv6 }binds an unconnected socket on[::]:0or0.0.0.0:0and wraps it inUdpOutbound. The socket is neverconnected, soEffect::SendTopicks the peer per packet. Only the address family is fixed at bind time. The two bind addresses are literals that always parse, so theInvalidInputmapping of a parse error is never reached.
Nothing in the workspace or in katana constructs SocketConnector at the pinned revisions. The policy-aware implementation of the same contract is environment/src/dial/mod.rs → Dialer, which implements Connector<SocketTarget> with the same Stream and Datagram types:
SocketConnector |
Dialer as Connector<SocketTarget> |
|
|---|---|---|
| TCP | TcpStream::connect(addr), no timeout of its own |
TcpDialer::connect(addr), with SocketOptions and the connect timeout (DEFAULT_CONNECT_TIMEOUT, 10 s; TimedOut, connect to {addr} timed out) |
| UDP | UdpSocket::bind on the unspecified address |
UdpDialer::bind(AddressFamily::V4) or V6, with SocketOptions; the IPv6 socket is v6-only |
Dialer also implements Connector<DialTarget>. DialTarget::Tcp(Vec<SocketAddr>) tries the addresses in order through TcpDialer::connect_any, and DialTarget::Udp(Vec<AddressFamily>) binds one socket per listed family as a DualStackUdp. At 46c12e4 both Dialer impls are exercised only by tests. The production code calls the dialers directly: FreedomConnector resolves a TCP destination and calls dialer.tcp.connect_any, and binds UDP with dialer.udp.bind_dual; TransportConnector resolves the upstream and calls dialer.tcp.connect_any. The dialers page covers both dialers and the socket policy.
NoStream and NoDatagram
Section titled “NoStream and NoDatagram”pub enum NoStream {}
pub enum NoDatagram { Never(Infallible),}
impl AsyncRead for NoStream { /* match *self {} */ }impl AsyncWrite for NoStream { /* match *self {} */ }
impl DatagramLink for NoDatagram { type Addr = Destination; // match *self { NoDatagram::Never(never) => match never {} }}These are the Stream and Datagram types of a connector that never produces that kind. Neither type can hold a value: NoStream has no variants, and NoDatagram’s one variant wraps an Infallible. Their trait methods are empty matches, which the compiler accepts because no value can reach them. An Outbound<TcpStream, NoDatagram> can only ever be Stream, so no check is needed at run time.
NoDatagram declares Addr = Destination deliberately. It then satisfies the runtime’s Conn::Datagram: DatagramLink<Addr = Destination> bound, so a stream-only connector can drive a ProxyServerRuntime.
| Type | Production user | Test users |
|---|---|---|
NoDatagram |
TransportConnector: a proxy’s UDP rides inside its stream, and a Udp destination is refused with a proxy transport carries no datagrams of its own; SssConnector, which requires it of the connector it wraps |
the duplex dialers in concepts/tests/runtime.rs and concepts/tests/client.rs; protocols/tests/support/pipeline.rs → TcpConnector; Prepared in protocols/tests/unit/socks/server.rs, a Connector<Flow<()>> that hands out one prepared DuplexStream (or dial error) through a std::future::Ready, and Buffered in the same file, which hands out a BufWriter over a DuplexStream; katana’s TcpConnector, DirectConnector and RelayedConnector in tests/unit/e2e.rs |
NoStream |
none | the UDP connectors in concepts/tests/runtime.rs, typed Outbound<NoStream, UdpOutbound> |
The codec-level counterpart is concepts/src/core.rs → NoCodec<Target, Error>, described on the client runtime page.
Net types
Section titled “Net types”UserAuthorization
Section titled “UserAuthorization”pub enum UserAuthorization { UsernamePassword { username: CompactString, password: CompactString, }, Uuid(Uuid),}UserAuthorization is the identity a user was matched by. It is Clone, PartialEq and Eq, but not Hash. Protocol-specific key material, such as derived keys or cipher state, belongs in NetworkUser::user_data, not here. Every server core in etemenanki-protocols builds it once the user is authenticated, and no core puts a password in it: password is always empty.
| Core | Variant | username |
password |
|---|---|---|---|
SOCKS5 with accounts (socks/handshake.rs) |
UsernamePassword |
the account name the client sent, once it matched | empty |
| SOCKS5 or SOCKS4 in the inbound’s open mode | UsernamePassword |
empty | empty |
HTTP (http/core.rs) |
UsernamePassword |
the matched account’s name; empty in the inbound’s open mode | empty |
Trojan, AnyTLS (anytls/core.rs), Shadowsocks and Shadowsocks 2022 with users |
UsernamePassword |
the matched user’s email |
empty |
sss (sss/core.rs) |
UsernamePassword |
the matched user’s name |
empty |
| Shadowsocks single password, Shadowsocks 2022 single key, TUN (stream and UDP) | UsernamePassword |
empty | empty |
| Hysteria 2 (streams and datagrams) | UsernamePassword |
the authenticated user’s label; empty for a shared password |
empty |
| VLESS, VMess | Uuid |
Under the supervisor, every email, sss name and Hysteria 2 label in an inbound’s user table is the admitted user’s principal label (Principal::label). That label is UserId::name() of the front end’s user id, so it is whatever the front end names its users by: etemenanki-app names a user by its email or by an account’s user name, and katana by the panel user id in decimal (see Lowering a node into a spec). The users and sessions page covers the user tables. The supervisor builds one UserAuthorization itself: anonymous_user() in supervisor/src/topology/flow.rs, with an empty user name and password, for flows the supervisor opens on its own behalf (the resolver’s queries through the route table).
Nothing downstream keys a user on UserAuthorization. The supervisor identifies a flow’s user by NetworkUser::user_data, an Arc<Principal>, and never reads authorization.
NetworkUser<T> and its hand-written Clone
Section titled “NetworkUser<T> and its hand-written Clone”pub struct NetworkUser<T> { pub authorization: UserAuthorization, pub user_data: std::sync::Arc<T>,}
impl<T> Clone for NetworkUser<T> { fn clone(&self) -> Self;}An authenticated user is its authorization plus an arbitrary per-user payload T behind an Arc. The payload is set by whoever built the inbound’s user table, and every flow the user opens shares the one instance:
| Consumer | T |
|---|---|
etemenanki-supervisor, and through it etemenanki-app, katana and the FFI (supervisor/src/topology/flow.rs: Flow = etemenanki_protocols::flow::Flow<Principal>) |
Principal: the user’s UserKey, their label, and a revocation mark |
| protocol, concepts and katana tests | () |
Clone is written out rather than derived. #[derive(Clone)] would add a T: Clone bound, but the payload only ever lives behind an Arc, and Arc<T> clones for any T. A payload that must remain a single shared instance can therefore be a non-Clone type, and the user can still be cloned. Principal is exactly such a type. It does not implement Clone, its constructors return Arc<Self>, and revoking it sets a mark on the one shared instance: Session::admit refuses to bind a session to a principal that is already marked, and Sessions::revoke finds the sessions bound to a principal by Arc::ptr_eq. A cloned principal would be a second instance that neither check recognises.
The same pattern recurs wherever a user payload is carried: Flow<T> writes its own Clone for the same reason, and so do, among others, SocksAuth<T>, SocksServerConfig<T>, HttpServerConfig<T>, TrojanServerConfig<T>, ShadowsocksServerConfig<T>, Ss2022ServerConfig<T>, VlessServerConfig<T>, the VLESS Validator<T>, the Hysteria 2 UserEntry<T> and Hy2Inbound<T>, and TunInbound<T>.
Principal
Section titled “Principal”#[derive(Debug)]pub struct Principal { /* user: Option<UserKey>, label: CompactString, a revocation mark */ }
impl Principal { pub fn user(user: UserKey, label: CompactString) -> Arc<Self>; pub fn anonymous() -> Arc<Self>; pub fn user_key(&self) -> Option<UserKey>; pub fn label(&self) -> &str;}
pub fn anonymous_user() -> NetworkUser<Principal>;Principal::useris what an inbound’s user table hands back for an admitted user. Each inbound holds its own principal per user.Principal::anonymoushas noUserKeyand an empty label. It is the payload of a flow that carries no admitted user, such as a TUN device’s flows and the flows the supervisor opens itself throughanonymous_user().- A principal also carries a revocation mark, which the supervisor sets when the inbound no longer admits the user.
Session::admitrefuses to bind a session to a marked principal. The users and sessions page covers how principals are kept across applies and how they are revoked. UserKey(supervisor/src/entity/id.rs) is a newtype overu64(UserKey::new,UserKey::get;Copy,OrdandHash) that the supervisor assigns to a front end’s user id, so a connection carries a number rather than the front end’s key type.
Three places read the principal of a flow: Session::admit, which binds a session to the principal of its first flow; the flow tracker in supervisor/src/track/mod.rs, which records the principal in each flow’s FlowMeta (FlowMeta::of) and picks the user’s pacer from its key when it opens the flow; and the flow and session listings, which report the principal’s label.
Flow::toward and where users are cloned
Section titled “Flow::toward and where users are cloned”Flow::toward(destination) builds a sub-flow toward a new destination with the carrier’s user and source. It clones the user and resets sniffed to None, so a sub-flow carries no sniffing result of the flow it came from. Three paths go through it:
- mux.cool sub-flows, in
protocols/src/mux/demux.rs. When the inbound sniffs and the sub-flow’s target is an IP, the demuxer sniffs the payload of the sub-flow’sNewframe and setssniffedon the new flow. - The flow a Trojan UDP association opens for its first packet, in
protocols/src/trojan/core.rs. - The supervisor’s per-packet UDP routing, in
supervisor/src/topology/outbound/udp_fanout.rs:FanOutLinkroutes each packet asself.flow.toward(to), and opens a sub-link, with that flow, on each outbound version a packet is routed to.
Other paths clone the user into a fresh Flow::new. The SOCKS server clones it into the one Flow it dials for a UDP association, when the first datagram from its client is forwarded; that datagram’s target becomes the flow’s destination. Among the cores, for example, the legacy Shadowsocks core clones the matched user into its Flow, the Shadowsocks 2022 and VMess cores clone it into each request’s Flow, the AnyTLS core clones the session’s user into each stream’s Flow, and the Hysteria 2 server builds each stream’s and each datagram flow’s NetworkUser from the authenticated entry (its label and a clone of its payload Arc).
DialNetwork
Section titled “DialNetwork”#[repr(u8)]pub enum DialNetwork { Unknown = 0, Tcp = 1, Udp = 2, Unix = 3,}DialNetwork is the transport network of a Destination. It is Copy, Eq and Hash. The protocol cores build only Tcp and Udp, nothing in the workspace or in katana constructs Unknown or Unix, and every consumer branches on Udp:
| Consumer | Udp |
Anything else |
|---|---|---|
AppConnector |
returns a FanOutLink without dialing |
routes the flow and dials a stream |
FreedomConnector |
binds a DualStackUdp with dialer.udp.bind_dual and wraps it in ResolvingUdp |
resolves the destination and connects over TCP |
TransportConnector::dial |
refuses with ErrorKind::Unsupported (a proxy transport carries no datagrams of its own) |
resolves the upstream, connects over TCP and wraps the transport |
route_target in supervisor/src/topology/router.rs |
TargetNetwork::Udp |
TargetNetwork::Tcp for Tcp; no network for any other value |
| katana’s lowering, which builds rather than reads it | builds it for a WireGuard endpoint | builds Tcp for every other outbound server |
route_target’s comment gives the reason for supplying the network at all: withholding it would leave every RouteMatch::Network rule permanently inert.
Remote
Section titled “Remote”pub enum Remote { IpAddr(std::net::IpAddr), Domain(CompactString),}Remote is a host that has not necessarily been resolved. A domain read from the wire stays a domain until it reaches the component that must contact it. Routing can then match it by name, and the chosen outbound’s resolver and address-family strategy decide how to reach it. No server core resolves a name; name lookups in etemenanki-protocols happen only on the outbound side.
The route model has its own borrowed Remote<'a> in environment/src/routing.rs. route_target converts one into the other, borrowing the domain string rather than copying it. The route model lower-cases both the requested and the sniffed domain before matching.
Destination
Section titled “Destination”pub struct Destination { pub network: DialNetwork, pub remote: Remote, pub port: u16,}
impl Destination { pub fn udp(addr: std::net::SocketAddr) -> Self; pub fn socket_addr(&self) -> Option<std::net::SocketAddr>;}Destination is what a request names. It is also the per-packet address of a datagram through an outbound: Effect::SendTo, Effect::SendToHeld, Event::Datagram and Event::SendFailed all carry one. Every UDP-carrying protocol puts a host that may be a domain on the wire for each packet, so the core passes that host on unchanged and the link decides how to reach it. Destination is Clone, Eq and Hash.
| Helper | Behaviour |
|---|---|
Destination::udp(addr) |
network: DialNetwork::Udp, remote: Remote::IpAddr(addr.ip()), port: addr.port(). UdpOutbound, DualStackUdp and ResolvingUdp use it to report the source of a received packet. |
destination.socket_addr() |
Some(SocketAddr) for Remote::IpAddr, None for Remote::Domain. It ignores network. The plain UDP outbounds use it to refuse domains, and the test connectors use it to refuse domains they cannot dial. |
Sniff types
Section titled “Sniff types”#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum SniffedProtocol { Tls, Http,}
#[derive(Debug, Clone)]pub struct SniffedBehavior { pub protocol: SniffedProtocol, pub domain: CompactString,}
pub trait Sniffer { fn sniff(&self, data: &[u8]) -> Option<SniffedBehavior>;}A Sniffer inspects the leading payload bytes of a flow and may recover a routing hint the proxy header did not carry: a TLS SNI or an HTTP Host. sniff takes &self and a plain slice and returns an Option, so a sniffer has no way to fail a connection. Malformed, truncated or unrecognised input yields None, and the flow routes on its destination as before.
The concepts crate defines only these shapes. protocols/src/sniff/ provides the rest:
TlsSnifferandHttpSniffer, unit structs and the twoSnifferimplementations;- the function
sniff(data), which tries TLS first because a TLS record header is the tighter discriminator; plausible_domain, which trims trailing dots and then rejects an empty name, names longer than 253 bytes (MAX_DOMAIN_LEN), characters outside[A-Za-z0-9._-]and IP literals. An IP literal is rejected because honouring it would let a peer relabel a flow with an address it is not talking to;worth_sniffing(destination), which istrueonly for aRemote::IpAddrdestination, since a domain destination already routes by name;- the budgets
SNIFF_TIMEOUT(300 ms) andSNIFF_LIMIT(4 KiB, counted across frames), and theCollectorthat enforces the byte budget.
The result travels in Flow::sniffed. An inbound sets it before it dials, and only when the inbound has sniffing enabled and worth_sniffing allowed it. Two consumers read only domain:
- Routing.
route_targetpasses it toRouteTarget::with_sniffed_domain, and every domain matcher, geosite included, then tries it as well as the request’s own host. - Flow tracking.
FlowMeta::ofcopies it intoFlowMeta::sniffed, which the flow listings report.
protocol is carried, but only tests read it. The sniffing page covers the collector and each protocol’s hold-and-open logic.
Relay futures
Section titled “Relay futures”relay.rs holds two hand-written futures for paths that have no protocol between the two sides. Each keeps one fixed buffer per direction, heap-allocated by boxed_array in new. There is no task per direction, no channel and no allocation after new. Neither future has a timeout of its own; a caller that needs one wraps the future.
UnidirectionalConnection
Section titled “UnidirectionalConnection”pub struct UnidirectionalConnection<I, O, const BUF_SIZE: usize = 8192> { /* … */ }
impl<I, O, const BUF_SIZE: usize> UnidirectionalConnection<I, O, BUF_SIZE> { pub fn new(input: I, output: O) -> Self; pub fn transferred(&self) -> u64;}
impl<I: AsyncRead, O: AsyncWrite, const BUF_SIZE: usize> Future for UnidirectionalConnection<I, O, BUF_SIZE>{ type Output = io::Result<u64>;}UnidirectionalConnection copies input to output until input reaches end of stream, flushes output, and resolves to the byte count. input and output are structurally pinned with #[pin_project], so neither has to be Unpin. Each poll loops over three steps: refill the buffer when it is drained, write out what it holds (writes may be partial), and flush and finish once input is at end of stream and the buffer is empty. Like the bidirectional half below, it flushes before it returns Pending on an idle reader, and a zero-length write fails with WriteZero. At end of stream it flushes but does not shut output down. No code in the workspace or in katana uses it at the pinned revisions.
BidirectionalConnection and Relayed
Section titled “BidirectionalConnection and Relayed”#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]pub struct Relayed { pub a_to_b: u64, pub b_to_a: u64,}
pub struct BidirectionalConnection<A, B, const BUF_SIZE: usize = 8192> { /* … */ }
impl<A, B, const BUF_SIZE: usize> BidirectionalConnection<A, B, BUF_SIZE> { pub fn new(a: A, b: B) -> Self; pub fn relayed(&self) -> Relayed;}
impl<A, B, const BUF_SIZE: usize> Future for BidirectionalConnection<A, B, BUF_SIZE>where A: AsyncRead + AsyncWrite + Unpin, B: AsyncRead + AsyncWrite + Unpin,{ type Output = io::Result<Relayed>;}BidirectionalConnection copies a → b and b → a in one future. Each direction is a private Half<BUF_SIZE> with its own buffer, cursors (pos, cap), flags (read_done, shutdown_done, need_flush) and byte count (transferred). Every poll steps both halves with the same Context, lending the same endpoint to one half as its reader and to the other as its writer. A socket therefore needs no split. The struct is #[pin_project] but pins no field, so the endpoints are not pinned, which is why the Future impl requires Unpin on both. The future resolves once both halves are done. relayed() can be read at any time, which is how a caller detects an idle relay.
One half moves through these states:
stateDiagram-v2 [*] --> Fill Fill --> Drain: read returned bytes Fill --> Parked: read Pending (flush first if need_flush) Drain --> Parked: write Pending Parked --> Fill: woken, buffer drained Parked --> Drain: woken, bytes left Fill --> ShutDown: read returned 0 bytes Drain --> Drain: partial write Drain --> Fill: buffer drained ShutDown --> Done: poll_shutdown ready Fill --> Failed: read error Drain --> Failed: write error or zero-length write Parked --> Failed: flush error ShutDown --> Failed: shutdown error Done --> [*] Failed --> [*]
- Parked. Before a half returns
Pendingon an idle reader, it flushes the writer if it wrote anything since the last flush (need_flush). Bytes buffered in a TLS or WebSocket writer therefore reach the peer even when no more input arrives. A flush that is itselfPendingleavesneed_flushset, so the next idle poll flushes again. A half also parks on a write that returnsPending, with the rest of its buffer kept for the next poll. - ShutDown. At end of stream the half calls
poll_shutdownon its writer: a half-close. The other direction keeps flowing.shutdown_donekeeps a finished half from shutting its writer down twice, so polling a done half again returnsReadyat once.UnidirectionalConnectionflushes at this point instead. - Failed. A read error, a write error, a write that returns
0(ErrorKind::WriteZero), a flush error while parking, or a shutdown error ends the whole future with that error. The?after thea → bhalf returns before theb → ahalf is polled in that call.
Where the relay is used
Section titled “Where the relay is used”The protocol cores run inside the server runtime and do not use relay.rs. At 46c12e4 it has two callers. One is an sss inbound that hands a refused stream to its fallback address: protocols/src/sss/server.rs → relay copies through a BidirectionalConnection with 8192-byte buffers, checks its counters every RELAY_IDLE_TIMEOUT like the SOCKS relay below, and fails with TimedOut sss: fallback idle when nothing moved (see sss). The other is the SOCKS CONNECT path in protocols/src/socks/server.rs, the rest of this section. SOCKS is the one inbound whose server does not fit a ProxyCoreDecode, because its UDP side lives on a second socket, and the control stream only keeps the association alive. The supervisor serves it for any front end that configures a SOCKS inbound, behind the inbound’s transport when it has one: the transport runs first, and the SOCKS driver reads the stream it yields. katana lowers a panel’s SOCKS node only over TLS and with UDP off (see Lowering inbounds and outbounds). No runtime reports what a SOCKS control stream moved, so the supervisor counts that stream’s bytes itself; the serving page covers how.
After the handshake (bounded by HANDSHAKE_TIMEOUT, 10 s) and the connector’s dial, the CONNECT path first writes the bytes it held while sniffing, if any, to the connector’s stream and flushes it. The relay’s own flushes follow only its own writes, so without that flush an upstream that holds small writes until it is flushed (a WebSocket sink, sss’s transform chains) would keep the client’s first bytes while a TLS or HTTP client waits for the answer to them. Then it relays the client stream and the connector’s stream through:
async fn relay_with_idle_guard<A, B>(a: A, b: B) -> io::Result<Relayed>where A: AsyncRead + AsyncWrite + Unpin, B: AsyncRead + AsyncWrite + Unpin,It builds a BidirectionalConnection::<A, B, RELAY_BUF> (16 KiB per direction) and, in a loop, races it against a fresh RELAY_IDLE_TIMEOUT (300 s) sleep. When the sleep fires, it compares relayed() with the previous snapshot. If nothing moved, it returns ErrorKind::TimedOut with the text socks: relay idle. Otherwise it stores the new snapshot and sleeps again. A relay that falls silent is therefore closed between one and two RELAY_IDLE_TIMEOUT periods later. Returning drops the future, which drops both endpoints and closes both connections. Under the supervisor, b is the connector’s Metered<OutboundStream>.
The UDP ASSOCIATE path does not use relay.rs either. It drives the connector’s DatagramLink from its own select! loop over the hub socket, outside any runtime, and ExpectedSender in protocols/src/socks/server.rs decides which hub datagrams reach that link:
admits(from)requires the control connection’s IP, or over a Unix socket the IP the request named. It compares withendpointfromprotocols/src/socks/protocol.rs, which puts the IP in canonical form and drops IPv6 flow info and scope, so an IPv4-mapped IPv6 sender is the IPv4 one. Once a port is fixed, by the request or bypin, it requires that port too. A datagram that fails the check is dropped before it is parsed.pin(from)runs for every admitted datagram that parses and carries a non-empty payload. The first pin holds, so the first such datagram fixes the client, andclient()then names the one address that replies from the link go to.- The first such datagram also opens the association’s one link: the connector dials a
Flowtoward that datagram’s target with a clone of the user. Under the supervisor that link is aFanOutLink, so each later packet is still routed on its own target.
Before it binds the hub socket, the association can be refused with a SOCKS5 reply:
| Condition | Reply | Error |
|---|---|---|
Over a Unix socket with no udp_bind configured, so there is no local IP to put the hub on |
0x07 (STATUS_CMD_NOT_SUPPORT) |
Unsupported, UDP associate over a unix socket needs udp_bind |
| Over a Unix socket, the request does not name a specified IP and a non-zero port | 0x02 |
PermissionDenied, socks: UDP associate over a unix socket must name its source address and port |
The client’s IP is in a family the hub does not receive. hears decides: an IPv4 or IPv4-mapped hub hears only IPv4, the unspecified IPv6 hub hears both, and any other IPv6 hub hears only IPv6. |
0x02 |
PermissionDenied, socks: UDP associate from an address family the relay is not bound in |
A hub that fails to bind ends the association with the bind error. Once the success reply is sent, the loop reads client datagrams into a HUB_BUF (64 KiB) buffer and link replies into a second buffer of the same size. A send the link refuses is logged as socks: packet to {dest:?} dropped: {e} at debug level, and the association carries on. The association ends when any of these happens:
- the control stream, read into a 256-byte buffer whose contents are discarded, reaches end of stream or fails;
- the link’s receive fails, logged as
socks: association link ended: {e}at debug level; - nothing moves for
RELAY_IDLE_TIMEOUT(300 s): the timer restarts after each client datagram handed to the link and after each reply sent to the client; - the connector fails to open the link, or answers with a stream (
Unsupported,socks: an association was answered with a stream), which ends the association with that error; - the hub socket’s receive fails, which ends it with that error.
The SOCKS page covers the port a request may pin up front.
The client-side link uses the same comparison. SocksUdpLink::poll_recv_from in protocols/src/socks/udp_link.rs skips every datagram whose endpoint differs from the relay’s, as well as one that does not parse. A link whose socket is bound dual-stack on [::] therefore still hears an IPv4 relay, which that socket reports in IPv4-mapped form.
Data flow: one UDP packet through an outbound link
Section titled “Data flow: one UDP packet through an outbound link”The datagram path shows the link contract most clearly. Every arrow below is a function call or a poll inside the connection’s task. A link may still hand work to a task of its own: the WireGuard device, a Hysteria 2 connection and a gRPC transport’s HTTP/2 driver each run on one, and the WireGuard link reaches its device through per-flow channels.
sequenceDiagram
participant C as ProxyCoreDecode
participant R as ProxyServerRuntime
participant K as Connector
participant L as DatagramLink (Addr = Destination)
C->>R: Effect::Open (key, target: Flow)
R->>K: connect(target), future boxed in the slot
K-->>R: Ok(Outbound::Datagram(link))
R->>C: Event::Connected (key)
C->>R: Effect::SendTo (key, to: Destination, range)
R->>L: poll_send_to(bytes, to)
alt Ready(Ok(n))
R->>R: outbound_tx += n
else Ready(Err(e)), for example a domain on a plain link
R->>C: Event::SendFailed (key, to, error), key stays live
end
L-->>R: poll_recv_from returns Ok(from)
R->>C: Event::Datagram (key, from, data)
L-->>R: poll_recv_from returns Err(e)
R->>C: Event::OutboundError (key, error), key removed
Under the supervisor, K is AppConnector and L is a FanOutLink. Its future is ready at the first poll, because connect builds the link without dialing. The outbounds page covers how a FanOutLink routes packets and opens its sub-links.
A stream outbound follows the same shape with Effect::Forward and Effect::Shutdown, the AsyncRead and AsyncWrite poll methods, and Event::Outbound and Event::OutboundEof. On a stream outbound, any read, write, flush or shutdown error removes the key, and so does a write that returns 0 (WriteZero). The connection lifecycle page follows a whole connection end to end.
Invariants
Section titled “Invariants”| Invariant | Mechanism | Pinned by |
|---|---|---|
| A live outbound can be moved. | DatagramLink: Unpin and Connector::Stream: Unpin. The runtime keeps slots by value in a BTreeMap. |
The compiler |
The server runtime only sends datagrams addressed by Destination. |
Conn::Datagram: DatagramLink<Addr = Destination> on the runtime’s impls. NoDatagram declares that Addr so stream-only connectors qualify. |
The compiler |
| A plain UDP outbound never resolves a name. | UdpOutbound and DualStackUdp call socket_addr() and return ErrorKind::Unsupported on None. |
No test sends a domain through either link. The refusal path they share is pinned by a_refused_datagram_send_keeps_the_key_alive in concepts/tests/runtime.rs, which sends to an IPv6 peer through an IPv4 socket. |
| A refused datagram send keeps the key; a failed receive removes it. | report_send_failure in concepts/src/runtime.rs leaves the slot alone; fail_outbound calls forget_key. |
a_refused_datagram_send_keeps_the_key_alive in concepts/tests/runtime.rs |
| A refused packet to a datagram transport peer is not fatal. | Send errors on a datagram transport become Event::TransportSendFailed. |
a_refused_transport_packet_is_reported_not_fatal and single_peer_datagram_transport_demuxes_sessions_and_reports_refusals in concepts/tests/runtime.rs |
| A failed dial reaches the core as an event, not as a runtime error. | Poll::Ready(Err(error)) from the boxed dial future → forget_key → Event::ConnectFailed. |
connect_failure_reaches_the_core_as_an_event in concepts/tests/runtime.rs |
| A stream effect never lands on a datagram outbound, or the reverse. | The LinkState match arms in the effect loop return RuntimeError::WrongLinkKind. |
No dedicated test |
| A client runtime’s wire is always a stream. | ProxyClientRuntime::wire maps Outbound::Datagram to ErrorKind::Unsupported and sets Wire::Down. |
No dedicated test |
| A UDP flow under the supervisor is routed packet by packet, and a route change reaches the next packet; a route change does not re-route an established stream. | AppConnector returns a FanOutLink for DialNetwork::Udp, and FanOutLink loads the plane and routes each packet as it is sent. For a stream, AppConnector::connect loads the plane once; Supervisor::close_rerouted closes, rather than re-routes, the streams the current plane would send elsewhere. |
a_route_change_reaches_the_next_udp_packet_but_not_an_established_tcp_flow in supervisor/tests/hot_swap.rs; a_udp_association_counts_each_sub_link_and_charges_its_session in supervisor/tests/tracking.rs |
| A drain closes every flow opened on its outbound version, and only those, including one still dialing when the drain came. | Target::close_flows sets the version’s drained flag and kills the flows filed under its OutboundId with Tracker::kill_where; AppConnector::connect and FanOutLink call close_if_drained on each new flow right after metering it, and a SeqCst fence on each side means the scan finds the flow or the flow sees the flag. |
closing_a_targets_flows_aborts_its_open_streams, closing_a_targets_flows_aborts_its_datagram_links_and_wakes_a_waiting_receive, closing_a_targets_flows_leaves_other_versions_running and a_flow_dialing_through_a_drain_is_closed_when_it_lands in supervisor/tests/unit/plane.rs |
Once a flow is killed, every read, write, flush, shutdown, send and receive on its Metered or MeteredDatagram wrapper fails with ConnectionAborted, and a task parked on one is woken to see it. |
guarded in supervisor/src/track/metered.rs checks the kill before the call, and again after it registers the waker of a call that is pending, so a kill landing in between is either seen at once or wakes the task. |
killing_a_flow_fails_its_pending_read in supervisor/tests/unit/track.rs |
| A session is bound to the principal of its first flow; a principal revoked before that bind is refused. | Session::admit, called first by AppConnector::connect. |
the_first_flow_binds_the_session_to_its_principal and a_session_whose_first_flow_presents_a_revoked_principal_is_refused_under_every_policy in supervisor/tests/unit/session.rs |
| A user’s bound sessions come from no more IPs than their device limit; a session from an IP already counted is not refused for it. | Session::admit checks over_device_limit under the session registry’s lock before it binds, from the limits publish_limits hands the registry at each commit. |
a_session_from_one_ip_too_many_is_refused_and_closed, an_ip_frees_its_slot_when_its_last_session_ends, the_limit_is_per_user_and_absent_means_any and a_source_told_before_binding_is_the_one_counted in supervisor/tests/unit/session.rs |
Cloning a user never requires T: Clone. |
The hand-written impl<T> Clone for NetworkUser<T> and impl<T> Clone for Flow<T> clone the Arc. |
The compiler: Principal is not Clone, and every supervisor flow clones a NetworkUser<Principal> |
| A domain from the wire reaches routing unresolved. | Remote::Domain is carried in Destination, and route_target maps it to routing::Remote::Domain. |
On the core side, connect_to_a_domain_answers_200_once_connected in protocols/tests/unit/http/core.rs checks that the opened Flow names the domain. No test pins the route_target conversion itself. |
| The route model sees the flow’s transport network and the right source. | route_target maps Tcp and Udp to TargetNetwork, and prefers flow.source over the listener’s ctx.source. |
every_rule_naming_a_tag_shares_that_tags_slot (a Network(Udp) rule), the_circuits_own_source_wins_over_the_listeners, without_one_the_listeners_source_is_used, with_neither_there_is_no_source_to_match_on and a_circuit_source_works_with_no_listener_source in supervisor/tests/unit/router.rs |
| A sniffed domain lets a domain rule match an IP-addressed flow. | Flow::sniffed, read by route_target through RouteTarget::with_sniffed_domain |
an_http_host_routes_an_ip_addressed_flow, a_tls_sni_routes_an_ip_addressed_flow and turning_sniffing_off_stops_the_domain_rule_matching in app/tests/integration/e2e_sniff.rs; a_sniffed_domain_makes_an_ip_target_match_domain_rules in environment/tests/unit/routing.rs |
| A relay half-closes each direction on its own and reports exact counts. | Half::poll calls poll_shutdown at end of stream, and the future resolves only when both halves are Ready. |
bidirectional_relays_both_ways_and_half_closes in concepts/src/relay.rs, with a 16-byte buffer and a 41-byte message so the copy wraps the buffer |
| Buffered relay output is not stranded when input goes quiet. | need_flush is flushed before a half returns Pending on its reader. |
No dedicated test |
The bytes a SOCKS CONNECT held while sniffing reach an upstream that buffers. |
The CONNECT path writes the prefix with write_all and then calls flush before it starts the relay. |
the_sniffed_prefix_reaches_an_upstream_that_buffers in protocols/tests/unit/socks/server.rs |
| A SOCKS UDP association feeds its link only from its own client, and replies only to it. | ExpectedSender::admits runs before the packet is parsed; pin runs before the link is dialed; replies go to client(). |
only_the_control_peer_is_heard_and_its_first_datagram_pins_the_port and an_ipv4_mapped_address_is_the_ipv4_one in protocols/tests/unit/socks/server.rs; udp_association_ignores_another_ip and udp_association_ignores_another_port_once_pinned in protocols/tests/pipeline/socks.rs |
A SocksUdpLink returns only the relay’s datagrams, whatever form its socket reports the relay’s address in. |
poll_recv_from compares endpoint(from) with endpoint(self.relay) and skips a mismatch. |
udp_link_ignores_datagrams_not_from_the_relay and udp_link_on_a_dual_stack_socket_hears_an_ipv4_relay in protocols/tests/pipeline/socks.rs; endpoint_sees_through_ipv4_mapping_and_ignores_flow_info in protocols/tests/unit/socks/protocol.rs |
Failure paths and cancellation
Section titled “Failure paths and cancellation”| Where | Failure | Outcome |
|---|---|---|
Connector::connect future |
Err(e) |
Server runtime: the key is forgotten and the core gets Event::ConnectFailed. Client runtime: Wire::Down, the first plaintext call fails with e, and every later call fails with NotConnected. SOCKS CONNECT: a refusal reply (SOCKS5 code 0x05 for ConnectionRefused, 0x04 for anything else; a SOCKS4 client gets 91, request rejected). When the inbound sniffs and the destination is an IP, the request was already granted before the dial, so no refusal is written and the client sees the connection close. |
AppConnector::connect |
the session refuses the flow | The future resolves to PermissionDenied (the session was closed, the user was removed before the session opened a flow, or the user's sessions already come from as many IPs as their device limit), which takes the Err(e) path above. |
DatagramLink::poll_send_to, outbound |
Err(e) |
The packet is dropped, the core gets Event::SendFailed, and the key stays. |
DatagramLink::poll_recv_from, outbound |
Err(e) |
The key is removed and the core gets Event::OutboundError. A ProxyClientRuntime datagram link returns UnexpectedEof here once the upstream has ended the flow; after a kill, by a caller or by a drain, a call on a MeteredDatagram link returns ConnectionAborted. |
FanOutLink sub-link |
failed open, or receive error | A failed open drops that packet and is logged at debug level. A receive error is logged as udp fan-out: sub-link {id} ended: {e} at debug level. The FanOutLink itself reports no error. |
DatagramLink, transport |
send Err / receive Err |
Event::TransportSendFailed / RuntimeError::Transport, which ends the runtime. |
Wrong Outbound variant |
see the table under Outbound<S, D> |
RuntimeError::WrongLinkKind, or ErrorKind::Unsupported or ErrorKind::Other from the consumer. |
BidirectionalConnection |
read, write, flush or shutdown error, or WriteZero, in either half |
The future resolves to Err. The caller drops it, which drops both endpoints. |
| SOCKS relay | no bytes in either direction across a full RELAY_IDLE_TIMEOUT check interval |
ErrorKind::TimedOut, socks: relay idle. |
| SOCKS UDP association | control stream ends or fails, link receive fails, RELAY_IDLE_TIMEOUT without traffic, the link cannot be opened, or the hub’s receive fails |
The loop ends and drops the link and the hub socket; see Where the relay is used. |
Cancellation is drop. Every link, dial future and relay future on this page is owned by the future that polls it. Dropping a ProxyServerRuntime drops the dial futures still in flight and every link in its map; a dropped FanOutLink drops its sub-links and any open still in flight. Dropping a relay future drops the endpoints it owns. None of the concepts types spawns a task, so nothing they own outlives the connection.
Limits
Section titled “Limits”| Constant | Value | Defined in | Applies to |
|---|---|---|---|
BUF_SIZE default of both relay futures |
8192 bytes per direction |
concepts/src/relay.rs |
UnidirectionalConnection, BidirectionalConnection |
RELAY_BUF |
16 * 1024 bytes per direction |
protocols/src/socks/server.rs |
The SOCKS CONNECT relay |
HUB_BUF |
64 * 1024 bytes |
protocols/src/socks/server.rs |
The largest relay packet a SOCKS association reads from its hub socket, and the buffer it reads link replies into |
| control-stream buffer | 256 bytes | protocols/src/socks/server.rs, protocols/src/socks/udp_link.rs |
What a SOCKS association and a SocksUdpLink read the control stream into and discard |
RECV_BUF |
64 * 1024 bytes |
protocols/src/socks/udp_link.rs |
The largest relay packet a SocksUdpLink reads |
HANDSHAKE_TIMEOUT |
10 s | protocols/src/core/mod.rs |
The SOCKS handshake, before any connector is called |
RELAY_IDLE_TIMEOUT |
300 s | protocols/src/core/mod.rs |
The SOCKS relay’s idle guard and association idle timer, and the cores’ idle deadline |
ProxyCoreDecode::MAX_DATAGRAM |
4096 bytes by default, overridable per core |
concepts/src/core.rs |
The size of the buffer the server runtime hands a DatagramLink to receive into; capped at BUF_SIZE - STAGING_RESERVE for an outbound and at BUF_SIZE for a transport |
MAX_SUBS |
64 | supervisor/src/topology/outbound/udp_fanout.rs |
Sub-links one FanOutLink keeps open; the least recently sent to goes first |
MAX_PENDING |
64 | supervisor/src/topology/outbound/dns.rs |
Queries one DnsUdpLink holds in flight |
DEFAULT_CONNECT_TIMEOUT |
10 s | environment/src/dial/tcp.rs |
Dialer’s TCP connects, unless TcpDialer::with_connect_timeout overrides it; SocketConnector has none |
SNIFF_TIMEOUT |
300 ms | protocols/src/sniff/mod.rs |
How long an inbound waits for the first payload before routing without a sniffed domain |
SNIFF_LIMIT |
4 * 1024 bytes |
protocols/src/sniff/mod.rs |
Bytes a sniffer may inspect, across frames |
MAX_DOMAIN_LEN |
253 bytes | protocols/src/sniff/mod.rs |
The longest name plausible_domain accepts |
| Test | File | What it pins |
|---|---|---|
bidirectional_relays_both_ways_and_half_closes |
concepts/src/relay.rs |
Both directions, half-close, and Relayed { a_to_b: 41, b_to_a: 5 } with a buffer smaller than the message |
datagrams_round_trip_through_a_real_udp_socket |
concepts/tests/runtime.rs |
A closure connector returning Outbound::<NoStream, UdpOutbound>::Datagram under a stream transport, with byte counts |
a_refused_datagram_send_keeps_the_key_alive |
concepts/tests/runtime.rs |
A poll_send_to error becomes SendFailed, and the same key relays afterwards |
connect_failure_reaches_the_core_as_an_event |
concepts/tests/runtime.rs |
A closure connector’s Err becomes ConnectFailed with the error text |
datagram_transport_demultiplexes_peers_and_frames_replies |
concepts/tests/runtime.rs |
A bare UdpSocket (Addr = SocketAddr) as a datagram transport, with the function udp_connector as the connector |
a_refused_transport_packet_is_reported_not_fatal |
concepts/tests/runtime.rs |
A transport-side send error becomes TransportSendFailed, and the refused packet is not counted as sent |
single_peer_datagram_transport_demuxes_sessions_and_reports_refusals |
concepts/tests/runtime.rs |
A link with Addr = () (TinyQuic) as a transport, and a refused oversized reply that leaves other sessions running |
dial_failure_surfaces_on_first_use |
concepts/tests/client.rs |
A closure connector’s dial error reaches the client runtime’s first call, then NotConnected on later calls |
socket_target_connector_binds_one_family |
environment/tests/integration/udp.rs |
Dialer as Connector<SocketTarget> binds one IPv4 socket and yields a UdpOutbound |
dual_stack_link_serves_a_proxy_runtime |
environment/tests/integration/udp.rs |
Dialer passed directly as a server runtime’s connector, yielding a DualStackUdp that relays a packet both ways |
transport_connector_refuses_udp |
protocols/tests/pipeline/transports.rs |
TransportConnector::dial, which connect wraps, refuses a Udp destination with ErrorKind::Unsupported |
new_server_vs_new_client_tcp, new_server_vs_new_client_udp |
protocols/tests/pipeline/socks.rs |
The SOCKS CONNECT relay end to end, and SocksUdpLink as a DatagramLink<Addr = Destination> |
udp_association_ignores_another_ip (Linux only), udp_association_ignores_another_port_once_pinned |
protocols/tests/pipeline/socks.rs |
A datagram from another IP, or from another port once the client is pinned, is never forwarded, and the sender on another IP gets no reply |
only_the_control_peer_is_heard_and_its_first_datagram_pins_the_port, an_ipv4_mapped_address_is_the_ipv4_one |
protocols/tests/unit/socks/server.rs |
ExpectedSender: the control peer’s IP only, the first pin holds, and an IPv4-mapped sender matches its IPv4 peer |
the_sniffed_prefix_reaches_an_upstream_that_buffers |
protocols/tests/unit/socks/server.rs |
A sniffing SOCKS inbound that dials through the Buffered connector, whose upstream is a BufWriter: the HTTP request the client sent after CONNECT reaches the far end within 2 s |
udp_link_ignores_datagrams_not_from_the_relay |
protocols/tests/pipeline/socks.rs |
SocksUdpLink::poll_recv_from skips an intruder’s datagram and returns the relay’s |
udp_link_on_a_dual_stack_socket_hears_an_ipv4_relay (Linux only) |
protocols/tests/pipeline/socks.rs |
A SocksUdpLink on a [::] socket relays through an IPv4 relay |
endpoint_sees_through_ipv4_mapping_and_ignores_flow_info |
protocols/tests/unit/socks/protocol.rs |
endpoint equates IPv4-mapped and IPv4 addresses and ignores IPv6 flow info |
connect_to_a_domain_answers_200_once_connected |
protocols/tests/unit/http/core.rs |
The HTTP core opens a Flow whose destination is the unresolved domain |
extracts_sni_from_a_real_client_hello, a_truncated_client_hello_yields_nothing_rather_than_garbage, an_ip_literal_sni_is_rejected, non_tls_and_malformed_input_yield_nothing |
protocols/tests/unit/sniff/tls.rs |
TlsSniffer as a Sniffer |
extracts_the_host_header, an_ip_host_is_rejected, bytes_that_merely_contain_a_host_header_are_not_http |
protocols/tests/unit/sniff/http.rs |
HttpSniffer as a Sniffer |
domain_plausibility |
protocols/tests/unit/sniff/mod.rs |
plausible_domain, the filter every sniffed name passes through |
the_first_flow_binds_the_session_to_its_principal, a_session_whose_first_flow_presents_a_revoked_principal_is_refused_under_every_policy |
supervisor/tests/unit/session.rs |
What AppConnector::connect relies on from Session::admit: the first principal binds, later ones do not rebind, and a principal revoked before the bind is refused with PermissionDenied |
a_session_from_one_ip_too_many_is_refused_and_closed, an_ip_frees_its_slot_when_its_last_session_ends, the_limit_is_per_user_and_absent_means_any, a_source_told_before_binding_is_the_one_counted |
supervisor/tests/unit/session.rs |
The device limit in Session::admit: a second session from a counted IP is admitted, a session from one IP too many is refused with PermissionDenied, its token cancelled and never bound; an IP frees its slot when its last session ends; the limit is per user and no limit admits any number; a source set with Session::set_source before the bind is the one counted |
closing_a_targets_flows_aborts_its_open_streams, closing_a_targets_flows_aborts_its_datagram_links_and_wakes_a_waiting_receive, closing_a_targets_flows_leaves_other_versions_running, a_flow_dialing_through_a_drain_is_closed_when_it_lands |
supervisor/tests/unit/plane.rs |
Drains through the tracker, over blackhole flows registered on a Tracker as the connector registers them: close_flows(&tracker) returns 1, after which reads, writes and flushes on the Metered stream and sends on the MeteredDatagram fail with ConnectionAborted, and a receive already waiting is woken to fail; a drain leaves the next version and other outbounds running; a flow that lands after the drain is killed as it registers |
the_circuits_own_source_wins_over_the_listeners and three siblings, every_rule_naming_a_tag_shares_that_tags_slot |
supervisor/tests/unit/router.rs |
route_target’s source precedence and network mapping |
udp_answers_from_the_address_asked |
supervisor/tests/unit/dns_outbound.rs |
DnsUdpLink reports each answer from the address its query was sent to |
killing_a_flow_fails_its_pending_read |
supervisor/tests/unit/track.rs |
A Metered stream parked on a read is woken by the kill and fails with ConnectionAborted |
a_route_change_reaches_the_next_udp_packet_but_not_an_established_tcp_flow |
supervisor/tests/hot_swap.rs |
FanOutLink routes every packet on the current plane, while a route change does not re-route an established stream |
a_udp_association_counts_each_sub_link_and_charges_its_session |
supervisor/tests/tracking.rs |
One sub-link per outbound under a SOCKS association, each a flow of its own, the payload charged to the session, and the principal’s label alice on the session |
an_http_host_routes_an_ip_addressed_flow, a_tls_sni_routes_an_ip_addressed_flow, turning_sniffing_off_stops_the_domain_rule_matching |
app/tests/integration/e2e_sniff.rs |
Flow::sniffed reaching the route table end to end |
a_sniffed_domain_makes_an_ip_target_match_domain_rules |
environment/tests/unit/routing.rs |
Domain matchers try the sniffed domain |
proxy_outbound_relays_and_meters, vmess_traffic_is_metered_and_reported |
katana tests/unit/e2e.rs |
katana’s test connectors: DirectConnector under the upstream VLESS server, TcpConnector under the VMess client |
UnidirectionalConnection and SocketConnector have no test and no caller.