SOCKS
Source files: 52 · checked against Etemenanki 46c12e4 · katana v6.1.0
Etemenanki/protocols/src/socks/mod.rsEtemenanki/protocols/src/socks/protocol.rsEtemenanki/protocols/src/socks/handshake.rsEtemenanki/protocols/src/socks/server.rsEtemenanki/protocols/src/socks/codec.rsEtemenanki/protocols/src/socks/udp_link.rsEtemenanki/protocols/src/socks/config.rsEtemenanki/protocols/src/core/mod.rsEtemenanki/protocols/src/flow.rsEtemenanki/protocols/src/helpers/address.rsEtemenanki/protocols/src/sniff/mod.rsEtemenanki/protocols/src/sniff/collector.rsEtemenanki/protocols/src/transports/connect.rsEtemenanki/concepts/src/relay.rsEtemenanki/concepts/src/link.rsEtemenanki/concepts/src/core.rsEtemenanki/environment/src/dial/udp.rsEtemenanki/environment/src/dial/socket.rsEtemenanki/supervisor/src/serve.rsEtemenanki/supervisor/src/guard.rsEtemenanki/supervisor/src/connector.rsEtemenanki/supervisor/src/build/inbound.rsEtemenanki/supervisor/src/build/validate.rsEtemenanki/supervisor/src/build/outbound.rsEtemenanki/supervisor/src/topology/inbound/mod.rsEtemenanki/supervisor/src/topology/spec_plan/inbound.rsEtemenanki/supervisor/src/topology/flow.rsEtemenanki/supervisor/src/topology/outbound/mod.rsEtemenanki/supervisor/src/topology/outbound/udp_fanout.rsEtemenanki/supervisor/src/entity/session.rsEtemenanki/supervisor/src/track/mod.rsEtemenanki/supervisor/src/policy.rsEtemenanki/supervisor/src/supervisor.rsEtemenanki/app/src/transport.rsEtemenanki/app/src/config.rsEtemenanki/app/src/lower.rsEtemenanki/protocols/tests/pipeline/socks.rsEtemenanki/protocols/tests/unit/socks/protocol.rsEtemenanki/protocols/tests/unit/socks/server.rsEtemenanki/protocols/tests/unit/socks/codec.rsEtemenanki/supervisor/tests/unit/validate.rsEtemenanki/supervisor/tests/tracking.rsEtemenanki/supervisor/tests/socket_policy.rsEtemenanki/app/tests/unit/transport.rsEtemenanki/app/tests/unit/config.rsEtemenanki/app/tests/unit/lower.rsEtemenanki/app/tests/integration/e2e_udp_route.rsEtemenanki/app/tests/integration/e2e_unix.rsEtemenanki/app/tests/integration/e2e_xray_wrapped.rskatana/src/lower/inbound.rskatana/src/lower/outbound.rskatana/src/api/newv2board.rs
The socks module in etemenanki-protocols (6.2.1) implements both ends of SOCKS. The server side is SocksInbound, one driver that serves SOCKS4, SOCKS4a and SOCKS5 on the same listener and relays a CONNECT or a UDP ASSOCIATE. The client side is a SOCKS5 CONNECT codec, SocksConnect, and a datagram link, SocksUdpLink, for UDP ASSOCIATE. The module is compiled unconditionally: it sits behind no Cargo feature.
A change to the handshake, the reply rules, the association relay, the client, or the way the supervisor builds and serves them starts here. The configuration a user writes is on the SOCKS user guide page.
Responsibilities
Section titled “Responsibilities”Inside etemenanki-protocols:
| Piece | File → symbol | Does | Leaves to others |
|---|---|---|---|
| Wire primitives | protocols/src/socks/protocol.rs |
Constants, the RFC 1929 reader, the NUL-terminated reader for SOCKS4, the UDP relay header codec, endpoint, and the client’s slice builders and parsers. |
Address encoding, which is AddressCodec::SOCKS in protocols/src/helpers/address.rs. |
| Server handshake | protocols/src/socks/handshake.rs → handshake_with_udp_source |
Version detection, method selection, authentication, the request, and every refusal the handshake writes. | The reply to a granted request, which depends on the connect. |
| Inbound driver | protocols/src/socks/server.rs → SocksInbound |
The handshake deadline, sniffing, the connect, the success or failure reply, the CONNECT relay with its idle guard, and the UDP ASSOCIATE relay held to one client by ExpectedSender. |
Routing, admission and dialing, which the Connector does. |
Client CONNECT |
protocols/src/socks/codec.rs → SocksConnect |
The SOCKS5 handshake as a sans-I/O codec, then plaintext verbatim. | Dialing and I/O, which the client runtime does. |
Client UDP ASSOCIATE |
protocols/src/socks/udp_link.rs → SocksUdpLink |
The association handshake over a control stream, then packet framing on a local UDP socket. | Dialing the control stream and binding the socket, which the caller does. |
| Settings | protocols/src/socks/config.rs |
SocksAuth and SocksServerConfig. |
Parsing configuration, which a front end does. |
protocols/src/socks/mod.rs declares the six submodules as public (codec, config, handshake, protocol, server, udp_link) and re-exports five types at etemenanki_protocols::socks: SocksConnect, SocksAuth, SocksServerConfig, SocksInbound and SocksUdpLink.
Around it:
| Piece | File → symbol | Does |
|---|---|---|
| Lowering | app/src/lower.rs → lower_inbound, lower_outbound; katana src/lower/inbound.rs → lower_stream_protocol |
Turns etemenanki-app’s [[inbound]] and [[outbound]] tables with protocol = "socks", and a panel’s SOCKS node, into InboundProtocolSpec::Socks and OutboundProtocolSpec::Socks. |
| Validation | supervisor/src/build/validate.rs → validate_inbound |
Refuses UDP on a Unix listener without udp_bind, UDP over any transport but plain TCP, and a Unix listener at all on a platform other than Unix; holds the inbound’s transport to the rules every protocol’s transport meets. |
| Handler build | supervisor/src/build/inbound.rs → user_table, build_handler |
Builds the SocksInbound<Principal> from the spec and the admitted users, and wraps it in StreamProtocol::Socks. |
| Serving | supervisor/src/serve.rs → serve_connection |
Calls SocksInbound::serve for each accepted connection, with a byte-counting stream and a connector that charges datagrams to the session. |
| Outbound | supervisor/src/topology/outbound/mod.rs → SocksOutbound |
Opens CONNECT flows through SocksConnect and UDP flows as a SocksUdpLink. |
Why SOCKS is a bespoke driver
Section titled “Why SOCKS is a bespoke driver”Every other stream protocol in the crate is a ProxyCoreDecode core: a sans-I/O state machine that the server runtime drives over one transport link (see Server core and Per-connection runtime). SOCKS does not fit that shape. A UDP ASSOCIATE carries no data on the connection that asked for it. The datagrams arrive on a second socket, a UDP “hub” the server binds for the association, and the TCP control connection only keeps the association alive. A core sees exactly one transport, so it has no place to put that second socket.
SocksInbound is therefore an ordinary async function that owns the control stream for the connection’s whole life. supervisor/src/serve.rs → serve_connection gives it its own branch: StreamProtocol::Socks(ArcSwap<SocksInbound<Principal>>) calls load_full().serve(stream, local_ip, source, connector.charging_datagrams()), and every other stream protocol goes through drive with its core. Unlike the core path, serve_connection does the SOCKS driver’s byte counting itself:
- No runtime reports what the stream moved, so
serve_connectionwraps the stream inWireCountedover the session’sWire.WireCounted::poll_readadds the bytes of each read that returnsReady(Ok)to the wire’s up count, andpoll_writeadds the bytes eachReady(Ok(n))write accepted to its down count;poll_flushandpoll_shutdownpass straight through. Its wire isNone, and it counts nothing, when the connector has no session. The SOCKS greeting, authentication and request count toward the session like any other bytes. - A UDP association’s datagrams never cross the control stream, so the connector is passed as
connector.charging_datagrams(), which setsAppConnector’scharge_datagramsfield.AppConnector::connectthen gives a UDP flow’sFanOutLinkaFlowScope { tracker, session, charge }whosechargeis the session’sWire, and the fan-out wraps each sub-link it opens inTracker::meter_datagram(meta, link, charge), which adds the payload the sub-link sends or receives to that wire. What that counts is on Per-user usage accounting.
The connection keeps its live-connection slot, one of the inbound’s MAX_LIVE_CONNECTIONS_PER_INBOUND (4,194,304), for the whole serve call, so an association counts as one live connection until it ends. The accept loop and its limits are on Listeners and the serve loop.
The driver reads whatever byte stream it is given, so the transport under it does not matter to it. InboundProtocolSpec::Socks carries an InboundTransportSpec, as Trojan’s does, and build_handler builds it with build_transport, so a SOCKS inbound runs over plain TCP, a Unix socket, TLS, WebSocket or gRPC, with or without TLS (REALITY is refused, as for every protocol but VLESS). The transport runs before the driver and nothing new is on the serving path. A UDP ASSOCIATE is the exception: its datagrams go to a UDP socket beside the listener, in the clear, so validation refuses udp = true over any shape but plain TCP. The comment in validate_inbound gives the reason: under TLS the datagrams would name every target the TLS hides, and behind a WebSocket or gRPC front the client reaches the front, not the relay. etemenanki-app reads [inbound.stream] for socks through the same inbound_transport as for Trojan (see Transports: TCP and TLS); udp keeps its default true, so a wrapped SOCKS inbound must say udp = false (see Configuration errors).
Key types
Section titled “Key types”Constants
Section titled “Constants”| Constant | Value | File | Meaning |
|---|---|---|---|
SOCKS5_VERSION, SOCKS4_VERSION |
0x05, 0x04 |
protocol.rs |
Version bytes. |
CMD_TCP_CONNECT |
0x01 |
protocol.rs |
CONNECT. |
CMD_TCP_BIND |
0x02 |
protocol.rs |
BIND, always refused. |
CMD_UDP_ASSOCIATE |
0x03 |
protocol.rs |
UDP ASSOCIATE. |
CMD_TOR_RESOLVE, CMD_TOR_RESOLVE_PTR |
0xF0, 0xF1 |
protocol.rs |
Tor’s resolve extensions, served as CONNECT. |
SOCKS4_REQUEST_GRANTED, SOCKS4_REQUEST_REJECTED |
90, 91 |
protocol.rs |
SOCKS4 reply codes. |
AUTH_NOT_REQUIRED, AUTH_PASSWORD, AUTH_NO_MATCHING_METHOD |
0x00, 0x02, 0xFF |
protocol.rs |
SOCKS5 methods. |
STATUS_SUCCESS, STATUS_CMD_NOT_SUPPORT |
0x00, 0x07 |
protocol.rs |
SOCKS5 reply codes. |
ADDR |
AddressCodec::SOCKS |
protocol.rs |
The address codec: 0x01 IPv4, 0x03 domain, 0x04 IPv6, port last. |
STATUS_NOT_ALLOWED |
0x02 |
server.rs (private) |
“Connection not allowed by ruleset”: a UDP ASSOCIATE the relay could not hold to its client. |
STATUS_HOST_UNREACHABLE, STATUS_CONNECTION_REFUSED |
0x04, 0x05 |
server.rs (private) |
Reply codes for a failed CONNECT. |
RELAY_BUF |
16,384 | server.rs (private) |
The CONNECT relay buffer per direction. |
HUB_BUF |
65,536 | server.rs (private) |
Each association buffer. |
RECV_BUF |
65,536 | udp_link.rs (private) |
The client link’s receive buffer. |
Configuration
Section titled “Configuration”pub enum SocksAuth<T> { None(Arc<T>), Password(HashMap<CompactString, (CompactString, Arc<T>)>),}
pub struct SocksServerConfig<T> { pub auth: SocksAuth<T>, pub udp_enabled: bool, pub udp_bind: Option<IpAddr>,}T is the per-user payload that follows the flow to the connector. SocksAuth::None holds the one payload that every anonymous connection gets. SocksAuth::Password maps a username to its password and payload. Both types implement Clone and Debug by hand so that neither needs T: Clone or T: Debug. SocksServerConfig implements Default only for T: Default: SocksServerConfig::default() is anonymous, with T::default() as the payload, UDP enabled and no udp_bind.
udp_bind must be in the address family clients connect over, because the relay hears only the address a client’s control connection came from (see UDP ASSOCIATE). On a Unix socket there is no such address. There udp_bind is required, and the client’s UDP ASSOCIATE request must name the exact address and port its datagrams will come from.
From configuration to a serving driver
Section titled “From configuration to a serving driver”flowchart LR toml["[inbound.settings]"] --> lower["lower_inbound"] lower --> spec["InboundProtocolSpec::Socks and a user set"] spec --> validate["validate_inbound"] validate --> table["user_table"] table --> socks["SocksInbound of Principal"] socks --> cell["StreamProtocol::Socks in an ArcSwap"] cell --> serve["serve_connection: load_full().serve"]
- etemenanki-app parses the settings.
app/src/config.rs→SocksInboundSettings(deny_unknown_fields, with defaults):auth("none"by default),accounts(a list ofAccount { user, pass }, alsodeny_unknown_fields, with both keys required),udp(defaulttrue) andudp_bind(an IP, default none). The inbound’ssniffingkey, defaulttrue, becomes the spec’ssniff. lower_inboundbuilds the spec. Its"socks"arm resolveslistenwithresolve_listen: a host (loopback127.0.0.1whenlistenis absent) with a requiredport, or a path starting with/, without aport, for a Unix socket; a value starting with@(an abstract socket) is refused. The listen rules and their errors are on etemenanki-app: from TOML to a spec. It then matchesauth:"none"makes the inbound open, with no user set;"password"builds its user set fromaccountswithaccount_set; anything else fails withunknown socks auth.account_setkeys each account by its username (UserName::Username): an emptyuseris refused, and so are two accounts with one name. The protocol isInboundProtocolSpec::Socks { udp, udp_bind, transport }on aBindSpec::TcporBindSpec::Unix, wheretransportcomes frominbound_transport: the plain shape on a Unix socket, where a stream block that asks for a transport is refused, and the[inbound.stream]shape otherwise.- The supervisor validates it.
validate_inboundpairs SOCKS with a TCP or Unix bind, runs the transport rules every protocol’s transport meets, refusesudp = trueover any shape but plain TCP, and refusesudp = trueon a Unix bind withoutudp_bind. Unix listeners are#[cfg(unix)]: on any other platform it refuses a Unix bind withunix sockets are not served on <os>. The other rules are on Validation and apply errors. user_tablebuilds the driver. An inbound whose spec names no user set (spec.usersisNone) is open:SocksAuth::None(Principal::anonymous()). Otherwise the table isSocksAuth::Password, mapping each admitted user’s account name to its password (copied out of itsSecretby the privatepass) andArc<Principal>. Only admitted users whose credential is aCredential::Accountenter the table; a user with any other kind of credential is skipped. The result isUserTable::Socks(SocksInbound::new(SocksServerConfig { auth, udp_enabled: udp, udp_bind }, spec.sniff)).build_handlerwraps it inStreamProtocol::Socks(ArcSwap::from_pointee(..))inside aStreamInboundwith the inbound’s transport:InboundTransport::Tcpon a Unix bind or for the plain shape, or the TLS, WebSocket or gRPC transportbuild_transportbuilds.- A user change swaps it in place.
UserTable::store_intostores a freshly builtSocksInboundinto the sameArcSwapcell. Each new connection authenticates against the table current whenserve_connectionloads the cell withload_full. - A settings change swaps the handler. A change to the inbound’s
udp,udp_bindorsniffon the same bind makes the supervisor build a new handler (Step::SwapHandler, see Planning and applying a change). The accept loop reads the current handler at each accept, so connections accepted after the swap are served by the new one.
katana lowers a panel’s SOCKS node to the same spec, over the transport the node names, always with TLS under it. A SOCKS node in the clear is refused before lowering, because its account and everything it relays would cross the network readable: the node config helium and katana share gives a SOCKS node no security to choose, and katana’s newV2board client refuses a UniProxy SOCKS node without TLS with node requests kernel-unsupported feature: socks without TLS (src/api/newv2board.rs → proxy). A katana SOCKS node relays TCP only (udp: false, no udp_bind), and each panel user’s account is their UUID, as both name and password (src/lower/inbound.rs → lower_stream_protocol, credentials; see Lowering inbounds and outbounds).
The Principal payload is what a session binds to on its first flow; see Users, principals and sessions.
The inbound
Section titled “The inbound”pub struct SocksInbound<T> { /* auth, udp_enabled, udp_bind, sniff */ }
impl<T> SocksInbound<T> { pub fn new(config: SocksServerConfig<T>, sniff: bool) -> Self}
impl<T: Send + Sync + 'static> SocksInbound<T> { pub async fn serve<S, C>( &self, mut stream: S, local_ip: Option<IpAddr>, source: Option<IpAddr>, mut connector: C, ) -> io::Result<()> where S: AsyncRead + AsyncWrite + Unpin, C: Connector<Flow<T>>, C::Datagram: DatagramLink<Addr = Destination>,}| Argument | Meaning | What the supervisor passes |
|---|---|---|
stream |
The accepted control connection. | The TCP or Unix stream, wrapped in WireCounted. |
local_ip |
The server’s own address on that connection. It is the bound address in a CONNECT success reply and the fallback bind address for the UDP hub. |
The IP of tcp.local_addr() for TCP; None for a Unix socket. |
source |
The client’s address. It goes into every Flow as Flow::source, and it is the one IP a UDP ASSOCIATE on this connection hears. |
AppConnector::source(): the peer IP the listener captured, or the client a PROXY protocol v2 header names when StreamInbound::proxy_protocol is set, or, for a socket a relay on the same host handed over on the inbound’s handoff socket, the client named beside it; None for a Unix socket. etemenanki-app and the mobile library set neither on a SOCKS inbound. katana sets proxy_protocol on every node on a TCP bind, its SOCKS nodes included, and gives them a handoff socket when [node.controller] handoff_dir is set; a katana SOCKS node relays TCP only, so it serves no UDP ASSOCIATE. |
connector |
Dials each flow. A CONNECT must come back as Outbound::Stream and an association as Outbound::Datagram. |
connector.charging_datagrams(). |
serve runs the handshake under HANDSHAKE_TIMEOUT, then calls the private connect for Request::Connect or associate for Request::UdpAssociate.
Connector and flow types
Section titled “Connector and flow types”The connector traits come from concepts/src/link.rs (see Links, connectors and net types):
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;}
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>>;}
pub enum Outbound<S, D> { Stream(S), Datagram(D),}The target is protocols/src/flow.rs → Flow<T>, the same type every server core in the crate hands its connector. In the supervisor it is Flow<Principal>, aliased as supervisor/src/topology/flow.rs → Flow.
pub struct Flow<T> { pub destination: Destination, pub user: NetworkUser<T>, pub sniffed: Option<SniffedBehavior>, 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}new leaves sniffed empty. toward copies the user and source for another destination and leaves sniffed empty too. Clone and Debug are written out so that T need be neither. For a UDP flow, destination is the first packet’s; later packets carry their own address through poll_send_to.
Handshake types
Section titled “Handshake types”#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum Version { V4, V5,}
#[derive(Debug, Clone, PartialEq, Eq)]pub enum Request { Connect(Destination), UdpAssociate,}
pub struct Handshake<T> { pub version: Version, pub user: NetworkUser<T>, pub request: Request,}
pub async fn handshake<S, T>( stream: &mut S, auth: &SocksAuth<T>, udp_enabled: bool,) -> io::Result<Handshake<T>>where S: AsyncRead + AsyncWrite + Unpin,
pub(crate) async fn handshake_with_udp_source<S, T>( stream: &mut S, auth: &SocksAuth<T>, udp_enabled: bool,) -> io::Result<(Handshake<T>, Option<Destination>)>where S: AsyncRead + AsyncWrite + Unpin,Version decides the reply format. Handshake derives nothing. handshake_with_udp_source runs version detection, authentication and the request, and SocksInbound::serve calls it. The public handshake is a wrapper that drops the second value; nothing in the workspace calls it. Request::UdpAssociate carries nothing. The DST.ADDR and DST.PORT of a UDP ASSOCIATE request, where the client says its datagrams will come from, come back as the second value, Some(source), read as a UDP destination. It is None for any other request and for SOCKS4. The inbound decides how far to believe it (see Whom an association hears).
The authenticated user becomes a NetworkUser with UserAuthorization::UsernamePassword (the private helper user). The username is the one the client sent, or empty for an anonymous or SOCKS4 client. The password field is always empty: the password never travels with the flow. user_data is the payload from SocksAuth, which in the supervisor is the account’s Principal or Principal::anonymous().
The reply writers are public so that the driver can answer after the connect:
pub async fn write_socks5_response<S: AsyncWrite + Unpin>( stream: &mut S, code: u8, remote: &Remote, port: u16,) -> io::Result<()>
pub async fn write_socks4_response<S: AsyncWrite + Unpin>( stream: &mut S, code: u8,) -> io::Result<()>
pub async fn write_refusal<S: AsyncWrite + Unpin>( stream: &mut S, version: Version, code: u8,) -> io::Result<()>
pub async fn write_granted<S: AsyncWrite + Unpin>( stream: &mut S, version: Version, bound: Option<IpAddr>,) -> io::Result<()>write_socks5_response builds 05 code 00, then the address and port through ADDR, in a BytesMut pre-sized to 22 bytes (3 + 1 + 16 + 2, room for an IPv6 address), and writes it with one write_all. write_socks4_response writes the 8 bytes 00 code 00 00 00 00 00 00. write_refusal sends code with the bound address 0.0.0.0:0 for SOCKS5, and always 91 for SOCKS4. write_granted sends 0x00 with bound (or 0.0.0.0) and port 0 for SOCKS5, and 90 for SOCKS4.
UDP relay header
Section titled “UDP relay header”pub fn decode_udp_packet(packet: &[u8]) -> io::Result<(Destination, Bytes)>pub fn parse_udp_packet(packet: &[u8]) -> io::Result<(Destination, usize)>pub fn encode_udp_packet(remote: &Remote, port: u16, data: &[u8]) -> Bytespub fn encode_udp_packet_into(remote: &Remote, port: u16, data: &[u8], out: &mut BytesMut)Both relays use the non-copying pair, parse_udp_packet and encode_udp_packet_into, with reused buffers. parse_udp_packet returns the destination, always with DialNetwork::Udp, and the offset the payload starts at. encode_udp_packet_into appends 00 00 00, the address and port, and the payload. decode_udp_packet and encode_udp_packet are the copying forms; encode_udp_packet pre-sizes its buffer to 22 bytes plus the payload.
The association’s client
Section titled “The association’s client”pub(crate) fn endpoint(addr: SocketAddr) -> (IpAddr, u16)endpoint is how both ends of an association compare the sender of a relay datagram: the IP in canonical form (to_canonical, so an IPv4-mapped IPv6 address becomes the IPv4 one) and the port. It ignores IPv6 flow info and scope ID. A dual-stack socket reports an IPv4 peer as IPv4-mapped, and endpoint makes the two forms equal.
#[derive(Debug)]struct ExpectedSender { ip: IpAddr, port: Option<u16>, client: Option<SocketAddr>,}
impl ExpectedSender { fn new( peer: Option<IpAddr>, declared: Option<&Destination>, hub: IpAddr, ) -> Result<Self, &'static str> fn admits(&self, from: SocketAddr) -> bool fn pin(&mut self, from: SocketAddr) fn client(&self) -> Option<SocketAddr>}
fn hears(hub: IpAddr, ip: IpAddr) -> boolExpectedSender is the one client a UDP ASSOCIATE hears (RFC 1928 §7). ip is the canonical address every datagram must come from. port is set when the request named it alongside ip. client is the first sender a datagram was forwarded for, as the hub saw it, and replies go there. new builds it from the control connection’s peer (None over a Unix socket), the request’s declared source and the hub’s address. Its error names why there is no client the relay could hold to. hears says whether a hub bound to hub receives datagrams from ip.
Client side
Section titled “Client side”pub struct SocksConnect { /* dest, auth, stage */ }
impl SocksConnect { pub fn new(dest: &Destination, auth: Option<(&str, &str)>) -> Self}
impl ProxyCoreEncodeHandshake for SocksConnect { type Target = Destination; type Error = io::Error; const STAGING_RESERVE: usize = 528; // start, reply, finish}
impl ProxyCoreEncode for SocksConnect { /* seal, open */ }SocksConnect owns copies of the destination and the credentials. Its private Stage is Method, UserPass, Request or Done. The traits are described on Client runtime: start stages the first message and returns Handshake::AwaitReply, each reply returns Reply::NeedMore or Reply::Step { consumed, next }, and finish stages nothing, because the wire’s own end of stream carries the close.
pub struct SocksUdpLink<S> { /* control, socket, relay, scratch, recv, sink, control_closed */}
impl<S> SocksUdpLink<S>where S: AsyncRead + AsyncWrite + Unpin,{ pub async fn associate( mut control: S, auth: Option<(&str, &str)>, bind: impl FnOnce(&SocketAddr) -> io::Result<UdpSocket>, ) -> io::Result<Self>
pub fn relay(&self) -> SocketAddr}
impl<S> DatagramLink for SocksUdpLink<S>where S: AsyncRead + AsyncWrite + Unpin,{ type Addr = Destination; // poll_send_to, poll_recv_from}| Field | Holds |
|---|---|
control |
The control stream, kept open for the association’s life. |
socket |
The local UDP socket the bind closure returned. |
relay |
The relay address the server named; relay() returns it. |
scratch |
A BytesMut, 2,048 bytes to start, reused to build each outgoing packet. |
recv |
A boxed RECV_BUF array for incoming relay packets. |
sink |
256 bytes that control-stream bytes are drained into and ignored. |
control_closed |
Set once the control stream ends or fails. |
Both clients build their messages with the slice helpers in protocol.rs:
| Function | Does |
|---|---|
encode_method_request(password) |
[05, 01, method]: one method, 0x02 with credentials and 0x00 without. |
parse_method_reply(buf) |
Some((method, 2)), None while fewer than 2 bytes, an error when VER is not 0x05. |
encode_userpass(user, pass) |
01, then each string with a one-byte length, each truncated to 255 bytes. |
parse_userpass_reply(buf) |
Some((status == 0, 2)), or None while fewer than 2 bytes. |
encode_request(command, dest) |
05 command 00 and the address; None writes 01 00 00 00 00 00 00, the IPv4 address 0.0.0.0 with port 0. |
parse_reply(buf) |
Some((Reply, used)) once the 3-byte head and a whole address have arrived; None before. Only a short buffer gives None: the address parser’s truncation error (UnexpectedEof) is mapped to None by protocols/src/helpers/parse.rs → need_more, while an unknown ATYP fails with unknown address type: N and a malformed domain fails as it does on the server. |
Reply::bound always carries DialNetwork::Udp, whatever the command.
#[derive(Debug, Clone, PartialEq, Eq)]pub struct Reply { pub status: u8, /// The server-bound address; the relay address on a `UDP ASSOCIATE`. pub bound: Destination,}Wire formats
Section titled “Wire formats”All multi-byte integers are big-endian. SOCKS5 addresses use AddressCodec::SOCKS (the constant ADDR), which puts the port after the address:
ATYP |
Address | Size |
|---|---|---|
0x01 |
IPv4 | 4 bytes |
0x03 |
Domain: a length byte, then the name | 1 + 1 to 255 bytes |
0x04 |
IPv6 | 16 bytes |
Any other ATYP fails with unknown address type: N. parse_domain_bytes checks a domain: an empty one fails with empty domain name, bytes that are not UTF-8 with non-utf8 domain, and a name with a character other than an ASCII letter, digit, -, . or _ with invalid domain name: <name>. A name that starts with a digit or [ and parses as an IP literal, brackets stripped, becomes an IP address instead. The longest encoded address is AddressCodec::MAX_LEN, 259 bytes including the port.
SOCKS4 and SOCKS4a
Section titled “SOCKS4 and SOCKS4a”| Field | Size | Meaning |
|---|---|---|
VN |
1 | 0x04. |
CD |
1 | Command. Only 0x01 (CMD_TCP_CONNECT) is granted. |
DSTPORT |
2 | Destination port. |
DSTIP |
4 | Destination IPv4 address. When its first octet is 0, the request is SOCKS4a and a domain follows the user ID. |
USERID |
variable | Bytes up to a NUL. The server reads it and discards it. |
DOMAIN |
variable | SOCKS4a only: bytes up to a NUL, taken as the destination domain. |
| Field | Size | Meaning |
|---|---|---|
VN |
1 | 0x00. |
CD |
1 | 90 (SOCKS4_REQUEST_GRANTED) or 91 (SOCKS4_REQUEST_REJECTED). |
DSTPORT |
2 | Always 0. |
DSTIP |
4 | Always 0.0.0.0. |
read_until_null reads the NUL-terminated fields a byte at a time and decodes them with lossy UTF-8. It keeps at most 512 bytes: a 513th byte that is not a NUL fails with buffer overrun (InvalidData).
SOCKS5 greeting and method selection
Section titled “SOCKS5 greeting and method selection”| Field | Size | Meaning |
|---|---|---|
VER |
1 | 0x05. |
NMETHODS |
1 | Number of method bytes that follow. |
METHODS |
NMETHODS |
Offered methods. |
| Field | Size | Meaning |
|---|---|---|
VER |
1 | 0x05. |
METHOD |
1 | 0x00 (AUTH_NOT_REQUIRED), 0x02 (AUTH_PASSWORD) or 0xFF (AUTH_NO_MATCHING_METHOD). |
The server does not negotiate. The configured SocksAuth fixes one method: 0x00 for None, 0x02 for Password. If the client’s list contains that method, the server selects it. If not, the server answers 0xFF and closes. A greeting with NMETHODS of 0 offers nothing and gets 0xFF.
RFC 1929 username/password
Section titled “RFC 1929 username/password”| Field | Size | Meaning |
|---|---|---|
VER |
1 | Sub-negotiation version; the client sends 0x01. |
ULEN |
1 | Username length. |
UNAME |
ULEN |
Username. |
PLEN |
1 | Password length. |
PASSWD |
PLEN |
Password. |
| Field | Size | Meaning |
|---|---|---|
VER |
1 | 0x01. |
STATUS |
1 | 0x00 accepted, 0xFF refused. The client treats any non-zero value as a refusal. |
read_username_password reads the lengths and the two strings with read_exact, and decodes both with lossy UTF-8 before the account lookup. The account must exist in SocksAuth::Password and its stored password must equal the one sent.
SOCKS5 request and reply
Section titled “SOCKS5 request and reply”| Field | Size | Meaning |
|---|---|---|
VER |
1 | 0x05. |
CMD |
1 | Command; see the table below. |
RSV |
1 | 0x00. |
ATYP |
1 | Address type. |
DST.ADDR |
variable | The destination for CONNECT. For UDP ASSOCIATE, RFC 1928 makes it the address the client’s datagrams will come from; this server treats it as a hint (see Whom an association hears). |
DST.PORT |
2 | Port, with the same two meanings. |
| Field | Size | Meaning |
|---|---|---|
VER |
1 | 0x05. |
REP |
1 | Reply code; see Failure replies. |
RSV |
1 | 0x00. |
ATYP |
1 | Address type of the bound address. |
BND.ADDR |
variable | CONNECT: the server’s local IP on the connection, or 0.0.0.0. UDP ASSOCIATE: the hub’s IP. |
BND.PORT |
2 | CONNECT: 0. UDP ASSOCIATE: the hub’s port. |
CMD |
Constant | Server handling |
|---|---|---|
0x01 |
CMD_TCP_CONNECT |
Request::Connect with a TCP destination. |
0x02 |
CMD_TCP_BIND |
Refused with 0x07. |
0x03 |
CMD_UDP_ASSOCIATE |
Request::UdpAssociate, or refused with 0x07 when UDP is disabled. |
0xF0 |
CMD_TOR_RESOLVE |
Request::Connect to the named destination. |
0xF1 |
CMD_TOR_RESOLVE_PTR |
Request::Connect to the named destination. |
| other | Refused with 0x07. |
The three refusals are written after the 3-byte head and before the request’s address is read.
UDP relay packet
Section titled “UDP relay packet”| Field | Size | Meaning |
|---|---|---|
RSV |
2 | 0x0000. |
FRAG |
1 | Fragment number. Anything other than 0 is rejected (discarding fragmented payload). |
ATYP |
1 | Address type. |
DST.ADDR |
variable | Client to hub: where the payload goes. Hub to client: where the reply came from. |
DST.PORT |
2 | Port, with the same two meanings. |
DATA |
rest | The payload. |
parse_udp_packet rejects a packet shorter than 5 bytes with insufficient length of packet (UnexpectedEof) and a non-zero FRAG with discarding fragmented payload (InvalidData). It then reads the address with ADDR.read_slice. An address cut short by the end of the packet fails with truncated input: fixed-size field (an IPv4 or IPv6 body, or the port) or truncated input: domain: both are ProtocolError::Truncated, which becomes UnexpectedEof (see Protocol crate foundations). An unknown ATYP or a malformed domain fails as in the table above. The function’s other checks (truncated input: socks udp frag byte, integer overflow: socks udp payload offset and a second insufficient length of packet) cannot fire once the 5-byte check has passed. Both relays drop a packet the parser rejects without logging it.
Data flow
Section titled “Data flow”Handshake flow
Section titled “Handshake flow”handshake_with_udp_source reads two bytes and branches on the first one:
flowchart TB head["read 2 bytes"] head -->|"0x05, NMETHODS"| methods["read METHODS"] head -->|"0x04, CD"| v4["handshake4"] head -->|"other"| badver["error: unknown SOCKS version"] methods -->|"configured method offered"| sel["reply 0x05, method"] methods -->|"not offered"| nomatch["reply 0x05 0xFF, error"] sel -->|"Password"| creds["RFC 1929 round"] sel -->|"None"| req["read VER CMD RSV"] creds -->|"match"| req creds -->|"no match"| authfail["reply 0x01 0xFF, error"] req -->|"CONNECT or Tor resolve"| dst["read DST, Request::Connect"] req -->|"UDP ASSOCIATE, UDP enabled"| udp["read DST as the declared source"] req -->|"BIND, unknown, or UDP disabled"| refuse["reply 0x07, error"]
A successful credential round answers 01 00 before the request is read.
The SOCKS4 path in handshake4 works like this:
- If
authisPassword, reply91and fail withSOCKS4 not allowed when auth is required. SOCKS4 has no password, so a password-protected inbound refuses every SOCKS4 client. - Read
DSTPORT,DSTIPandUSERID. When the first octet ofDSTIPis0, read the SOCKS4a domain. - If
CDis notCONNECT, reply91and fail withunsupported SOCKS4 command N. The whole request is read before this check. - Return
Version::V4with an anonymous user and a TCP destination.
Every refusal is written before the error returns. A granted request is not answered yet: the driver decides when to answer.
CONNECT
Section titled “CONNECT”sequenceDiagram
participant C as Client
participant S as SocksInbound::serve
participant K as Connector
participant U as Upstream
C->>S: greeting, auth, request CONNECT
alt granted early: sniffing on and the target is an IP
S->>C: success reply
C->>S: first bytes, until a match, 4 KiB or 300 ms
S->>K: connect(Flow with sniffed)
K->>U: open the flow
S->>U: the collected prefix, when there is one
else otherwise
S->>K: connect(Flow)
K->>U: open the flow
S->>C: success reply, or a refusal on error
end
loop until both halves end or the idle guard fires
C->>U: bytes through BidirectionalConnection
U->>C: bytes through BidirectionalConnection
end
serve builds Flow::new(dest, hs.user, source) and hands it to the private connect, which computes granted = self.sniff && worth_sniffing(&flow.destination): whether the request is answered before the connect. worth_sniffing holds only for a bare-IP destination, because a destination that names a domain already routes by that name.
When the request is not granted early, the driver answers after the connect, so the client learns whether the destination was reachable. The failure reply comes from refusal_code: io::ErrorKind::ConnectionRefused becomes 0x05 (STATUS_CONNECTION_REFUSED) and every other error becomes 0x04 (STATUS_HOST_UNREACHABLE). SOCKS4 always gets 91. After a success reply the driver relays.
Sniffing before the connect
Section titled “Sniffing before the connect”The early grant exists because a SOCKS client sends no payload before it gets the reply. When the request is granted early, the driver:
- writes the success reply with
write_granted; - collects the client’s first bytes in
collect_prefix: aCollectorreads until a sniffer recognises TLS or HTTP (Verdict::Found),SNIFF_LIMIT(4 KiB) is filled (Verdict::Exhausted), the deadlineSNIFF_TIMEOUT(300 ms) after the start passes, or a read returns end of stream or an error. Each read offers at mostCollector::remaining()bytes, andtokio::time::timeout_atbounds it by the one deadline; - puts what the collector recovered in
Flow::sniffedand connects; - writes the collected prefix to the upstream with
write_alland flushes it when it is not empty, then relays. The flush is there for an upstream that holds small writes until it is flushed, such as a WebSocket sink or sss’s transform chains: the relay flushes only after its own writes, so the client’s first bytes would otherwise wait until the client sent more, which a client waiting for the answer to them never does.
collect_prefix returns no error: a read error or an end of stream only ends the collection, with whatever was collected so far. What the sniffers recognise and how a sniffed name reaches the route are on Sniffing and The plane.
A granted request has no reply left to give. If the connect fails, the driver returns the error without writing anything, and the client sees the connection close. The client never gets a second reply either: the success reply after the connect is written only when the request was not granted early.
A client that waits for the server to speak first, such as SSH, sends nothing during the window. It gets its one success reply at once, the window closes empty after SNIFF_TIMEOUT, the flow opens with nothing sniffed, and the server’s first bytes follow the reply. etemenanki-app’s sniffing defaults to true, so this is the default behaviour for an IP destination.
If the connector answers a CONNECT with Outbound::Datagram, the driver fails with socks: a CONNECT was answered with a datagram link and writes nothing more: no reply when the request was not granted early, and nothing after the early success reply when it was.
The relay
Section titled “The relay”async fn relay_with_idle_guard<A, B>(a: A, b: B) -> io::Result<Relayed>where A: AsyncRead + AsyncWrite + Unpin, B: AsyncRead + AsyncWrite + Unpin,relay_with_idle_guard wraps concepts/src/relay.rs → BidirectionalConnection, with the client stream as a and the upstream as b:
pub struct BidirectionalConnection<A, B, const BUF_SIZE: usize = 8192> { /* a, b, a_to_b, b_to_a */ }
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}
pub struct Relayed { pub a_to_b: u64, pub b_to_a: u64,}The driver instantiates it with RELAY_BUF (16 KiB), which gives one boxed 16 KiB buffer per direction. BidirectionalConnection is one hand-written future: there is no task per direction, no channel and no allocation after construction. Each poll steps both halves. A half refills its buffer when it is drained, writes what it holds (writes may be partial), and flushes the writer when its reader has nothing more for now. When a reader reaches end of stream, its half drains the buffer and calls poll_shutdown on the other side’s writer, so half-close propagates. The future resolves with the byte counts when both halves are done. A reader error, a writer error or a zero-length write (WriteZero) ends it at once.
The idle guard runs select! between the relay and a RELAY_IDLE_TIMEOUT (300 s) sleep. On each tick it compares relayed() with the previous sample. If neither counter moved, it returns TimedOut with socks: relay idle and drops the relay with both streams. Sampling happens once per window, so an idle connection ends between 300 and 600 seconds after its last byte, depending on where the idle period starts inside the window.
UDP ASSOCIATE
Section titled “UDP ASSOCIATE”sequenceDiagram
participant C as Client control
participant D as Client UDP
participant S as SocksInbound::associate
participant H as Hub socket
participant L as Connector link
C->>S: request UDP ASSOCIATE, DST kept as the declared source
break ExpectedSender::new fails
S->>C: reply 0x02, then close
end
S->>H: bind at bind_ip, port 0
S->>C: reply 0x00, BND is bind_ip and the hub port
D->>H: RSV FRAG ATYP DST DATA
H->>S: recv_from
S->>S: admits, parse the header, pin
opt no link yet
S->>L: connect(Flow for this destination)
end
S->>L: poll_send_to(payload, dest)
L->>S: poll_recv_from gives a payload and its source
S->>H: header naming the source, then the payload
H->>D: send_to the pinned client
Note over C,S: ends when the control stream closes or fails, the link fails, or 300 s pass idle
SocksInbound::associate runs these steps:
- Choose the hub address.
bind_ipisudp_bind, or elselocal_ip. Over a Unix socket there is nolocal_ip, so withoutudp_bindthe driver replies0x07and fails withUDP associate over a unix socket needs udp_bind. The supervisor refuses that configuration before anything is served (validate_inbound, see Configuration errors), so this path is a backstop. - Decide whom to hear.
ExpectedSender::new(source, declared, bind_ip)applies the rules in Whom an association hears. On an error the driver writeswrite_refusal(…, 0x02)(STATUS_NOT_ALLOWED) and returnsPermissionDeniedwith the error’s message, before any hub socket is bound. - Bind the hub. The driver binds a fresh
UdpSocketatbind_ipwith port 0, so each association gets its own ephemeral port, read back withhub.local_addr(). If the bind orlocal_addrfails, the error returns before any reply is written. The success reply namesbind_ipand that port. - Relay. One
tokio::select!loop in the same future serves four arms. The loop owns twoHUB_BUFbuffers (upfor datagrams from the client,downfor replies), a reusableBytesMutfor outgoing relay packets that starts at 2,048 bytes, a 256-byte sink for the control stream, and one pinned idlesleep.
| Arm | Action |
|---|---|
hub.recv_from into up |
Drop the datagram when !sender.admits(from), when parse_udp_packet fails or when the payload is empty. Otherwise call sender.pin(from), create the link on first use, send the payload with poll_send_to toward the header’s destination, and reset the idle timer, whether or not the send succeeded. A send error is logged at debug (socks: packet to <destination> dropped: <error>, the destination in its Debug form) and the packet is dropped. A recv_from error ends the association with that error. |
recv_reply into down (guarded by if link.is_some()) |
Wrap the payload with encode_udp_packet_into, naming the address it came from, and send_to(sender.client()). A send error is ignored. The idle timer is reset. A link error is logged at debug (socks: association link ended: <error>) and ends the association without an error. |
stream.read into the sink |
Bytes the client sends on the control stream are discarded. End of stream or an error ends the association. |
idle |
RELAY_IDLE_TIMEOUT (300 s) after the last reset ends the association. |
Each admitted datagram that parses and carries a payload resets the idle timer, whether or not the link accepts it, and each reply the link hands back resets it too, whether or not the send to the client succeeds. Datagrams dropped by admits, by parse_udp_packet or for an empty payload do not reset it, and neither do bytes on the control stream. The private after(d) helper, tokio::time::Instant::now() + d, computes each reset.
async fn recv_reply<D: DatagramLink<Addr = Destination>>( link: &mut Option<D>, buf: &mut [u8],) -> io::Result<(usize, Destination)>recv_reply reads one packet from the link into a ReadBuf over buf (the down buffer) with poll_recv_from, and returns the filled length and the address the packet came from. With no link it awaits std::future::pending() and never resolves. The if link.is_some() guard on its select! arm keeps it from being polled at all before the first datagram creates the link.
Only a datagram worth forwarding, one that parses and carries a payload, pins the client, so a neighbour on the client’s IP cannot claim the association by sending junk first.
The link is created once, for the destination of the first forwarded datagram: Flow::new(dest, user, source) with a UDP destination. Later datagrams go through the same link with their own dest in poll_send_to, so the link has to route per packet. If the connector returns an error for that first flow, the association ends with the error. If it answers with Outbound::Stream, the association fails with socks: an association was answered with a stream.
An association that ends because the control stream closed, the link failed or the idle timer fired returns Ok(()). Dropping the future drops the hub socket and the link with it.
Whom an association hears
Section titled “Whom an association hears”Accepting datagrams only from the association’s own client is a rule every change to this relay must keep, each illegal source with a negative test (listed under Tests).
ExpectedSender::new fixes the IP and, when it can, the port before the hub is bound. The peer and the named IP are both compared after to_canonical, so ::ffff:127.0.0.1 names 127.0.0.1. declared counts as naming an address only when it is an IP that is not unspecified. A domain, 0.0.0.0, ::ffff:0.0.0.0 or :: names nothing.
| Control connection | The request names | Heard IP | Port |
|---|---|---|---|
| TCP peer P | P with port N ≠ 0 | P | N from the start |
| TCP peer P | P with port 0 | P | pinned by the first forwarded datagram |
| TCP peer P | anything else: another IP, an unspecified address or a domain | P; the named source is set aside | pinned by the first forwarded datagram |
| Unix socket (no peer) | an IP A that is not unspecified, with port N ≠ 0 | A | N from the start |
| Unix socket (no peer) | anything else | refused: socks: UDP associate over a unix socket must name its source address and port |
A request that names a source other than the peer is set aside rather than refused, because it is not where the datagrams come from: a client behind NAT names its LAN address, sing-box names a loopback address of the other family whenever its first target is private, and PySocks names only a port. Naming another address never lets that address in.
new then calls hears(hub, ip). An IPv4 or IPv4-mapped hub hears only IPv4, :: hears both families, and any other IPv6 hub hears only IPv6. If the hub cannot hear ip, the request is refused with socks: UDP associate from an address family the relay is not bound in, instead of an association that would never receive a datagram.
admits(from) holds when the canonical IP of from equals ip, its port equals the request-named port if there is one, and, once a client is pinned, endpoint(from) == endpoint(client). pin uses get_or_insert, so the first pin holds for the life of the association. Replies go to the pinned address in the form the hub saw it, which can be IPv4-mapped on a dual-stack hub.
The association’s link in the supervisor
Section titled “The association’s link in the supervisor”supervisor/src/connector.rs → AppConnector::connect first asks the session to admit the flow (Session::admit with the flow’s Principal). The first flow a session opens binds the session to that principal. A session that is already closed refuses with the session was closed; one whose first flow presents a principal already revoked refuses with the user was removed before the session opened a flow; and one whose user’s sessions already come from as many IPs as the user’s device limit, when this session’s source would be a new one, refuses with the user's sessions already come from as many IPs as their device limit. All three are PermissionDenied. In the last two cases Session::admit also cancels the session’s token itself, whatever the removal policy, so the whole connection ends. Admission is on Users, principals and sessions.
A UDP flow is then not dialed at all. connect returns an Outbound::Datagram(FanOutLink) (supervisor/src/topology/outbound/udp_fanout.rs) that routes packet by packet on the plane current when each packet is sent, opens one sub-link per routed target, keeps at most MAX_SUBS (64) of them, and merges the replies back. Each sub-link is a tracked flow of its own. Because the SOCKS connector was built with charging_datagrams(), the fan-out is given the session’s Wire, and each sub-link’s payload bytes are added to it. The fan-out is described on Outbounds, UDP fan-out and balancers.
A CONNECT flow is routed once on the plane loaded for it, filed as a flow under the outbound that carries it, and opened with that outbound’s connect_stream; the stream comes back wrapped in the tracker’s Metered. See The plane.
Client side: SocksConnect
Section titled “Client side: SocksConnect”SocksConnect is a client codec that the client runtime drives (see Client runtime). In the supervisor, supervisor/src/topology/outbound/mod.rs → SocksOutbound holds a ProxyClient<SOCKS_BUF, SocksConnect, NoUdp>: for each flow, its closure builds SocksConnect::new(&flow.destination, auth) and the client runtime dials the upstream server over the outbound’s TransportConnector, with SOCKS_BUF (16 KiB) buffers. A SOCKS outbound can therefore run over TLS, WebSocket or gRPC, while the inbound cannot.
stateDiagram-v2 [*] --> Method: start stages 05 01 method Method --> UserPass: method 0x02, stage credentials Method --> Request: method 0x00, stage CONNECT UserPass --> Request: status 0x00, stage CONNECT Request --> Done: REP 0x00 Done --> [*]
| Stage | Parses | Fails with |
|---|---|---|
Method |
parse_method_reply: 2 bytes, VER must be 0x05 |
unexpected server version (InvalidData); auth method not supported (PermissionDenied) when the selected method is not the one offered |
UserPass |
parse_userpass_reply: 2 bytes |
server rejects account (PermissionDenied) |
Request |
parse_reply: VER REP RSV plus an address |
server rejects request: N (ConnectionRefused), where N is the reply code |
Done |
nothing | socks: handshake already done |
The client offers exactly one method: 0x02 when it has credentials, 0x00 otherwise. Every parser returns Reply::NeedMore until its whole message has arrived. Each Reply::Step reports the bytes it consumed, so bytes after the final reply are the first data from the destination. After the handshake, seal copies plaintext into staging and open hands back every wire byte as one frame (Opened::NeedMore for an empty slice). STAGING_RESERVE is 528 bytes, enough for the largest credential message (513 bytes) or a request with a 259-byte address. If the staging area has no room for a message, the codec fails with socks: staging room below the declared reserve.
Client side: SocksUdpLink
Section titled “Client side: SocksUdpLink”SocksUdpLink::associate runs the same rounds directly on the control stream. The private async helper round reads the control stream in 512-byte chunks into a growing buffer and parses it; it drains the bytes the parsed message used, so bytes that arrive with one reply stay for the next round. A stream that ends before the message is complete fails with socks: server closed during the handshake (UnexpectedEof). The steps:
- Write the method request and read the method; one other than the offered method fails with
auth method not supported. - With credentials, write them and read the status; a refusal fails with
server rejects account. - Write
encode_request(CMD_UDP_ASSOCIATE, None), which declares0.0.0.0:0, as RFC 1928 has a client do when it does not know its source: the local socket is bound only after the relay address is known, and a local address would be the wrong one behind NAT anyway. A server that checks sources, asSocksInbounddoes, holds the association to the control connection’s address and the port of the first datagram. - Read the reply. A non-zero code fails with
server rejects request: N(ConnectionRefused). The bound address must be an IP; a domain fails withsocks: the relay address is a domain(Unsupported). - Call
bind(&relay), so the closure can choose the family, and keep the socket.
| Method | Behaviour |
|---|---|
poll_send_to |
Calls poll_control, wraps the payload in the relay header in the reused scratch buffer and sends it to the relay. Returns the payload length. |
poll_recv_from |
Calls poll_control, receives into recv, drops datagrams unless endpoint(from) == endpoint(self.relay), drops datagrams that do not parse, and copies the payload into buf. A payload larger than buf is truncated. Returns the source address from the header. |
poll_control |
Drains the control stream into sink. A read error is returned as is, once. After that, and after end of stream, every call returns BrokenPipe with socks: the control connection closed. |
Because the comparison goes through endpoint, a dual-stack client socket, which reports an IPv4 relay’s replies as coming from its IPv4-mapped address, still hears that relay.
The control stream lives inside the link, so dropping the link closes it and ends the association on the server.
In the supervisor, the outbound that uses both clients is SocksOutbound:
pub struct SocksOutbound { transport: TransportConnector, udp: UdpDialer, server: Destination, auth: Option<(CompactString, CompactString)>, tcp: ProxyClient<SOCKS_BUF, SocksConnect, NoUdp>,}
impl SocksOutbound { pub fn new( transport: TransportConnector, udp: UdpDialer, server: Destination, auth: Option<(CompactString, CompactString)>, ) -> Self}| Field | Holds |
|---|---|
transport |
The TransportConnector both the CONNECT flows and each association’s control connection are dialed over. |
udp |
The UdpDialer that binds an association’s local relay socket. |
server |
The upstream server, a TCP Destination (supervisor/src/build/outbound.rs → tcp(upstream)). |
auth |
The user and password, when the spec has an account. |
tcp |
The client runtime for CONNECT flows, described above. |
SocksOutbound::connect_datagram dials the control connection to the upstream server with transport.dial(&server), then runs associate with a bind closure that calls UdpDialer::bind(AddressFamily::of(relay)). That socket is opened under the host’s socket policy: an IPv6 socket is v6-only (a dual-stack socket would report IPv4 peers as IPv4-mapped addresses that no longer match the address a datagram was sent to), the policy’s options and hook are applied, and it binds the policy’s bind address for the family, or the unspecified address, on an ephemeral port (see Dialers). The flow’s own destination is not used: each packet names its own. Every sub-link a fan-out opens on a SOCKS outbound is therefore an association of its own, with its own control connection.
The outbound is built by supervisor/src/build/outbound.rs → build_outbound from OutboundProtocolSpec::Socks { upstream, account }, with UdpDialer::new over the supervisor’s socket policy. etemenanki-app lowers [outbound.settings] (ProxyOutboundSettings, with user and pass) to it in app/src/lower.rs → lower_outbound. katana lowers an outbound whose protocol is socks or socks5, in any letter case, to the same spec, always over plain TCP, with an account when the config gives both username and password (katana src/lower/outbound.rs → lower_outbound and account; see Lowering inbounds and outbounds).
Invariants
Section titled “Invariants”| Invariant | Mechanism | Pinned by |
|---|---|---|
A granted CONNECT gets exactly one reply: after the connect when it is not granted early, before the sniff window when it is. |
granted decides where write_granted runs; the refusal and the post-connect grant run only if !granted. |
new_server_refuses_an_unreachable_target_after_trying, new_server_lets_the_upstream_speak_first_while_sniffing in protocols/tests/pipeline/socks.rs; a_client_silent_through_the_sniff_window_gets_one_reply_then_the_upstream, a_client_silent_through_the_sniff_window_sees_a_failed_dial_as_the_close in protocols/tests/unit/socks/server.rs |
| Only the client’s own bytes reach the upstream. | The prefix is written only when it is not empty, then the relay copies verbatim. | a_client_silent_through_the_sniff_window_gets_one_reply_then_the_upstream; new_server_vs_new_client_tcp |
| Every refusal is on the wire before the error returns. | Each refusal branch in handshake5, handshake4 and associate awaits write_refusal, write_socks4_response or the method or status bytes before return Err. |
The 0x02 refusals in associate: udp_association_over_a_unix_socket_needs_its_exact_source, udp_association_refuses_a_relay_that_cannot_hear_the_client |
| The whole handshake has one deadline. | serve wraps handshake_with_udp_source in tokio::time::timeout(HANDSHAKE_TIMEOUT, …) and turns an elapsed deadline into handshake_timed_out(). |
|
| An association relays for one client, the control connection’s IP (or, over a Unix socket, the exact source the request named), pinned to one port, and replies go only to it. | ExpectedSender: admits checks each sender, and the first forwarded datagram’s pin holds. |
udp_association_ignores_another_ip, udp_association_ignores_another_port_once_pinned, udp_association_holds_to_the_port_the_request_names, udp_association_is_not_widened_by_the_request, udp_association_over_a_unix_socket_needs_its_exact_source in protocols/tests/pipeline/socks.rs; the unit tests in protocols/tests/unit/socks/server.rs |
| An association the relay could never hear is refused before the hub is bound. | ExpectedSender::new and hears, answered with 0x02. |
a_relay_that_cannot_hear_the_client_is_refused; udp_association_refuses_a_relay_that_cannot_hear_the_client |
| The client link accepts replies only from the relay the server named. | SocksUdpLink::poll_recv_from compares endpoint(from) with endpoint(self.relay). |
udp_link_ignores_datagrams_not_from_the_relay, udp_link_on_a_dual_stack_socket_hears_an_ipv4_relay |
| An association lives no longer than its control stream. | The server’s stream.read arm; the client’s poll_control. |
|
| Fragmented relay packets are never forwarded. | parse_udp_packet rejects FRAG ≠ 0, and both relays drop what it rejects. |
|
| No task or channel beyond the connection’s own. | serve spawns nothing. The CONNECT relay is one BidirectionalConnection future and an association is one select! loop, both inside the task the supervisor runs the connection on. |
The relay part: bidirectional_relays_both_ways_and_half_closes in concepts/src/relay.rs |
| A session counts its SOCKS control bytes and its association’s payload. | WireCounted around the stream; charging_datagrams() hands the session’s Wire to the fan-out. |
a_udp_association_counts_each_sub_link_and_charges_its_session in supervisor/tests/tracking.rs |
A SOCKS inbound behind a transport relays CONNECT only. |
validate_inbound refuses udp = true over any shape but plain TCP. |
socks_relays_udp_over_plain_tcp_only in supervisor/tests/unit/validate.rs |
| A SOCKS inbound meets the transport rules every protocol meets. | validate.rs → inbound_transport, run for every protocol InboundProtocolSpec::transport names. |
every_protocol_meets_the_same_transport_rules in supervisor/tests/unit/validate.rs |
| The sniffed prefix reaches the upstream without waiting for more client bytes. | upstream.flush() after the prefix’s write_all. |
the_sniffed_prefix_reaches_an_upstream_that_buffers in protocols/tests/unit/socks/server.rs |
UDP on a Unix listener needs udp_bind. |
validate_inbound. |
socks_over_a_unix_socket_needs_a_udp_bind_to_serve_udp in supervisor/tests/unit/validate.rs |
| A SOCKS outbound’s control connection and relay socket are opened under the socket policy. | TransportConnector::dial and UdpDialer::bind. |
a_socks_upstream_is_dialed_on_hooked_sockets in supervisor/tests/socket_policy.rs |
Failure paths and cancellation
Section titled “Failure paths and cancellation”Failure replies
Section titled “Failure replies”| Situation | SOCKS5 reply | SOCKS4 reply | Error returned |
|---|---|---|---|
First byte is neither 0x04 nor 0x05 |
none | none | InvalidData: unknown SOCKS version: N (an HTTP request on the port gives 71, the letter G) |
Handshake not complete within HANDSHAKE_TIMEOUT (10 s) |
none | none | TimedOut: client did not complete its request in time |
| Configured method not offered | method 0xFF |
PermissionDenied: no matching auth method |
|
| Unknown user or wrong password | status 0xFF |
PermissionDenied: invalid username or password |
|
| SOCKS4 on a password inbound | 91 |
PermissionDenied: SOCKS4 not allowed when auth is required |
|
SOCKS4 command other than CONNECT |
91 |
Unsupported: unsupported SOCKS4 command N |
|
BIND |
0x07 |
Unsupported: TCP bind is not supported |
|
| Unknown command | 0x07 |
InvalidData: unknown command Some(N) |
|
UDP ASSOCIATE with UDP disabled |
0x07 |
Unsupported: UDP not enabled |
|
UDP ASSOCIATE over a Unix socket without udp_bind |
0x07 |
Unsupported: UDP associate over a unix socket needs udp_bind |
|
UDP ASSOCIATE over a Unix socket without an exact source (no address, an unspecified address, a domain or port 0) |
0x02 |
PermissionDenied: socks: UDP associate over a unix socket must name its source address and port |
|
UDP ASSOCIATE from an address family the hub does not hear |
0x02 |
PermissionDenied: socks: UDP associate from an address family the relay is not bound in |
|
| The hub socket cannot be bound, or its local address cannot be read | none | the socket error | |
| Malformed or truncated address, a SOCKS4 field over 512 bytes, or the stream ends mid-handshake | none | none | the read or parse error, for example unknown address type: N, invalid domain name: <name> or buffer overrun |
The session refuses the CONNECT flow (closed, or its user removed before its first flow) |
0x04, or none when granted early |
91, or none when granted early |
PermissionDenied: the session was closed or the user was removed before the session opened a flow |
Connect refused (ConnectionRefused) |
0x05, or none when granted early |
91, or none when granted early |
the connector’s error |
| Any other connect error | 0x04, or none when granted early |
91, or none when granted early |
the connector’s error |
CONNECT answered with a datagram link |
none, or the early success reply already sent | none, or the early success reply already sent | Unsupported: socks: a CONNECT was answered with a datagram link |
| The first datagram’s flow is refused or fails to open | already granted | the connector’s error | |
| Association answered with a stream | already granted | Unsupported: socks: an association was answered with a stream |
|
The hub’s recv_from fails |
already granted | the socket error | |
CONNECT relay idle |
already granted | already granted | TimedOut: socks: relay idle |
The timeout error comes from protocols/src/core/mod.rs → handshake_timed_out, the same error the cores return on Expired::Handshake. The supervisor’s drive, which watches the handshake of every other stream protocol, words its own timeout differently: inbound handshake timed out after 10s.
serve returns every error to its caller; the SOCKS module does not log handshake failures itself. supervisor/src/serve.rs → serve_connection logs each error at debug under the target etemenanki_supervisor::serve with the line {} connection from {:?} ended: {e}: the protocol name (StreamProtocol::name(), here socks) and the client address in its Debug form. An Ok is silent:
socks connection from Some(203.0.113.7) ended: invalid username or passwordsocks connection from None ended: client did not complete its request in timeInside an association, per-packet problems are logged under etemenanki_protocols::socks::server at debug (a failed send toward the link) or ignored (a failed send to the client) and do not end the association.
Configuration errors
Section titled “Configuration errors”etemenanki-app refuses these configurations. --test prints them as below, and a start prints the same text after failed to start:. The first five come from app/src/lower.rs (the stream ones through app/src/transport.rs). The last three come from the supervisor’s validate_inbound; the second of them is what a stream block that asks for TLS, WebSocket or gRPC gets while udp keeps its default true, and the third is what security = "reality" gets. --test reaches them because it runs etemenanki_supervisor::check (validation, then a prepare that binds nothing) after lowering; see etemenanki-app: from TOML to a spec.
ERROR etemenanki_app: configuration invalid: inbound socks-in: unknown socks auth "passwd"ERROR etemenanki_app: configuration invalid: inbound socks-in: unknown stream network "kcp"ERROR etemenanki_app: configuration invalid: inbound socks-in: protocol socks over a unix socket does not support stream network "ws"ERROR etemenanki_app: configuration invalid: inbound socks-in: accounts[0] has no userERROR etemenanki_app: configuration invalid: inbound socks-in: accounts[0] and accounts[1] are both named "alice"ERROR etemenanki_app: configuration invalid: inbound socks-in: socks over a unix socket has no local IP for UDP associate; set udp_bind or turn udp offERROR etemenanki_app: configuration invalid: inbound socks-in: socks serves udp associate over plain tcp only; turn udp off to wrap it in a transportERROR etemenanki_app: configuration invalid: inbound socks-in: reality is for vless onlyA mistyped key in [inbound.settings] is refused with the list of keys SocksInboundSettings accepts:
ERROR etemenanki_app: configuration invalid: inbound socks-in: invalid settings: unknown field `udp_bnd`, expected one of `auth`, `accounts`, `udp`, `udp_bind`An entry in accounts needs both user and pass and accepts no other key. The first line of the error names the key:
ERROR etemenanki_app: configuration invalid: inbound socks-in: invalid settings: missing field `pass`ERROR etemenanki_app: configuration invalid: inbound socks-in: invalid settings: unknown field `extra`, expected `user` or `pass`Cancellation
Section titled “Cancellation”serve spawns nothing. Everything it owns lives in its own future: the control stream, the upstream stream, the hub socket, the datagram link and the buffers. Dropping the future closes all of them together, and no task is left behind to clean up.
The accept loop opens a session for each accepted socket before it spawns anything; once the listener’s stop token is cancelled, Sessions::open returns None and the loop ends without serving that socket. The supervisor then runs the connection under that session’s token with Shared::spawn_until, a task on the supervisor’s TaskTracker that wraps the future in until_cancelled (with_cancellation_token_owned), which drops it as soon as the token is cancelled:
- Over a Unix socket (a
#[cfg(unix)]branch), the task the accept loop spawned runsConnection::serve_socket, which awaitsserve_connectiondirectly, withconnector_for(tag, None, carrier)andReport::new(guard, None, None): no source and nolocal_ip. - Over TCP,
serve_socketfirst reads a PROXY protocol v2 header when the inbound asks for one, underPROXY_HEADER_TIMEOUT(10 s), and takes the client it names as the session’s source; a socket handed over on the inbound’s handoff socket comes with its client instead (see Transports: TCP and TLS).Connection::serve_tcpthen drops the connection if its source is an IP the guard has banned. Otherwise it runs the inbound transport’saccept, which sets TCP keepalive on the socket, runs the TLS, WebSocket or gRPC handshake when the inbound has one, and hands each stream to its callback (for plain TCP, the socket itself); the callback spawnsserve_connectionwithspawn_untilunder the same session’s token (on gRPC, each stream under a session of its own), withlocal_ipfromtcp.local_addr().
Among the things that cancel the token:
Supervisor::closeis given a selector that names the session;- its user is removed from the inbound, or the user’s credentials change, under the inbound’s removal policy (
InboundSpec::user_removal, or else the supervisor-wide default): at once underUserRemovalPolicy::Close, the default, or when aCloseAfterperiod ends; - the inbound is removed or its tag changes (
Step::CloseSessions); Supervisor::shutdown(grace)has waited out its grace.
The full rules are on Users, principals and sessions.
A flow kill (Tracker::kill) is narrower. FlowEntry::kill sets the flow’s kill flag and wakes the read and write wakers of its Metered stream, so a task parked on that stream is polled again, and every poll of the stream from then on fails with the flow was killed (ConnectionAborted). When the CONNECT relay polls it, BidirectionalConnection returns that error and serve returns it. For an association, each fan-out sub-link is a flow of its own: killing one ends that sub-link, the association runs on, and a later packet routed to the same target opens a new sub-link.
On the client side, dropping a SocksUdpLink closes its control connection, which ends the association on the upstream server.
Limits
Section titled “Limits”| Constant | Value | Where | Governs |
|---|---|---|---|
HANDSHAKE_TIMEOUT |
10 s | protocols/src/core/mod.rs |
The whole server handshake, from the start of serve to the parsed request. |
RELAY_IDLE_TIMEOUT |
300 s | protocols/src/core/mod.rs |
The CONNECT idle guard window; the association idle timer. |
SNIFF_TIMEOUT |
300 ms | protocols/src/sniff/mod.rs |
How long collect_prefix waits for the first bytes. |
SNIFF_LIMIT |
4,096 bytes | protocols/src/sniff/mod.rs |
How many bytes collect_prefix collects at most. |
RELAY_BUF |
16,384 bytes | protocols/src/socks/server.rs |
CONNECT relay buffer per direction. |
HUB_BUF |
65,536 bytes | protocols/src/socks/server.rs |
Each of the two association buffers (up, down). |
RECV_BUF |
65,536 bytes | protocols/src/socks/udp_link.rs |
The client link’s receive buffer. |
STAGING_RESERVE |
528 bytes | protocols/src/socks/codec.rs |
Staging room one SocksConnect call may need. |
AddressCodec::MAX_LEN |
259 bytes | protocols/src/helpers/address.rs |
Longest encoded SOCKS address with port. |
read_until_null cap |
512 bytes | protocols/src/socks/protocol.rs |
SOCKS4 USERID and SOCKS4a domain. |
encode_userpass cap |
255 bytes each | protocols/src/socks/protocol.rs |
Client username and password on the wire. |
round chunk |
512 bytes | protocols/src/socks/udp_link.rs |
Each read of the client link’s handshake. |
SOCKS_BUF |
16,384 bytes | supervisor/src/topology/outbound/mod.rs |
The client runtime buffers of a SOCKS outbound’s CONNECT flows. |
MAX_SUBS |
64 | supervisor/src/topology/outbound/udp_fanout.rs |
Sub-links one association’s fan-out keeps open. |
MAX_LIVE_CONNECTIONS_PER_INBOUND |
4,194,304 | supervisor/src/serve.rs |
Live connections per inbound, each SOCKS connection for its whole serve call. |
The reusable association reply buffer and the client’s scratch buffer start at 2,048 bytes and grow as needed. Both control-stream sinks are 256 bytes.
Run the module’s tests and the supervisor and app tests that exercise it from the Etemenanki workspace:
cargo test -p etemenanki-protocols --lib sockscargo test -p etemenanki-protocols --test pipeline sockscargo test -p etemenanki-concepts --lib relaycargo test -p etemenanki-supervisor --lib socks_cargo test -p etemenanki-supervisor --test tracking a_udp_associationcargo test -p etemenanki-supervisor --test socket_policycargo test -p etemenanki-app --libcargo test -p etemenanki-app --test integration e2e_udp_routecargo test -p etemenanki-app --test integration e2e_unixcargo test -p etemenanki-app --test integration e2e_xray_wrapped::| File | Tests | Covers |
|---|---|---|
protocols/tests/unit/socks/protocol.rs |
udp_encoding_roundtrip, read_username_password_ok, read_username_password_err, read_until_null_ok, read_until_null_err |
Wire primitives, ported from Xray-core’s SOCKS tests. |
client_handshake_messages_round_trip_through_slices |
Every client builder and parser, including None on short input and the all-zero UDP ASSOCIATE request. |
|
endpoint_sees_through_ipv4_mapping_and_ignores_flow_info |
endpoint equates an IPv4-mapped address with the IPv4 one, ignores IPv6 flow info, and still tells ports, IPs and families apart. |
|
protocols/tests/unit/socks/server.rs (mounted from server.rs) |
only_the_control_peer_is_heard_and_its_first_datagram_pins_the_port |
Another IP is never admitted, any port of the peer is admitted until a pin, and the first pin holds. |
an_ipv4_mapped_address_is_the_ipv4_one |
A mapped peer or sender matches its IPv4 form, and the pinned client keeps the form the hub saw. | |
a_request_naming_the_peer_pins_its_port_up_front |
Naming the peer with a port admits only that port; naming it with port 0 pins nothing. |
|
a_request_naming_any_other_source_is_set_aside |
The IPv6 loopback, a LAN address, an unspecified address with a port, another host and a domain all leave only the peer admitted. | |
over_a_unix_socket_the_request_must_name_the_exact_source |
Without a peer, anything short of a specified IP and a non-zero port is refused, and an exact source admits only itself. | |
a_relay_that_cannot_hear_the_client_is_refused |
hears for IPv4, IPv6, ::, 0.0.0.0 and IPv4-mapped hubs, over TCP and over a Unix socket. |
|
a_client_silent_through_the_sniff_window_gets_one_reply_then_the_upstream |
With paused time: one success reply, then the upstream’s banner after at least SNIFF_TIMEOUT; only the client’s own bytes reach the upstream; a clean half-close both ways. |
|
a_client_silent_through_the_sniff_window_sees_a_failed_dial_as_the_close |
A refused dial after the early grant: no refusal follows the success reply, the connection closes, and serve returns ConnectionRefused. |
|
the_sniffed_prefix_reaches_an_upstream_that_buffers |
An upstream that holds writes until it is flushed (a BufWriter) still receives the collected HTTP request while the client waits for the answer. |
|
protocols/tests/unit/socks/codec.rs |
anonymous_connect_takes_two_rounds |
SocksConnect without credentials: bytes staged, NeedMore, consumed counts, data after the reply. |
credentials_add_a_round_and_a_refusal_is_an_error |
The credential round, a refused request, a refused account and a 0xFF method reply. |
|
protocols/tests/pipeline/socks.rs |
new_server_vs_new_client_tcp |
SocksInbound against SocksConnect with credentials, 100,000 bytes echoed and a clean half-close. Sniffing is on and the destination is an IP, so this runs the early grant with a collected prefix. |
new_server_refuses_an_unreachable_target_after_trying |
With sniffing off, a closed port produces a refusal that the client sees as server rejects request. |
|
new_server_lets_the_upstream_speak_first_while_sniffing |
Against a real SSH-style upstream that greets first: one 10-byte success reply (an IPv4 bound address), then the banner. | |
new_server_vs_new_client_udp |
SocksInbound against SocksUdpLink, including a 1,400-byte payload. |
|
udp_association_ignores_another_ip |
Negative: a datagram from 127.0.0.2, sent before the client’s first and again later, is never forwarded or answered. |
|
udp_association_ignores_another_port_once_pinned |
Negative: after the first datagram, another socket on the client’s IP is not forwarded. | |
udp_association_holds_to_the_port_the_request_names |
Negative: a request naming the client’s address and port shuts out a neighbour on the same IP that sends first. | |
udp_association_sets_aside_a_source_it_cannot_hold_to |
A request naming [::1]:0 from an IPv4 client is granted and relays for the client. |
|
udp_association_is_not_widened_by_the_request |
Negative: a request naming another host does not let that host in. | |
udp_association_over_a_unix_socket_needs_its_exact_source |
Negative: over a Unix socket, 0.0.0.0:0 is refused with 0x02 and the connection closes; an exact source is granted and a neighbour is not heard. |
|
udp_association_refuses_a_relay_that_cannot_hear_the_client |
An IPv6 udp_bind with an IPv4 client is refused with 0x02 and the connection closes. |
|
udp_link_ignores_datagrams_not_from_the_relay |
Negative, client side: against a hand-written server, a well-formed datagram from another socket is not taken as the reply. | |
udp_link_on_a_dual_stack_socket_hears_an_ipv4_relay |
A link bound to :: hears an IPv4 relay whose replies arrive IPv4-mapped. |
|
concepts/src/relay.rs |
bidirectional_relays_both_ways_and_half_closes |
BidirectionalConnection with a buffer smaller than the payload. |
supervisor/tests/unit/validate.rs |
socks_over_a_unix_socket_needs_a_udp_bind_to_serve_udp |
UDP on a Unix bind without udp_bind is invalid; with udp_bind, with UDP off, or on TCP it is valid. |
socks_relays_udp_over_plain_tcp_only, every_protocol_meets_the_same_transport_rules, shadowsocks_and_socks_over_websocket_read_a_real_ip_header |
UDP over any transport but plain TCP is invalid; a SOCKS inbound meets the shared transport rules; a SOCKS inbound over WebSocket may read a real-IP header. | |
supervisor/tests/tracking.rs |
a_udp_association_counts_each_sub_link_and_charges_its_session |
One association routed to two outbounds makes two UDP sub-link flows in one session; the session counts greeting (3), authentication (13) and request (10) up, method (2), status (2) and reply (10) down, plus 15 payload bytes each way, and take_usage reports that for the account. |
supervisor/tests/socket_policy.rs |
a_socks_upstream_is_dialed_on_hooked_sockets |
A SOCKS outbound’s CONNECT dial, its association’s control connection and its relay socket all pass the socket policy’s hook. |
app/tests/unit/transport.rs |
a_default_or_plain_tcp_stream_is_accepted, a_transport_the_protocol_cannot_honour_is_rejected, security_on_a_protocol_without_a_transport_is_rejected |
reject_stream_settings, with socks as the protocol its messages name; the app calls it for a SOCKS inbound only on a Unix socket. |
app/tests/unit/config.rs |
a_mistyped_key_is_rejected_rather_than_ignored |
A misspelled accounts key fails to deserialise into SocksInboundSettings. |
app/tests/unit/lower.rs |
a_server_config_lowers_to_its_spec |
A password SOCKS inbound on a Unix socket lowers to BindSpec::Unix, InboundProtocolSpec::Socks { udp: false, udp_bind: None, transport } with the plain shape, and a set keyed by the account name. |
socks_and_shadowsocks_lower_their_stream, socks_and_shadowsocks_on_a_unix_socket_refuse_a_stream |
A SOCKS inbound with udp = false lowers its [inbound.stream] into the spec’s transport, and one on a Unix socket refuses a stream block. |
|
a_user_without_the_name_it_is_keyed_by_is_refused, two_users_with_one_name_are_refused |
accounts[0] has no user, and two accounts with one name refused with both entries named. |
|
app/tests/integration/e2e_udp_route.rs |
one_association_routes_each_peer_separately, replies_from_several_peers_merge_back_correctly |
One association through the real binary, routed per packet by the fan-out, with replies attributed to the right peer. |
app/tests/integration/e2e_xray_wrapped.rs |
app_server_socks_over_tls, app_client_socks_over_tls |
SOCKS5 with credentials inside TLS, against the pinned Xray in both directions: the app’s inbound behind Xray’s client, and the app’s outbound in front of Xray’s server. |
app/tests/integration/e2e_unix.rs |
socks_over_a_unix_socket_relays_and_cleans_up |
CONNECT over a Unix socket through the real binary, with udp = false; the socket file is gone after SIGTERM. The same file’s http_connect_over_a_unix_socket_relays does the same for an HTTP inbound. |
udp_association_ignores_another_ip, udp_association_is_not_widened_by_the_request and udp_link_on_a_dual_stack_socket_hears_an_ipv4_relay are #[cfg(target_os = "linux")], because they rely on 127.0.0.2 being a loopback address or on a dual-stack socket. udp_association_over_a_unix_socket_needs_its_exact_source is #[cfg(unix)], and e2e_unix.rs is compiled only on Unix (#![cfg(unix)]).
Other tests use a SOCKS inbound as their entry point and exercise it indirectly:
supervisor/tests/support/mod.rsbuilds one withsocks_inbound(tag, port, users)(UDP on,udp_bindon loopback, sniffing off, a named user set whenusersis given) and speaks to it withsocks_connect,socks_associate,socks_associate_asandsocks_udp_roundtrip.supervisor/tests/hot_swap.rsandsupervisor/tests/tracking.rsuse these helpers throughout.app/tests/support/mod.rshas the hand-written SOCKS5 clientssocks5_roundtrip,socks5_roundtrip_over,socks5_roundtrip_domain,Socks5Udpandsocks5_udp_roundtrip, which everyapp/tests/integration/e2e_*.rsfile excepte2e_tun.rsuses to reach the real binary.
No test pins the handshake deadline, the relay idle guard, the association idle timer, the refusals the handshake writes, the SOCKS4 and SOCKS4a paths, the reply code a connect error maps to (new_server_refuses_an_unreachable_target_after_trying checks only that a refusal arrives), or the unknown socks auth text. A change to any of these needs a new test.