feat: share-variants
This commit is contained in:
13 files changed
+593
-25
No files matched your search
@@ -144,8 +144,9 @@ Changes and secrets need root or the userControl group.
|
||||
apps run <profile> -- <cmd> [args] run a command through a profile
|
||||
|
||||
inbounds [list] server inbounds
|
||||
inbounds link <tag> [user] [--onion] [--qr|--json]
|
||||
share link or client JSON; --onion: via the onion service
|
||||
inbounds link <tag> [user] [--onion|--variant=<name>] [--qr|--json]
|
||||
share link or client JSON; --onion: via the onion
|
||||
service; --variant: one of the listener's shareVariants
|
||||
inbounds link <tag> [user] --config [--qr]
|
||||
AmneziaWG client .conf or its QR code
|
||||
inbounds link <tag> --server-json the server's inbound JSON
|
||||
@@ -199,6 +200,7 @@ INBOUND_ADD_FLAGS = {
|
||||
"--method": "shadowsocks cipher",
|
||||
"--share-port": "port in share links",
|
||||
"--share-address": "address in share links",
|
||||
"--fingerprint": "browser fingerprint in share links (fp)",
|
||||
"--order": "position in links and subscriptions",
|
||||
"--masquerade": "hysteria2: site shown to anything else",
|
||||
"--salamander": "hysteria2: Salamander obfuscation",
|
||||
@@ -870,6 +872,7 @@ COMPLETE = {
|
||||
"flags": {
|
||||
"--qr": "print a QR code",
|
||||
"--onion": "the link through the onion service",
|
||||
"--variant=": "one of the listener's share variants: --variant=<name>",
|
||||
"--json": "the client's outbound JSON",
|
||||
"--config": "an AmneziaWG client's .conf",
|
||||
"--server-json": "the server's inbound JSON",
|
||||
@@ -1370,9 +1373,25 @@ class _UnixHTTPConnection(http.client.HTTPConnection):
|
||||
self._path = path
|
||||
|
||||
def connect(self):
|
||||
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
self.sock.settimeout(self.timeout)
|
||||
self.sock.connect(self._path)
|
||||
# A Unix socket whose listen queue is full refuses at once with EAGAIN, timeout or
|
||||
# not: a burst of callers (a whole outbounds test) is waited out, not read as no API.
|
||||
deadline = time.monotonic() + (self.timeout or 0)
|
||||
while True:
|
||||
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
sock.settimeout(self.timeout)
|
||||
try:
|
||||
sock.connect(self._path)
|
||||
except BlockingIOError:
|
||||
sock.close()
|
||||
if time.monotonic() >= deadline:
|
||||
raise
|
||||
time.sleep(0.05)
|
||||
continue
|
||||
except BaseException:
|
||||
sock.close()
|
||||
raise
|
||||
self.sock = sock
|
||||
return
|
||||
|
||||
|
||||
def _clash_via_broker(broker, method, path, body, timeout):
|
||||
@@ -1532,6 +1551,9 @@ def _clash_broker_server(path):
|
||||
class Server(socketserver.ThreadingMixIn, socketserver.UnixStreamServer):
|
||||
daemon_threads = True
|
||||
slots = threading.BoundedSemaphore(CLASH_BROKER_MAX_CLIENTS)
|
||||
# socketserver listens with a queue of 5: the rest of a burst that arrives while
|
||||
# this thread checks a caller's groups was refused before it could be accepted.
|
||||
request_queue_size = CLASH_BROKER_MAX_CLIENTS
|
||||
|
||||
def verify_request(self, request, client_address):
|
||||
# Someone in no userControl group is closed on before sending a byte.
|
||||
@@ -4570,7 +4592,8 @@ def _inbound_server_json(tag):
|
||||
|
||||
|
||||
def _inbound_link_for(tag, user="", *_, field="link", variant=""):
|
||||
"""variant "onion": the link to the listener through the onion service."""
|
||||
"""variant "onion": the link to the listener through the onion service; any other: the
|
||||
listener's share variant of that name."""
|
||||
matches = [
|
||||
x
|
||||
for x in _inbound_links()
|
||||
@@ -4579,6 +4602,8 @@ def _inbound_link_for(tag, user="", *_, field="link", variant=""):
|
||||
if not matches:
|
||||
if variant == "onion":
|
||||
die(f"No onion link for {tag}: is it in tor.onionService.listeners, and has Tor written its address?")
|
||||
if variant:
|
||||
die(f"No share variant '{variant}' for {tag}: see its shareVariants, or `proxy-ctl inbounds list`.")
|
||||
die(f"Unknown inbound, or no share link for it: {tag}")
|
||||
if len(matches) > 1:
|
||||
sys.stdout.flush()
|
||||
@@ -4884,15 +4909,18 @@ def cmd_inbounds(verb="list", *args):
|
||||
row = " {:<24} {:<16} {:<14} {:<8} {:<8}" + (" {}" if sources else "")
|
||||
print(row.format("TAG", "USER", "TYPE", "PORT", "STATE", "SOURCE").rstrip())
|
||||
for x in _inbound_links():
|
||||
kind = _s(x.get("type")) + (" (onion)" if x.get("variant") == "onion" else "")
|
||||
kind = _s(x.get("type")) + (f" ({_s(x.get('variant'))})" if x.get("variant") else "")
|
||||
tag = _s(x.get("tag"))
|
||||
print(row.format(tag, _s(x.get("user")), kind, _s(x.get("port")), state, sources.get(tag, "nix")).rstrip())
|
||||
elif verb in ("link", "qr"):
|
||||
rest = [a for a in args if not a.startswith("--")]
|
||||
if not rest:
|
||||
usage("inbounds link <tag> [user] [--onion] [--qr|--json|--config|--server-json]")
|
||||
usage("inbounds link <tag> [user] [--onion|--variant=<name>] [--qr|--json|--config|--server-json]")
|
||||
qr = verb == "qr" or "--qr" in args
|
||||
variant = "onion" if "--onion" in args else ""
|
||||
for a in args:
|
||||
if a.startswith("--variant="):
|
||||
variant = a[len("--variant=") :]
|
||||
if "--server-json" in args:
|
||||
_inbound_server_json(rest[0])
|
||||
elif "--json" in args:
|
||||
|
||||
@@ -429,14 +429,15 @@ def inbound_rows(_):
|
||||
# No presence column: XRay keys the online map by user alone (no inbound dimension),
|
||||
# so a per-listener row could only repeat the same verdict once per listener. The
|
||||
# "who is online" action shows it once per user, which is the shape the data has.
|
||||
# A listener behind the onion service has a second row, for its .onion link.
|
||||
# A listener behind the onion service has a second row, for its .onion link, and one per
|
||||
# share variant.
|
||||
sources = ctl._inbound_runtime_names("listeners")
|
||||
return [
|
||||
{
|
||||
# The TUI titles its menu with the key: no trailing "/" for the plain link.
|
||||
"key": "/".join(ctl._s(x.get(k)) for k in ("tag", "user", "variant") if x.get(k)),
|
||||
**{k: ctl._s(x.get(k) or "") for k in ("tag", "user", "type", "port", "variant")},
|
||||
**({"type": f"{ctl._s(x.get('type') or '')} (onion)"} if x.get("variant") == "onion" else {}),
|
||||
**({"type": f"{ctl._s(x.get('type') or '')} ({ctl._s(x.get('variant'))})"} if x.get("variant") else {}),
|
||||
"source": sources.get(ctl._s(x.get("tag")), "nix"),
|
||||
}
|
||||
for x in ctl._inbound_links()
|
||||
@@ -543,8 +544,9 @@ def _natural(value):
|
||||
|
||||
|
||||
def _link(row, *extra):
|
||||
onion = ["--onion"] if row.get("variant") == "onion" else []
|
||||
return ["inbounds", "link", row["tag"], *([row["user"]] if row["user"] else []), *onion, *extra]
|
||||
variant = row.get("variant") or ""
|
||||
which = ["--onion"] if variant == "onion" else ([f"--variant={variant}"] if variant else [])
|
||||
return ["inbounds", "link", row["tag"], *([row["user"]] if row["user"] else []), *which, *extra]
|
||||
|
||||
|
||||
def _amneziawg(row):
|
||||
|
||||
@@ -11,6 +11,7 @@ import stat
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
import urllib.parse
|
||||
from unittest import mock
|
||||
@@ -217,6 +218,99 @@ class ClashBrokerTest(EnvTest):
|
||||
self.assertEqual(ask("GET", "/proxies"), (0, None))
|
||||
self.assertEqual(len(seen), 3)
|
||||
|
||||
def test_a_full_listen_queue_is_waited_out(self):
|
||||
# Nothing accepts at first, and the queue holds one: a Unix socket refuses the next
|
||||
# connect at once (EAGAIN), which the client must retry rather than read as no API.
|
||||
path = self.path("busy.sock")
|
||||
server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
self.addCleanup(server.close)
|
||||
server.bind(path)
|
||||
server.listen(0)
|
||||
queued = [socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) for _ in range(4)]
|
||||
for s in queued:
|
||||
self.addCleanup(s.close)
|
||||
s.setblocking(False)
|
||||
try:
|
||||
s.connect(path)
|
||||
except BlockingIOError:
|
||||
pass
|
||||
|
||||
def drain():
|
||||
time.sleep(0.3)
|
||||
server.settimeout(5)
|
||||
for _ in range(len(queued) + 1):
|
||||
try:
|
||||
server.accept()[0].close()
|
||||
except OSError:
|
||||
return
|
||||
|
||||
threading.Thread(target=drain, daemon=True).start()
|
||||
conn = ctl._UnixHTTPConnection(path, 5)
|
||||
self.addCleanup(conn.close)
|
||||
conn.connect()
|
||||
self.assertIsNotNone(conn.sock)
|
||||
# With no one ever accepting, it still gives up once its timeout has passed.
|
||||
stuck = self.path("stuck.sock")
|
||||
never = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
self.addCleanup(never.close)
|
||||
never.bind(stuck)
|
||||
never.listen(0)
|
||||
fillers = [socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) for _ in range(4)]
|
||||
for s in fillers:
|
||||
self.addCleanup(s.close)
|
||||
s.setblocking(False)
|
||||
try:
|
||||
s.connect(stuck)
|
||||
except BlockingIOError:
|
||||
pass
|
||||
start = time.monotonic()
|
||||
with self.assertRaises(BlockingIOError):
|
||||
ctl._UnixHTTPConnection(stuck, 0.3).connect()
|
||||
self.assertLess(time.monotonic() - start, 3)
|
||||
|
||||
@unittest.skipIf(os.geteuid() == 0, "root holds every scope")
|
||||
def test_a_burst_of_delay_tests_all_get_answers(self):
|
||||
import grp
|
||||
import http.server
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
try:
|
||||
group = grp.getgrgid(os.getgid()).gr_name
|
||||
except KeyError:
|
||||
self.skipTest("no name for this group")
|
||||
|
||||
class Api(http.server.BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
time.sleep(0.2) # a delay test takes a while
|
||||
raw = json.dumps({"delay": 1}).encode()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Length", str(len(raw)))
|
||||
self.end_headers()
|
||||
self.wfile.write(raw)
|
||||
|
||||
def log_message(self, *_):
|
||||
pass
|
||||
|
||||
api = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Api)
|
||||
self.addCleanup(api.server_close)
|
||||
threading.Thread(target=api.serve_forever, daemon=True).start()
|
||||
self.addCleanup(api.shutdown)
|
||||
self.write("clash-secret", "s3cret\n")
|
||||
os.environ.update(
|
||||
CLASH_API=f"http://127.0.0.1:{api.server_address[1]}",
|
||||
OUTBOUND_INVENTORY_FILE=self.path("outbounds.json"),
|
||||
USER_CONTROL_GROUPS=json.dumps({group: ["outbounds"]}),
|
||||
)
|
||||
sock = self.path("api.sock")
|
||||
broker = ctl._clash_broker_server(sock)
|
||||
self.addCleanup(broker.server_close)
|
||||
threading.Thread(target=broker.serve_forever, daemon=True).start()
|
||||
self.addCleanup(broker.shutdown)
|
||||
# As `proxy outbounds test` asks: every outbound's delay at once.
|
||||
with ThreadPoolExecutor(max_workers=32) as pool:
|
||||
statuses = list(pool.map(lambda i: ctl._clash_via_broker(sock, "GET", f"/proxies/o{i}/delay?url=x", None, 5)[0], range(32)))
|
||||
self.assertEqual(statuses, [200] * 32)
|
||||
|
||||
|
||||
class WarpDevicesTest(EnvTest):
|
||||
def test_every_device_or_the_one_named(self):
|
||||
@@ -1681,6 +1775,25 @@ class ShareTest(EnvTest):
|
||||
self.patch("svc_state", lambda unit: "active")
|
||||
self.assertRegex(ok(ctl.cmd_inbounds, "list"), r"(?m)^ in +u +vless \(onion\) +443 +active$")
|
||||
|
||||
def test_inbound_share_variant_link(self):
|
||||
self.write(
|
||||
"inbounds/links.json",
|
||||
[
|
||||
{"tag": "in", "user": "u", "type": "vless", "port": 443, "link": "vless://x@h:443?fp=chrome", "outbound": {"server": "h"}},
|
||||
{"tag": "in", "user": "u", "type": "vless", "port": 443, "link": "vless://x@h:443?fp=firefox",
|
||||
"outbound": {"server": "h", "fp": "firefox"}, "variant": "firefox"},
|
||||
],
|
||||
)
|
||||
# The listener's own link unless --variant names one of its variants.
|
||||
self.assertEqual(ok(ctl.cmd_inbounds, "link", "in", "u"), "vless://x@h:443?fp=chrome\n")
|
||||
self.assertEqual(ok(ctl.cmd_inbounds, "link", "in", "--variant=firefox"), "vless://x@h:443?fp=firefox\n")
|
||||
self.assertEqual(json.loads(ok(ctl.cmd_inbounds, "link", "in", "u", "--variant=firefox", "--json"))["fp"], "firefox")
|
||||
status, _, err = run(ctl.cmd_inbounds, "link", "in", "--variant=safari")
|
||||
self.assertNotEqual(status, 0)
|
||||
self.assertIn("No share variant 'safari'", err)
|
||||
self.patch("svc_state", lambda unit: "active")
|
||||
self.assertRegex(ok(ctl.cmd_inbounds, "list"), r"(?m)^ in +u +vless \(firefox\) +443 +active$")
|
||||
|
||||
@unittest.skipIf(os.geteuid() == 0, "root reads anything")
|
||||
def test_unreadable(self):
|
||||
os.chmod(self.share, 0)
|
||||
|
||||
@@ -166,6 +166,13 @@ class ModelTest(unittest.TestCase):
|
||||
self.assertFalse(model._amneziawg(onion))
|
||||
self.assertEqual(model.TOGGLES["proxy-suite-tor"], ["tor"])
|
||||
|
||||
def test_share_variant_rows_link_to_their_variant(self):
|
||||
links = [{"tag": "xh", "user": "alice", "type": "vless", "port": 443, "variant": "h1"}]
|
||||
with mock.patch.object(ctl, "_inbound_links", lambda: links):
|
||||
(row,) = model.inbound_rows({})
|
||||
self.assertEqual((row["key"], row["type"]), ("xh/alice/h1", "vless (h1)"))
|
||||
self.assertEqual(model._link(row, "--json"), ["inbounds", "link", "xh", "alice", "--variant=h1", "--json"])
|
||||
|
||||
def test_whitelist_bypass_rows(self):
|
||||
"""A creator or joiner is a unit on the services tab: toggled, restarted, and its call handled there."""
|
||||
tab = model.TABS[0]
|
||||
|
||||
Reference in new issue
Block a user