Dialers
Source files: 71 · checked against Etemenanki 46c12e4 · katana v6.1.0
Etemenanki/environment/Cargo.tomlEtemenanki/environment/src/lib.rsEtemenanki/environment/src/dial/mod.rsEtemenanki/environment/src/dial/socket.rsEtemenanki/environment/src/dial/tcp.rsEtemenanki/environment/src/dial/udp.rsEtemenanki/environment/src/dial/quic.rsEtemenanki/concepts/src/link.rsEtemenanki/concepts/src/net.rsEtemenanki/concepts/src/core.rsEtemenanki/concepts/src/runtime.rsEtemenanki/protocols/src/helpers/address_family.rsEtemenanki/protocols/src/transports/connect.rsEtemenanki/protocols/src/transports/accept.rsEtemenanki/protocols/src/transports/reality.rsEtemenanki/protocols/src/transports/keepalive.rsEtemenanki/protocols/src/dns/mod.rsEtemenanki/protocols/src/socks/server.rsEtemenanki/protocols/src/socks/udp_link.rsEtemenanki/protocols/src/socks/protocol.rsEtemenanki/protocols/src/anytls/client/mod.rsEtemenanki/protocols/src/sss/client.rsEtemenanki/protocols/src/sss/server.rsEtemenanki/protocols/src/hysteria/config.rsEtemenanki/protocols/src/hysteria/connection.rsEtemenanki/protocols/src/hysteria/server/inbound.rsEtemenanki/protocols/src/hysteria/server/endpoint.rsEtemenanki/protocols/src/tun/device.rsEtemenanki/protocols/src/wireguard/config.rsEtemenanki/protocols/src/wireguard/connector.rsEtemenanki/protocols/src/wireguard/slot.rsEtemenanki/protocols/src/wireguard/device.rsEtemenanki/supervisor/src/supervisor.rsEtemenanki/supervisor/src/build/outbound.rsEtemenanki/supervisor/src/build/inbound.rsEtemenanki/supervisor/src/build/dns.rsEtemenanki/supervisor/src/build/validate.rsEtemenanki/supervisor/src/topology/outbound/mod.rsEtemenanki/supervisor/src/topology/outbound/proxy.rsEtemenanki/supervisor/src/topology/outbound/freedom.rsEtemenanki/supervisor/src/topology/outbound/dns.rsEtemenanki/supervisor/src/topology/balancer.rsEtemenanki/supervisor/src/topology/spec_plan/outbound.rsEtemenanki/supervisor/src/topology/spec_plan/transport.rsEtemenanki/supervisor/src/system/listener.rsEtemenanki/supervisor/src/serve.rsEtemenanki/ffi/src/platform.rsEtemenanki/ffi/src/proxy.rsEtemenanki/app/src/lower.rsEtemenanki/app/src/instance.rsEtemenanki/app/src/api.rsEtemenanki/webclient/src/listen.rsEtemenanki/environment/tests/integration.rsEtemenanki/environment/tests/integration/tcp.rsEtemenanki/environment/tests/integration/udp.rsEtemenanki/environment/tests/integration/quic.rsEtemenanki/environment/tests/unit/dial/socket.rsEtemenanki/protocols/tests/unit/helpers/address_family.rsEtemenanki/protocols/tests/unit/dns/mod.rsEtemenanki/protocols/tests/unit/socks/server.rsEtemenanki/protocols/tests/pipeline/socks.rsEtemenanki/supervisor/tests/socket_policy.rsEtemenanki/ffi/tests/proxy.rskatana/Cargo.tomlkatana/Cargo.lockkatana/src/lower/outbound.rskatana/src/manager/node.rskatana/src/runtime.rskatana/src/api/mod.rskatana/tests/unit/lower/outbound.rskatana/tests/unit/api/http.rs
The dial module of etemenanki-environment is where the supervisor’s outbounds, balancer probes and resolvers open their host sockets, and where a REALITY inbound opens its connection to the site it passes itself off as. It holds three dialers (TCP, UDP and, behind the quic feature, QUIC) that apply one SocketOptions policy between creating a socket and binding or connecting it, plus a Dialer that bundles the TCP and UDP dialers and implements the concepts crate’s Connector. Next to it, in etemenanki-protocols, helpers::address_family turns a Destination into the ordered list of addresses a dialer walks. The supervisor joins the two: it takes one SocketOptions from its builder and hands it to every outbound, resolver and health probe it builds.
This page is for contributors who add a socket knob, change how a direct or proxy outbound reaches the network, embed the kernel in an app that must keep its own sockets out of a VPN tunnel, or port it to another OS. It covers every public item in environment/src/dial/, the address-family helpers, every place the supervisor opens a host socket through the dialers, and the places that open sockets without them. The other half of the crate, the route model, is on Route model.
Responsibilities
Section titled “Responsibilities”The module docs draw a hard line between host policy and everything else. The dialers own the host-policy and socket rows; the rest belongs to their callers.
| Decision | Owner | Where |
|---|---|---|
| Source address, interface, packet mark, TCP keepalive idle time, a per-socket hook | Host policy | environment/src/dial/socket.rs → SocketOptions |
| One policy for every outbound socket of a running instance | The supervisor’s builder | supervisor/src/supervisor.rs → SupervisorBuilder::socket_options |
| Which family a socket is opened in, v6-only UDP, the per-attempt connect timeout, trying addresses in turn | Dialers | TcpDialer, UdpDialer, QuicDialer |
| Name resolution, caching, which resolver answers | Routing policy | protocols/src/dns/mod.rs → Resolver |
| Which resolved families an outbound may use, and in what order | Routing policy | protocols/src/helpers/address_family.rs |
| TLS, ALPN, QUIC transport parameters | Protocol policy | the caller’s config: a TCP transport’s ClientConfig, or a quinn::ClientConfig |
Three consequences follow, and all are deliberate:
- No dialer resolves a name.
TcpDialertakes resolvedSocketAddrs,UdpDialertakes address families, andQuicDialertakes aSocketAddr(itsserver_nameargument is only the TLS name).DualStackUdpsends only to IP addresses: itsDatagramLinkimplementation refuses a domain rather than resolving it. Nothing inetemenanki-environmentperforms a DNS lookup. - The dialers never retry or race on their own.
TcpDialer::connect_anywalks the list it is given, in the order given. The order itself comes fromselect_candidate_ips. - The dialers hold no state beyond their options. They take no lock and keep no cache. The only tasks any of them causes are quinn’s: an endpoint driver for each endpoint
QuicDialerbuilds, and a connection driver for each connection it opens. The one log line in the module is the debug linebind_dualwrites when a family fails to bind.
The crate
Section titled “The crate”environment/Cargo.toml names the package etemenanki-environment, version 3.2.1, published to a private Cargo registry. Its dependencies are etemenanki-concepts (requirement 2.1; inside the workspace the path crate, 2.1.2), tokio, pin-project, the routing dependencies (cidr, compact_str, smallvec, regex, prost, tracing), socket2 (0.6.5 in the lockfile, with the workspace’s all feature) and, optionally, quinn. The workspace aliases quinn to shinku-quinn 0.1.0, which is quinn 0.11.12, unmodified, built on a patched quinn-proto 0.11.19 (see shinku-quic). On Windows only, it also depends on windows-sys 0.61 (0.61.2 in the lockfile) with the Win32_Networking_WinSock feature, for IP_UNICAST_IF, which socket2 does not offer there. The dev-dependencies are tokio with test-util, rustls, rustls-pki-types and rcgen 0.14, which the QUIC test uses for a self-signed certificate.
| Feature | Default | Pulls in | Why |
|---|---|---|---|
quic |
off | dep:quinn, that is shinku-quinn (and so rustls) |
The comment in Cargo.toml: a consumer that only wants TCP, UDP and routing should not inherit a second TLS stack. |
The crate root (environment/src/lib.rs) enforces a panic-free style for the whole crate with #![deny(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing, clippy::arithmetic_side_effects)], relaxed only under cfg(test). Its module docs say the two halves, dial and routing, are deliberately independent of each other, and that what the host supports is decided per target OS at compile time while the rest of the crate is the same everywhere.
environment/src/dial/mod.rs declares socket, tcp, udp and, under cfg(feature = "quic"), quic. It re-exports AddressFamily, Interface, SocketHook, SocketOptions, DEFAULT_CONNECT_TIMEOUT, TcpDialer, DualStackUdp, UdpDialer and, with the feature, QuicDialer and SocketWrap, so callers write etemenanki_environment::dial::TcpDialer.
Key types
Section titled “Key types”SocketOptions and AddressFamily
Section titled “SocketOptions and AddressFamily”environment/src/dial/socket.rs defines the policy and the small vocabulary around it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]pub enum AddressFamily { V4, V6,}
impl AddressFamily { pub fn of(addr: &SocketAddr) -> Self; pub fn of_ip(ip: IpAddr) -> Self; pub fn unspecified(self) -> IpAddr; // 0.0.0.0 or :: pub fn is_v6(self) -> bool; pub(crate) fn domain(self) -> socket2::Domain;}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]pub enum Interface { Name(CompactString), Index(NonZeroU32),}
pub type SocketHook = Arc<dyn Fn(&Socket) -> io::Result<()> + Send + Sync>;
#[derive(Clone, Default)]pub struct SocketOptions { pub bind_address: Option<IpAddr>, pub interface: Option<Interface>, pub mark: Option<u32>, pub tcp_keepalive: Option<Duration>, pub hook: Option<SocketHook>,}
impl SocketOptions { pub fn new() -> Self; // Self::default() pub fn with_bind_address(mut self, ip: IpAddr) -> Self; pub fn with_interface(mut self, interface: Interface) -> Self; pub fn with_mark(mut self, mark: u32) -> Self; pub fn with_tcp_keepalive(mut self, idle: Duration) -> Self; pub fn with_hook(mut self, hook: SocketHook) -> Self; pub fn bind_address_for(&self, family: AddressFamily) -> Option<IpAddr>; pub fn apply(&self, socket: &Socket, family: AddressFamily) -> io::Result<()>;}Socket is socket2::Socket. AddressFamily::domain maps to socket2::Domain::IPV4 or IPV6 and is used only by UdpDialer::bind, which builds its socket with socket2.
SocketOptions::default() sets nothing: no bind address, no interface, no mark, the platform’s keepalive, no hook. etemenanki-app and katana run with that default. The only in-tree front end that sets anything is the mobile bindings, and they set only the hook (see How the supervisor uses it). No crate in the workspace or in katana sets bind_address, interface, mark or tcp_keepalive, or changes a dialer’s connect timeout; only the environment’s own tests do.
The five knobs are applied in two places, because binding differs per socket type:
| Field | Applied by | Effect |
|---|---|---|
bind_address |
the dialer, through bind_address_for(family) |
Bound only on a socket of the same family. A v4 bind address leaves v6 sockets to the kernel’s source selection, and the other way round. |
interface |
SocketOptions::apply |
Ties the socket to one interface; see the platform table below. |
mark |
SocketOptions::apply |
SO_MARK, for policy routing on Linux and Android. |
hook |
SocketOptions::apply, last |
Runs arbitrary code on the raw socket2::Socket. |
tcp_keepalive |
TcpDialer::socket only |
Sets the keepalive idle time with socket2::TcpKeepalive::new().with_time(idle), which also turns keepalive on. Interval and probe count stay at the platform defaults. UDP and QUIC sockets ignore the field. |
bind_address_for(family) is self.bind_address.filter(|ip| AddressFamily::of_ip(*ip) == family). apply runs interface, then mark, then hook, and returns the first error, so a failed interface binding means the mark is never set and the hook never runs. Its doc comment states the split: the bind address is the dialer’s to apply, since binding differs per socket type.
SocketOptions implements Debug by hand, because a closure has no Debug of its own: the hook prints as hook: Some("...") (or None), and every other field prints normally. Hy2Config (protocols/src/hysteria/config.rs), which carries the policy in its socket field, prints that field through this impl. The hook is an Arc, so every clone of the options (each dialer holds its own clone) calls the same closure.
Interface binding and marks per platform
Section titled “Interface binding and marks per platform”What the host supports is decided at compile time with cfg(target_os). A knob the platform lacks is an error, never a silent no-op. The module docs give the reason: a no-op would leave traffic leaving by the wrong path.
| Knob | Linux | Android, Fuchsia | macOS, iOS, tvOS, watchOS, visionOS | Windows | Everything else (the BSDs) |
|---|---|---|---|---|---|
Interface::Name |
socket.bind_device (SO_BINDTODEVICE) |
socket.bind_device (SO_BINDTODEVICE) |
Unsupported: binding by interface name needs an interface index on Apple platforms |
Unsupported: binding by interface name needs an interface index on Windows |
Unsupported: binding a socket to an interface is not supported on {os} |
Interface::Index |
bind_device_by_index_v4 or _v6, chosen by the socket’s family; in socket2 0.6.5 both set SO_BINDTOIFINDEX |
Unsupported: binding a socket to an interface by index is not supported on {os} |
bind_device_by_index_v4 or _v6 (IP_BOUND_IF, IPV6_BOUND_IF) |
setsockopt through windows-sys, chosen by the socket’s family: IP_UNICAST_IF with the index in network byte order, or IPV6_UNICAST_IF with it in host order; a failure is the WSAGetLastError code |
Unsupported, as for a name |
mark |
socket.set_mark (SO_MARK) |
socket.set_mark (SO_MARK) |
Unsupported: a socket mark is not supported on {os} |
Unsupported, as on Apple |
Unsupported, as on Apple |
bind_address, hook, tcp_keepalive |
yes | yes | yes | yes | yes |
The Windows functions are environment/src/dial/socket.rs → bind_interface and bind_interface_index under #[cfg(windows)]. Every Unsupported except the Apple and Windows name cases comes from the crate-private unsupported(what), which formats {what} is not supported on {std::env::consts::OS}, for example a socket mark is not supported on macos or binding a socket to an interface is not supported on freebsd. The function carries #[allow(dead_code)] because on a platform that has every knob nothing calls it.
On Linux the kernel may refuse a mark or a device binding to a process without the needed capability; the unit test’s comment names CAP_NET_ADMIN or CAP_NET_RAW. The refusal is EPERM, which apply returns unchanged as io::ErrorKind::PermissionDenied. The unit test mark_and_loopback_device_take_effect_or_are_refused_by_the_kernel accepts exactly those two outcomes, success or PermissionDenied, for with_mark(7) and for Interface::Name("lo").
SocketHook
Section titled “SocketHook”A hook runs on every socket a dialer opens, after the interface and mark and before any bind or connect: TCP sockets, UDP sockets (after the v6-only flag is set on an IPv6 one), the UDP socket under a QUIC endpoint, and the probe socket of UdpDialer::source_toward. It sees the raw socket2::Socket, so it can do anything the platform allows. Its error propagates unchanged: hook_runs_on_apply_and_its_error_propagates checks that the hook runs once per apply and that vpn refused to protect the socket comes back as the exact error text.
The hook runs synchronously inside TcpDialer::socket, UdpDialer::bind or UdpDialer::source_toward, which are not async, on the thread that runs the task opening the socket. Every in-tree caller runs on a tokio runtime, so that is a tokio worker thread. A hook that blocks stalls that worker and every task scheduled on it, not only the one dial, so it must return promptly.
The doc comment names the use it exists for: a mobile VPN app that must keep its own outbound sockets out of the tunnel it provides. The in-tree embedder is etemenanki-ffi, the Android and iOS library described on Mobile library (etemenanki-ffi). ffi/src/platform.rs → socket_options builds its policy:
pub(crate) fn socket_options(platform: Arc<dyn Platform>) -> SocketOptions { SocketOptions::default().with_hook(Arc::new(move |socket| { if platform.protect(socket.as_raw_fd()) { Ok(()) } else { Err(io::Error::new( io::ErrorKind::PermissionDenied, "the platform refused to protect the socket", )) } }))}Platform::protect(fd) is the app’s callback, implemented in Kotlin or Swift. Its doc comment defines it:
- on Android it is
VpnService.protect(fd), called before the socket connects; - a socket the platform refuses (
false) is closed unused, and the dial it was for fails; - where the tunnel already excludes the app’s own traffic, as on iOS, the platform returns
true.
So on iOS every socket still passes through the hook, which lets it through unchanged. The Platform trait’s doc comment adds the threading contract: its methods are called from the proxy’s own threads, any of them, at any time until Proxy::stop returns, and they must not throw, because an exception is a panic on the Rust side. For protect that means the callback runs on whichever tokio worker opens the socket, as described above.
TcpDialer
Section titled “TcpDialer”environment/src/dial/tcp.rs:
pub const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
#[derive(Debug, Clone)]pub struct TcpDialer { options: SocketOptions, connect_timeout: Duration,}
impl TcpDialer { pub fn new(options: SocketOptions) -> Self; // DEFAULT_CONNECT_TIMEOUT pub fn with_connect_timeout(mut self, timeout: Duration) -> Self; pub fn options(&self) -> &SocketOptions; pub fn connect_timeout(&self) -> Duration; pub fn socket(&self, family: AddressFamily) -> io::Result<TcpSocket>; pub async fn connect(&self, addr: SocketAddr) -> io::Result<TcpStream>; pub async fn connect_any(&self, addrs: &[SocketAddr]) -> io::Result<TcpStream>;}TcpDialer::default() is TcpDialer::new(SocketOptions::default()), so it also has DEFAULT_CONNECT_TIMEOUT. The constant’s doc comment defines it as how long one connect attempt may take before the next address is tried.
socket(family)creates a tokioTcpSocketof that family (TcpSocket::new_v4()ornew_v6()), applies the policy through asocket2::SockRefof it, sets the keepalive idle time whentcp_keepaliveisSome, and bindsbind_address_for(family)on port 0 when there is one. Without a bind address the socket stays unbound and the kernel picks the source at connect time. The socket is returned unconnected, so a caller that needs another option can still set it.connect(addr)openssocket(AddressFamily::of(&addr))and wrapssocket.connect(addr)intokio::time::timeout(self.connect_timeout, …). When the timer fires first the error isio::ErrorKind::TimedOutwithconnect to {addr} timed out. Any other error, including one fromsocket, is returned as it is.connect_any(addrs)callsconnecton each address in turn and returns the first stream that connects.
connect_any is sequential on purpose. Its doc comment names the case it exists for, a dual-stack host that resolves a name to an address it cannot reach (a stale AAAA record, a v6 route that black-holes), where giving up after the first failure would strand the destination for as long as DNS keeps that ordering. It says outright that this is not Happy Eyeballs: attempts are never raced, the per-attempt timeout bounds the worst case, and every failure is kept so the cause is not lost.
flowchart TB
start["connect_any(addrs)"] --> more{"next address?"}
more -- yes --> attempt["connect(addr): socket(family), then connect under connect_timeout"]
attempt -- "Ok(stream)" --> done["return Ok(stream)"]
attempt -- "Err(e)" --> record["failures.push(addr: e)"]
record --> more
more -- "no, failures empty" --> none["Err ConnectionRefused: none given"]
more -- "no, failures recorded" --> all["Err ConnectionRefused: every failure, joined"]
The final error always has kind io::ErrorKind::ConnectionRefused, whatever the individual causes were. Its message is failed to connect to any address (…), where the parentheses hold either none given (an empty slice) or every {addr}: {error} joined with ; . A caller that needs the per-attempt kinds has to call connect itself.
UdpDialer
Section titled “UdpDialer”environment/src/dial/udp.rs:
#[derive(Debug, Clone, Default)]pub struct UdpDialer { options: SocketOptions,}
impl UdpDialer { pub fn new(options: SocketOptions) -> Self; pub fn options(&self) -> &SocketOptions; pub fn bind(&self, family: AddressFamily) -> io::Result<UdpSocket>; pub fn source_toward(&self, peer: SocketAddr) -> io::Result<IpAddr>; pub fn bind_dual( &self, families: impl IntoIterator<Item = AddressFamily>, ) -> io::Result<DualStackUdp>;}bind(family) builds the socket with socket2 rather than tokio, because the v6-only flag and the policy must be set before the bind. Both dialers follow the same order (create, apply the policy, bind), with one difference: a UDP socket is always bound (to the wildcard address when there is no bind address), because an unconnected UDP socket has to be bound to receive anything.
| Step | UdpDialer::bind |
TcpDialer::socket |
|---|---|---|
| 1. Create | Socket::new(family.domain(), Type::DGRAM, Some(Protocol::UDP)) |
TcpSocket::new_v4() or TcpSocket::new_v6() |
| 2. Family flag | for V6 only: set_only_v6(true) |
none |
| 3. Policy | options.apply(&socket, family) (interface, mark, hook) |
options.apply(&SockRef::from(&socket), family) (interface, mark, hook) |
| 4. Socket-type option | set_nonblocking(true) |
if tcp_keepalive is set: set_tcp_keepalive(&TcpKeepalive::new().with_time(idle)) |
| 5. Bind | always: bind_address_for(family), or else family.unspecified(), on port 0 |
only when bind_address_for(family) is Some: that address on port 0 |
| 6. Hand over | UdpSocket::from_std(socket.into()) |
the unconnected TcpSocket; connect does the rest |
The last step of bind registers the socket with tokio’s reactor, so bind and bind_dual must run inside a tokio runtime with I/O enabled; tokio’s UdpSocket::from_std panics outside one. Every caller in the workspace runs on the runtime.
The IPv6 socket is v6-only by design. The doc comment on bind gives the reason: a dual-stack socket would report an IPv4 peer back as a v4-mapped address (::ffff:192.0.2.1), which no longer equals the address the datagram was sent to, and every layer above that keys state by peer address would then miss. IPv4 gets its own socket instead, and bind_dual pairs the two.
bind_dual(families) binds one socket per requested family and tolerates a family that fails. Its doc comment gives the example of a host without IPv6. A failed bind is logged at debug level as udp: no {family:?} socket: {e} (for example udp: no V6 socket: …) and that slot stays empty. A family listed twice is bound twice, and a second socket that binds replaces the first. Only when no slot is filled at the end does it return io::ErrorKind::AddrNotAvailable, with one of two messages:
| Situation | Message |
|---|---|
| At least one family requested, none bound | udp: no usable local socket in any requested family |
| The iterator was empty | udp: no address family requested |
source_toward(peer) asks which source address the kernel would send from to reach peer from a socket under this policy, without sending anything. It opens a probe socket with socket2 in peer’s family (v6-only for IPv6), runs apply (interface, mark, hook), binds bind_address_for(family) on port 0 when there is one, and UDP-connects it to peer, which only looks the route up. It returns the socket’s local IP, and the socket is dropped. An error means the kernel has no route, or that the policy refused the socket; a local address that is not an IP is udp: a probe socket has no IP address. The socket is never registered with tokio, so the call needs no runtime. Its one caller is supervisor/src/topology/outbound/freedom.rs → FreedomConnector::lacks_ipv6, which the supervisor’s TUN IPv6 screen asks about each IPv6 TCP connection (see Route model).
DualStackUdp
Section titled “DualStackUdp”DualStackUdp is up to one socket per family, addressed as one link.
#[derive(Debug)]pub struct DualStackUdp { v4: Option<UdpSocket>, v6: Option<UdpSocket>,}
impl DualStackUdp { pub fn v4(&self) -> Option<&UdpSocket>; pub fn v6(&self) -> Option<&UdpSocket>; pub fn socket_for(&self, peer: &SocketAddr) -> io::Result<&UdpSocket>; pub fn poll_send_to( &self, cx: &mut Context<'_>, buf: &[u8], to: SocketAddr, ) -> Poll<io::Result<usize>>; pub fn poll_recv_from( &self, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll<io::Result<SocketAddr>>; pub async fn send_to(&self, buf: &[u8], to: SocketAddr) -> io::Result<usize>; pub async fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)>;}
impl DatagramLink for DualStackUdp { type Addr = Destination; // poll_send_to(&mut self, cx, buf, to: &Destination) // poll_recv_from(&mut self, cx, buf) -> Poll<io::Result<Destination>>}Only bind_dual constructs one; the fields are private.
The receive side polls the two sockets in a fixed order:
flowchart LR
recv["poll_recv_from(buf)"] --> r4{"v4 socket ready?"}
r4 -- yes --> got["Ready(peer)"]
r4 -- "no or not bound" --> r6{"v6 socket ready?"}
r6 -- yes --> got
r6 -- "no or not bound" --> pend["Pending, waker registered on each bound socket"]
- Send goes out of
socket_for(&to), the socket of the peer’s family. When that family was not bound, the call fails withio::ErrorKind::AddrNotAvailableandudp: no local socket in the family of {peer}.send_tois the async form of the same choice. - Receive polls the v4 socket first, then the v6 socket, and returns the first datagram found. A socket that is not ready registers the task’s waker, so a datagram on either family wakes the task. The returned peer is the real source address, never v4-mapped, because of the v6-only flag.
recv_fromwrapspoll_recv_frominstd::future::poll_fnand returns the filled length with the peer. - As a
DatagramLinkthe link is addressed byDestination(concepts/src/net.rs).poll_send_toaccepts only aDestinationwhoseremoteis an IP (Destination::socket_addr()isSome). A domain fails withio::ErrorKind::Unsupportedandudp: a plain dual-stack link cannot resolve a domain. Received peers come back asDestination::udp(addr).
When a datagram outbound refuses a send, ProxyServerRuntime (concepts/src/runtime.rs → report_send_failure) drops the packet, keeps the key and tells the core with Event::SendFailed. Of the datagram link’s own errors, only a failed receive removes the key (fail_outbound, which tells the core with Event::OutboundError); the core can still close the key itself with Effect::Close. The concepts crate’s own UdpOutbound behaves the same way for a single socket (a plain UDP outbound cannot resolve a domain). Resolving belongs in a wrapper that owns a resolver, such as the supervisor’s freedom link ResolvingUdp.
Dialer and DialTarget
Section titled “Dialer and DialTarget”environment/src/dial/mod.rs bundles the two everyday dialers and makes them a Connector, so a server core’s Effect::Open can land directly on a host socket.
#[derive(Debug, Clone, PartialEq, Eq)]pub enum DialTarget { /// Connect to the first of these that answers, in order. Tcp(Vec<SocketAddr>), /// Bind an unconnected socket per listed family; the peer is chosen per packet. Udp(Vec<AddressFamily>),}
#[derive(Debug, Clone, Default)]pub struct Dialer { pub tcp: TcpDialer, pub udp: UdpDialer,}
impl Dialer { pub fn new(options: SocketOptions) -> Self;}
impl Connector<DialTarget> for Dialer { type Stream = TcpStream; type Datagram = DualStackUdp; type Future = DialFuture<TcpStream, DualStackUdp>; fn connect(&mut self, target: DialTarget) -> Self::Future;}
impl Connector<SocketTarget> for Dialer { type Stream = TcpStream; type Datagram = UdpOutbound; type Future = DialFuture<TcpStream, UdpOutbound>; fn connect(&mut self, target: SocketTarget) -> Self::Future;}
type DialFuture<S, D> = Pin<Box<dyn Future<Output = io::Result<Outbound<S, D>>> + Send>>;Dialer::new(options) gives both dialers the same SocketOptions: a clone to the TCP dialer, the original to the UDP dialer. The fields are public, so a caller can replace tcp with one that has another connect timeout; nothing in the workspace does. Each connect clones both dialers into a boxed future, so the future owns everything it needs and does not borrow the Dialer.
| Target | What connect does |
Result |
|---|---|---|
DialTarget::Tcp(addrs) |
tcp.connect_any(&addrs) |
Outbound::Stream(TcpStream) |
DialTarget::Udp(families) |
udp.bind_dual(families) |
Outbound::Datagram(DualStackUdp) |
SocketTarget::Tcp(addr) |
tcp.connect(addr) (one address) |
Outbound::Stream(TcpStream) |
SocketTarget::Udp { ipv6 } |
udp.bind(V6) if ipv6, else udp.bind(V4) |
Outbound::Datagram(UdpOutbound(socket)) |
SocketTarget is the concepts crate’s own target (concepts/src/link.rs), which its policy-free SocketConnector also implements. Dialer differs from SocketConnector in three ways: it applies the SocketOptions policy, it bounds the TCP connect with connect_timeout (SocketConnector calls TcpStream::connect with no timer), and it opens the IPv6 UDP socket v6-only (SocketConnector binds [::]:0 with tokio’s UdpSocket::bind, leaving IPV6_V6ONLY at the OS default, and binds 0.0.0.0:0 for IPv4). SocketConnector is a unit struct deriving Debug, Clone, Copy and Default; SocketTarget derives Debug, Clone, Copy, PartialEq and Eq.
No code outside the tests calls either Connector implementation. The supervisor’s outbounds call dialer.tcp.connect_any, dialer.udp.bind_dual and UdpDialer::bind directly, after their own resolution step, a REALITY inbound calls dialer.tcp.connect_any for its cover site the same way, and the balancer probe calls TcpDialer::connect. The implementations are exercised by the environment’s integration tests, including a full ProxyServerRuntime run. The connector traits are described on Links, connectors and net types.
QuicDialer and SocketWrap
Section titled “QuicDialer and SocketWrap”feature quic environment/src/dial/quic.rs is compiled only with the crate’s quic feature. No workspace member and no katana dependency enables it, so QuicDialer is compiled only when the feature is switched on (for example by --all-features), and only the environment’s integration tests call it. The Hysteria 2 client in protocols/src/hysteria/connection.rs binds its sockets through UdpDialer::bind, so the socket policy and the v6-only rule reach them, but it builds its own quinn::Endpoint on that socket, or on a shinku_quic::hop::HoppingSocket when port hopping is set (see Port hopping), rather than going through QuicDialer.
pub type SocketWrap = Box<dyn FnOnce(Arc<dyn AsyncUdpSocket>) -> io::Result<Arc<dyn AsyncUdpSocket>> + Send>;
#[derive(Debug, Clone, Default)]pub struct QuicDialer { udp: UdpDialer,}
impl QuicDialer { pub fn new(options: SocketOptions) -> Self; pub fn options(&self) -> &SocketOptions; pub fn endpoint( &self, family: AddressFamily, wrap: Option<SocketWrap>, ) -> io::Result<Endpoint>; pub async fn connect( &self, endpoint: &Endpoint, addr: SocketAddr, server_name: &str, config: ClientConfig, ) -> io::Result<Connection>; pub async fn dial( &self, addr: SocketAddr, server_name: &str, config: ClientConfig, wrap: Option<SocketWrap>, ) -> io::Result<(Endpoint, Connection)>;}endpoint(family, wrap)takes a socket fromUdpDialer::bind(family)(so the wholeSocketOptionspolicy and the v6-only rule apply), converts it back to a standard socket withinto_std, hands it toquinn::Runtime::wrap_udp_socketonTokioRuntime, passes the result throughwrapif one is given, and builds a client-only endpoint withEndpoint::new_with_abstract_socket(EndpointConfig::default(), None, socket, Arc::new(TokioRuntime)). TheNoneserver config means the endpoint accepts no incoming connections.SocketWrapreplaces the socket underneath QUIC. Its doc comment says it is meant for an obfuscation layer that must see every packet after QUIC has sealed it. It is called once, while the endpoint is built.connect(endpoint, addr, server_name, config)maps a refusal fromendpoint.connect_with(a bad config or address) toio::ErrorKind::InvalidInput, and a failed handshake toio::ErrorKind::ConnectionRefused, each carrying quinn’s error. The endpoint must be able to reachaddr’s family.dial(addr, server_name, config, wrap)builds an endpoint foraddr’s family and connects through it. It returns theEndpointtogether with theConnection, so the caller holds the endpoint: to close it, to wait for it to go idle, or to open another connection through it.
Building an endpoint makes quinn spawn its endpoint driver task on the tokio runtime, and each connect makes it spawn a connection driver task for the new connection. In quinn 0.11.12 (shinku-quinn 0.1.0) the endpoint driver finishes only once no Endpoint handle and no connection remain; dropping the last handle wakes it, and it keeps running while a connection is open.
The TLS side (certificate verification, ALPN, transport parameters) is entirely the caller’s quinn::ClientConfig; the module docs call it protocol policy rather than host policy.
Address-family policy
Section titled “Address-family policy”protocols/src/helpers/address_family.rs answers the question the dialers refuse to: given a Destination, which IPs may be tried, and in what order. The module docs split the answer into two independent inputs:
- policy, what the operator asked for: an
AddressFamilyStrategy; - capability, which families the outbound can actually source traffic from: a
FamilySupport.
For a kernel-routed dialer the kernel answers capability (it consults the routing table, picks a source address and fails fast with ENETUNREACH), so those callers pass FamilySupport::both() and let policy alone decide. A userspace netstack with no routing table, such as the WireGuard outbound, derives capability from its tunnel-local addresses instead.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]pub enum AddressFamilyStrategy { #[default] Auto, Ipv4Only, Ipv6Only, PreferIpv4, PreferIpv6,}
impl AddressFamilyStrategy { pub fn allows(self, ip: IpAddr) -> bool; // false only for the other family under *_only pub fn as_str(self) -> &'static str;}
impl FromStr for AddressFamilyStrategy { type Err = AddressFamilyStrategyParseError; fn from_str(s: &str) -> Result<Self, Self::Err>;}
#[derive(Debug, thiserror::Error, Clone, Copy, PartialEq, Eq)]#[error("unknown address family strategy")]pub struct AddressFamilyStrategyParseError;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct FamilySupport { ipv4: bool, ipv6: bool,}
impl FamilySupport { pub fn both() -> Self; pub fn from_addrs(addrs: &[IpAddr]) -> Self; pub fn supports(self, ip: IpAddr) -> bool; pub fn describe(self) -> &'static str;}
pub async fn resolve_candidates( context: &str, dest: &Destination, strategy: AddressFamilyStrategy, support: FamilySupport, resolver: &Resolver,) -> io::Result<Vec<IpAddr>>;
pub fn select_candidate_ips( resolved: Vec<IpAddr>, strategy: AddressFamilyStrategy, support: FamilySupport,) -> Vec<IpAddr>;
pub fn no_candidate_error( context: &str, dest: &Destination, strategy: AddressFamilyStrategy, support: FamilySupport,) -> io::Error;
pub async fn destination_to_socketaddrs( dest: &Destination, strategy: AddressFamilyStrategy, resolver: &Resolver,) -> io::Result<Vec<SocketAddr>>;The doc comment on AddressFamilyStrategy explains the default: Auto keeps the resolver’s own order, which already reflects the host’s address-selection rules, and the explicit variants exist for the cases where the resolver’s answer is wrong for one particular outbound. FamilySupport::default() is both(). from_addrs sets each flag when any address of that family is present. describe() yields IPv4 and IPv6, IPv4 only, IPv6 only or no address family.
Parsing a strategy
Section titled “Parsing a strategy”FromStr trims the input, lower-cases it (ASCII) and reads - as _ before matching. Anything else is AddressFamilyStrategyParseError (unknown address family strategy), which each front end turns into its own config error.
| Variant | as_str() |
Accepted spellings |
|---|---|---|
Auto |
auto |
auto, the empty string |
Ipv4Only |
ipv4_only |
ipv4, v4, 4, ipv4_only, ipv4only |
Ipv6Only |
ipv6_only |
ipv6, v6, 6, ipv6_only, ipv6only |
PreferIpv4 |
prefer_ipv4 |
prefer_ipv4, prefer_v4, ipv4_prefer, v4_prefer |
PreferIpv6 |
prefer_ipv6 |
prefer_ipv6, prefer_v6, ipv6_prefer, v6_prefer |
So " Prefer-IPv4 " parses as PreferIpv4, and ipv4-only as Ipv4Only. The error texts the front ends print for a bad value are in The address_family settings.
Candidate ordering
Section titled “Candidate ordering”resolve_candidates gets the raw answer first:
Remote::IpAddr(ip)is used as it is, without the resolver.Remote::Domain(name)goes throughresolver.resolve(name)(protocols/src/dns/mod.rs). The resolver answers an address literal as it is; otherwise it answers from its hosts table when it has one (ResolverOptions::hosts, which the supervisor fills for a split DNS spec withuse_hosts), then from its cache while an entry is fresh, and otherwise asks each configured upstream in turn until one answers (Resolver::lookup). The answer is de-duplicated in the backend’s order. With the system backend that order isgetaddrinfo’s, which applies the host’s address-selection rules. With a configured UDP, DoT or DoH server the A and AAAA queries run together (tokio::join!inquery_both), and the A answers come before the AAAA answers.
select_candidate_ips then keeps the addresses for which strategy.allows(ip) && support.supports(ip) holds, and reorders. The prefer_* sorts are stable sorts on a single bit (sort_by_key(|ip| usize::from(ip.is_ipv6())) for PreferIpv4), so each family keeps the resolver’s order internally and the other family stays in the list as a fallback.
| Strategy | Resolver answer [2001:db8::1, 192.0.2.1, 2001:db8::2], support both() |
|---|---|
Auto |
2001:db8::1, 192.0.2.1, 2001:db8::2 (unchanged) |
Ipv4Only |
192.0.2.1 |
Ipv6Only |
2001:db8::1, 2001:db8::2 |
PreferIpv4 |
192.0.2.1, 2001:db8::1, 2001:db8::2 |
PreferIpv6 |
2001:db8::1, 2001:db8::2, 192.0.2.1 |
With FamilySupport::from_addrs(&[192.0.2.2]) (a v4-only capability), even Auto drops every IPv6 candidate.
destination_to_socketaddrs is the kernel-routed shortcut: resolve_candidates("dial", dest, strategy, FamilySupport::both(), resolver), then each IP paired with dest.port. It keeps all candidates, unlike a bare lookup_host(..).next(); its doc comment says this is what lets TcpDialer::connect_any fall back when the leading address is unreachable. The context string names the caller in error texts: dial for everything that goes through destination_to_socketaddrs, wireguard for destinations inside a WireGuard tunnel.
Errors from resolution
Section titled “Errors from resolution”| Situation | Kind | Message |
|---|---|---|
The lookup itself fails: a getaddrinfo error, or, with configured servers, no server gave an answer |
as the backend reports it | the backend’s error, unchanged; with several servers, the last one’s (for one server, the last failed A or AAAA query when neither returned an address), for example dns: query timed out |
| The resolver has no server and the name is not in its hosts table | NotFound |
dns: {host} is not in the hosts file and no server is configured |
| The lookup succeeds with no addresses | NotFound |
dns: {host} did not resolve (from Resolver::resolve_with_ttl) |
| The resolver returns an empty list (defensive check) | NotFound |
{context}: destination did not resolve |
| Addresses resolved (or an IP literal was given), but policy and capability rule all of them out | AddrNotAvailable |
{context}: no usable {strategy} destination address for {remote}:{port} |
As above, with a capability narrower than both() |
AddrNotAvailable |
the same, followed by (local address supports {describe()}) |
For example, a freedom outbound with ipv6_only asked to reach a name that has only A records fails with dial: no usable ipv6_only destination address for example.com:443. The capability clause is left out for a kernel-routed dialer on purpose; the code’s comment says that there it is always “both” and would not help.
Data flow
Section titled “Data flow”A proxy upstream dial
Section titled “A proxy upstream dial”TransportConnector::dial in protocols/src/transports/connect.rs is the path every TCP-carried proxy outbound takes (SOCKS, HTTP, Trojan, VLESS, VMess, Shadowsocks, Shadowsocks 2022, AnyTLS and sss; not Hysteria 2 or WireGuard). The supervisor builds it in supervisor/src/build/outbound.rs → transport_connector, with Dialer::new(socket), its servers resolver and the outbound’s address_family. Two outbounds reach it through a layer of their own:
- AnyTLS (
protocols/src/anytls/client/mod.rs→AnyTlsConnector::new) keeps a pool of sessions and callsTransportConnector::dialonly when a flow finds no usable idle session, or the idle session it took fails as the flow opens, so a flow on a reused session opens no socket. See AnyTLS. - sss dials through
SssConnector(protocols/src/sss/client.rs), which calls theTransportConnectorit wraps and puts the stream it returns inside the client’s transform chains.ProxyClient(supervisor/src/topology/outbound/proxy.rs) takes its connector as a type parameter,TransportConnectorby default, for this. See sss.
sequenceDiagram
participant T as TransportConnector
participant F as address_family
participant R as Resolver
participant D as TcpDialer
participant K as kernel
T->>F: destination_to_socketaddrs(dest, strategy, resolver)
opt remote is a domain
F->>R: resolve(domain)
R-->>F: Vec of IpAddr, de-duplicated
end
F-->>T: candidates filtered and ordered, paired with dest.port
T->>D: connect_any(addrs)
loop each address until one connects
D->>K: socket(family), apply policy, bind if asked
D->>K: connect under connect_timeout
K-->>D: stream, or an error recorded in failures
end
D-->>T: TcpStream, or ConnectionRefused listing every failure
T->>T: set_keepalive(tcp), then wrap in TLS, WS, gRPC or REALITY
TransportConnector::dial refuses a UDP destination up front with Unsupported (a proxy transport carries no datagrams of its own), since a proxy’s UDP rides inside its stream. After the connect it calls transports::keepalive::set_keepalive, which sets idle TCP_KEEPALIVE_IDLE (120 s), interval TCP_KEEPALIVE_INTERVAL (30 s) and TCP_KEEPALIVE_RETRIES (3). The comment on the constants gives the reason: Linux waits two hours before its first probe, and a proxy’s peers routinely disappear without a FIN. The doc comment of set_keepalive calls it best effort: a backstop for dead peers rather than a substitute for the idle timeouts above it, and a peer that keeps answering probes is not reclaimed by it. A platform that refuses the options is not a reason to drop the connection; the refusal is logged at debug level as could not enable TCP keepalive: {e}. TransportConnector::tcp() is a convenience constructor with Dialer::default(), the system resolver and Auto; the supervisor does not use it. What happens after the wrap is on Transports: TCP and TLS; a VLESS outbound over REALITY wraps the socket in REALITY’s own TLS 1.3, and with the Vision flow also in the Vision adapter (see REALITY transport and VLESS Vision).
A direct flow
Section titled “A direct flow”The supervisor’s freedom outbound (supervisor/src/topology/outbound/freedom.rs → FreedomConnector) is the one outbound that dials the flow’s own destination from this host.
flowchart TB
start["FreedomConnector::dial(dest)"] --> kind{"dest.network"}
kind -- "Udp" --> fam["families(): V4, V6, or both"]
fam --> dual["dialer.udp.bind_dual(families)"]
dual --> udplink["ResolvingUdp over the DualStackUdp"]
kind -- "anything else" --> res["destination_to_socketaddrs(dest, strategy, destinations resolver)"]
res --> tcpdial["dialer.tcp.connect_any(addrs)"]
tcpdial --> stream["TcpStream"]
The UDP side is described under Direct flows.
How the supervisor uses it
Section titled “How the supervisor uses it”Every host socket an outbound opens itself goes through the dialers, and so does a REALITY inbound’s connection to its cover site; every dialer the supervisor builds carries one policy. Lookups through the system resolver are the exception, since getaddrinfo opens its own sockets, and so is an sss inbound’s fallback connection, which tokio opens (see Sockets that do not go through the dialers). The configurable parts are the policy itself, which only an embedder sets, and the per-outbound address_family settings, which become AddressFamilyStrategy values.
One policy per supervisor
Section titled “One policy per supervisor”pub struct SupervisorBuilder<U: UserId> { options: ApplyOptions, sample_interval: Duration, usage_sink: Option<PushUsage<U>>, socket: SocketOptions, // SocketOptions::default() unless set}
impl<U: UserId> SupervisorBuilder<U> { pub fn socket_options(mut self, socket: SocketOptions) -> Self;}The doc comment of socket_options lists what the policy covers: each dial of an outbound or a balancer probe, each UDP socket of a direct flow, a SOCKS UDP relay, a Hysteria 2 or WireGuard tunnel, and every query a resolver sends from this host. It holds for the supervisor’s lifetime; an apply cannot change it. The system resolver (getaddrinfo) opens its sockets inside the C library, where no policy reaches them. The policy also covers one socket the list leaves out: a REALITY inbound’s connection to its cover site.
SupervisorBuilder::start moves the policy into the actor (Actor::new(self.socket)), which keeps it in its socket field. From there it reaches three places:
- Staging (
Actor::stage, which plans a spec and stages its users before prepare) passes a clone tostage_users, which hands it tosupervisor/src/build/inbound.rs→build_handlerfor every inbound handler it builds. Only a REALITY transport keeps it:build_transport→build_realitygives the REALITY serverDialer::new(socket)for its cover site. - Prepare passes a reference to
build_dnswhen the plan containsStep::Build(Resource::Dns), or when no resolver has been built yet; otherwise it reuses the resolvers it has, together with their DNS service target. It also passes the policy tobuild_outboundfor every outbound it builds. - Commit passes a clone to
TcpDialer::newfor each new balancer’s probes.
check (supervisor/src/supervisor.rs) builds everything a start would (outbounds, routes with their geodata, handlers with their certificates, user tables) short of binding a listener or device. It builds its actor with SocketOptions::default(), stages the spec and runs prepare, never commit. Its callers:
| Front end | Where | When |
|---|---|---|
| etemenanki-app | app/src/instance.rs → check |
--test |
| etemenanki-app | app/src/api.rs → ConfigFile::set_route → instance::check_bytes |
the REST API’s route switch, before it writes the edited config file |
| katana | src/runtime.rs → check_node |
--test (test_config); build_node, before a node is built; a reload, for each node it adds or whose config or shared settings changed |
Building opens no socket, so a hook never runs during a check. A WireGuard tunnel’s socket, for example, is opened by the first dial through it (WgConnector::dial → acquire_device → WgDevice::start), balancer probes start only at commit, and a REALITY inbound dials its cover site only for a connection it has accepted. The supervisor side of this is also covered on Outbounds, UDP fan-out and balancers and The supervisor.
| Front end | How it starts the supervisor | Policy |
|---|---|---|
| etemenanki-app | app/src/instance.rs → Instance::start passes Supervisor::builder() to Core::start |
SocketOptions::default() |
| katana | src/manager/node.rs calls Supervisor::start(spec) for each node, which is Supervisor::builder().start(spec) |
SocketOptions::default() |
| etemenanki-ffi | ffi/src/proxy.rs → Proxy::start_on calls Supervisor::builder().socket_options(platform::socket_options(platform)) |
only the protect hook |
Every dialer the supervisor builds
Section titled “Every dialer the supervisor builds”supervisor/src/build/outbound.rs → build_outbound(spec, dns, socket) builds each outbound with the policy; its doc comment says every socket the handler opens gets it. Dns (supervisor/src/build/dns.rs) carries two resolvers, next to the DNS service when there is one: servers looks up the proxy servers the outbounds dial, and destinations looks up what this process connects to itself (through freedom and inside a WireGuard tunnel). Every outbound except a blackhole holds one of these resolvers, which is why, as the doc comment on Dns says, a changed DNS spec rebuilds every outbound.
build_dns(spec, plane, socket) decides which resolvers open host sockets under the policy:
| DNS spec | servers |
destinations |
Host sockets |
|---|---|---|---|
Single(Backend::System) |
Resolver::system() |
the same resolver | none of its own: getaddrinfo opens them |
Single(backend) |
Resolver::with_upstreams([backend], ResolverOptions { socket, .. }) |
the same resolver | every query, under the policy |
Split with no through_proxy servers |
the pre_proxy servers, asked directly (with the system hosts table when use_hosts) |
the same resolver: the direct servers answer everything | every query, under the policy |
Split with through_proxy servers |
the pre_proxy servers, asked directly (hosts table as above) |
the through_proxy servers, reached through RoutedDialer, with the direct resolver as bootstrap for their names |
the direct resolver’s queries only; a through-proxy query leaves on whatever socket the routed outbound opens |
Each host socket the outbounds, probes, resolvers and REALITY inbounds open, and how its family is chosen:
| Socket | Built with | Environment call | Family policy |
|---|---|---|---|
freedom TCP connect |
FreedomConnector::new(Dialer::new(socket), dns.destinations, address_family) |
dialer.tcp.connect_any |
destination_to_socketaddrs(&dest, strategy, &resolver) |
freedom UDP sockets |
the same Dialer |
dialer.udp.bind_dual(self.families()) |
in ResolvingUdp, under the outbound’s strategy |
Proxy upstream TCP: HTTP, SOCKS (CONNECT and a UDP ASSOCIATE control stream), Trojan, VLESS, VMess, Shadowsocks, Shadowsocks 2022, sss (inside SssConnector), AnyTLS (each new session of its pool) |
transport_connector → TransportConnector::new(kind, Dialer::new(socket), dns.servers, spec.address_family) |
dialer.tcp.connect_any |
destination_to_socketaddrs with the transport’s address_family |
| SOCKS outbound UDP relay socket | SocksOutbound::new(.., UdpDialer::new(socket), ..) |
udp.bind(AddressFamily::of(relay)), the bind closure of SocksUdpLink::associate |
the relay’s family |
| Hysteria 2 QUIC socket | Hy2Config::new(server, server_name, password) with socket (and hop) set afterwards, with Hy2Connector::with_address_family(.., address_family).with_resolver(dns.servers) |
bind_socket(config, addr) → UdpDialer::new(options).bind(AddressFamily::of(&addr)) for each attempt, or for each hop’s socket under port hopping |
destination_to_socketaddrs with the outbound’s address_family |
| WireGuard tunnel socket | WgConfig { socket, endpoint_resolution: Some((dns.servers, endpoint_address_family)), .. } |
WgDevice::start → UdpDialer::new(config.socket).bind(AddressFamily::of(&endpoint)), then connect(endpoint) |
destination_to_socketaddrs under endpoint_address_family; the socket is opened in the family of the address it dials |
freedom IPv6 reachability probe |
the same Dialer as the freedom dials |
dialer.udp.source_toward(destination), from FreedomConnector::lacks_ipv6 |
the IPv6 destination’s own |
| Balancer probe | TcpDialer::new(self.socket.clone()) passed to Balancer::spawn_probe in Actor::commit |
dialer.connect(addr) per candidate |
destination_to_socketaddrs(dest, Auto, servers) |
| Queries to configured DNS servers | build_dns → ResolverOptions { socket, .. } → Inner::local = Dialer::new(socket) |
UDP: local.udp.bind(AddressFamily::of(&server)), then connect; a truncated answer is asked again with local.tcp.connect(server); DoT and DoH: local.tcp.connect(server) |
the server’s own address |
| Queries sent through the proxy | RoutedDialer over the plane (supervisor/src/topology/outbound/dns.rs) |
none of its own: the outbound the route table picks opens the socket | that outbound’s |
A REALITY inbound’s cover site (dest) |
build_reality → RealityServer::dial_with(Dialer::new(socket), Resolver::default(), AddressFamilyStrategy::default()) |
dialer.tcp.connect_any in RealityServer::dial_dest, once for each accepted connection |
destination_to_socketaddrs under Auto, through the system resolver |
Some details the table cannot hold:
- The SOCKS relay socket is bound only after the
UDP ASSOCIATEhandshake has named the relay’s address, so it can be opened in the relay’s family.SocksUdpLink::associate(protocols/src/socks/udp_link.rs) hands that address to itsbindclosure; a reply that names the relay by domain fails withUnsupportedsocks: the relay address is a domainbefore the closure runs, so no socket is opened.SocksUdpLinkthen keeps only datagrams from the relay, comparing addresses in canonical form (protocols/src/socks/protocol.rs→endpoint). The client side is described on SOCKS. - Hysteria 2 resolves the server with
destination_to_socketaddrsand tries each candidate in turn, each attempt on its own socket frombind_socket. Withhopset, the attempt’s socket is ashinku_quic::hop::HoppingSocketover the candidate’s IP andhop.ports, and every hop’s socket comes from the sameUdpDialerclosure; etemenanki-app sets the server’s port toports[0]when a hopping outbound givesportsand noport(app/src/lower.rs→lower_hysteria2_outbound). The salamander obfuscation, whenobfsis set, wraps the outermost socket, so every hop’s packets are obfuscated alike. A name with no usable address fails with the resolution error, for exampledial: no usable ipv6_only destination address for example.com:443(AddrNotAvailable) or the resolver’s own error such asdns: example.com did not resolve.Hy2Conn::connectalso checks for an empty candidate list (hysteria2: the server name resolved to no usable address), a defensive check thatdestination_to_socketaddrsnever lets through. A server none of whose addresses answers fails withConnectionRefusedhysteria2: no address answered ({addr}: {error}; …). See Hysteria 2: protocol and client. - WireGuard opens its tunnel socket on the first dial, not when the outbound is built:
WgConnector::dial→acquire_device(protocols/src/wireguard/slot.rs) →WgDevice::start(protocols/src/wireguard/device.rs).WgDevice::startfirst refuses an emptylocal_addrswithInvalidInputwireguard: no tunnel-local addresses configured, before it resolves or binds anything. It then resolves the endpoint withresolve_endpoint, binds a socket throughUdpDialer::new(config.socket)in the family of the address it dials, and connects it there. Withendpoint_resolutionset, as the supervisor always sets it, the endpoint goes throughdestination_to_socketaddrsunderendpoint_address_family, and a failure is that function’s own error (dial: no usable {strategy} destination address for {host}:{port}, or the resolver’s error). Withendpoint_resolution: None, the default ofWgConfig::new, a domain goes totokio::net::lookup_host, and a lookup with no answer fails withNotFoundwireguard: endpoint domain did not resolve.WgConfig::newalso defaultssockettoSocketOptions::default(). Destinations inside the tunnel are not host sockets; see Sockets that do not go through the dialers and WireGuard. - The balancer probe (
supervisor/src/topology/balancer.rs→probe) resolves the member’s upstream withdestination_to_socketaddrsunderAddressFamilyStrategy::Autoand theserversresolver, callsTcpDialer::connectfor each candidate in order, ignores failures, and reports the member up at the first stream; the stream is dropped at once.tokio::time::timeout(timeout, …)bounds the whole probe, resolution included, with the spec’sprobe_timeout, and each attempt is also bounded by the dialer’sDEFAULT_CONNECT_TIMEOUT.Balancer::spawn_probespawns one task per member on the supervisor’sTaskTracker; each task probes, sleepsprobe_interval, and probes again until the balancer’s cancellation token fires. When a member’s health changes, the task logsbalancer member {tag} is now uporbalancer member {tag} is now downat info level. etemenanki-app lowers an absentprobe_timeouttoDEFAULT_PROBE_TIMEOUT(5 s) and an absentprobe_intervaltoDEFAULT_PROBE_INTERVAL(30 s) (app/src/lower.rs); katana builds no balancers. - A delay test (
Supervisor::http_ping,supervisor/src/ping.rs) has no dialer of its own. It opens its connection through the named outbound’s or balancer’s ownconnect_stream, so the host sockets it opens are those the rows above list for that outbound, under the same policy and family rules. See Delay tests through an outbound. - DNS. Each exchange with a server runs under
QUERY_TIMEOUT(5 s), which covers looking up a server written by name, the socket, the connect and the answer, so a DNS server’s TCP connect is cut off by that timer before the dialer’s 10 s would fire; when it fires the error isTimedOutdns: query timed out. A UDP query (exchange_udp) binds a socket in the server’s family withlocal.udp.bindand connects it to the server. A server written by name is looked up through the bootstrap resolver: without one the exchange fails withInvalidInputdns: nothing resolves the server name {host:?}, and a lookup with no answer withNotFounddns: server {host} did not resolve.Resolver::with_upstreamsrefuses two arrangements at build time, both withInvalidInput: asystembackend given a dialer (dns: the system resolver cannot be reached through a proxy, sincegetaddrinfocannot be sent through a tunnel), and a server written by name with no bootstrap (dns: server {host:?} is a name, and nothing resolves it; write its address). A resolver built with adialer(RoutedDialer) opens every server connection through it instead of from this host: each is a TCP flow to the server’s IP, routed withroute_upstreamon the current plane, and when the plane is gone the dial fails withNotConnecteddns: the supervisor this resolver dials through is gone. The resolver itself (backends, cache and TTLs) is described on DNS resolver, and the supervisor’s arrangement of resolvers on Name resolution and the DNS service. - A REALITY inbound’s cover site.
protocols/src/transports/reality.rs→RealityServer::acceptdials the inbound’sdestfor every connection it accepts, before it reads the client’s ClientHello, which goes todestas it arrives. The socket is closed once a client authenticates; for anyone else it becomes the far side of the relay todest.dial_destresolvesdestthrough the system resolver (Resolver::default()) underAuto, whatever the spec’sDnsSpecsays, and callsconnect_anyon the candidates. The doc comment ofbuild_realitygives the reason:destis the operator’s cover site, not proxied traffic, so the dial is a direct one outside the routing plane, as Xray’s own REALITY does.TRANSPORT_HANDSHAKE_TIMEOUT(10 s) bounds resolution and every connect attempt together; when it fires the error isTimedOutdialing dest timed out. The socket gets the sameset_keepaliveschedule as a proxy upstream. When the dial fails, the accepted connection is closed with the debug lineinbound transport failed: {e}(supervisor/src/serve.rs), andRealityServerlogsreality: dest {remote:?}:{port} unreachable, so no client gets in: {e}at warn level, at most once everyDEST_WARN_INTERVAL(60 s). See REALITY transport.
Direct flows
Section titled “Direct flows”FreedomConnector::families maps the outbound’s strategy to the sockets a UDP flow binds:
address_family |
families() |
|---|---|
ipv4_only |
[V4] |
ipv6_only |
[V6] |
auto, prefer_ipv4, prefer_ipv6 |
[V4, V6] |
A UDP flow resolves nothing when it is dialed: it binds with bind_dual(families()) and returns a ResolvingUdp, which wraps the DualStackUdp together with the outbound’s resolver and strategy:
- Domain targets are resolved on their way out, through the outbound’s resolver under its strategy (
destination_to_socketaddrs), and sent from theDualStackUdp. - IP targets are sent from the
DualStackUdpas they are. - Received datagrams come back as
Destination::udp(from), the real source address.
The full outbound, including how a UDP association reaches it packet by packet, is on Outbounds, UDP fan-out and balancers. FreedomConnector::default() exists (Dialer::default(), Resolver::default(), Auto), but the supervisor builds every freedom through FreedomConnector::new.
The address_family settings
Section titled “The address_family settings”Each front end parses its outbound settings into the spec’s strategies with str::parse, maps an absent key to Auto, and reports a bad value with its own wrapper around the key’s name. The spec carries them in supervisor/src/topology/spec_plan/outbound.rs and transport.rs.
| Spec field | What it steers | etemenanki-app key | katana key |
|---|---|---|---|
OutboundProtocolSpec::Freedom { address_family } |
freedom TCP candidates and UDP sockets |
address_family on a freedom or direct outbound |
address_family on a direct or freedom [[outbound]]; the built-in direct and freedom are Auto |
OutboundTransportSpec::address_family |
the upstream’s candidates for every TCP-carried proxy client | address_family on the outbound |
address_family on the [[outbound]] |
Hysteria2OutboundSpec::address_family |
the server’s candidates | address_family on the outbound |
none: katana has no Hysteria 2 outbound |
WireguardSpec::endpoint_address_family |
which of the endpoint’s addresses is dialed | endpoint_address_family in [outbound.settings] |
endpoint_address_family on the [[outbound]] |
WireguardSpec::address_family |
which family is used inside the tunnel | address_family on the outbound |
address_family on the [[outbound]] |
The error texts differ by one colon. Captured with --test from the pinned binaries:
| Front end | Function | Output for address_family = "either" |
|---|---|---|
| etemenanki-app | app/src/lower.rs → parse_family(ctx, key, raw) |
configuration invalid: outbound direct: invalid address_family "either" |
| katana | src/lower/outbound.rs → parse_address_family(cfg), which calls parse_family(cfg, raw, field) |
configuration error: node 1: outbound wg-egress invalid address_family "either" |
A bad endpoint_address_family reads the same with the key’s name, for example outbound wg: invalid endpoint_address_family "v5" from the app and outbound wg-egress invalid endpoint_address_family "v5" from katana.
A WireGuard tunnel’s address_family of one family also needs a tunnel-local address of that family, because FamilySupport::from_addrs would otherwise rule out every destination. The doc comment on WireguardSpec::addresses states the rule and supervisor validation (supervisor/src/build/validate.rs) enforces it with wireguard address_family {strategy} needs an {family} address. katana with address_family = "ipv6_only" and only 10.8.0.2/32 as local_address prints configuration error: node 1: outbound wg-egress@v0: wireguard address_family ipv6_only needs an IPv6 address. katana’s tests wireguard_ipv4_only_builds_with_ipv4_address and wireguard_ipv6_only_requires_ipv6_address pin both sides.
katana lowers every proxy outbound onto StreamShape::Tcp with no TLS, so its upstreams are reached over plain TCP. The operator’s side is on the etemenanki-app outbounds guide and the katana outbounds guide; katana’s lowering is on Lowering inbounds and outbounds.
Sockets that do not go through the dialers
Section titled “Sockets that do not go through the dialers”Some sockets are opened without the dialers. A new SocketOptions knob does not reach them unless they are changed too, and the socket policy does not apply to them.
| Socket | Where | How it is opened |
|---|---|---|
| Inbound listeners | supervisor/src/system/listener.rs → bind |
std::net::TcpListener::bind on the listen address; std::net::UdpSocket::bind for a Hysteria 2 inbound, whose QUIC endpoint Hy2Inbound::open → endpoint::from_socket then builds on that socket; a Unix listener or a handoff socket, on Unix only (a handoff socket is a socket2 Unix socket that gets its mode and group before it listens; elsewhere bind fails with Unsupported unix socket {path}: not served on this platform); a TUN device through tun::open (on Windows a Wintun adapter) or, on Unix only, tun::adopt. How katana picks its listen addresses is on Lowering inbounds and outbounds. A TCP socket a relay hands over on a handoff socket was opened by the relay, so no policy of this supervisor applies to it. |
| Hysteria 2 port-release probe | protocols/src/hysteria/server/inbound.rs → Hy2Inbound::shutdown |
After closing the endpoint and dropping its handle, std::net::UdpSocket::bind on the endpoint’s old local address every RELEASE_POLL (20 ms) until a bind succeeds, for at most RELEASE_TIMEOUT (3 s); each probe socket is dropped at once. When the time runs out it logs hysteria2: {local} did not come free within {RELEASE_TIMEOUT:?} at warn level. See Hysteria 2: server. |
| Hysteria 2 listening endpoint helper | protocols/src/hysteria/server/endpoint.rs → bind |
std::net::UdpSocket::bind(listen), then from_socket. A public helper that no crate in the workspace or katana calls. |
| The REST API listener | webclient/src/listen.rs → ApiListener::bind |
tokio’s TcpListener::bind, or UnixListener::bind for a Unix path on Unix; off Unix a Unix path fails with Unsupported unix socket {path}: not served on this platform. See The REST API (etemenanki-webclient). |
| katana’s panel HTTP client | katana src/api/mod.rs → build_http_client |
a reqwest::Client with a request timeout, built from http_client_builder, which asks every panel for a gzip-compressed answer (Accept-Encoding: gzip) and decompresses one that comes compressed (a_panel_answer_is_asked_for_and_read_gzip_compressed); reqwest opens its own connections to the panel. katana presents a client certificate when a panel asks for one, unless the node sets enable_mtls = false, and does not follow redirects. See Panel clients. |
| The system resolver | protocols/src/dns/mod.rs → lookup_system |
tokio::net::lookup_host, which runs getaddrinfo; the C library opens its own sockets |
| SOCKS server UDP relay | protocols/src/socks/server.rs → SocksInbound::associate |
tokio::net::UdpSocket::bind on the configured udp_bind address, or else the control connection’s local IP, port 0. Before any socket is bound, associate refuses: over a Unix control socket with no udp_bind, reply 0x07 (STATUS_CMD_NOT_SUPPORT) and UDP associate over a unix socket needs udp_bind; with reply 0x02 when ExpectedSender::new finds no client to hold to, either socks: UDP associate from an address family the relay is not bound in (the bind address does not hear the client’s family, hears) or socks: UDP associate over a unix socket must name its source address and port. See SOCKS. |
| WireGuard tunnelled TCP and UDP (a userspace netstack, not host sockets) | protocols/src/wireguard/connector.rs → WgConnector::dial, WgDatagramLink; protocols/src/wireguard/slot.rs → connect_tcp_any |
TCP: resolve_candidates("wireguard", …) with FamilySupport::from_addrs(local_addrs) and the destinations resolver, then a sequential loop with TCP_CONNECT_ATTEMPT_TIMEOUT (10 s) per address. UDP: a datagram’s domain target is resolved with resolve_candidates("wireguard", …) under the tunnel’s address_family and the same capability. |
| sss inbound fallback | protocols/src/sss/server.rs → Rejection::run |
tokio::net::TcpStream::connect on the SocketAddr of the inbound’s Reject::Fallback, so there is no name to resolve, within what is left of the stream’s header time T_h. A fallback that refuses or does not answer in time leaves the stream to drain instead, with the debug line sss: fallback {address} unreachable, draining: {e} or sss: fallback {address} timed out, draining. Like a REALITY cover site, it is dialed outside the routing plane. See sss. |
The WireGuard loop follows the same rule as connect_any: sequential attempts, a bounded time per attempt, every failure in the final error. Its final error differs: it has kind TimedOut and the message wireguard: tunnel TCP connect failed for all resolved addresses ({ip}: {error}; …), where an attempt whose timer fired reads {ip}: timed out.
Invariants
Section titled “Invariants”| Invariant | Enforced by | Pinned by |
|---|---|---|
| Policy is applied after creation and before bind or connect | TcpDialer::socket, UdpDialer::bind and UdpDialer::source_toward call SocketOptions::apply before binding; connect always goes through socket |
no test checks the order; connects_and_binds_the_requested_source_address (environment/tests/integration/tcp.rs) checks that the bind address takes effect |
| A bind address binds only sockets of its own family | SocketOptions::bind_address_for filters with AddressFamily::of_ip |
bind_address_applies_only_to_its_own_family (environment/tests/unit/dial/socket.rs) |
| An unsupported knob is an error, never a no-op | per-OS cfg variants of bind_interface, bind_interface_index and set_mark returning ErrorKind::Unsupported |
no test reaches the Unsupported branches, which are not compiled on Linux; mark_and_loopback_device_take_effect_or_are_refused_by_the_kernel covers the Linux side (applied or PermissionDenied) |
| A hook’s error aborts the socket | apply returns hook(socket)? |
hook_runs_on_apply_and_its_error_propagates |
| Nothing leaves on a socket the policy refused | the error from apply fails the dial it was for |
a_refusing_hook_fails_the_dial (supervisor/tests/socket_policy.rs): the SOCKS request through a direct outbound is answered with a failure |
| The builder’s policy reaches outbound sockets | socket_options → Actor::socket → build_outbound, transport_connector, build_dns, balancer probes, and stage_users → build_handler → build_reality for a REALITY cover site |
direct_flows_are_dialed_on_hooked_sockets, a_socks_upstream_is_dialed_on_hooked_sockets (supervisor/tests/socket_policy.rs); a_query_socket_gets_the_socket_policy (protocols/tests/unit/dns/mod.rs) for the resolver; a_tun_device_carries_tcp_and_udp_to_the_outbound (ffi/tests/proxy.rs) for the FFI’s protect hook; no test checks the REALITY cover site’s socket |
Debug output of SocketOptions never shows the hook |
manual Debug for SocketOptions |
debug_hides_the_hook_body |
| One connect attempt cannot stall the rest | tokio::time::timeout(connect_timeout, …) in connect |
no test fires the timer; connect_any_falls_through_a_dead_address uses a port that refuses at once |
| An unreachable address does not strand the destination | connect_any walks every candidate; resolution keeps every answer |
connect_any_falls_through_a_dead_address; auto_keeps_resolver_order_when_both_families_are_supported |
| No failure cause is lost | connect_any joins every {addr}: {e}; an empty list says none given |
connect_any_falls_through_a_dead_address |
| A UDP peer is reported as the address it was sent to | v6 sockets are set_only_v6(true); v4 has its own socket |
v6_socket_is_v6_only_and_dual_stack_picks_by_family (environment/tests/integration/udp.rs) compares each reply’s source with the echo server’s address; it does not read IPV6_V6ONLY back |
| A datagram leaves from the socket of its peer’s family | DualStackUdp::socket_for |
v6_socket_is_v6_only_and_dual_stack_picks_by_family (a v6 send on a v4-only link gives AddrNotAvailable) |
| A dual-stack bind fails only when nothing bound | bind_dual skips failed families and checks both slots at the end |
only the empty case: v6_socket_is_v6_only_and_dual_stack_picks_by_family checks that bind_dual([]) is an error; no test makes one family fail |
| The environment never resolves names | DatagramLink for DualStackUdp refuses a domain with Unsupported |
no dedicated test in environment; the DialTarget::Udp runtime test sends to IPs only |
prefer_* reorders but never drops the other family |
stable sort_by_key in select_candidate_ips |
prefer_ipv4_keeps_ipv6_as_fallback (protocols/tests/unit/helpers/address_family.rs) |
Capability filters even under Auto |
support.supports(ip) in the filter |
auto_skips_families_without_a_local_address |
| A kernel-routed dialer is limited by policy alone | callers pass FamilySupport::both() |
a_kernel_routed_dialer_is_limited_by_policy_alone; the_capability_clause_is_omitted_for_a_kernel_routed_dialer |
Every protocol honours its address_family in katana |
lower_outbound parses it for every protocol, direct included |
address_family_applies_to_every_protocol (katana tests/unit/lower/outbound.rs: socks, http, vmess, vless); direct_is_configurable_as_an_outbound; a_wireguard_endpoint_address_family_is_lowered (the endpoint’s family is separate from the tunnel’s) |
A bad address_family is refused, never ignored |
parse_family in both front ends |
an_invalid_address_family_is_rejected_for_every_protocol (katana: socks, http, vmess, vless, wireguard); an_invalid_wireguard_endpoint_address_family_is_rejected |
Failure paths and cancellation
Section titled “Failure paths and cancellation”TcpDialer, UdpDialer and Dialer spawn no tasks and hold no locks. Every operation is either synchronous (bind, bind_dual, socket, endpoint) or a single future owned by the caller. The exception is QuicDialer: QuicDialer::endpoint makes quinn spawn an endpoint driver task, and each connect (and so each dial) makes it spawn a connection driver task. The endpoint driver ends once no Endpoint handle and no connection remain.
- Cancellation. Dropping a
connectorconnect_anyfuture drops the in-flightTcpSocketand closes it. Addresses not yet tried are never touched. The boxed futures fromDialer::connectown clones of the dialers, so they can be dropped at any point without affecting theDialer. The balancer probe races each probe against its cancellation token and abandons the one in flight when the token is cancelled. - Partial construction. A socket that fails
apply, keepalive or bind is dropped before it is returned, so no half-configured socket escapes. Inbind_dual, a socket already bound for one family is kept when the other family fails. - Timeouts. The one timer in the TCP and UDP dialers is the per-attempt
connect_timeoutinTcpDialer::connect.bind,bind_dual,socketandendpointare system calls that do not wait on the network.
Errors
Section titled “Errors”| Source | Kind | Message |
|---|---|---|
TcpDialer::connect, timer fired |
TimedOut |
connect to {addr} timed out |
TcpDialer::connect_any |
ConnectionRefused |
failed to connect to any address ({addr}: {e}; …) or (none given) |
UdpDialer::bind_dual |
AddrNotAvailable |
udp: no usable local socket in any requested family / udp: no address family requested |
DualStackUdp::socket_for |
AddrNotAvailable |
udp: no local socket in the family of {peer} |
DatagramLink for DualStackUdp |
Unsupported |
udp: a plain dual-stack link cannot resolve a domain |
SocketOptions::apply on a platform without the knob |
Unsupported |
{what} is not supported on {os}, or the Apple or Windows interface-name message |
SocketOptions::apply, kernel refusal |
as the OS reports, typically PermissionDenied |
the OS error |
SocketOptions::apply, the FFI’s hook refused |
PermissionDenied |
the platform refused to protect the socket |
QuicDialer::connect |
InvalidInput (bad config or address), ConnectionRefused (handshake failed) |
quinn’s error text |
RealityServer::dial_dest, timer fired |
TimedOut |
dialing dest timed out |
Log lines: udp: no {family:?} socket: {e} (debug, bind_dual) is the only one in the environment’s dialers. could not enable TCP keepalive: {e} (debug) comes from set_keepalive in the protocols crate.
What a refused socket does to each dial
Section titled “What a refused socket does to each dial”A hook that returns an error, or a kernel that refuses a mark or device binding, fails the socket. What the caller sees depends on which dialer call it was:
| Socket | Call | Outcome |
|---|---|---|
freedom TCP, proxy upstream TCP |
connect_any |
Each address fails the same way, so the dial fails with failed to connect to any address ({addr}: the platform refused to protect the socket; …) for the FFI’s hook. A server core hears Event::ConnectFailed; a SOCKS client gets a failure reply (a_refusing_hook_fails_the_dial). |
freedom UDP |
bind_dual |
A family whose socket is refused is skipped with the debug line. The dial fails only if every family is refused, with udp: no usable local socket in any requested family. |
| SOCKS relay socket | bind |
The association fails with the error itself. |
| Hysteria 2 socket | bind inside each attempt |
The attempt fails; with every attempt refused, hysteria2: no address answered ({addr}: {error}; …). |
| WireGuard tunnel socket | bind in WgDevice::start |
The dial that started the tunnel returns the error, and acquire_device logs wireguard: tunnel start failed: {e} at warn level. |
freedom IPv6 probe |
source_toward |
Only the kernel’s “no route” answers (NetworkUnreachable, HostUnreachable, AddrNotAvailable) count the destination as unreachable. Any other error, a refusing hook included, refuses nothing and is logged at debug level as direct: cannot tell whether {destination} is reachable: {e}. |
| Balancer probe | connect per candidate |
The probe counts the member as down. |
| REALITY cover site | connect_any in RealityServer::dial_dest |
Each address fails the same way. The accepted connection is closed before its ClientHello is read, and the warn line about an unreachable dest is logged, at most once a minute. |
| DNS query | bind or connect inside the exchange |
That query fails; the resolver moves on to its next server, and the lookup fails with the last error when every server failed. |
Limits
Section titled “Limits”| Constant | Value | Defined in | Meaning |
|---|---|---|---|
DEFAULT_CONNECT_TIMEOUT |
10 s | environment/src/dial/tcp.rs |
Per TCP connect attempt; override with TcpDialer::with_connect_timeout |
Worst case of connect_any |
number of candidates × connect_timeout |
follows from the sequential loop | The longest one connect_any call can take |
Sockets per DualStackUdp |
at most 2, one per family | bind_dual |
A repeated family replaces its own slot |
| Local port | 0 (ephemeral) | UdpDialer::bind, and TcpDialer::socket when it binds |
Every bind asks the kernel for a fresh port |
TCP_KEEPALIVE_IDLE / TCP_KEEPALIVE_INTERVAL / TCP_KEEPALIVE_RETRIES |
120 s / 30 s / 3 | protocols/src/transports/keepalive.rs |
The schedule set_keepalive sets; TransportConnector::dial calls it on every proxy upstream socket |
DEFAULT_PROBE_TIMEOUT |
5 s | supervisor/src/topology/balancer.rs |
etemenanki-app’s value for an absent probe_timeout; the spec’s probe_timeout bounds a whole probe, resolution included |
DEFAULT_PROBE_INTERVAL |
30 s | supervisor/src/topology/balancer.rs |
etemenanki-app’s value for an absent probe_interval, the sleep between two probes of one member |
QUERY_TIMEOUT |
5 s | protocols/src/dns/mod.rs |
Bounds one exchange with a DNS server, sockets included |
TCP_CONNECT_ATTEMPT_TIMEOUT |
10 s | protocols/src/wireguard/slot.rs |
Per TCP connect attempt inside a WireGuard tunnel |
RELEASE_TIMEOUT / RELEASE_POLL |
3 s / 20 ms | protocols/src/hysteria/server/inbound.rs |
How long, and how often, Hy2Inbound::shutdown probes its old port with a bind |
TRANSPORT_HANDSHAKE_TIMEOUT |
10 s | protocols/src/transports/accept.rs |
Bounds a REALITY inbound’s whole dial to its cover site, resolution and every connect attempt included |
DEST_WARN_INTERVAL |
60 s | protocols/src/transports/reality.rs |
The shortest gap between two warn lines about an unreachable REALITY cover site |
The environment’s tests run on real loopback sockets. environment/tests/integration.rs pulls in the TCP and UDP modules always and the QUIC module only under cfg(feature = "quic"); the unit tests are attached to socket.rs with #[path].
| Test | File | What it pins |
|---|---|---|
bind_address_applies_only_to_its_own_family |
environment/tests/unit/dial/socket.rs |
bind_address_for returns the address for its family and None for the other, and None without a bind address |
family_of_addresses |
same | AddressFamily::of and unspecified |
hook_runs_on_apply_and_its_error_propagates |
same | the hook runs once per apply; its error text comes back unchanged |
mark_and_loopback_device_take_effect_or_are_refused_by_the_kernel |
same (Linux only) | with_mark(7) and Interface::Name("lo") either apply or fail with PermissionDenied |
debug_hides_the_hook_body |
same | Debug prints hook: Some("...") |
connects_and_binds_the_requested_source_address |
environment/tests/integration/tcp.rs |
a bind address becomes the connection’s source |
connect_any_falls_through_a_dead_address |
same | fallback to the second address; the error text names the dead address; an empty slice says none given |
dialer_is_a_connector_for_the_runtime |
same | Connector::<DialTarget> yields a working Outbound::Stream |
v6_socket_is_v6_only_and_dual_stack_picks_by_family |
environment/tests/integration/udp.rs |
per-family send and receive, real peer addresses, AddrNotAvailable for a missing family, bind_dual([]) fails |
dual_stack_link_serves_a_proxy_runtime |
same | a toy core (TinyUdp) opens DialTarget::Udp under ProxyServerRuntime and relays a datagram both ways; the summary counts 4 bytes out and 4 in |
socket_target_connector_binds_one_family |
same | Connector::<SocketTarget> with ipv6: false binds an IPv4 socket |
dials_a_quic_server_over_loopback |
environment/tests/integration/quic.rs (feature quic) |
QuicDialer::dial honours the bind address and carries a stream |
a_socket_wrap_sees_the_endpoint_socket |
same | SocketWrap is called while building the endpoint |
parses_address_family_strategy_aliases |
protocols/tests/unit/helpers/address_family.rs |
ipv4-only and prefer_ipv6 parse; either does not |
auto_skips_families_without_a_local_address |
same | capability filters under Auto |
auto_keeps_resolver_order_when_both_families_are_supported |
same | Auto does not reorder |
ipv4_only_filters_to_ipv4 |
same | Ipv4Only drops IPv6 |
prefer_ipv4_keeps_ipv6_as_fallback |
same | stable reordering |
a_kernel_routed_dialer_is_limited_by_policy_alone |
same | FamilySupport::both() filters nothing |
the_capability_clause_is_omitted_for_a_kernel_routed_dialer |
same | the error text adds local address supports IPv4 only only for a narrower capability |
a_query_socket_gets_the_socket_policy |
protocols/tests/unit/dns/mod.rs |
a resolver asking a UDP server runs the policy’s hook at least once |
a_relay_that_cannot_hear_the_client_is_refused |
protocols/tests/unit/socks/server.rs |
the SOCKS server refuses an association from a family its relay address does not hear |
udp_association_refuses_a_relay_that_cannot_hear_the_client |
protocols/tests/pipeline/socks.rs |
the same, end to end |
udp_link_ignores_datagrams_not_from_the_relay |
same | the SOCKS client’s link drops a well-formed reply from another address and returns the relay’s |
udp_link_on_a_dual_stack_socket_hears_an_ipv4_relay |
same (Linux only) | with a bind closure that opens a dual-stack [::] socket, replies from an IPv4 relay arrive from its v4-mapped address and still count as the relay’s |
direct_flows_are_dialed_on_hooked_sockets |
supervisor/tests/socket_policy.rs |
through a SOCKS inbound and the default direct outbound, the TCP dial runs the hook once and a UDP association runs it at least once (bind_dual may bind two sockets) |
a_socks_upstream_is_dialed_on_hooked_sockets |
same | through a SOCKS upstream, the CONNECT dial and the association’s control connection each run the hook on a stream socket, and the relay socket runs it once on a datagram socket |
a_refusing_hook_fails_the_dial |
same | a hook returning PermissionDenied makes the SOCKS request fail |
a_tun_device_carries_tcp_and_udp_to_the_outbound |
ffi/tests/proxy.rs |
through the FFI, protect is called once for the TCP dial and at least twice once UDP has flowed |
address_family_applies_to_every_protocol |
katana tests/unit/lower/outbound.rs |
ipv6_only reaches the upstream transport of socks, http, vmess and vless |
an_invalid_address_family_is_rejected_for_every_protocol |
same | ipv7 is refused by socks, http, vmess, vless and wireguard with invalid address_family |
direct_is_configurable_as_an_outbound |
same | a direct [[outbound]] needs no server and keeps its ipv4_only |
a_wireguard_endpoint_address_family_is_lowered |
same | unset is Auto; ipv4_only is kept, independently of the tunnel’s address_family |
an_invalid_wireguard_endpoint_address_family_is_rejected |
same | ipv7 fails with invalid endpoint_address_family |
wireguard_ipv4_only_builds_with_ipv4_address |
same | a tunnel with ipv4_only and a 10.0.0.2/32 local address passes etemenanki_supervisor::check |
wireguard_ipv6_only_requires_ipv6_address |
same | the same tunnel with ipv6_only fails the check with an error naming IPv6 |
The QUIC tests need the feature: run cargo test -p etemenanki-environment --features quic. The workspace gate cargo clippy --workspace --all-targets --all-features compiles them but does not run them, and cargo test --workspace skips them. The mark and device test does not read the options back: it passes whether the kernel applies them or refuses them with PermissionDenied.
Changing this code
Section titled “Changing this code”- Adding a knob. Put it on
SocketOptionswith awith_*builder, apply it inapply(or in the dialer if it depends on the socket type), and give every platform acfgbranch. Where the platform has no equivalent, returnunsupported(…); do not skip it.bind_dualturns such an error into a skipped family, and the sockets listed in Sockets that do not go through the dialers will not see the knob.SupervisorBuilder::socket_optionsis the only entry point outside tests for a policy, so a knob an operator should set also needs a front end to expose it; no front end exposes anySocketOptionsfield in its configuration today. - A new outbound that opens sockets takes the policy from
build_outbound’ssocketargument, and an inbound transport that dials, as REALITY does, takes it frombuild_handler’s; either opens every host socket through aDialer,TcpDialerorUdpDialerbuilt from it. A socket opened directly with tokio or the standard library escapes the policy; in the mobile library that meansprotectnever sees it, so it is not kept out of the app’s tunnel. - Keep
connect_anysequential. Its doc comment states that it is not Happy Eyeballs. While attempts are sequential, the order fromselect_candidate_ipsalone decides which address a flow uses, and the error lists one entry per address tried. Racing attempts would change both for every outbound. - Keep resolution out of
environment. A resolving link belongs to the program that owns the resolver, asResolvingUdpdoes in the supervisor. - Downstream impact. katana 6.1.0 requires etemenanki-concepts 2.1, etemenanki-environment 3.0, etemenanki-protocols 7.1.1 (with its
vendored-openssl,hysteriaandrealityfeatures) and etemenanki-supervisor 2.1 from a private Cargo registry; its lockfile resolves concepts 2.2.0, environment 3.2.2 (this page documents 3.2.1), protocols 7.2.1 and supervisor 2.1.0. It calls no dialer itself: of this crate it uses onlyetemenanki_environment::routing. A change to the dialers or the address-family helpers reaches katana through the supervisor, once katana’s lockfile picks up the release.