Lowering a node into a spec
Source files: 35 · checked against katana v6.1.0 · Etemenanki 46c12e4
katana/src/lower/mod.rskatana/src/lower/route.rskatana/src/lower/inbound.rskatana/src/lower/outbound.rskatana/src/rule.rskatana/src/api/mod.rskatana/src/api/hysteria.rskatana/src/config.rskatana/src/manager/node.rskatana/src/runtime.rskatana/src/main.rskatana/tests/unit/lower/spec.rskatana/tests/unit/lower/inbound.rskatana/tests/unit/e2e.rsEtemenanki/supervisor/src/topology/spec_plan/mod.rsEtemenanki/supervisor/src/topology/spec_plan/route.rsEtemenanki/supervisor/src/topology/spec_plan/inbound.rsEtemenanki/supervisor/src/topology/inbound/mod.rsEtemenanki/supervisor/src/topology/flow.rsEtemenanki/supervisor/src/entity/user.rsEtemenanki/supervisor/src/entity/usage.rsEtemenanki/supervisor/src/policy.rsEtemenanki/supervisor/src/guard.rsEtemenanki/supervisor/src/build/users.rsEtemenanki/supervisor/src/build/inbound.rsEtemenanki/supervisor/src/build/validate.rsEtemenanki/supervisor/src/build/route.rsEtemenanki/supervisor/src/supervisor.rsEtemenanki/supervisor/src/track/mod.rsEtemenanki/supervisor/src/track/pace.rsEtemenanki/environment/src/routing.rsEtemenanki/supervisor/tests/hot_swap.rsEtemenanki/supervisor/tests/unit/track.rsEtemenanki/supervisor/tests/unit/validate.rsEtemenanki/environment/tests/unit/routing.rs
katana does not run listeners, routers or meters of its own. Each [[node]] owns one etemenanki_supervisor::Supervisor<Uid>, and katana’s job is to describe what that supervisor should run: a Spec<Uid> built from the node’s TOML, the process-wide [[outbound]] and [dns], the panel’s node description, the panel’s user list and the panel’s audit rules. That translation is called lowering, and it lives in src/lower/. This page covers src/lower/mod.rs (the spec as a whole, users, credentials, speed limits, policies and the --test spec) and src/lower/route.rs (the route table).
This page is for contributors who change how a panel answer becomes a spec. Two sibling files are covered elsewhere: Lowering inbounds and outbounds owns src/lower/inbound.rs and src/lower/outbound.rs (the listener, TLS, Hysteria 2, the outbound clients and DNS), and Destination audit owns src/rule.rs. What the supervisor does with a spec is on The spec: desired state, Validation and apply errors and Users, principals and sessions.
Responsibilities
Section titled “Responsibilities”Lowering:
- builds the
Spec<Uid>for one node: the inbound, the outbounds and DNS every node shares, the audit outbounds and routes, the node’s own route table, the user set and the policies; - turns each panel user into a
UserSpec: the one credential the node’s protocol reads, a speed limit, and, underenable_device_limit, the panel’s device limit; - builds the policies, the IP ban and the gRPC carrier close, from
[node.controller]; - skips, with a
WARN, a user the node cannot admit, a uid listed twice and a user whose credential an earlier user already presents, so one bad row does not makenode_specfail; - refuses, by name and before any spec exists, what the TOML asks for and the kernel cannot do. What a panel asks for that katana cannot serve never reaches it: the contract’s types cannot write it, and the newV2board client refuses it as it reads the answer (Panel clients);
- builds the smaller spec that
--testand a config reload check a node against before its panel is asked (test_spec), after judging the node’s real-IP and handoff keys and its Hysteria 2 congestion control; - lowers, for
--testand for a node that names its own port (only a newV2board node can), the Hysteria 2 nodeapi::hysteria::localbuilds from[node.hysteria].
Lowering does not:
- bind, dial or spawn anything. The only side effects are reading the certificate, key and DNS CA files a spec carries as bytes, reading
/etc/groupfor a handoff socket’s group, one probe of whether this host’s IPv6 sockets also take IPv4 (inbound::dual_stack, a socket that is created once and never bound), stamping each geo file the route names with the file found at its path (RouteFile::stat, inlower_route), and the log lines below. - load geo data. The route spec names the
.datfiles by path, each with its stamp, and the supervisor loads the sets the rules use. - check references, or what needs a parser: geo codes in the
.datfiles, and the PEM it carries as bytes. A rule ordefaultnaming an outbound that does not exist is passed through, and the supervisor refuses it (Validation and apply errors). The per-user rules ofvalidate_admissionalso stay the supervisor’s;lower_usersonly skips the users who would break them (Users). - decide when a spec is applied or which connections an apply closes. That is The node manager.
katana does judge a few values itself. lower_outbounds refuses a repeated or reserved [[outbound]] tag, so the supervisor never sees a colliding one. A Hysteria 2 node’s udp_idle_timeout outside 2 to 600 seconds, a Salamander obfs_password shorter than 4 bytes and a masquerade the contract does not allow are refused before lowering: by api::hysteria for [node.hysteria] and a UniProxy node, by the contract’s Deserialize for helium’s. lower_hysteria judges the masquerade once more, against what the Hysteria 2 server accepts (inbound::masquerade_spec), and the supervisor’s validate judges all three values again. For the masquerade the doc comment of masquerade_spec gives the reason: the answer is “refused as the supervisor would refuse it: judged here too so the refusal reads as it always has.”
| File → symbol | Role |
|---|---|
src/lower/mod.rs → node_spec |
The spec a running node applies. |
src/lower/mod.rs → shared_spec (private) |
Everything but the inbound and the users: outbounds, audit outbounds, DNS, route, policies. |
src/lower/mod.rs → policies (private) |
The supervisor’s Policies from [node.controller]. |
src/lower/mod.rs → lower_users (private) |
The panel users as one BTreeMap<Uid, UserSpec>. |
src/lower/mod.rs → identity (private) |
The bytes two users’ credentials collide on. |
src/api/hysteria.rs → local |
The Node [node.hysteria] describes on its own, which test_spec and the node manager lower (Panel clients). |
src/lower/mod.rs → test_spec |
The spec --test and reload checks run through etemenanki_supervisor::check. |
src/lower/route.rs → lower_route |
[node.route] as a RouteSpec. |
src/lower/inbound.rs → credentials |
One user’s credential for the node’s inbound protocol. |
src/lower/inbound.rs → lower_inbound, inbound_tag, src/lower/outbound.rs → lower_outbounds, lower_dns |
The inbound and its tag, the outbounds and DNS (Lowering inbounds and outbounds). |
src/rule.rs → audit_routes |
One blackhole outbound and one route per audit rule id (Destination audit). |
Where lowering runs
Section titled “Where lowering runs”| Caller | Calls | Result goes to |
|---|---|---|
src/manager/node.rs → NodeManager::try_bootstrap, through NodeManager::lower_off_runtime |
node_spec with the node and users the bootstrap attempt read, and the current audit rules |
Supervisor::start. The spec is kept as the applied one. |
src/manager/node.rs → NodeManager::reconcile, through NodeManager::lower_off_runtime, from a poll cycle and from a StaticUpdate::Globals |
node_spec with the node and users the poll settled on, or, for a globals update, the last stored answer |
Compared with the applied spec, then Supervisor::apply_with(spec, ApplyOptions { allow_disruptive: true }). |
src/manager/node.rs → NodeManager::node_info |
api::hysteria::local, when [node.api].node_type parses as Hysteria 2 and [node.hysteria].port is not 0 (the helium client refuses both keys) |
Stands in for the panel’s node answer; the panel is not asked. |
src/runtime.rs → check_node, from test_config (--test), build_node and apply_reload |
test_spec |
etemenanki_supervisor::check(&spec). |
NodeManager::lower_off_runtime clones the node config under its mutex, clones the Arc<Globals>, and takes the rule set as an Arc<[DetectRule]> from RuleManager::rules. node_spec then runs with no lock held, on the blocking pool, because its work grows with the user list; the comparison with the applied spec and the copy the supervisor takes run there too. Which answers a poll settles on, when a spec is applied, and when every connection is closed are on The node manager. How the runtime uses check_node is on Runtime and config reload.
What katana refuses and what the supervisor refuses
Section titled “What katana refuses and what the supervisor refuses”The module comment puts the split as: “The panel’s answer arrives as the contract’s node, which says nothing the kernel cannot serve; what the TOML asks for and the kernel cannot do is refused here, by name, before a spec exists; how the typed pieces fit together (tags, references, credential collisions) is the supervisor’s to check when the spec is applied.”
| Refused by | Kind of rule | Examples, as --test prints them after configuration error: node 1: |
|---|---|---|
katana lowering (ErrorKind::InvalidInput) |
Syntax of a value: a CIDR, a port spec, a key, a cert mode | invalid cidr "192.0.2.1/24": host part of address was not zero, invalid port spec: "80-", hysteria2 node requires cert.mode = "file" |
katana lowering (ErrorKind::InvalidInput) |
katana’s own reservations | duplicate/reserved outbound tag audit#1 |
api::hysteria (ErrorKind::InvalidInput), and the supervisor’s validate again |
Hysteria 2 ranges of [node.hysteria] |
udp_idle_timeout must be between 2 and 600 seconds, obfs_password must be at least 4 bytes for salamander |
katana lowering (ErrorKind::Unsupported) |
A setting of this host, or an outbound, the kernel does not implement | node requests kernel-unsupported feature: cert.reject_unknown_sni, node requests kernel-unsupported feature: ACME cert mode "dns", unsupported shadowsocks cipher "<name>" (an [[outbound]]) |
katana lowering (the read’s own io::Error) |
A certificate, key or DNS CA file that cannot be read | a read failure (Lowering inbounds and outbounds) |
supervisor validate |
References, tags, and the users an inbound admits | route references unknown outbound nowhere |
supervisor build (check or start) |
What needs a file or a parser: geo data, PEM | building route failed: a geosite matcher is used but no geosite file is configured, building route failed: geosite code not found: no-such-code-xyz, building inbound Hysteria2_0.0.0.0_1 failed: hysteria2: the certificate file contains no certificates |
No caller branches on the io::ErrorKind; every caller prints the error with Display. The kind records which side of the split a refusal is on.
What a panel asks for and katana cannot serve is refused before lowering, as the panel client reads the answer, and logged as a failed node_info (node 1: node_info failed: parse UniProxy config response: node requests kernel-unsupported feature: tcp header type "http"; retrying in 1s at bootstrap). --test never asks the panel, so it never prints one; the refusals are on Panel clients. Until 6.1.0 lowering refused them, and they were logged as lowering errors.
Key types
Section titled “Key types”/// A panel user, as the supervisor keys them: their panel id.#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]pub struct Uid(pub i64);
impl UserId for Uid { fn name(&self) -> UserName { UserName::Username(self.0.to_string().into()) }}Uid is the U of every supervisor type katana uses: Supervisor<Uid>, Spec<Uid>, UserSet<Uid>, UsageDelta<Uid>. The UserId bound is Clone + Eq + Ord + Hash + Debug + Send + Sync + 'static: the derives supply Clone + Eq + Ord + Hash + Debug, and an i64 newtype is Send + Sync + 'static automatically. Its name is UserName::Username holding the uid in decimal, so uid 1001 is named 1001. UserName is “never a secret”, which is why it is what logs and the protocols’ user labels carry.
The decimal uid is the one thread between a flow and the panel user it belongs to:
| Where | What carries the uid |
|---|---|
| The user set | BTreeMap<Uid, UserSpec>, so the set iterates in uid order. |
| The supervisor’s principal | supervisor/src/build/users.rs → admit keeps the principal of a user still admitted by the credential they were admitted by, and otherwise mints Principal::user(keys.key(id), id.name().as_str().into()): its label is the decimal uid. |
| The protocol user tables | supervisor/src/build/inbound.rs → user_table gives Trojan, AnyTLS, Shadowsocks and Shadowsocks 2022 users the principal’s label as their email, and the sss table and the Hysteria 2 authenticator get it as each user’s label. VLESS and VMess tables carry only the UUID and the principal, SOCKS and HTTP tables the account and the principal. |
| A flow | FlowEntry::user_label() returns the principal’s label. |
| A client address | src/manager/node.rs → NodeManager::spawn_client_ips parses the label of each opened flow back into an i64, and files the flow’s source address under that uid where the panel keeps client addresses (Traffic accounting and reporting). |
| Usage | Supervisor::take_usage() returns UsageDelta<Uid>, and NodeManager::take_traffic reports delta.user.0 as the panel uid (Traffic accounting and reporting). |
| Supervisor errors about users | validate_admission names a user by id.name(), and user_table names one by the principal’s label; both are the decimal uid. |
USER_SET
Section titled “USER_SET”/// The tag of the one user set a node's inbound admits.pub const USER_SET: &str = "users";inbound::lower_inbound sets InboundSpec::users to Some(USER_SET.into()), and node_spec tags the set it builds with the same constant. Each node has its own supervisor, so the tag only has to be unique within one spec.
Inputs
Section titled “Inputs”| Input | Type, file | What lowering reads from it |
|---|---|---|
| The node’s config | NodeConfig, src/config.rs |
[node.controller]: listen_ip, disable_sniffing, disable_vmess_clock_check, cert, enable_device_limit, real_ip_header, real_ip_from, ban_max_failures, ban_window_secs, ban_secs, carrier_max_failures, handoff_dir, handoff_group. [node.api]: node_type, for test_spec only. [node.hysteria]: credential and congestion in lower_hysteria, congestion in test_spec for every node, and the whole block in test_spec for a Hysteria 2 node, through api::hysteria::local; a helium node can set only congestion. [node.route]. |
| The globals | Globals { outbounds: Vec<OutboundConfig>, dns: DnsConfig }, src/config.rs |
Every [[outbound]] and [dns]. Config::globals() clones them; every node lowers the same ones. |
| The node | Node, the contract’s helium_node_api::config::NodeConfig, src/api/mod.rs |
Its variant, its port, and what lower_inbound reads of it: the transport, the security, REALITY’s settings, the flow, the cipher and key, the padding scheme, sss’s chains and datagram limit, and Hysteria 2’s obfuscation, rates, UDP relay and masquerade (Lowering inbounds and outbounds). It holds no setting of this host’s, and no speed limit. |
| The users | &[UserInfo], src/api/mod.rs |
uid, uuid, speed_limit (bytes per second, 0 for none), device_limit (0 for none), and, through traffic_email (src/api/mod.rs), email for a Hysteria 2 user_pass node. |
| The audit rules | &[DetectRule], src/api/mod.rs, where DetectRule { id: i64, pattern: Regex } |
Each rule’s id and its pattern’s source text. |
A user’s speed limit arrives in bytes per second. helium’s users answer states one speed limit in bytes per second, which its client copies onto every user; the newV2board client converts the panel’s Mbps with api::mbps_to_bps (MBPS_TO_BPS = 1_000_000.0 / 8.0, so 1 Mbps is 125,000 bytes per second, and a value of 0 or below is 0), and a [node.api].speed_limit above 0 replaces the panel’s values; see Panel clients.
Functions
Section titled “Functions”pub fn node_spec( cfg: &NodeConfig, globals: &Globals, node: &Node, users: &[UserInfo], audit: &[DetectRule],) -> io::Result<Spec<Uid>>;
pub fn test_spec(cfg: &NodeConfig, globals: &Globals) -> io::Result<Spec<Uid>>;
fn shared_spec(cfg: &NodeConfig, globals: &Globals, audit: &[DetectRule]) -> io::Result<Spec<Uid>>;fn policies(c: &ControllerConfig) -> Policies;fn lower_users( protocol: &InboundProtocolSpec, users: &[UserInfo], device_limits: bool,) -> BTreeMap<Uid, UserSpec>;fn identity(c: &Credentials) -> Vec<u8>;pub fn lower_route(route: &RouteConfig) -> io::Result<RouteSpec>;pub fn local(cfg: &HysteriaConfig, port: NonZeroU16) -> io::Result<Node>;/// The credential `u` presents to an inbound serving `protocol`. The reason/// a user cannot be admitted names no credential: the value is a secret.pub fn credentials(protocol: &InboundProtocolSpec, u: &UserInfo) -> Result<Credentials, String>;credentials returns its reason as a String, and lower_users logs that reason and skips the user.
The spec katana builds
Section titled “The spec katana builds”node_spec builds these fields of Spec<Uid> (The spec: desired state describes each type):
Spec field |
What node_spec puts there |
Built by | From |
|---|---|---|---|
inbounds |
At most one InboundSpec, the node’s. Tag <Type>_<listen_ip>_<port> from inbound::inbound_tag, where <Type> is V2ray, Trojan, Shadowsocks, Hysteria2, AnyTLS, Socks, Http or Sss (for example V2ray_0.0.0.0_443); BindSpec::Tcp or, for Hysteria 2, BindSpec::Udp on inbound::bind_host(listen_ip) and the node’s port; handoff, a HandoffSpec at <handoff_dir>/<port>.sock, or <handoff_dir>/<ip>-<port>.sock when listen_ip is one address (inbound::handoff_file), with mode 0o660 and handoff_group’s gid on a TCP bind whose handoff_dir is set, None otherwise; sniff: !disable_sniffing; the protocol; users: Some("users"); user_removal: None; proxy_protocol: true for a TCP bind, false for Hysteria 2’s UDP one; real_ip, a RealIpSpec on a WebSocket node whose real_ip_header is set, None otherwise. |
inbound::lower_inbound |
Node, [node.controller], [node.hysteria] |
outbounds |
direct, block, freedom, blackhole, then every [[outbound]] in file order, then one audit#<id> blackhole per audit rule id, in the order the ids first appear. Rules from a local rule list all carry id -1, so they share one audit#-1 outbound (Destination audit). Every drain is None. |
outbound::lower_outbounds, rule::audit_routes |
Globals.outbounds, the audit rules |
balancers |
Always empty. katana has no balancer configuration. | shared_spec |
— |
route |
The audit routes first, then [[node.route.rule]] in file order; default from [node.route].default, or "direct"; the geo file paths as written, each stamped with the file at that path. |
route::lower_route, rule::audit_routes |
[node.route], the audit rules |
dns |
DnsSpec::Single(backend), with the bytes of [dns].ca_file when it is set. |
outbound::lower_dns |
Globals.dns |
user_sets |
At most one: UserSet { tag: "users", users }. The supervisor’s validate checks it with validate_admission against the inbound whose users tag names it. |
lower_users |
The panel’s users, enable_device_limit |
policies |
user_removal: UserRemovalPolicy::Close and drain: DrainPolicy::Keep, the defaults; ip_ban and carrier_max_failures from [node.controller]. |
policies, from shared_spec |
[node.controller] |
The inbound’s tag and its bind are both built from listen_ip. The tag uses it as written, and the bind host goes through bind_host, which binds 0.0.0.0 as :: where this host’s IPv6 sockets take IPv4 too (Lowering inbounds and outbounds).
Policies
Section titled “Policies”fn policies(c: &ControllerConfig) -> Policies { let ip_ban = NonZeroU32::new(c.ban_max_failures) .filter(|_| c.enable_device_limit) .map(|max_failures| IpBanPolicy { max_failures, window: Duration::from_secs(c.ban_window_secs), duration: Duration::from_secs(c.ban_secs), }); Policies { ip_ban, carrier_max_failures: NonZeroU32::new(c.carrier_max_failures), ..Policies::default() }}The removal and drain policies are the supervisor defaults, and nothing overrides them: the inbound’s user_removal and every outbound’s drain are None.
| Policy | Value | Effect |
|---|---|---|
UserRemovalPolicy |
Close |
The supervisor-wide default for a principal the supervisor revokes (the user left the set, or no longer presents the credential they were admitted by). What Close does is on Users, principals and sessions. |
DrainPolicy |
Keep |
The supervisor-wide default; what it means for a changed or removed outbound is on Outbounds, UDP fan-out and balancers and Planning and applying a change. |
ip_ban |
IpBanPolicy { max_failures: ban_max_failures, window: ban_window_secs, duration: ban_secs } under enable_device_limit, with the defaults 30 failures in 120 s banning for 300 s; None without it, or when ban_max_failures is 0 |
A client IP whose authentications fail that often is banned (an IPv6 client’s whole /64 counts and is banned as one IP): its new TCP connections are dropped at accept, while its open ones run on. A successful authentication clears its count. |
carrier_max_failures |
carrier_max_failures, default 8; None when 0 |
A gRPC connection is closed once that many of its streams in a row fail to authenticate. |
The IP ban, like the device limit, counts client addresses, so it is set only where enable_device_limit says the addresses katana sees are the clients’ own: clients connect directly, the relays in front send a PROXY protocol v2 header, or, on a WebSocket node, a trusted reverse proxy names them in real_ip_header (Lowering inbounds and outbounds). The carrier close counts streams on one connection and holds without it. The supervisor takes the policies at every commit; how it applies them is on Listeners and the serve loop.
katana closes connections itself where it has to. When a [[node]] edit that the panel’s answer cannot show needs every connection dropped, when an [[outbound]] or [dns] change arrives as a StaticUpdate::Globals, or when the panel changes a part of the node whose change drops every connection (disruptive_part: all of it but an AnyTLS padding scheme and a Hysteria 2 node’s rates and UDP idle timeout), NodeManager::reconcile calls Supervisor::close(Selector::All) after the apply commits (The node manager).
Why every tag is unique by construction
Section titled “Why every tag is unique by construction”lower_outboundsrefuses a[[outbound]]whose tag repeats a built-in (direct,block,freedom,blackhole) or an earlier entry, or starts withAUDIT_TAG_PREFIX("audit#"):duplicate/reserved outbound tag <tag>.audit_routesgroups rules by id before it builds outbounds, so eachaudit#<id>appears once.- A node’s spec never holds more than one inbound and one user set.
So the supervisor’s DuplicateTag refusal never fires for a spec node_spec returns. References are another matter: a rule or default naming an outbound that does not exist is passed through and refused by the supervisor (route references unknown outbound <tag>).
Data flow
Section titled “Data flow”flowchart LR AR["DetectRule list"] --> A1["rule::audit_routes"] G["Globals"] --> A2["outbound::lower_outbounds"] G --> A3["outbound::lower_dns"] CFG["NodeConfig"] --> A4["route::lower_route"] A1 --> SS["shared_spec"] A2 --> SS A3 --> SS A4 --> SS N["Node"] --> LI["inbound::lower_inbound"] CFG --> LI LI --> LU["lower_users"] U["UserInfo list"] --> LU SS --> S["Spec of Uid"] LI --> S LU --> S S --> SUP["Supervisor::start or apply_with"]
node_spec runs these steps in order and returns the first error:
shared_spec(cfg, globals, audit):rule::audit_routes(audit)returns the audit outbounds and routes (Destination audit).outbound::lower_outbounds(globals)?returns the four built-ins and every[[outbound]].- The audit outbounds are appended.
outbound::lower_dns(&globals.dns)?readsca_filewhen set, and builds the backend.route::lower_route(&cfg.route)?lowers the node’s rules.route.rules.splice(0..0, audit_rules)puts the audit routes in front.- The spec is assembled with no inbound, no user set, no balancers and
policies(&cfg.controller).
inbound::lower_inbound(cfg, node)?lowers the listener, its handoff socket on a stream node, and on a WebSocket node itsreal_ip. For a TLS stream node and for every Hysteria 2 node it reads the certificate and key files;read_cert_keyfirst refuses an emptycert_fileorkey_filewithTLS node requires cert.cert_file and cert.key_file, before it reads anything.lower_users(&inbound.protocol, users, cfg.controller.enable_device_limit)lowers the users against the protocol from step 2, because the protocol decides which credential each user presents.- When at least one user was admitted,
spec.inboundsandspec.user_setsare filled from steps 2 and 3, the user set taggedUSER_SET; a node spec never holds more than one of each. A node nobody may use gets neither, so it listens nowhere, though an inbound the kernel cannot serve was still refused in step 2.
The order decides which error is reported when there are several: a bad [[outbound]] is reported before a bad [dns], which is reported before a bad [node.route], which is reported before anything wrong with the inbound.
Credentials per node type
Section titled “Credentials per node type”inbound::credentials(protocol, u) fills exactly one field of Credentials, the one the supervisor reads for that protocol (supervisor/src/build/users.rs → credential_kind). Every credential is derived from the user’s uuid string; a panel user carries no other secret katana uses.
| Node | Inbound protocol | Credentials field |
Value |
|---|---|---|---|
Vless |
Vless |
uuid |
Uuid::parse_str(uuid): any form the uuid crate parses (hyphenated, simple, braced, URN). |
Vmess |
Vmess |
uuid |
As for VLESS. |
Sss |
Sss |
uuid |
As for VLESS. |
Trojan |
Trojan |
password |
The uuid text as is (the XrayR convention: the password is the user’s UUID). |
Anytls |
Anytls |
password |
The uuid text as is. |
Socks, Http |
Socks, Http |
account |
Account { user: uuid, pass: uuid }: the panel’s users carry nothing but their UUID, so it is both the name and the password. |
Shadowsocks with a legacy cipher (SsCipher::Legacy) |
Shadowsocks |
password |
The uuid text as is. |
Shadowsocks with a 2022 cipher (SsCipher::Ss2022) |
Ss2022 |
ss2022_psk |
The first method.key_len() bytes of the uuid text: 16 for 2022-blake3-aes-128-gcm, 32 for 2022-blake3-aes-256-gcm. |
Hysteria2, [node.hysteria].credential empty or "uuid" |
Hysteria2, Hysteria2UserAuth::Password |
password |
The uuid text as is. The client’s whole auth string is the UUID. |
Hysteria2, credential = "user_pass" |
Hysteria2, Hysteria2UserAuth::Account |
account |
Account { user: traffic_email(u), pass: uuid }. traffic_email is the panel’s email, or the decimal uid when the email is empty. The client sends user:pass. |
A Shadowsocks 2022 user’s key is the first method.key_len() bytes of their uuid text. For the placeholder UUID 11111111-2222-3333-4444-555555555555 on 2022-blake3-aes-128-gcm, the key is the 16 ASCII bytes 11111111-2222-33, which a client writes as MTExMTExMTEtMjIyMi0zMw==. Because only a prefix counts, two users whose UUID texts share their first 16 characters present the same key on an AES-128 node, and the second one in panel order is skipped as sharing a credential. The server key comes from the node’s server_key (Lowering inbounds and outbounds).
Whether a node is VLESS or VMess is the panel client’s to say: the newV2board client builds a Node::Vless for a V2ray node with [node.api].enable_vless set and a Node::Vmess otherwise, and a helium config names vless or vmess itself. Lowering reads no [node.api] key to choose between them.
On a helium node the users answer carries each user’s UUID as a UUID, not as free text, and helium::user_infos writes it into UserInfo.uuid in its lowercase hyphenated form (uuid.hyphenated()). So on helium every credential in the table is that 36-character text, or the UUID it parses back to. One row of the table never applies there: a helium node cannot set [node.hysteria].credential, so its Hysteria 2 users always present the UUID itself. Since helium-node-api 0.2.0 a helium node may be legacy Shadowsocks, whose users present the UUID text as their password.
Walking the user list
Section titled “Walking the user list”lower_users walks the panel’s list once, in panel order:
flowchart TB
U["next user in panel order"] --> C{"credentials ok?"}
C -- "no" --> W1["WARN: skipping user uid: reason"]
C -- "yes" --> D{"uid already lowered?"}
D -- "yes" --> W2["WARN: skipping user uid: listed twice"]
D -- "no" --> I{"identity owned by an earlier user?"}
I -- "yes" --> W3["WARN: skipping user uid: shares its credential with user first"]
I -- "no" --> K["record the owner, insert Uid with credentials, speed limit and device limit"]
Every skip logs at WARN under the target katana::lower, names the uid, and continues with the next user. The reasons come from credentials, which never includes the value it rejected:
| Log message | Cause |
|---|---|
skipping user <uid>: uuid is empty |
The panel sent an empty uuid. Checked first, for every protocol. |
skipping user <uid>: uuid is not a valid UUID |
VLESS, VMess or sss, and Uuid::parse_str failed. |
skipping user <uid>: shadowsocks-2022 key too short (< <key_len>) |
Shadowsocks 2022, and the uuid text is shorter than 16 or 32 bytes. |
skipping user <uid>: its name holds ':' |
Hysteria 2 user_pass, and the user’s name (email or uid) contains a colon, which the user:pass wire form cannot carry. |
skipping user <uid>: the inbound admits no panel users |
The inbound is TUN. katana never lowers one for a panel node, so this arm is not reached. |
skipping user <uid>: listed twice |
The uid is already in the set. The first row of that uid whose credential lowers wins. |
skipping user <uid>: shares its credential with user <first> |
Another user, earlier in panel order, presents the same credential. |
The checks run in that order: credentials first, then the duplicate uid, then the shared credential. A second row for a uid whose credential does not lower is logged with the credential’s reason, not as listed twice, and a later row of a uid whose first row was skipped can still be admitted. The comment on the function gives the reason for skipping rather than failing: “one malformed row must not take everyone else down.”
The first two reasons do not arise on a helium node: a users answer with an empty or malformed UUID does not parse, and the client fails it as a whole with parse helium users response, so the node keeps the users it has, as for any failed fetch. listed twice and shares its credential with user <first> can still arise there.
What counts as a shared credential
Section titled “What counts as a shared credential”identity(c) returns the bytes two users collide on: the UUID’s 16 bytes, else the password’s bytes, else the Shadowsocks 2022 key’s bytes, else the account’s user name lower-cased with to_ascii_lowercase. credentials sets exactly one field, so the first one present is the only one. With no field set, identity returns an empty Vec (unwrap_or_default); credentials always sets one, so that case is not reached. lower_users remembers which uid presented each identity first, in a HashMap keyed by the identity bytes and sized for the list: the walk runs on every poll, over lists of tens of thousands of users, so each check is a lookup rather than a scan. lowering_a_large_list_is_not_quadratic lowers 200 001 users, the last sharing the first one’s UUID, and checks that the last is still skipped.
The rules match the supervisor’s validate_admission (supervisor/src/build/validate.rs), which refuses the whole inbound when two users present one credential:
| Credential | katana compares | validate_admission compares |
|---|---|---|
| UUID | the 16 bytes | the 16 bytes |
| Password | the bytes | the bytes |
| Shadowsocks 2022 key | the key’s bytes | the key’s bytes |
| Account (SOCKS, HTTP, Hysteria 2) | the name, ASCII lower-cased; the password is ignored | the name, lower-cased on a Hysteria 2 inbound (“Hysteria 2 compares usernames case-insensitively on the wire”) and as written on SOCKS and HTTP |
Had katana passed both users on, the supervisor would refuse the whole spec with inbound <tag>: users <a> and <b> present the same credential (or username), where <a> and <b> are decimal uids. Keeping the first user instead is what the comment in lower_users says: “The supervisor refuses a whole set over one shared credential, so the first user keeps it.”
validate_admission has two more per-user rules for Hysteria 2, and a set lower_users built never breaks them, because a Hysteria 2 password is the non-empty UUID and an account has a non-empty name without : and the non-empty UUID as its password:
inbound <tag>: user <uid>: a hysteria2 account needs a name without ':' and a passwordinbound <tag>: user <uid>: a hysteria2 password must not be emptyWhat the supervisor does with the set
Section titled “What the supervisor does with the set”This is the supervisor’s side, in brief; Users, principals and sessions has the detail.
- The inbound admits every user of the
usersset that holds the credential kind its protocol reads, and gives each one a principal of that inbound’s own, labelled with the decimal uid. - A principal is kept across applies while the user is still admitted by the same credential. So an unchanged user, and a user whose only change is their speed limit or device limit, keep their sessions when the set changes.
- A user’s device limit holds when a session binds: a session from an address beyond the limit is refused while the user’s other sessions come from as many addresses as the limit. A lowered limit closes no session.
- A principal that is replaced (the credential changed) or dropped (the user left the set) is revoked; what the spec’s
UserRemovalPolicy::Closethen does is on Users, principals and sessions. - The inbound names the set by tag, so the users are not part of its
InboundSpec; how the supervisor swaps the user tables is on Users, principals and sessions.
Speed limits
Section titled “Speed limits”A user’s limit
Section titled “A user’s limit”lower_users sets each user’s UserSpec::speed_limit to NonZeroU64::new(u.speed_limit): the user’s own rate in bytes per second, a 0 meaning no limit and becoming None. The panel clients have already put [node.api].speed_limit in its place where that is above 0 (its comment: “Already the local speed_limit where one overrides the panel’s: the panel clients read it into every user”), so lowering never reads the override itself. The unit is bytes per second throughout, as the supervisor’s UserSpec::speed_limit expects (a_user_is_held_to_their_speed_limit).
katana 6.1.0 removed the node-level limit, NodeInfo.speed_limit, and determine_rate, which gave each user the smaller non-zero of the node’s limit and their own. No panel client set a node limit but 0, and a local Hysteria 2 node’s was [node.api].speed_limit, the override its users already carried, so every user’s limit is what it was.
The whole chain, from the panel to a paced read:
| Step | Value | Where |
|---|---|---|
The panel’s rate, or a [node.api].speed_limit above 0 |
Mbps, f64; bytes per second from helium |
panel answer, src/config.rs |
mbps_to_bps |
bytes per second, u64, 0 for none |
src/api/mod.rs, in the panel clients (not for helium’s own figures) |
UserInfo.speed_limit |
bytes per second | src/api/mod.rs |
NonZeroU64::new |
Option<NonZeroU64> |
src/lower/mod.rs → lower_users |
UserSpec::speed_limit |
payload bytes per second, shared by all the user’s flows in both directions, TCP and UDP, with a one-second burst | supervisor/src/entity/user.rs |
Actor::publish_limits, Tracker::change_speed_limits, Pacer::set_rate |
the user’s token bucket | supervisor/src/supervisor.rs, supervisor/src/track/mod.rs, supervisor/src/track/pace.rs |
For example, 8 Mbps is 1,000,000 bytes per second: the e2e test a_users_speed_limit_paces_their_traffic gives a panel user "speed_limit":8 and needs at least 1.5 s to move 3 MB through one VMess connection. How the bucket runs into debt and why is on Tracking flows, stats and speed limits.
How a changed limit reaches live flows
Section titled “How a changed limit reaches live flows”A new limit from the panel (a user’s on newV2board, the users answer’s on helium) or from a [node.api].speed_limit edit reaches the flows that are already open without closing them:
sequenceDiagram participant P as Panel participant N as NodeManager participant L as node_spec participant A as Supervisor actor participant T as Tracker pacers participant F as Live flow N->>P: user_list during a poll cycle P-->>N: a user with a new speed_limit N->>L: lower the node and its users L-->>N: spec whose UserSpec speed_limit changed N->>A: apply_with, since the spec differs from the applied one A->>A: plan and prepare, then commit A->>T: publish_limits, then change_speed_limits T->>T: Pacer::set_rate on the user's pacer F->>T: next read or write polls the same pacer
- The new rate is a change to one
UserSpecin theusersset, so the lowered spec differs from the applied one, and the node manager applies it. The node itself did not change, so this change alone does not make the node manager close connections. - The user’s credential did not change, so their principal is kept and their sessions stay open.
a_speed_limit_change_keeps_the_users_sessionscovers this on the supervisor’s user-update path (Supervisor::set_users), which admits users through the sameadmitas an apply. - At commit, and only then,
publish_limitspublishes the limits that changed to the tracker (“a refused apply must not change live limits”). A user in several sets gets the smallest of their limits; a katana spec has one set.Tracker::change_speed_limitscallsPacer::set_rateon each changed user’s pacer: a user whosespeed_limitbecameNoneis set unlimited. The same commit replaces every user’s device limit. Pacer::set_ratekeeps “what was earned at the old rate”, up to the new burst; a user just limited starts with a full bucket, and a removed limit clears the balance. Every live flow of the user already holds the sameArc<Pacer>, so it feels the new rate at its next read or write. A flow sleeping off a debt sleeps at leastMIN_WAIT= 1 ms and looks again after at mostMAX_WAIT= 1 s, so a raised or removed limit is felt within one second (a_raised_or_removed_limit_is_felt_within_a_second).
A [node.api].speed_limit edit rebuilds the panel client, and the poll cycle that follows at once reads the users with the new value. A node described by [node.hysteria] takes its users from the panel too, so the same poll gives it the new value. The edit is not in the set of local edits that drop every connection (The node manager).
Each [[node]] runs its own supervisor, with its own tracker and pacers. A panel user served by two nodes is limited on each node separately.
Route lowering
Section titled “Route lowering”lower_route
Section titled “lower_route”lower_route(&cfg.route) turns [node.route] into a RouteSpec, one RouteRuleSpec per [[node.route.rule]], in file order:
| TOML key | RouteMatch |
How it is lowered |
|---|---|---|
domain_suffix |
DomainSuffix(s) |
Lower-cased with to_ascii_lowercase. |
cidr |
Cidr(IpCidr) |
Parsed with the cidr crate’s IpCidr. A bare address is a single host; host bits set are refused. Error: invalid cidr "<s>": <e>. |
port |
PortRange(lo, hi) |
etemenanki_environment::routing::parse_port_match: "443" is PortRange(443, 443), "8000-8080" is inclusive, spaces around each number are trimmed. |
geosite |
GeoSite(code) |
As written. |
geoip |
GeoIp(code) |
As written. |
outbound |
RouteRuleSpec::outbound |
As written. |
[node.route] key |
RouteSpec field |
Value |
|---|---|---|
default |
default |
As written, or "direct" when absent. The doc comment on lower_route: “A flow no rule matches leaves by direct unless default says otherwise.” |
geoip |
geoip |
RouteFile::stat of the path as written: the path, stamped with the file at it when the route is lowered (Option<RouteFile>). |
geosite |
geosite |
The same, for the geosite path. |
lower_route stamps each geo file every time it lowers the route. Its module comment: “Each is stamped with the file at its path when the route is lowered, so a file replaced at the same path rebuilds the route on the next apply.” A file replaced at the same path gives a different stamp, and so a lowered spec that differs from the applied one. Every poll lowers the node and compares the result with the applied spec (The node manager), so the node’s next poll, or any reconcile before it, applies the new spec, and the supervisor builds the route again from the new file. The stamp never fails the lowering: RouteFile::stat returns a RouteFile, not a Result, and whether the rules can use the file is judged when the supervisor builds the route (What the supervisor checks later).
The matchers of one rule are pushed kind by kind, whatever the order in the file: every domain_suffix, then cidr, port, geosite and geoip. The supervisor’s route table tries rules in order and a rule matches when any one of its matchers does (RouteTable::pick, “First rule with any matching matcher wins”), so the order inside a rule changes only the order the matchers are evaluated in. A rule with domain_suffix = ["example.com"] and port = ["443"] matches every flow to example.com and every flow to port 443. A rule with no matcher never matches; the routing guide says so for operators.
Domain suffixes are lower-cased once here because the router lower-cases a flow’s requested and sniffed domains once per routing decision and compares them with the matcher as stored; a suffix stored with capitals would never match. The module comment gives the other half: “domains are lower-cased once here rather than on every match.”
The errors lower_route returns, all ErrorKind::InvalidInput, as --test prints them:
configuration error: node 1: invalid cidr "10.0.0.0/33": invalid length for network: Network length 33 is too long for Ipv4 (maximum: 32)configuration error: node 1: invalid cidr "192.0.2.1/24": host part of address was not zeroconfiguration error: node 1: invalid port spec: "80-"configuration error: node 1: invalid port spec: "70000"configuration error: node 1: invalid port spec: "443-80" has a lower bound above its upper boundparse_port_match refuses an inverted range because it would compile into a rule that can never match, and such a rule looks the same as one that is never hit.
What the supervisor checks later
Section titled “What the supervisor checks later”lower_route names geo files and outbound tags without looking at them. The supervisor’s validate refuses a rule or default naming an outbound that does not exist, and supervisor/src/build/route.rs → compile_routes loads only the geosite and geoip codes the rules use:
configuration error: node 1: route references unknown outbound nowhereconfiguration error: node 1: building route failed: a geosite matcher is used but no geosite file is configuredconfiguration error: node 1: building route failed: geosite code not found: no-such-code-xyzHow the compiled table and the plane serve flows is on The plane: routing each flow and Route model.
Audit routes first
Section titled “Audit routes first”shared_spec splices the audit routes in front of the node’s own rules, so an audited domain is caught before any [[node.route.rule]] can send it elsewhere. Each audit rule id becomes one RouteRuleSpec with a single RouteMatch::DomainRegex over all of that id’s patterns, pointing at the blackhole outbound audit#<id>. With audit rules 7: ^ads\., 9: tracker and 7: ^promo\. and one block rule in [node.route], the route’s outbounds read audit#7, audit#9, block (audit_rules_route_first_to_one_blackhole_per_rule_id). Matching is on Destination audit.
The local Hysteria 2 node
Section titled “The local Hysteria 2 node”A Hysteria 2 node that names its own port is described by [node.hysteria] instead of its panel. NodeManager::node_info builds that node with api::hysteria::local(&cfg.hysteria, port) when NodeType::parse(&cfg.api.node_type) is Some(NodeType::Hysteria2) (hysteria2, hysteria or hy2, in any case) and [node.hysteria].port is not 0; with port 0 the panel is asked, as for every other node type (Hysteria 2 guide). A helium node is never local: its client refuses both node_type and [node.hysteria].port, so its panel is always asked. The doc comment of NodeManager::node_info says so: “A helium node is never local”.
local returns a Node::Hysteria2 on the block’s port, with the block’s obfuscation, its rates (0, no cap and no limit, when unset), ignore_client_bandwidth (on when unset), its UDP relay and its masquerade, and runs the contract’s validate on it; its rules and messages are on Panel clients. The result is a Node like any panel’s, so lower_inbound lowers it as it lowers one, and lower_hysteria reads only credential and congestion from [node.hysteria]. The node’s users still come from the panel, and their speed limits with them.
On newV2board the same block completes a Hysteria 2 node the panel describes: api::hysteria::uniproxy takes the panel’s obfuscation and rates, the block’s overrides of the rates, and the block’s UDP relay and masquerade, which UniProxy has no field for. On helium the panel describes the obfuscation, the rates, the UDP relay, the idle timeout and the masquerade; the credential kind stays the default uuid, and congestion is the one [node.hysteria] key a helium node may set (Lowering inbounds and outbounds).
Until 6.1.0 this was lower::local_hysteria_node, which wrote out a NodeInfo field by field, took [node.api].speed_limit as its node-level limit, and left the UDP relay, the masquerade and the rates for lower_hysteria to read from the block. The unit tests now build their nodes as the contract’s values: vmess_node() in tests/unit/lower/spec.rs is a Node::Vmess on port 443 over TCP without TLS.
test_spec: what --test and reload checks run
Section titled “test_spec: what --test and reload checks run”runtime::check_node runs etemenanki_supervisor::check(&lower::test_spec(cfg, globals)?). test_spec first calls inbound::real_ip(&cfg.controller)?, then inbound::handoff(&cfg.controller)?, then inbound::congestion(&cfg.hysteria)?, for every node, and drops the results. Its comment gives the reason: “Local, so judged now for every node type, not only once a panel names a WebSocket node or a port, or (helium) a Hysteria 2 node.” So --test, a start and a reload refuse half a real-IP setting or a typo in it, a handoff setting the relay could not use, and a congestion control that is not cubic, bbr or reno, for example configuration error: node 1: real_ip_header needs real_ip_from: the proxies trusted to set it, configuration error: node 1: handoff_group is set without handoff_dir or configuration error: node 1: unknown hysteria congestion "vegas" (expected "cubic", "bbr" or "reno") under --test, although the inbound that would read them is not lowered here. The congestion check holds on a node of any type, so a VMess node whose [node.hysteria] names an unknown congestion control is refused too. handoff looks handoff_group up in /etc/group, so the check fails on a host that lacks the group. check validates the spec, plans it against an empty supervisor and prepares everything it describes (outbounds, routes with their geo data, handlers with their certificates, user tables) without binding a listener or starting anything. It “refuses what a start would, short of a port or device that cannot be bound” (Validation and apply errors).
[node.api].node_type, as NodeType::parse reads it |
test_spec returns |
|---|---|
Hysteria 2 (hysteria2, hysteria or hy2, any case) |
node_spec(cfg, globals, &node, &[placeholder], &[]), where node is api::hysteria::local(&cfg.hysteria, port), port being [node.hysteria].port or, when that is 0, 1 (NonZeroU16::MIN). No audit rules. |
| Anything else | shared_spec(cfg, globals, &[]): no inbound, no user set, no audit rules. |
A Hysteria 2 node’s own settings are local on newV2board (The local Hysteria 2 node), so test_spec builds the node from them and lowers its inbound. api::hysteria::local judges the block’s obfuscation, UDP relay and masquerade first, whether or not the panel will name the port, and its comment says why the node is built at all: “A node whose panel names its port is judged on a placeholder one.” NodeType::parse lower-cases the value and accepts v2ray, vmess and vless (V2ray), trojan, shadowsocks, hysteria2, hysteria and hy2 (Hysteria2), anytls, socks and socks5 (Socks), http and sss. test_spec takes the second branch for any other value too, including one NodeType::parse does not recognise; every caller of check_node builds the node’s PanelClient first, and the newV2board client refuses such a value (unknown node_type "<value>").
A helium node names no node_type: its panel describes the protocol, and the helium client refuses a node_type, enable_vless or any [node.hysteria] key but congestion before check_node runs. Its empty node_type takes the second branch, so test_spec judges it as every other non-Hysteria node is, with the three local checks above and no inbound, whatever protocol its panel will name (a_helium_nodes_check_judges_its_congestion_control). The doc comment on test_spec: “A helium node names no node_type (its panel describes the protocol), so it is judged as every other node is.”
test_spec lowers the Hysteria 2 inbound with one placeholder user:
UserInfo field |
Value |
|---|---|
uid |
0 |
email |
"placeholder" |
uuid |
"placeholder" |
speed_limit, device_limit |
0 |
It lowers to password: "placeholder" for credential empty or "uuid", or account: placeholder / placeholder for "user_pass". Port 1 stands in for a port the panel will supply, so a node with port = 0 is checked as Hysteria2_<listen_ip>_1; check binds nothing, so the port is never opened.
runtime::test_config loads the file and refuses a config without nodes with config defines no [[node]] entries, which carries no node prefix. It logs the shared-WireGuard warning, then, for each node in turn, builds its PanelClient and runs check_node; an error from either is prefixed with the node’s node_id (node 1: …). src/main.rs prints Configuration OK on stdout with exit status 0, or configuration error: <e> on stderr with exit status 1. Captured with the 6.1.0 binary:
configuration error: node 1: duplicate/reserved outbound tag audit#1configuration error: node 1: hysteria2 node requires cert.mode = "file"configuration error: node 1: unknown node_type "Hysterai"configuration error: node 1: obfs_password must be at least 4 bytes for salamanderconfiguration error: node 1: masquerade.status must not be 233, the Hysteria 2 authentication success statusThe last two come from api::hysteria::local, which runs before the inbound is lowered, so a node with both a short obfuscation password and cert.mode = "none" reports the password; the masquerade’s is the contract’s text. Inside lower_hysteria too every judgement about the config runs before the certificate is read, so a node with a missing certificate file reports anything else that is wrong first. A Hysteria 2 node with port = 0, a valid certificate and key, and either credential kind prints Configuration OK.
On a helium node, the same binary prints:
configuration error: node 1: [node.api] node_type is set, but a helium node's protocol is described by the panel; remove it (of [node.hysteria], only congestion is this host's to choose)configuration error: node 1: [node.hysteria] up_mbps is set, but a helium node's protocol is described by the panel; remove it (of [node.hysteria], only congestion is this host's to choose)configuration error: node 1: unknown hysteria congestion "vegas" (expected "cubic", "bbr" or "reno")The first two come from PanelClient::new, which names the first refused key it finds; the third from test_spec. A helium node that sets no protocol key, with congestion unset or bbr, prints Configuration OK without reading its certificate files, since no inbound is lowered.
A config reload runs the same check for each added or changed node, and for every node when [[outbound]] or [dns] changed, before it touches any running node. A refusal is logged at ERROR as reload: node <node>: <e>; keeping current config, where <node> is <panel_type>@<host>#<node_id>, with <panel_type> lower-cased and /<node_type> appended when the panel finds nodes by type (Runtime and config reload).
Changes from 3.x
Section titled “Changes from 3.x”katana 3 built its own listeners, user tables, meters and router. In katana 4 that code is gone, and each concept this page touches lives here:
| katana 3.0.1 | katana 4 |
|---|---|
src/traffic.rs → AuthKey, UserTag (the payload a protocol user table handed back) |
lower::Uid and the supervisor’s Principal, labelled with the decimal uid (Users, principals and sessions) |
src/traffic.rs → determine_rate |
src/lower/mod.rs → determine_rate, unchanged until katana 6.1.0 removed it with the node-level limit; a user’s limit is now their own, which the panel clients override with [node.api].speed_limit |
src/manager/proxy.rs → ProxyManager::refresh (building and publishing the protocol user tables) |
lower_users builds a UserSet; the supervisor builds and swaps the tables |
src/connector.rs → Admission |
the supervisor’s sessions and principals |
src/meter.rs (metering and the per-user token bucket) |
the supervisor’s tracker and Pacer (Tracking flows, stats and speed limits) |
src/router.rs → build_router (compiling [node.route], loading geo data) |
src/lower/route.rs → lower_route; the supervisor compiles the table and loads geo data (The plane: routing each flow) |
src/inbound.rs, src/manager/transport.rs, src/outbound/* |
src/lower/inbound.rs, src/lower/outbound.rs; the supervisor’s listeners and outbounds (Lowering inbounds and outbounds) |
src/rule.rs → RuleManager::detect |
route-based audit, rule::audit_routes (Destination audit) |
Invariants
Section titled “Invariants”| Invariant | Why | Pinned by |
|---|---|---|
The same inputs, with the same certificate, key and CA bytes, give equal specs. Users are a BTreeMap in uid order; outbounds, routes and audit groups keep their input order. |
A spec that differed between two lowerings of the same inputs would be applied although nothing changed; how the node manager compares specs is on The node manager, and the supervisor’s equality contract on The spec: desired state. | No katana test; follows from the types. |
| A user whose credential does not lower is skipped, and the other users are still lowered. | “One malformed row must not take everyone else down.” | users_without_a_usable_credential_are_skipped (not-a-uuid and an empty UUID skipped, the valid user admitted) |
| A uid appears once in the set; the first row of that uid whose credential lowers wins. | BTreeMap keys are unique; the first lowered row is the one kept. |
a_shared_credential_admits_only_the_first_user (“a uid listed twice keeps its first row”) |
| No two users in the set present one credential; the first in panel order keeps it. Hysteria 2 account names compare lower-cased. | The supervisor refuses the whole inbound over one shared credential. | a_shared_credential_admits_only_the_first_user (katana); two_users_may_not_present_the_same_credential and hysteria2_usernames_collide_case_insensitively (supervisor/tests/unit/validate.rs, the rule katana keeps its sets clear of) |
| A skip names the uid and never the credential. | The credential is a secret (“name the user, never the value”). | By construction: no credentials reason contains the input. |
A user’s limit is their own panel limit, or [node.api].speed_limit when that is set; 0 is unlimited (None). |
The panel clients apply the override; lower_users takes the value as it is. |
a_user_is_held_to_their_speed_limit; the_local_speed_override_wins (tests/unit/api/helium.rs) |
| A panel speed limit paces the user’s traffic. | The limit is enforced by the supervisor’s pacer. | a_users_speed_limit_paces_their_traffic (tests/unit/e2e.rs) |
Under enable_device_limit a user’s panel device limit and the IP ban hold; without it neither does, and the carrier close holds either way. A 0 turns the ban, or the carrier close, off. |
The device limit and the ban count client addresses, which only enable_device_limit vouches for. |
enable_device_limit_holds_the_panels_limit_and_bans_ips, without_enable_device_limit_no_limit_holds_and_no_ip_is_banned, zero_turns_the_ip_ban_and_the_grpc_close_off |
| A TCP inbound reads PROXY protocol headers; Hysteria 2’s UDP one does not. | proxy_protocol is set from the bind kind. |
without_enable_device_limit_no_limit_holds_and_no_ip_is_banned |
| The node check refuses half a real-IP setting on a node no panel has described yet, and accepts both keys together. | test_spec calls inbound::real_ip first. |
the_node_check_refuses_a_half_real_ip_setting |
The node check refuses a handoff setting the relay could not use (a relative handoff_dir, a handoff_group without one) before any panel names a port, and accepts a valid pair. |
test_spec calls inbound::handoff second. |
the_node_check_refuses_a_handoff_setting_the_relay_could_not_use |
| The node check refuses an unknown congestion control on every node, a helium node’s included, before any panel names a Hysteria 2 node; a helium node’s check lowers no inbound. | test_spec calls inbound::congestion third, and a helium node’s empty node_type takes the non-Hysteria branch. |
a_helium_nodes_check_judges_its_congestion_control |
| Lowering a large list stays linear. | The credential owners are a HashMap. |
lowering_a_large_list_is_not_quadratic (200 001 users within 20 s) |
| A changed limit keeps the user’s sessions and reaches live flows within a second. | A limit is not part of how a user is admitted; MAX_WAIT = 1 s bounds a paced sleep. |
a_speed_limit_change_keeps_the_users_sessions (supervisor/tests/hot_swap.rs, through set_users), a_raised_or_removed_limit_is_felt_within_a_second (supervisor/tests/unit/track.rs) |
| An unchanged user keeps a live connection across a user-set change. | The principal is kept while the credential is unchanged. | unchanged_user_survives_user_refresh, repeated_user_refreshes_never_disturb_a_live_connection (tests/unit/e2e.rs) |
Audit routes come before every [[node.route.rule]], one audit#<id> blackhole per rule id, in first-appearance order. |
An audited domain must be caught before a node rule sends it elsewhere. | audit_rules_route_first_to_one_blackhole_per_rule_id |
No [[outbound]] tag starts with audit#. |
The audit outbounds are named audit#<id>, so a configured outbound must never take one of their tags. |
an_audit_tag_is_reserved |
| Each Hysteria 2 credential kind lowers to the auth mode it names. | "" and "uuid" are Password, "user_pass" is Account. |
hysteria_accepts_both_credential_kinds (tests/unit/lower/inbound.rs) |
| A port range with its lower bound above its upper bound is refused; ranges are inclusive. | An inverted range would never match. | port_parser_rejects_an_inverted_range, port_ranges_are_inclusive (environment/tests/unit/routing.rs) |
| A geo file replaced at the same path changes the lowered spec, so the next apply rebuilds the route. | lower_route wraps each geo path in RouteFile::stat. |
No katana test. |
| Stored domain matchers are lower case. | The router folds only the flow’s domains. | domain_matching_is_case_insensitive (environment/tests/unit/routing.rs) for the router side |
Failure paths and cancellation
Section titled “Failure paths and cancellation”Errors
Section titled “Errors”node_spec, test_spec and lower_route return io::Result; the first error ends the lowering, and no partial spec is returned.
| Error | ErrorKind |
Raised in |
|---|---|---|
invalid cidr "<s>": <e> |
InvalidInput |
lower_route |
invalid port spec: "<s>", invalid port spec: "<s>" has a lower bound above its upper bound |
InvalidInput |
parse_port_match, from lower_route |
Outbound refusals such as duplicate/reserved outbound tag <tag> |
InvalidInput, or Unsupported for unsupported shadowsocks cipher "<name>" |
lower_outbounds; every text is listed on Lowering inbounds and outbounds |
DNS refusals such as dns: unknown backend "<name>" (expected "system", "udp", "tls" or "https") |
InvalidInput |
Backend::from_spec, from lower_dns; every text is listed on Lowering inbounds and outbounds |
node requests kernel-unsupported feature: <feature> |
Unsupported |
lower_inbound |
real_ip_from is set without real_ip_header, real_ip_header needs real_ip_from: the proxies trusted to set it, real_ip_header "<header>" is not a header name, real_ip_from "<entry>": <e> |
InvalidInput |
inbound::real_ip, from test_spec and lower_inbound (Lowering inbounds and outbounds) |
handoff_group is set without handoff_dir, handoff_dir "<dir>" must be an absolute path, handoff_dir "<dir>" is too long: with "<name>" in it, a socket's path would pass the 107 bytes a Unix socket's path may have, handoff_group "<name>": reading /etc/group: <e>, handoff_group "<name>" is not a group in /etc/group |
InvalidInput |
inbound::handoff, from test_spec and lower_inbound (Lowering inbounds and outbounds) |
Inbound refusals such as TLS node requires cert.cert_file and cert.key_file, hysteria2 node requires cert.mode = "file", unknown hysteria credential kind "<kind>" (expected "uuid" or "user_pass") or sss transform.up: <e> |
InvalidInput |
lower_inbound |
unknown hysteria congestion "<value>" (expected "cubic", "bbr" or "reno") |
InvalidInput |
inbound::congestion, from test_spec on every node and from lower_hysteria |
A certificate, key or ca_file read failure |
from std::fs::read |
read_cert_key and lower_dns |
lower_users never fails; it logs and leaves out what it cannot lower.
Where the errors surface:
| Path | What is logged or printed |
|---|---|
--test |
configuration error: node <node_id>: <e> on stderr, exit status 1. |
| Config reload | reload: node <node>: <e>; keeping current config at ERROR. |
| Bootstrap | NodeManager::try_bootstrap reports a lowering or start error as initial start failed: <e>, and a refusal of api::hysteria::local for a local Hysteria 2 node as node_info failed: <e> (The node manager). |
Log lines
Section titled “Log lines”| Message | Level, target | When |
|---|---|---|
skipping user <uid>: <reason> |
WARN, katana::lower |
lower_users skips a user; the reasons are in Walking the user list. |
IPv6 sockets here take IPv6 alone (net.ipv6.bindv6only), so listen_ip 0.0.0.0 serves IPv4 only |
WARN, katana::lower::inbound |
Once per process, from inbound::dual_stack, when a listen_ip of 0.0.0.0 is lowered on a host where net.ipv6.bindv6only is set (Lowering inbounds and outbounds). |
audit rule <id> skipped: <e> |
WARN, katana::rule |
rule::audit_routes leaves out an audit rule id and its outbound (Destination audit). |
Cancellation
Section titled “Cancellation”Lowering has no await point and spawns no task, so a cancellation cannot stop it halfway. NodeManager::lower_off_runtime takes its inputs under the node’s locks, releases them, and hands the lowering to the blocking pool; a lowering whose caller is dropped still runs to its end there, and its result is discarded. A shutdown during a bootstrap attempt drops the attempt at its next await point (try_bootstrap runs inside a biased tokio::select! on the shutdown token); a spec that was lowered but not yet started is dropped with it. check is async because preparing a spec awaits the builders; test_spec itself has no await point, like node_spec.
Limits
Section titled “Limits”| Limit | Value |
|---|---|
| Inbounds per node spec | at most 1 |
| User sets per node spec | at most 1, tagged users |
| Balancers | none; katana has no balancer configuration |
| DNS | always DnsSpec::Single, one backend for every outbound of the node |
| User key | Uid(i64), the panel’s numeric user id |
| Credential source | the panel user’s uuid string, which on helium is always the lowercase hyphenated UUID |
| Device limit | the panel user’s device_limit, kept only under enable_device_limit; 0 is none |
| IP ban defaults | 30 failures in 120 s ban an address (an IPv6 client’s /64) for 300 s, under enable_device_limit |
| gRPC carrier close default | 8 failed streams in a row |
| Shadowsocks 2022 user key | the first 16 (AES-128) or 32 (AES-256, ChaCha20) bytes of the uuid text; a hyphenated UUID has 36 |
| Speed limit unit | bytes per second, u64; 0 is unlimited; one-second burst; a paced sleep lasts from MIN_WAIT = 1 ms to MAX_WAIT = 1 s, so a change is felt within 1 s |
| Mbps conversion | × 1,000,000 / 8: 1 Mbps = 125,000 bytes per second |
| Port spec | a u16, or an inclusive lo-hi range of two |
| Hysteria 2 values katana judges | udp_idle_timeout 2 to 600 s; Salamander obfs_password at least 4 bytes; a masquerade the contract allows; judged by api::hysteria for [node.hysteria] and a UniProxy node, by the contract for helium’s |
test_spec Hysteria 2 port |
1 (NonZeroU16::MIN) when [node.hysteria].port is 0 |
Placeholder user in test_spec |
uid 0, UUID and email "placeholder" |
handoff_dir |
absolute, and short enough that it, a / and the node’s socket name at port 65535 fit a Unix socket’s 107-byte path: 96 bytes on every address, less on one address |
| Test | File | What it pins |
|---|---|---|
a_user_is_held_to_their_speed_limit |
tests/unit/lower/spec.rs |
A user’s limit of 2000 bytes per second is their UserSpec.speed_limit, and 0 is None, unlimited. |
users_without_a_usable_credential_are_skipped |
tests/unit/lower/spec.rs |
On a VMess node, uids 1 (not-a-uuid) and 2 (empty) are skipped and uid 3 is admitted. |
a_shared_credential_admits_only_the_first_user |
tests/unit/lower/spec.rs |
Rows 5:A, 2:A, 3:B, 5:B admit [3, 5], and uid 5 keeps UUID A. |
without_enable_device_limit_no_limit_holds_and_no_ip_is_banned |
tests/unit/lower/spec.rs |
A panel device limit of 3 is dropped, ip_ban is None, carrier_max_failures is 8, and the TCP inbound reads PROXY headers. |
enable_device_limit_holds_the_panels_limit_and_bans_ips |
tests/unit/lower/spec.rs |
The device limit 3 is kept, ip_ban is 30 failures in 120 s for 300 s, and a panel limit of 0 is None. |
zero_turns_the_ip_ban_and_the_grpc_close_off |
tests/unit/lower/spec.rs |
ban_max_failures = 0 and carrier_max_failures = 0 give None for both. |
lowering_a_large_list_is_not_quadratic |
tests/unit/lower/spec.rs |
200 000 distinct users and one sharing the first UUID lower within 20 s, the last skipped. |
the_node_check_refuses_a_half_real_ip_setting |
tests/unit/lower/spec.rs |
test_spec fails with real_ip_header alone, and succeeds once real_ip_from = ["127.0.0.1/32"] is added. |
the_node_check_refuses_a_handoff_setting_the_relay_could_not_use |
tests/unit/lower/spec.rs |
test_spec fails with handoff_dir = "run/katana/handoff" and with handoff_group = "root" alone, and succeeds with /run/katana/handoff and the group root. |
a_helium_nodes_check_judges_its_congestion_control |
tests/unit/lower/spec.rs |
On a helium node with no node_type, test_spec lowers no inbound, accepts congestion = "bbr", and refuses "vegas" with unknown hysteria congestion. |
the_nodes_hysteria_udp_and_masquerade_reach_the_spec |
tests/unit/lower/spec.rs |
A Hysteria 2 node that says a 90 s idle timeout and a 502 masquerade lowers both; one that says no UDP and no masquerade lowers neither, whatever [node.hysteria] says; a node from api::hysteria::uniproxy takes both from [node.hysteria] (60 s, status 403). |
audit_rules_route_first_to_one_blackhole_per_rule_id |
tests/unit/lower/spec.rs |
Route outbounds audit#7, audit#9, block; the first rule is one DomainRegex; both audit outbounds are Blackhole. |
an_audit_tag_is_reserved |
tests/unit/lower/spec.rs |
An [[outbound]] tagged audit#1 fails node_spec with an error containing reserved. |
acme_cert_mode_rejected, reject_unknown_sni_is_refused_rather_than_ignored, tls_without_cert_file_errors |
tests/unit/lower/inbound.rs |
What lowering still refuses of a node is this host’s: an ACME cert mode, reject_unknown_sni, a TLS node without its certificate files. What a panel asks for and katana cannot serve is refused in tests/unit/api/newv2board.rs (Panel clients). |
anytls_socks_and_http_users_are_their_uuid, sss_users_are_their_uuid |
tests/unit/lower/inbound.rs |
AnyTLS users present their UUID as password, SOCKS and HTTP users as account name and password, sss users as UUID. |
the_new_node_kinds_pass_the_supervisors_validation |
tests/unit/lower/spec.rs |
A REALITY node with Vision, an AnyTLS, a SOCKS and an HTTP node, a legacy Shadowsocks node and an sss node over WebSocket with TLS, a Shadowsocks 2022 node, and a Hysteria 2 node as helium describes it each lower through node_spec, with one user, to a spec the supervisor’s validate accepts. |
ss2022_builds |
tests/unit/lower/inbound.rs |
A Shadowsocks 2022 user’s key from credentials is the first 16 bytes of the UUID’s text on 2022-blake3-aes-128-gcm. |
hysteria_accepts_both_credential_kinds, hysteria_refuses_an_unknown_credential_kind |
tests/unit/lower/inbound.rs |
"" and "uuid" lower to Hysteria2UserAuth::Password, "user_pass" to Account, and an unknown kind is refused with unknown hysteria credential kind. |
a_users_speed_limit_paces_their_traffic |
tests/unit/e2e.rs |
A panel speed_limit of 8 (1,000,000 bytes per second) holds 3 MB of echo traffic to at least 1.5 s. |
unchanged_user_survives_user_refresh |
tests/unit/e2e.rs |
Adding a second user keeps the first user’s VMess connection relaying on the same socket. |
repeated_user_refreshes_never_disturb_a_live_connection |
tests/unit/e2e.rs |
Six user-set flips leave one Hysteria 2 QUIC connection alive and relaying. |
a_speed_limit_change_keeps_the_users_sessions |
supervisor/tests/hot_swap.rs |
The supervisor side: a new speed_limit set through Supervisor::set_users keeps the session id. |
a_raised_or_removed_limit_is_felt_within_a_second |
supervisor/tests/unit/track.rs |
The supervisor side: MAX_WAIT bounds how late a limit change is felt. |
two_users_may_not_present_the_same_credential, hysteria2_usernames_collide_case_insensitively |
supervisor/tests/unit/validate.rs |
The supervisor rule lower_users keeps its sets clear of. |
port_parser_rejects_an_inverted_range, port_ranges_are_inclusive, any_matcher_within_a_rule_matches, domain_matching_is_case_insensitive |
environment/tests/unit/routing.rs |
The port parser and the matching rules lower_route relies on. |
lower_route is exercised through audit_rules_route_first_to_one_blackhole_per_rule_id, which lowers a [node.route] with one domain_suffix rule, and no katana test pins the geo file stamp; test_spec has three katana unit tests, the_node_check_refuses_a_half_real_ip_setting, the_node_check_refuses_a_handoff_setting_the_relay_could_not_use and a_helium_nodes_check_judges_its_congestion_control, which cover its real-IP, handoff and congestion checks and its helium branch, and no katana test pins that credentials fills the field the Hysteria 2 credential kind names. --test against a config file exercises lower_route and test_spec, and the texts on this page were captured that way, with the 6.1.0 binary. How to run the suites is on Testing.