feat: xhttp xmux

This commit is contained in:
FUFSoB committed 2026-10-18 16:53:08 +05:00
1 parent 2fc8ef5567
commit a41fbc10e6
16 files changed
+231 -18

No files matched your search

+1
View File
@@ -335,6 +335,7 @@ services.proxy-suite = {
};
xray = {
package = ‹proxy-suite's xray (pkgs/xray.nix)›;
xhttpXmux = null;
};
};
sshProxy = {
+26
View File
@@ -140,6 +140,7 @@ Part of the [proxy-suite options reference](./index.md).
- [url](#services-proxy-suite-proxy-urltest-url)
- xray
- [package](#services-proxy-suite-proxy-xray-package)
- [xhttpXmux](#services-proxy-suite-proxy-xray-xhttpxmux)
<a id="services-proxy-suite-proxy-enable"></a>
## services\.proxy-suite\.proxy\.enable
@@ -1213,3 +1214,28 @@ XRay package, for the “xray” and “hybrid” backends\.
**Type:** package\
**Default:** proxy-suite’s ` xray ` (` pkgs/xray.nix `)\
**Example:** `pkgs.xray`
<a id="services-proxy-suite-proxy-xray-xhttpxmux"></a>
## services\.proxy-suite\.proxy\.xray\.xhttpXmux
XRay’s ` xmux ` for every XHTTP outbound whose link sets none (in its ` extra `): how
its connections are spread over HTTP/2 or HTTP/3 connections to the server, and how
soon a dead one is noticed\. XRay notices a connection that stopped answering only by
` hKeepAlivePeriod `’s ping: after that many seconds without a frame, plus 15 for the
ping, default 45, so a minute in which everything on it hangs, new connections too\.
XRay applies its own defaults (` maxConnections ` 3, ` hMaxRequestTimes ` “600-900”,
` hMaxReusableSecs ` “1800-3000”) only to an empty ` xmux `: give them here too\.
` null `: XRay’s defaults\.
**Type:** null or (attribute set of (signed integer or string matching the pattern \[0-9]+(-\[0-9]+)?))\
**Default:** `null`\
**Example:**
```nix
{
hKeepAlivePeriod = 10;
hMaxRequestTimes = "600-900";
hMaxReusableSecs = "1800-3000";
maxConnections = 3;
}
```
+7
View File
@@ -644,6 +644,12 @@ let
}
.${cfg.debug.logLevel};
connectionLogEnabled = cfg.enable && clashApiEnabled && cfg.debug.connectionLog.enable;
# proxy.xray.xhttpXmux, as a jq step over one XRay outbound: an XHTTP one whose link set no
# xmux takes it. JSON is a jq literal.
xhttpXmuxJq = lib.optionalString (xrayCfg.xhttpXmux != null) ''
| if .streamSettings.network? == "xhttp" and ((.streamSettings.xhttpSettings.extra.xmux? // {}) == {})
then .streamSettings.xhttpSettings.extra.xmux = ${builtins.toJSON xrayCfg.xhttpXmux}
else . end'';
perAppZapretEnabled = perAppZapretCfg.enable;
# The global units each per-app backend steps aside for (constants.refuseUnderGlobal), as
# systemctl patterns: they stop it as they start, and the standby unit waits them out.
@@ -1260,6 +1266,7 @@ in
singBoxLogLevel
xrayLogLevel
connectionLogEnabled
xhttpXmuxJq
singBoxCfg
xrayCfg
proxyEnabled
+22
View File
@@ -195,6 +195,28 @@ in
example = literalExpression "pkgs.xray";
description = ''XRay package, for the "xray" and "hybrid" backends.'';
};
xhttpXmux = mkOption {
# A number, or a range XRay picks from at random.
type = types.nullOr (types.attrsOf (types.either types.int (types.strMatching "[0-9]+(-[0-9]+)?")));
default = null;
description = ''
XRay's `xmux` for every XHTTP outbound whose link sets none (in its `extra`): how
its connections are spread over HTTP/2 or HTTP/3 connections to the server, and how
soon a dead one is noticed. XRay notices a connection that stopped answering only by
`hKeepAlivePeriod`'s ping: after that many seconds without a frame, plus 15 for the
ping, default 45, so a minute in which everything on it hangs, new connections too.
XRay applies its own defaults (`maxConnections` 3, `hMaxRequestTimes` "600-900",
`hMaxReusableSecs` "1800-3000") only to an empty `xmux`: give them here too.
`null`: XRay's defaults.
'';
example = {
maxConnections = 3;
hMaxRequestTimes = "600-900";
hMaxReusableSecs = "1800-3000";
hKeepAlivePeriod = 10;
};
};
};
};
}
@@ -46,6 +46,8 @@ def xray_pin_server_names:
# Slurped (a list of one), not an argument: it grows with the rules.
$route_rules[0] as $route_rules
| .outbounds = ($obs[0] + .outbounds)
# proxy.xray.xhttpXmux.
| .outbounds |= map(. @setXhttpXmux@)
| if $xray_loglevel == "" then . else .log.loglevel = $xray_loglevel end
| if $auth_enabled then
(.inbounds[] | select(.protocol == "socks" and .tag == "mixed-in") | .settings.auth) = "password"
@@ -15,6 +15,8 @@
awgRuntimeDnsServer ? null,
# proxy.listener on an address other machines reach (0.0.0.0, a LAN address).
listenerExposed ? false,
# derived.xhttpXmuxJq.
xhttpXmuxJq ? "",
}:
let
@@ -60,6 +62,7 @@ if pureXrayEnabled then
(fillTemplate ./backend-filter-xray.template.jq {
inherit selectionMode;
hostClosedPorts = lib.concatStringsSep "," closedPorts;
setXhttpXmux = xhttpXmuxJq;
})
else
(fillTemplate ./backend-filter-sing-box.template.jq {
@@ -7,6 +7,7 @@ let
jq
hybridEnabled
xraySidecarRoutingMark
xhttpXmuxJq
;
in
@@ -21,6 +22,7 @@ lib.optionalString hybridEnabled (
setSidecarMark = lib.optionalString (
xraySidecarRoutingMark != null
) "| .streamSettings.sockopt.mark = $mark";
setXhttpXmux = xhttpXmuxJq;
hopRoutingMark = lib.optionalString (
routingMark != null
) " + {routing_mark: ${toString routingMark}}";
@@ -30,6 +30,7 @@ _proxy_suite_add_xray_sidecar_obs() {
| .value.tag as $tag
| {outbound: (.value
@setSidecarMark@
@setXhttpXmux@
| .streamSettings.sockopt.domainStrategy = (.streamSettings.sockopt.domainStrategy // "UseIP")),
client: {id: $id, email: $tag},
rule: {type: "field", inboundTag: ["sidecar-in"], user: [$tag], outboundTag: $tag},
+1 -1
View File
@@ -167,7 +167,7 @@ let
proxyInboundsGuardStrategy
;
proxyInboundsBlockPrivate = proxyInboundsCfg.routing.blockPrivate;
inherit (ctx) proxyInboundsLoopback proxyInboundsHostClosedPorts;
inherit (ctx) proxyInboundsLoopback proxyInboundsHostClosedPorts xhttpXmuxJq;
listenerExposed =
let
address = proxyCfg.listener.address;
+5
View File
@@ -30,6 +30,7 @@ let
hybridTproxyConfig
hybridTunConfig
hybridTunStartScript
hybridXmuxStartScript
hybridXrayRawStartScript
;
in
@@ -90,6 +91,10 @@ in
assert pkgs.lib.hasInfix "--backend sing-box" hybridStartScript;
assert pkgs.lib.hasInfix "--backend xray" hybridStartScript;
assert pkgs.lib.hasInfix "_proxy_suite_add_xray_sidecar_ob" hybridStartScript;
# proxy.xray.xhttpXmux reaches the sidecar's outbounds, and nothing without it.
assert !pkgs.lib.hasInfix "xmux" hybridStartScript;
assert pkgs.lib.hasInfix ''.streamSettings.xhttpSettings.extra.xmux = {"hKeepAlivePeriod":10}''
hybridXmuxStartScript;
# The outbounds test pings a sidecar outbound's real server, over UDP when XRay dials
# XHTTP over HTTP/3 or mKCP: no TCP handshake to time there.
assert pkgs.lib.hasInfix ''.streamSettings.tlsSettings.alpn? == ["h3"]'' hybridStartScript;
+5
View File
@@ -36,6 +36,10 @@ let
};
};
hybridFixture = evalProxySuite [ hybridModule ];
hybridXmuxStartScript = startScript (evalProxySuite [
hybridModule
{ services.proxy-suite.proxy.xray.xhttpXmux.hKeepAlivePeriod = 10; }
]);
hybridTproxyConfig = mkTProxyConfig hybridFixture;
hybridTunConfig = mkTunConfig hybridFixture;
hybridStartScript = startScript hybridFixture;
@@ -106,6 +110,7 @@ in
hybridTproxyConfig
hybridTunConfig
hybridTunStartScript
hybridXmuxStartScript
hybridXrayRawStartScript
;
}
+5
View File
@@ -96,6 +96,11 @@ pkgs.lib.mapAttrs mkPythonCheck {
ZBARIMG = "${pkgs.zbar}/bin/zbarimg";
};
};
# The per-app routes' DNS forwarder: its log lines, and a lost query asked again.
per-app-dns = {
file = "${scripts}/test-per-app-dns.py";
env = withPath scripts;
};
# The NFQWS_OPT rewrites the zapret v1 package build applies.
patch-zapret-config = {
file = "${scripts}/test-patch-zapret-config.py";
+6
View File
@@ -2394,15 +2394,21 @@ class GroupWatch:
return status == 200 and isinstance(body, dict) and "delay" in body
def record(self, tag, ok, hinted=False):
# Logged: each miss of a member still up, and its going down and up. A hiccup that heals
# before the member goes down leaves those misses, and nothing else, behind.
h = self.health.setdefault(tag, {"up": True, "misses": 0, "passes": 0, "since": self.wall()})
if ok:
h["misses"], h["passes"] = 0, h["passes"] + 1
if not h["up"] and h["passes"] >= GROUP_PASSES_UP:
h["up"], h["since"] = True, self.wall()
print(f"{tag}: up again", file=sys.stderr)
else:
h["passes"], h["misses"] = 0, h["misses"] + 1
if h["up"]:
print(f"{tag}: test failed ({h['misses']}/{1 if hinted else GROUP_MISSES_DOWN}{', after a hint' if hinted else ''})", file=sys.stderr)
if h["up"] and (hinted or h["misses"] >= GROUP_MISSES_DOWN):
h["up"], h["since"] = False, self.wall()
print(f"{tag}: down", file=sys.stderr)
def up(self, tag):
return self.health.get(tag, {}).get("up", True)
+19
View File
@@ -419,6 +419,25 @@ class GroupWatchTest(EnvTest):
self.assertEqual(self.step(), [])
self.assertEqual(self.step(), [("warp", "warp-1")])
def test_logs_misses_and_outages(self):
def lines(fn, *args):
return run(fn, *args)[2].splitlines()
self.step(0)
self.working["warp-1"] = False
# A hiccup that heals before the member goes down still leaves its miss behind.
self.assertEqual(lines(self.step), ["warp-1: test failed (1/2)"])
self.working["warp-1"] = True
self.assertEqual(lines(self.step), [])
self.working["warp-1"] = False
self.assertEqual(lines(self.step), ["warp-1: test failed (1/2)"])
self.assertEqual(lines(self.step), ["warp-1: test failed (2/2)", "warp-1: down", "warp: warp-1 -> warp-2"])
# Down, its misses are not repeated every test.
self.assertEqual(lines(self.step), [])
self.working["warp-1"] = True
self.step(), self.step()
self.assertEqual(lines(self.step), ["warp-1: up again", "warp: warp-2 -> warp-1"])
def test_a_hint_moves_at_once(self):
self.step(0)
self.working["warp-1"] = False
+48 -17
View File
@@ -21,6 +21,8 @@ import sys
import time
TIMEOUT = 4.0
# A UDP query is sent again after this long without an answer (ask_udp).
RESEND_AFTER = 1.5
MAX_MESSAGE = 65535
# --log (debug.perAppDns): a line per lookup sent on, to the journal.
@@ -48,7 +50,7 @@ def question(query: bytes) -> str:
return f"{'.'.join(labels) or '.'} {QTYPES.get(qtype, qtype)}"
def log_lookup(port: int, proto: str, query: bytes, reply: bytes | None, started: float):
def log_lookup(port: int, proto: str, query: bytes, reply: bytes | None, started: float, asked: int = 1):
if not LOG:
return
if reply is None:
@@ -58,7 +60,8 @@ def log_lookup(port: int, proto: str, query: bytes, reply: bytes | None, started
else:
outcome = RCODES.get(reply[3] & 0x0F, f"rcode {reply[3] & 0x0F}")
took = (time.monotonic() - started) * 1000
print(f"per-app-dns: :{port} {proto} {question(query)}: {outcome} in {took:.0f} ms", flush=True)
again = f", asked {asked} times" if asked > 1 else ""
print(f"per-app-dns: :{port} {proto} {question(query)}: {outcome} in {took:.0f} ms{again}", flush=True)
# The source address of the queries sent on (--bind): on a TProxy route's local route the
@@ -80,23 +83,51 @@ def upstream_socket(server: str, kind: int, mark: int) -> socket.socket:
return sock
async def ask_udp(query: bytes, servers: list[str], mark: int) -> bytes | None:
"""The first answer any server gives, in order; None when none does."""
async def ask_udp_once(query: bytes, server: str, mark: int) -> bytes:
loop = asyncio.get_running_loop()
sock = upstream_socket(server, socket.SOCK_DGRAM, mark)
try:
await loop.sock_connect(sock, (server, 53))
await loop.sock_sendall(sock, query)
return await loop.sock_recv(sock, MAX_MESSAGE)
finally:
sock.close()
async def ask_udp(query: bytes, servers: list[str], mark: int) -> tuple[bytes | None, int]:
"""(the first answer any server gives, in order, or None; how many times it was asked).
Unanswered after RESEND_AFTER, a query goes again from a new socket, the first still
waiting: through a proxy one is often lost (a tunnel that stalled, a session it was
opening), and the app asks again only after its own timeout, glibc's 5 s. Silence, not
SERVFAIL, when none answers: on SERVFAIL glibc gives up, on silence it retries.
"""
loop = asyncio.get_running_loop()
asked = 0
for server in servers:
attempts = []
deadline = loop.time() + TIMEOUT
# Set as each attempt goes out; the first goes out at once.
resend_at = loop.time()
try:
sock = upstream_socket(server, socket.SOCK_DGRAM, mark)
except OSError:
continue
try:
await loop.sock_connect(sock, (server, 53))
await loop.sock_sendall(sock, query)
return await asyncio.wait_for(loop.sock_recv(sock, MAX_MESSAGE), TIMEOUT)
except (OSError, asyncio.TimeoutError):
continue
while loop.time() < deadline:
pending = [a for a in attempts if not a.done()]
if not pending and len(attempts) == 2:
break
if not pending or (len(attempts) == 1 and loop.time() >= resend_at):
attempts.append(asyncio.ensure_future(ask_udp_once(query, server, mark)))
asked += 1
resend_at = loop.time() + RESEND_AFTER
pending = [a for a in attempts if not a.done()]
wake = min(deadline, resend_at) if len(attempts) == 1 else deadline
done, _ = await asyncio.wait(pending, timeout=max(0, wake - loop.time()), return_when=asyncio.FIRST_COMPLETED)
for attempt in done:
if attempt.exception() is None:
return attempt.result(), asked
finally:
sock.close()
return None
for attempt in attempts:
attempt.cancel()
return None, asked
class UdpListener(asyncio.DatagramProtocol):
@@ -114,8 +145,8 @@ class UdpListener(asyncio.DatagramProtocol):
async def answer(self, query, addr):
started = time.monotonic()
reply = await ask_udp(query, self.servers, self.mark)
log_lookup(self.port, "udp", query, reply, started)
reply, asked = await ask_udp(query, self.servers, self.mark)
log_lookup(self.port, "udp", query, reply, started, asked)
if reply is not None and self.transport is not None:
self.transport.sendto(reply, addr)
+78
View File
@@ -0,0 +1,78 @@
#!/usr/bin/env python3
"""per_app_dns.py: the question in a log line, and a lost UDP query asked again."""
import asyncio
import struct
import unittest
from unittest import mock
import per_app_dns as dns
def query(name: str, qtype: int = 1) -> bytes:
labels = b"".join(bytes([len(p)]) + p.encode() for p in name.split("."))
return struct.pack("!HHHHHH", 7, 0x100, 1, 0, 0, 0) + labels + b"\0" + struct.pack("!HH", qtype, 1)
class QuestionTest(unittest.TestCase):
def test_question(self):
self.assertEqual(dns.question(query("pbs.twimg.com", 65)), "pbs.twimg.com HTTPS")
self.assertEqual(dns.question(query("x.com", 999)), "x.com 999")
# The app's name, shown safely; garbage is "?".
self.assertEqual(dns.question(query("a\x1bb.com")), "a?b.com A")
self.assertEqual(dns.question(b"\0" * 5), "?")
self.assertEqual(dns.question(query("x.com")[:-3]), "?")
class AskUdpTest(unittest.TestCase):
def ask(self, behaviours, servers=("192.0.2.53",)):
"""ask_udp with each attempt, in order, answering after its delay (None: never, an
exception: failing)."""
behaviours = iter(behaviours)
async def once(q, server, mark):
delay, result = next(behaviours)
await asyncio.sleep(delay)
if isinstance(result, Exception):
raise result
if result is None:
await asyncio.sleep(3600)
return result
async def run():
loop = asyncio.get_running_loop()
started = loop.time()
reply = await dns.ask_udp(b"q", list(servers), 0)
return reply, loop.time() - started
with mock.patch.object(dns, "ask_udp_once", once), mock.patch.multiple(dns, TIMEOUT=0.4, RESEND_AFTER=0.15):
return asyncio.run(run())
def check(self, behaviours, reply, asked, took, **kw):
result, elapsed = self.ask(behaviours, **kw)
self.assertEqual(result, (reply, asked))
# A busy builder runs late, never early.
self.assertGreaterEqual(elapsed, took - 0.01)
self.assertLess(elapsed, took + 0.1)
def test_answered_at_once(self):
self.check([(0, b"a")], b"a", 1, 0)
def test_lost_query_is_asked_again(self):
# The first never answers; the second, sent at 0.15, answers 0.05 later.
self.check([(0, None), (0.05, b"b")], b"b", 2, 0.2)
def test_the_first_may_still_answer(self):
self.check([(0.3, b"late"), (1, b"never")], b"late", 2, 0.3)
def test_failing_socket_is_asked_again_at_once(self):
self.check([(0, OSError()), (0, b"b")], b"b", 2, 0)
def test_silence(self):
# Asked twice at most per server, then the next server.
self.check([(0, None), (0, None)], None, 2, 0.4)
self.check([(0, None), (0, None), (0, b"c")], b"c", 3, 0.4, servers=("192.0.2.53", "192.0.2.54"))
if __name__ == "__main__":
unittest.main()