feat: runtime routing
This commit is contained in:
34 files changed
+1926
-112
No files matched your search
+469
-2
@@ -13,6 +13,7 @@ import http.client
|
||||
import importlib
|
||||
import ipaddress
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
@@ -96,6 +97,18 @@ Changes and secrets need root or the userControl group.
|
||||
lower goes first; up/down renumbers the top level
|
||||
proxy mode [default|whitelist|blacklist|all-proxy|all-bypass]
|
||||
show or override the routing mode
|
||||
proxy rules [list] routing rules, the configuration's and runtime ones,
|
||||
in the order they are checked
|
||||
proxy rules add <target> <match...> [--name <name>] [--priority <n>]
|
||||
send domains, addresses, geosite:x, geoip:x or ruleset:x
|
||||
to proxy, direct, block or an outbound; no --name: the
|
||||
rule named after the target, extended (priority 50:
|
||||
ahead of the configuration's, at 100 to 500)
|
||||
proxy rules matches <name> add|rm <match...>
|
||||
proxy rules target <name> <target>
|
||||
proxy rules priority <name> <n>|up|down
|
||||
lower goes first; up/down moves past the next row
|
||||
proxy rules disable|enable|rm <name>
|
||||
proxy subs [list|update] subscriptions; update refetches them
|
||||
proxy subs add [tag] <url|-> add a subscription (no tag: named after its host; -: stdin)
|
||||
proxy subs rm <tag> remove a runtime subscription
|
||||
@@ -755,6 +768,7 @@ COMPLETE = {
|
||||
"groups": "outbound groups",
|
||||
"priority": "the order the top level picks in",
|
||||
"mode": "show or override the routing mode",
|
||||
"rules": "routing rules added at runtime",
|
||||
"subs": "subscription caches",
|
||||
"rulesets": "routing rule sets",
|
||||
"tun": "global TUN mode",
|
||||
@@ -841,6 +855,26 @@ COMPLETE = {
|
||||
}
|
||||
},
|
||||
"proxy rulesets": {"words": {"list": "when each rule set was fetched", "update": "fetch the rule sets now"}},
|
||||
"proxy rules": {
|
||||
"words": {
|
||||
"list": "the routing rules in the order they are checked",
|
||||
"add": "add a rule, or extend one: <target> <match...>",
|
||||
"matches": "add or remove a rule's domains, addresses and lists",
|
||||
"target": "where a rule sends what it matches",
|
||||
"priority": "where a rule is checked: a number, up or down",
|
||||
"disable": "keep a rule without applying it",
|
||||
"enable": "apply a disabled rule again",
|
||||
"rm": "remove a rule",
|
||||
}
|
||||
},
|
||||
"proxy rules add": {
|
||||
"args": lambda: {**_names(RULE_TARGETS), **_outbound_choices(), **_group_choices()},
|
||||
"flags": {"--name": "the rule's name (default: the target)", "--priority": "where it is checked (default 50)"},
|
||||
},
|
||||
**{
|
||||
f"proxy rules {verb}": {"args": lambda: {r["name"]: f"-> {r['target']}" for r in _runtime_rules()}}
|
||||
for verb in ("matches", "target", "priority", "disable", "enable", "rm")
|
||||
},
|
||||
"proxy subs link": {"args": lambda: _names(_sub_tags() + _runtime_tags("subscription")), "flags": {"--qr": "print a QR code"}},
|
||||
"proxy subs rm": {"args": lambda: _names(_runtime_tags("subscription"))},
|
||||
"proxy tun": {"words": TOGGLE},
|
||||
@@ -1353,6 +1387,8 @@ def cmd_proxy(verb="status", *args):
|
||||
cmd_subscription(*args)
|
||||
elif verb == "rulesets":
|
||||
cmd_rulesets(*args)
|
||||
elif verb == "rules":
|
||||
cmd_rules(*args)
|
||||
elif verb in ("tun", "tproxy"):
|
||||
action = _flip(f"proxy-suite-{verb}", *args[:1])
|
||||
_toggle(f"proxy-suite-{verb}", f"proxy {verb}", action)
|
||||
@@ -1367,7 +1403,7 @@ def cmd_proxy(verb="status", *args):
|
||||
elif verb in ("probe", "learn", "forget", "relearn", "queue", "learned"):
|
||||
cmd_proxy_auto(verb, *args)
|
||||
else:
|
||||
usage("proxy [status|on|off|toggle|restart|outbounds|groups|priority|pin|unpin|mode|subs|rulesets|tun|tproxy|auto|config]")
|
||||
usage("proxy [status|on|off|toggle|restart|outbounds|groups|priority|pin|unpin|mode|rules|subs|rulesets|tun|tproxy|auto|config]")
|
||||
|
||||
|
||||
def cmd_outbounds(verb="list", *args):
|
||||
@@ -3201,6 +3237,433 @@ def cmd_rulesets(verb="list", *_):
|
||||
usage("proxy rulesets [list|update]")
|
||||
|
||||
|
||||
# --- proxy rules: routing rules added at runtime ------------------------------
|
||||
#
|
||||
# rules.json in the routing spool (RUNTIME_ROUTING_DIR), which userControl's groups with the
|
||||
# routing scope write: {"rules": [{name, target, priority, disabled, domains, ips, geosites,
|
||||
# geoips, ruleSets}]}. proxy-suite-routing-apply renders it for the backends (routing-render.jq
|
||||
# keeps what it can check) and restarts those whose config it changes; a rule's domains and
|
||||
# addresses alone reach a running sing-box without one. A rule's priority places it among the
|
||||
# configuration's sections ("sections" in ROUTING_RULES_FILE, 100 to 500): lower goes first,
|
||||
# and a runtime rule goes first among equals.
|
||||
|
||||
ROUTING_APPLY_UNIT = "proxy-suite-routing-apply"
|
||||
RULE_DEFAULT_PRIORITY = 50
|
||||
RULE_PRIORITY_LIMIT = 1_000_000
|
||||
RULE_MATCH_KINDS = ("domains", "ips", "geosites", "geoips", "ruleSets")
|
||||
# What a match spells, as `rules add` takes it and `rules list` prints it back.
|
||||
RULE_MATCH_PREFIXES = {"geosite:": "geosites", "geoip:": "geoips", "ruleset:": "ruleSets"}
|
||||
RULE_MATCH_SPELLING = {"domains": "", "ips": "", "geosites": "geosite:", "geoips": "geoip:", "ruleSets": "ruleset:"}
|
||||
RULE_DOMAIN = re.compile(r"[a-z0-9_-]+(\.[a-z0-9_-]+)*")
|
||||
RULE_GEO = re.compile(r"[A-Za-z0-9!@._-]{1,64}")
|
||||
RULE_TARGETS = ("proxy", "direct", "block")
|
||||
# As much as routing-render.jq reads of the spool.
|
||||
RULES_MAX_BYTES = 4 * 1024 * 1024
|
||||
|
||||
|
||||
def _rules_path():
|
||||
return os.path.join(env("RUNTIME_ROUTING_DIR", f"{state_dir()}/routing.d"), "rules.json")
|
||||
|
||||
|
||||
def _rules_rendered_path():
|
||||
return os.path.join(env("ROUTING_RULES_DIR", f"{state_dir()}/routing"), "rules.json")
|
||||
|
||||
|
||||
def _rule_target_ok(target):
|
||||
# As routing-render.jq: no control character ([[:cntrl:]]).
|
||||
return 1 <= len(target) <= 128 and not re.search(r"[\x00-\x1f\x7f-\x9f]", target)
|
||||
|
||||
|
||||
def _rule_normal(rule):
|
||||
"""One rule with every field there and of its type, or None for what is not a rule: what
|
||||
routing-render.jq keeps, so the list shows what root applies."""
|
||||
if not isinstance(rule, dict) or not isinstance(rule.get("name"), str) or not isinstance(rule.get("target"), str):
|
||||
return None
|
||||
if not _rule_name_ok(rule["name"]) or not _rule_target_ok(rule["target"]):
|
||||
return None
|
||||
priority = rule.get("priority")
|
||||
# JSON as Python reads it has Infinity and NaN too.
|
||||
if isinstance(priority, (int, float)) and not isinstance(priority, bool) and not math.isnan(priority):
|
||||
priority = max(-RULE_PRIORITY_LIMIT, min(RULE_PRIORITY_LIMIT, priority))
|
||||
priority = math.floor(priority)
|
||||
else:
|
||||
priority = RULE_DEFAULT_PRIORITY
|
||||
out = {
|
||||
"name": rule["name"],
|
||||
"target": rule["target"],
|
||||
"priority": priority,
|
||||
"disabled": rule.get("disabled") is True,
|
||||
}
|
||||
for kind in RULE_MATCH_KINDS:
|
||||
values = rule.get(kind)
|
||||
out[kind] = [v for v in values if isinstance(v, str)] if isinstance(values, list) else []
|
||||
return out
|
||||
|
||||
|
||||
def _rules_sorted(rules):
|
||||
return sorted(rules, key=lambda r: (r["priority"], r["name"]))
|
||||
|
||||
|
||||
def _runtime_rules(writing=False):
|
||||
"""The runtime rules, in match order: as saved, or, where the spool is the routing scope's
|
||||
alone, as root last applied them. writing: the spool or nothing."""
|
||||
path = _rules_path()
|
||||
try:
|
||||
data = json.loads(read_shared_text(path, RULES_MAX_BYTES))
|
||||
rules = data.get("rules") if isinstance(data, dict) else None
|
||||
except FileNotFoundError:
|
||||
rules = []
|
||||
except PermissionError:
|
||||
if writing:
|
||||
denied(path, "change")
|
||||
rules = read_json_or(_rules_rendered_path(), [])
|
||||
except (OSError, ValueError):
|
||||
if writing:
|
||||
die(f"{path} is not valid; fix or remove it first.")
|
||||
rules = []
|
||||
# A name once, the first, as root reads it.
|
||||
seen = {}
|
||||
for rule in map(_rule_normal, rules if isinstance(rules, list) else []):
|
||||
if rule and rule["name"] not in seen:
|
||||
seen[rule["name"]] = rule
|
||||
return _rules_sorted(seen.values())
|
||||
|
||||
|
||||
def _rules_save(rules):
|
||||
path = _rules_path()
|
||||
text = json.dumps({"rules": _rules_sorted(rules)}, indent=2, ensure_ascii=False) + "\n"
|
||||
try:
|
||||
_spool_write(path, text)
|
||||
except OSError:
|
||||
denied(path, "write")
|
||||
|
||||
|
||||
def _routing_apply():
|
||||
if systemctl("start", f"{ROUTING_APPLY_UNIT}.service")[0]:
|
||||
die(f"Saved, but applying it failed - see: proxy-ctl logs {ROUTING_APPLY_UNIT}")
|
||||
|
||||
|
||||
def _routing_sections():
|
||||
"""The configuration's routing, a section per priority: [{id, priority, label, entries}]."""
|
||||
sections = read_json_or(env("ROUTING_RULES_FILE"), {}).get("sections")
|
||||
return [s for s in sections if isinstance(s, dict) and isinstance(s.get("priority"), int)] if isinstance(sections, list) else []
|
||||
|
||||
|
||||
def _routing_skipped():
|
||||
"""{rule: why} for the rules the running proxy left out."""
|
||||
skipped = read_json_or(_runtime_file("routing-skipped.json"), [])
|
||||
return {_s(x.get("name")): _s(x.get("why")) for x in skipped if isinstance(x, dict)}
|
||||
|
||||
|
||||
def _rule_matches(rule, limit=None):
|
||||
words = [f"{RULE_MATCH_SPELLING[kind]}{v}" for kind in RULE_MATCH_KINDS for v in rule.get(kind) or []]
|
||||
if limit is not None and len(words) > limit:
|
||||
return ", ".join(words[:limit]) + f" and {len(words) - limit} more"
|
||||
return ", ".join(words)
|
||||
|
||||
|
||||
def _section_empty(section):
|
||||
# The direct section always holds the private ranges.
|
||||
return section.get("id") != "direct" and not any(
|
||||
e.get(kind) for e in section.get("entries") or [] if isinstance(e, dict) for kind in RULE_MATCH_KINDS
|
||||
)
|
||||
|
||||
|
||||
def _routing_rows():
|
||||
"""The routing in match order: the configuration's sections and the runtime rules, as rows
|
||||
of {key, priority, name, target, matches, source, notes, runtime, disabled}."""
|
||||
skipped = _routing_skipped()
|
||||
rows = []
|
||||
for rule in _runtime_rules():
|
||||
notes = "disabled" if rule["disabled"] else (f"left out: {skipped[rule['name']]}" if rule["name"] in skipped else "")
|
||||
rows.append(
|
||||
{
|
||||
"key": f"rule:{rule['name']}",
|
||||
"priority": rule["priority"],
|
||||
"name": rule["name"],
|
||||
"target": rule["target"],
|
||||
"matches": _rule_matches(rule, 6) or "nothing yet",
|
||||
"source": "runtime",
|
||||
"notes": notes,
|
||||
"runtime": True,
|
||||
"disabled": rule["disabled"],
|
||||
"order": 0,
|
||||
}
|
||||
)
|
||||
for section in _routing_sections():
|
||||
if _section_empty(section):
|
||||
continue
|
||||
entries = [e for e in section.get("entries") or [] if isinstance(e, dict)]
|
||||
for n, entry in enumerate(entries):
|
||||
matches = _rule_matches(entry, 6)
|
||||
if not matches and section.get("id") != "direct":
|
||||
continue
|
||||
if section.get("id") == "direct":
|
||||
matches = ", ".join(x for x in (matches, "private addresses") if x)
|
||||
rows.append(
|
||||
{
|
||||
"key": f"config:{_s(section.get('id'))}:{n}",
|
||||
"priority": section["priority"],
|
||||
"name": _s(section.get("label") or section.get("id")),
|
||||
"target": _s(entry.get("target") or ""),
|
||||
"matches": matches,
|
||||
"source": "config",
|
||||
"notes": "",
|
||||
"runtime": False,
|
||||
"disabled": False,
|
||||
"order": 1,
|
||||
}
|
||||
)
|
||||
# Stable: runtime rules in their order, then sections in theirs, at each priority.
|
||||
rows.sort(key=lambda r: (r["priority"], r["order"]))
|
||||
for r in rows:
|
||||
del r["order"]
|
||||
return rows
|
||||
|
||||
|
||||
def _rule_name_ok(name):
|
||||
return bool(RUNTIME_TAG.fullmatch(name)) and len(name) <= 64
|
||||
|
||||
|
||||
def _rule_match(word):
|
||||
"""(kind, value) of one match as typed: a domain (or a URL), an address or a CIDR,
|
||||
geosite:NAME, geoip:NAME or ruleset:NAME."""
|
||||
for prefix, kind in RULE_MATCH_PREFIXES.items():
|
||||
if word.lower().startswith(prefix):
|
||||
name = word[len(prefix) :]
|
||||
if kind == "ruleSets":
|
||||
declared = [_s(rs.get("name")) for rs in read_json_or(env("RULE_SETS_FILE"), []) if isinstance(rs, dict)]
|
||||
if name not in declared:
|
||||
die(f"No rule set named '{name}' in routing.ruleSets" + (f" (there are: {', '.join(declared)})." if declared else "."))
|
||||
return kind, name
|
||||
if not RULE_GEO.fullmatch(name) or name.startswith("."):
|
||||
die(f"Not a {prefix[:-1]} name: {name}")
|
||||
directory = env("GEODATA_GEOSITE_DIR" if kind == "geosites" else "GEODATA_GEOIP_DIR")
|
||||
if directory and os.path.isdir(directory) and not os.path.exists(os.path.join(directory, f"{prefix[:-1]}-{name}.srs")):
|
||||
die(f"No {prefix[:-1]} named '{name}' in this host's geodata.")
|
||||
return kind, name
|
||||
try:
|
||||
return "ips", str(ipaddress.ip_network(word, strict=False))
|
||||
except ValueError:
|
||||
pass
|
||||
host = word.split("://", 1)[1].split("/", 1)[0].rsplit("@", 1)[-1] if "://" in word else word
|
||||
host = host.lower().lstrip(".")
|
||||
if "://" in word:
|
||||
host = re.sub(r":\d+$", "", host)
|
||||
if RULE_DOMAIN.fullmatch(host) and len(host) <= 253:
|
||||
return "domains", host
|
||||
die(f"Not a domain, an address, or geosite:, geoip: or ruleset: something: {word}")
|
||||
|
||||
|
||||
def _rule_check_target(target):
|
||||
if target in RULE_TARGETS:
|
||||
return
|
||||
if not _rule_target_ok(target):
|
||||
die(f"Not an outbound: {target!r}")
|
||||
tags = set(_outbound_tags()) | set(_outbound_groups())
|
||||
if not tags:
|
||||
print(f"Cannot check '{target}' until the proxy has run; a rule naming no outbound is left out.", file=sys.stderr)
|
||||
elif target not in tags:
|
||||
die(f"Unknown outbound or group: {target} (or proxy, direct, block)")
|
||||
|
||||
|
||||
def _rule_find(rules, name):
|
||||
for rule in rules:
|
||||
if rule["name"] == name:
|
||||
return rule
|
||||
die(f"No runtime routing rule named '{name}'. See: proxy-ctl proxy rules")
|
||||
|
||||
|
||||
def _rule_parse_priority(value):
|
||||
if not re.fullmatch(r"-?[0-9]+", value or "") or abs(int(value)) > RULE_PRIORITY_LIMIT:
|
||||
die(f"A priority is a whole number, -{RULE_PRIORITY_LIMIT} to {RULE_PRIORITY_LIMIT}: {value}")
|
||||
return int(value)
|
||||
|
||||
|
||||
def _rules_edit(change):
|
||||
"""change(rules) under the spool's lock, saved and applied. It returns what to print."""
|
||||
path = _rules_path()
|
||||
with _file_lock(path):
|
||||
rules = _runtime_rules(writing=True)
|
||||
message = change(rules)
|
||||
_rules_save(rules)
|
||||
_routing_apply()
|
||||
print(message)
|
||||
|
||||
|
||||
def _rules_move(rules, name, direction):
|
||||
"""Moves a rule one row up or down in the match order, past a runtime rule or a section of
|
||||
the configuration, then numbers the runtime rules where it landed, 10 apart where they fit."""
|
||||
rows = [("rule", r["name"], r["priority"]) for r in rules]
|
||||
rows += [("section", s.get("id"), s["priority"]) for s in _routing_sections() if not _section_empty(s)]
|
||||
rows.sort(key=lambda r: (r[2], 0 if r[0] == "rule" else 1))
|
||||
order = [r[:2] for r in rows]
|
||||
i = order.index(("rule", name))
|
||||
j = i - 1 if direction == "up" else i + 1
|
||||
if not 0 <= j < len(order):
|
||||
return f"{name} is already {'first' if direction == 'up' else 'last'}."
|
||||
order[i], order[j] = order[j], order[i]
|
||||
priority = {r[:2]: r[2] for r in rows}
|
||||
k = order.index(("rule", name))
|
||||
# The run of runtime rules it is in now, and the sections around it.
|
||||
lo = k
|
||||
while lo > 0 and order[lo - 1][0] == "rule":
|
||||
lo -= 1
|
||||
hi = k
|
||||
while hi + 1 < len(order) and order[hi + 1][0] == "rule":
|
||||
hi += 1
|
||||
below = priority[order[lo - 1]] if lo > 0 else None
|
||||
above = priority[order[hi + 1]] if hi + 1 < len(order) else None
|
||||
run = order[lo : hi + 1]
|
||||
# After a section: above its number. Before one: at most its number (runtime first).
|
||||
if below is None and above is None:
|
||||
numbers = [10 * (n + 1) for n in range(len(run))]
|
||||
elif below is None:
|
||||
numbers = [above - 10 * (len(run) - n) for n in range(len(run))]
|
||||
elif above is None:
|
||||
numbers = [below + 10 * (n + 1) for n in range(len(run))]
|
||||
else:
|
||||
step = min(10, (above - below) // len(run))
|
||||
if step < 1:
|
||||
die(f"No room for {len(run)} rules between priorities {below} and {above}; set them by hand.")
|
||||
numbers = [below + step * (n + 1) for n in range(len(run))]
|
||||
by_name = {r["name"]: r for r in rules}
|
||||
for (_, rule_name), number in zip(run, numbers, strict=True):
|
||||
by_name[rule_name]["priority"] = number
|
||||
return f"{name}: moved {direction}, priority {by_name[name]['priority']}"
|
||||
|
||||
|
||||
def _rules_list():
|
||||
rows = _routing_rows()
|
||||
if not rows:
|
||||
print("No routing rules: everything goes to the final outbound.")
|
||||
return
|
||||
print("In the order they are checked; lower priority first, a runtime rule first among equals:")
|
||||
width = max(len(r["name"]) for r in rows)
|
||||
for r in rows:
|
||||
notes = f" ({r['notes']})" if r["notes"] else ""
|
||||
print(f" {r['priority']:>7} {r['name']:<{width}} {r['source']:<7} -> {r['target']}: {r['matches']}{notes}")
|
||||
print(f"Then the final outbound ({_route_mode_label(_route_mode_current())}).")
|
||||
|
||||
|
||||
def cmd_rules(verb="list", *args):
|
||||
if not svc_exists("proxy-suite-socks"):
|
||||
die("proxy is not enabled in this configuration.")
|
||||
if verb == "list":
|
||||
_rules_list()
|
||||
elif verb == "add":
|
||||
_rules_add(*args)
|
||||
elif verb == "matches" and len(args) >= 3 and args[1] in ("add", "rm"):
|
||||
_rules_matches(*args)
|
||||
elif verb == "target" and len(args) == 2:
|
||||
_rule_check_target(args[1])
|
||||
|
||||
def change(rules):
|
||||
_rule_find(rules, args[0])["target"] = args[1]
|
||||
return f"{args[0]}: -> {args[1]}"
|
||||
|
||||
_rules_edit(change)
|
||||
elif verb == "priority" and len(args) == 2:
|
||||
name, value = args
|
||||
|
||||
def change(rules):
|
||||
rule = _rule_find(rules, name)
|
||||
if value in ("up", "down"):
|
||||
return _rules_move(rules, name, value)
|
||||
rule["priority"] = _rule_parse_priority(value)
|
||||
return f"{name}: priority {rule['priority']}"
|
||||
|
||||
_rules_edit(change)
|
||||
elif verb in ("disable", "enable") and len(args) == 1:
|
||||
|
||||
def change(rules):
|
||||
_rule_find(rules, args[0])["disabled"] = verb == "disable"
|
||||
return f"{args[0]}: {verb}d"
|
||||
|
||||
_rules_edit(change)
|
||||
elif verb == "rm" and len(args) == 1:
|
||||
|
||||
def change(rules):
|
||||
rules.remove(_rule_find(rules, args[0]))
|
||||
return f"Removed routing rule: {args[0]}"
|
||||
|
||||
_rules_edit(change)
|
||||
else:
|
||||
usage(
|
||||
"proxy rules [list] | add <target> <match...> [--name <name>] [--priority <n>]"
|
||||
" | matches <name> add|rm <match...> | target <name> <target>"
|
||||
" | priority <name> <n>|up|down | disable|enable <name> | rm <name>"
|
||||
)
|
||||
|
||||
|
||||
def _rules_add(*args):
|
||||
name, priority, words = None, None, []
|
||||
rest = list(args)
|
||||
while rest:
|
||||
word = rest.pop(0)
|
||||
if word in ("--name", "--priority"):
|
||||
if not rest:
|
||||
usage(f"proxy rules add <target> <match...> [{word} <value>]")
|
||||
if word == "--name":
|
||||
name = rest.pop(0)
|
||||
else:
|
||||
priority = _rule_parse_priority(rest.pop(0))
|
||||
else:
|
||||
words.append(word)
|
||||
if len(words) < 2:
|
||||
usage("proxy rules add <target> <match...> [--name <name>] [--priority <n>]")
|
||||
target, matches = words[0], [_rule_match(w) for w in words[1:]]
|
||||
_rule_check_target(target)
|
||||
name = name or target
|
||||
if not _rule_name_ok(name):
|
||||
die(f"'{name}' cannot name a rule: letters, digits, dot, dash and underscore only; give one with --name.")
|
||||
|
||||
def change(rules):
|
||||
rule = next((r for r in rules if r["name"] == name), None)
|
||||
if rule is None:
|
||||
rule = {"name": name, "target": target, "priority": RULE_DEFAULT_PRIORITY if priority is None else priority, "disabled": False}
|
||||
rule.update({kind: [] for kind in RULE_MATCH_KINDS})
|
||||
rules.append(rule)
|
||||
verb = "Added"
|
||||
elif rule["target"] != target:
|
||||
die(f"Rule '{name}' sends to {rule['target']}, not {target}: name another with --name, or change it with: proxy-ctl proxy rules target {name} {target}")
|
||||
else:
|
||||
verb = "Extended"
|
||||
if priority is not None:
|
||||
rule["priority"] = priority
|
||||
added = _rule_add_matches(rule, matches)
|
||||
return f"{verb} routing rule {name} (priority {rule['priority']}) -> {target}: {', '.join(added) or 'nothing new'}"
|
||||
|
||||
_rules_edit(change)
|
||||
|
||||
|
||||
def _rule_add_matches(rule, matches):
|
||||
added = []
|
||||
for kind, value in matches:
|
||||
if value not in rule[kind]:
|
||||
rule[kind].append(value)
|
||||
added.append(f"{RULE_MATCH_SPELLING[kind]}{value}")
|
||||
return added
|
||||
|
||||
|
||||
def _rules_matches(name, op, *words):
|
||||
matches = [_rule_match(w) for w in words]
|
||||
|
||||
def change(rules):
|
||||
rule = _rule_find(rules, name)
|
||||
if op == "add":
|
||||
done = _rule_add_matches(rule, matches)
|
||||
else:
|
||||
done = []
|
||||
for kind, value in matches:
|
||||
if value in rule[kind]:
|
||||
rule[kind].remove(value)
|
||||
done.append(f"{RULE_MATCH_SPELLING[kind]}{value}")
|
||||
return f"{name}: {'added' if op == 'add' else 'removed'} {', '.join(done) or 'nothing'}"
|
||||
|
||||
_rules_edit(change)
|
||||
|
||||
|
||||
# --- proxy auto: reachability probe -------------------------------------------
|
||||
#
|
||||
# Fetches a URL through one exit after another (direct first) and finds one
|
||||
@@ -4366,7 +4829,11 @@ def _where_sing_box(config, domain):
|
||||
hit = hit or next((f"domain_keyword {k}" for k in rule.get("domain_keyword") or [] if k in domain), "")
|
||||
hit = hit or next((f"domain_regex {r}" for r in rule.get("domain_regex") or [] if re.search(r, domain)), "")
|
||||
hit = hit or next(
|
||||
(f"rule-set {t}" for t in rule.get("rule_set") or [] if _where_rule_set_match(rule_sets.get(t, {}), domain)),
|
||||
(
|
||||
f"runtime rule {t.removeprefix('user:')}" if t.startswith("user:") else f"rule-set {t}"
|
||||
for t in rule.get("rule_set") or []
|
||||
if _where_rule_set_match(rule_sets.get(t, {}), domain)
|
||||
),
|
||||
"",
|
||||
)
|
||||
if hit:
|
||||
|
||||
@@ -93,6 +93,7 @@ CSS = """
|
||||
.status-chip.ok .chip-label, .status-chip.warn .chip-label, .status-chip.bad .chip-label { opacity: 0.8; }
|
||||
|
||||
.summary { padding: 8px 14px 0 14px; }
|
||||
.selector-bar { padding: 8px 14px 0 14px; }
|
||||
.filter-bar { padding: 8px 12px; }
|
||||
.row-count { font-feature-settings: "tnum"; }
|
||||
|
||||
@@ -309,6 +310,20 @@ class Page(Gtk.Box):
|
||||
|
||||
self.summary = Gtk.Label(xalign=0, wrap=True, selectable=True, visible=False, css_classes=["summary", "dim-label"])
|
||||
|
||||
# The tab's one choice apart from its rows (Routing: the mode), above everything else, so
|
||||
# it is there whatever the rows are.
|
||||
self.selector_values = []
|
||||
self.selector_setting = False
|
||||
self.selector_drop = None
|
||||
if tab.selector:
|
||||
self.selector_drop = Gtk.DropDown(model=Gtk.StringList(), valign=Gtk.Align.CENTER, tooltip_text=f"Shortcut: {display_key(tab.selector.key)}")
|
||||
self.selector_drop.connect("notify::selected", self.on_selector_changed)
|
||||
label = Gtk.Label(label=tab.selector.label, css_classes=["heading"], mnemonic_widget=self.selector_drop)
|
||||
self.selector_bar = Gtk.Box(spacing=12, css_classes=["selector-bar"], visible=False)
|
||||
self.selector_bar.append(label)
|
||||
self.selector_bar.append(self.selector_drop)
|
||||
self.append(self.selector_bar)
|
||||
|
||||
self.search = Gtk.SearchEntry(placeholder_text="Filter: words in any column, or column:value", hexpand=True)
|
||||
self.search.connect("search-changed", lambda _: self.refill())
|
||||
self.search.connect("stop-search", self.on_stop_search)
|
||||
@@ -420,6 +435,7 @@ class Page(Gtk.Box):
|
||||
("o", lambda *_: self.win.show_last_output()),
|
||||
("r", lambda *_: self.win.app.reload(fresh_root=True)),
|
||||
("Menu|<Shift>F10", lambda *_: self.open_menu(None)),
|
||||
*([(accelerator(self.tab.selector.key), lambda *_: self.open_selector())] if self.tab.selector else []),
|
||||
):
|
||||
if trigger not in self.triggers():
|
||||
controller.add_shortcut(Gtk.Shortcut(trigger=Gtk.ShortcutTrigger.parse_string(trigger), action=Gtk.CallbackAction.new(self.keyed(trigger, callback))))
|
||||
@@ -464,10 +480,44 @@ class Page(Gtk.Box):
|
||||
|
||||
# --- filling ------------------------------------------------------------------------
|
||||
|
||||
def fill(self, rows, summary):
|
||||
def fill(self, rows, summary, selector=None):
|
||||
self.rows, self.summary_text, self.loaded = rows, summary, True
|
||||
self.fill_selector(selector)
|
||||
self.refill()
|
||||
|
||||
def fill_selector(self, state):
|
||||
"""The selector as read: its options and the current one, set without running anything."""
|
||||
if self.selector_drop is None:
|
||||
return
|
||||
self.selector_bar.set_visible(state is not None)
|
||||
if state is None:
|
||||
return
|
||||
options, current = state
|
||||
values = [v for v, _ in options]
|
||||
self.selector_setting = True
|
||||
try:
|
||||
if values != self.selector_values:
|
||||
self.selector_values = values
|
||||
self.selector_drop.set_model(Gtk.StringList.new([label for _, label in options]))
|
||||
if current in values and self.selector_drop.get_selected() != values.index(current):
|
||||
self.selector_drop.set_selected(values.index(current))
|
||||
finally:
|
||||
self.selector_setting = False
|
||||
|
||||
def on_selector_changed(self, drop, _):
|
||||
index = drop.get_selected()
|
||||
if self.selector_setting or not 0 <= index < len(self.selector_values):
|
||||
return
|
||||
argv = model.selector_argv(self.tab, self.selector_values[index])
|
||||
if argv:
|
||||
self.win.app.run_argv("run", argv, self.win)
|
||||
|
||||
def open_selector(self):
|
||||
if self.selector_drop is None or not self.selector_bar.get_visible():
|
||||
return False
|
||||
self.selector_drop.grab_focus()
|
||||
return self.selector_drop.activate()
|
||||
|
||||
def refill(self):
|
||||
rows, summary = self.rows, self.summary_text
|
||||
if text := self.search.get_text().strip():
|
||||
@@ -929,7 +979,7 @@ class Window(Adw.ApplicationWindow):
|
||||
chip.append(Gtk.Label(label=value, css_classes=["chip-value"], ellipsize=Pango.EllipsizeMode.END))
|
||||
self.status.append(chip)
|
||||
|
||||
def fill(self, states, visible, status, tab_id, rows, summary, stale=False):
|
||||
def fill(self, states, visible, status, tab_id, rows, summary, stale=False, selector=None):
|
||||
# A read that came back empty after a good one keeps what is on screen: every tab
|
||||
# and row blinking out and back is worse than a banner saying the read failed.
|
||||
if stale:
|
||||
@@ -943,7 +993,7 @@ class Window(Adw.ApplicationWindow):
|
||||
if visible != self.shown():
|
||||
self.show_tabs(visible)
|
||||
if tab_id in self.pages and tab_id in visible:
|
||||
self.pages[tab_id].fill(rows, summary)
|
||||
self.pages[tab_id].fill(rows, summary, selector)
|
||||
|
||||
# --- acting ----------------------------------------------------------------------------------
|
||||
|
||||
@@ -1072,6 +1122,8 @@ class Window(Adw.ApplicationWindow):
|
||||
section = Adw.ShortcutsSection(title=page.tab.title)
|
||||
for key, label in model.key_labels(actions):
|
||||
section.add(Adw.ShortcutsItem(title=cap(label), accelerator=accelerator(key)))
|
||||
if page.tab.selector:
|
||||
section.add(Adw.ShortcutsItem(title=f"Choose the {page.tab.selector.label.lower()}", accelerator=accelerator(page.tab.selector.key)))
|
||||
dialog.add(section)
|
||||
section = Adw.ShortcutsSection(title="Everywhere")
|
||||
for accel, title in GLOBAL_SHORTCUTS:
|
||||
@@ -1263,6 +1315,7 @@ class ProxySuiteGui(Adw.Application):
|
||||
result["visible"] = model.available_tabs(states)
|
||||
result["status"] = model._safe(model.status_items, states, fallback=[("", "Status unavailable", "bad")])
|
||||
result["tab"] = (tab.id, *self.load_tab(tab, states, elevated, fresh_root))
|
||||
result["selector"] = model.selector_state(tab)
|
||||
return result
|
||||
|
||||
def load_tab(self, tab, states, elevated, fresh_root=False):
|
||||
@@ -1317,7 +1370,7 @@ class ProxySuiteGui(Adw.Application):
|
||||
self.tray.update(model.icon_name(overall), tooltip, tree, attention=bool(failed))
|
||||
self.notify_failures(snap)
|
||||
if "tab" in result and self.window:
|
||||
self.window.fill(self.states, result["visible"], result["status"], *result["tab"], stale=stale)
|
||||
self.window.fill(self.states, result["visible"], result["status"], *result["tab"], stale=stale, selector=result.get("selector"))
|
||||
if self.pending:
|
||||
fresh, self.pending, self.pending_fresh = self.pending_fresh, False, False
|
||||
self.reload(fresh_root=fresh)
|
||||
|
||||
@@ -72,6 +72,17 @@ class Action:
|
||||
stdin: Callable = None # (selected row or None, prompt text) -> text proxy-ctl reads on stdin, or None
|
||||
|
||||
|
||||
@dataclass
|
||||
class Selector:
|
||||
"""One choice a tab makes apart from its rows (the Routing tab's mode), drawn above the table."""
|
||||
|
||||
label: str
|
||||
options: Callable # () -> [(value, label)]
|
||||
current: Callable # () -> the value chosen now
|
||||
argv: Callable # value -> proxy-ctl argv that chooses it
|
||||
key: str = "m" # opens the choice
|
||||
|
||||
|
||||
@dataclass
|
||||
class Tab:
|
||||
id: str
|
||||
@@ -82,6 +93,7 @@ class Tab:
|
||||
summary: Callable = None # () -> text above the table, read with every load
|
||||
actions: list = field(default_factory=list)
|
||||
tree: bool = False # rows carry "ancestors" (row keys) and "group": the order means something, so no sorting
|
||||
selector: Selector = None
|
||||
|
||||
|
||||
def ROW(_):
|
||||
@@ -248,12 +260,21 @@ def service_rows(states):
|
||||
]
|
||||
|
||||
|
||||
def route_rows(_):
|
||||
current = ctl._route_mode_current()
|
||||
return [
|
||||
{"key": m, "active": "●" if m == current else "", "mode": ctl._route_mode_label(m)}
|
||||
for m in ("default", *ctl.ROUTE_MODES)
|
||||
]
|
||||
def route_mode_options():
|
||||
"""The route modes as the Routing tab's selector and the tray offer them: (mode, label)."""
|
||||
return [(m, ctl._route_mode_label(m)) for m in ("default", *ctl.ROUTE_MODES)]
|
||||
|
||||
|
||||
def routing_rows(_):
|
||||
return ctl._routing_rows()
|
||||
|
||||
|
||||
def routing_summary():
|
||||
return (
|
||||
f"Configured default: {ctl._route_mode_default()}; an override lasts until you switch back to default. "
|
||||
"Checked top to bottom: a lower # first, a runtime rule first among equals, then the final outbound. "
|
||||
"On sing-box, a rule's domains and addresses change without a restart."
|
||||
)
|
||||
|
||||
|
||||
def outbound_rows(_):
|
||||
@@ -655,6 +676,10 @@ def _rule_sets():
|
||||
return bool(ctl.read_json_or(ctl.env("RULE_SETS_FILE"), []))
|
||||
|
||||
|
||||
def _runtime_rule(row):
|
||||
return bool(row.get("runtime"))
|
||||
|
||||
|
||||
def _zapret_toggle(row, _, states):
|
||||
return ["zapret", "off" if states.get("proxy-suite-zapret") == "active" else "on"]
|
||||
|
||||
@@ -748,11 +773,40 @@ TABS = [
|
||||
"routing",
|
||||
"Routing",
|
||||
_socks,
|
||||
[("active", ""), ("key", "Mode"), ("mode", "Meaning")],
|
||||
route_rows,
|
||||
summary=lambda: f"Configured default: {ctl._route_mode_default()}. An override lasts until you switch back to default.",
|
||||
[("priority", "#"), ("name", "Rule"), ("source", "Source"), ("target", "Target"), ("matches", "Matches"), ("notes", "Notes")],
|
||||
routing_rows,
|
||||
summary=routing_summary,
|
||||
tree=True,
|
||||
selector=Selector(
|
||||
"Mode",
|
||||
route_mode_options,
|
||||
# Looked up at each read: tests and the front ends patch proxy_ctl's.
|
||||
lambda: ctl._route_mode_current(),
|
||||
lambda mode: ["proxy", "mode", mode],
|
||||
),
|
||||
actions=[
|
||||
Action("space", "switch to this mode", lambda r, *_: ["proxy", "mode", r["key"]], when=lambda r: not r["active"]),
|
||||
Action(
|
||||
"n",
|
||||
"add a rule…",
|
||||
lambda r, t, _: ["proxy", "rules", "add", *shlex.split(t)],
|
||||
prompt="<proxy|direct|block|outbound> <domain, address, geosite:x, geoip:x or ruleset:x…> [--name n] [--priority n]"
|
||||
" - e.g. direct bank.example 10.0.0.0/8",
|
||||
),
|
||||
Action("a", "add domains or addresses to it…", lambda r, t, _: ["proxy", "rules", "matches", r["name"], "add", *t.split()], when=_runtime_rule, prompt="<domain, address, geosite:x, geoip:x or ruleset:x…>"),
|
||||
Action("x", "remove domains or addresses from it…", lambda r, t, _: ["proxy", "rules", "matches", r["name"], "rm", *t.split()], when=_runtime_rule, prompt="<domain, address, geosite:x, geoip:x or ruleset:x…>"),
|
||||
Action("t", "send it elsewhere…", lambda r, t, _: ["proxy", "rules", "target", r["name"], t.strip()], when=_runtime_rule, prompt="<proxy, direct, block or an outbound>"),
|
||||
Action(
|
||||
"y",
|
||||
"set its priority…",
|
||||
lambda r, t, _: ["proxy", "rules", "priority", r["name"], t.strip()],
|
||||
when=_runtime_rule,
|
||||
prompt="<number> - lower goes first; the configuration's sections are at 100 to 500",
|
||||
),
|
||||
Action("plus", "move it up", lambda r, *_: ["proxy", "rules", "priority", r["name"], "up"], when=_runtime_rule),
|
||||
Action("minus", "move it down", lambda r, *_: ["proxy", "rules", "priority", r["name"], "down"], when=_runtime_rule),
|
||||
Action("e", "disable it", lambda r, *_: ["proxy", "rules", "disable", r["name"]], when=lambda r: _runtime_rule(r) and not r["disabled"]),
|
||||
Action("e", "enable it again", lambda r, *_: ["proxy", "rules", "enable", r["name"]], when=lambda r: _runtime_rule(r) and r["disabled"]),
|
||||
Action("d", "remove it", lambda r, *_: ["proxy", "rules", "rm", r["name"]], when=_runtime_rule, confirm=True),
|
||||
Action("i", "rule sets and when each was fetched", lambda r, *_: ["proxy", "rulesets", "list"], mode="dialog", offered=_rule_sets),
|
||||
Action("u", "fetch the rule sets now", lambda r, *_: ["proxy", "rulesets", "update"], mode="dialog", offered=_rule_sets),
|
||||
],
|
||||
@@ -1017,7 +1071,7 @@ WHERE = Action("w", "How is a domain routed", lambda r, t, _: ["where", t], prom
|
||||
PROXY_SCHEMES = ("vless", "vmess", "trojan", "ss", "hysteria2", "hy2", "tuic", "anytls", "naive+https", "naive+quic", "socks5", "socks5h", "socks4", "socks4a")
|
||||
HOST = re.compile(r"(?!-)[A-Za-z0-9-]{1,63}(?<!-)(\.(?!-)[A-Za-z0-9-]{1,63}(?<!-))+")
|
||||
# A bare host means something only where a tab collects hosts.
|
||||
HOST_ARGV = {"zapret": ["zapret", "auto", "add"], "autoproxy": ["proxy", "auto", "learn"]}
|
||||
HOST_ARGV = {"zapret": ["zapret", "auto", "add"], "autoproxy": ["proxy", "auto", "learn"], "routing": ["proxy", "rules", "add", "proxy"]}
|
||||
OUTBOUND_ADD = ["proxy", "outbounds", "add"]
|
||||
|
||||
|
||||
@@ -1069,6 +1123,33 @@ def applicable(tab, row):
|
||||
return [a for a in tab.actions if offered(a) and (a.when is None or (row is not None and a.when(row)))]
|
||||
|
||||
|
||||
def selector_state(tab):
|
||||
"""(options, current value) of a tab's selector, or None: without one, or unreadable."""
|
||||
if tab.selector is None:
|
||||
return None
|
||||
options = _safe(tab.selector.options, fallback=None)
|
||||
if not options:
|
||||
return None
|
||||
return options, _safe(tab.selector.current, fallback=None)
|
||||
|
||||
|
||||
def selector_argv(tab, value):
|
||||
"""What choosing value runs, or None when it is already the choice or no option."""
|
||||
state = selector_state(tab)
|
||||
if state is None or value == state[1] or value not in dict(state[0]):
|
||||
return None
|
||||
return tab.selector.argv(value)
|
||||
|
||||
|
||||
def selector_line(tab):
|
||||
"""The selector as one line of text: "Mode: ● Default … ○ Whitelist …"."""
|
||||
state = selector_state(tab)
|
||||
if state is None:
|
||||
return ""
|
||||
options, current = state
|
||||
return f"{tab.selector.label}: " + " ".join(f"{'●' if v == current else '○'} {label}" for v, label in options)
|
||||
|
||||
|
||||
def load_tab(tab, states):
|
||||
"""(rows, summary) for a tab: a failed read empties the rows and says why in the summary."""
|
||||
summary = (_safe(tab.summary, fallback="") or "") if tab.summary else ""
|
||||
@@ -1330,8 +1411,8 @@ def tray_menu(snap, outbounds=None):
|
||||
f"Routing: {ctl._route_mode_label(current)}",
|
||||
kind="submenu",
|
||||
children=[
|
||||
MenuItem(f"mode-{m}", ctl._route_mode_label(m), kind="radio", checked=m == current, argv=["proxy", "mode", m])
|
||||
for m in ("default", *ctl.ROUTE_MODES)
|
||||
MenuItem(f"mode-{m}", label, kind="radio", checked=m == current, argv=["proxy", "mode", m])
|
||||
for m, label in route_mode_options()
|
||||
],
|
||||
)
|
||||
)
|
||||
|
||||
@@ -4,6 +4,7 @@ What it shows and does lives in proxy_model, shared with proxy-suite-gui; this i
|
||||
"""
|
||||
|
||||
import faulthandler
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
@@ -277,6 +278,29 @@ class Menu(Dialog):
|
||||
self.dismiss(self.actions[int(event.option.id)])
|
||||
|
||||
|
||||
class Pick(Dialog):
|
||||
"""A tab's selector: its options, the current one first in focus, picked with the arrows."""
|
||||
|
||||
BINDINGS = [Binding("escape,q", "dismiss", "close")]
|
||||
|
||||
def __init__(self, title, options, current):
|
||||
super().__init__()
|
||||
self.heading, self.options, self.current = title, options, current
|
||||
|
||||
def compose(self) -> ComposeResult:
|
||||
values = [v for v, _ in self.options]
|
||||
with Vertical(classes="dialog menu"):
|
||||
yield Label(printable(self.heading), classes="dialog-title", markup=False)
|
||||
choices = Choices(*(Option(f"{'●' if v == self.current else '○'} {label}", id=str(i)) for i, (v, label) in enumerate(self.options)))
|
||||
if self.current in values:
|
||||
choices.highlighted = values.index(self.current)
|
||||
yield choices
|
||||
yield hint("↑↓ or click to choose", ("esc close", "dismiss"))
|
||||
|
||||
def on_option_list_option_selected(self, event):
|
||||
self.dismiss(self.options[int(event.option.id)][0])
|
||||
|
||||
|
||||
class Output(Dialog):
|
||||
BINDINGS = [Binding("escape,q", "dismiss", "close"), Binding("c", "copy", "copy"), Binding("exclamation_mark", "retry_root", "retry as root")]
|
||||
|
||||
@@ -344,9 +368,23 @@ class Table(DataTable):
|
||||
def _pane(tab):
|
||||
"""A pane whose bindings are its tab's action keys, live while its table has focus."""
|
||||
bindings = [Binding(a.key, f"app.act({i})") for i, a in enumerate(tab.actions)]
|
||||
if tab.selector:
|
||||
bindings.append(Binding(tab.selector.key, "app.choose"))
|
||||
return type(f"{tab.id.title()}Pane", (TabPane,), {"BINDINGS": bindings})
|
||||
|
||||
|
||||
def selector_markup(tab, state):
|
||||
"""The selector's line, each option a link that chooses it."""
|
||||
options, current = state
|
||||
parts = [
|
||||
f"[b]{escape(label)}[/]" if value == current else f"[@click=app.choose({json.dumps(value)})]{escape(label)}[/]"
|
||||
for value, label in options
|
||||
]
|
||||
return f"[b ansi_cyan]{escape(model.display_key(tab.selector.key))}[/] {escape(tab.selector.label)}: " + " · ".join(
|
||||
f"{'●' if value == current else '○'} {part}" for (value, _), part in zip(options, parts, strict=True)
|
||||
)
|
||||
|
||||
|
||||
WIDE, TALL = 130, 40 # from here on the detail panel shows beside, or below, the table
|
||||
|
||||
|
||||
@@ -379,6 +417,8 @@ class MainScreen(Screen):
|
||||
with TabbedContent(id="tabs"):
|
||||
for tab in self.tabs.values():
|
||||
with _pane(tab)(tab.title, id=tab.id):
|
||||
if tab.selector:
|
||||
yield Static(id=f"{tab.id}-selector", classes="selector")
|
||||
yield Static(id=f"{tab.id}-summary", classes="summary")
|
||||
with Container(classes="body"):
|
||||
table = Table(id=f"{tab.id}-table", cursor_type="row")
|
||||
@@ -412,6 +452,7 @@ class ProxyTui(App):
|
||||
#tabs ContentSwitcher { height: 1fr; }
|
||||
#tabs TabPane { height: 1fr; padding: 0; }
|
||||
.summary { display: none; height: auto; padding: 0 1; text-style: dim; }
|
||||
.selector { display: none; height: auto; padding: 0 1; }
|
||||
DataTable { background: $background; }
|
||||
#tabs DataTable { height: 1fr; }
|
||||
DataTable > .datatable--header { background: $background; color: $accent; text-style: bold; }
|
||||
@@ -447,6 +488,7 @@ class ProxyTui(App):
|
||||
self.sorts = {} # tab id -> (column, descending)
|
||||
self.collapsed = {} # tree tab id -> keys of the groups folded away
|
||||
self.loaded = {} # tab id -> the last load, refilled at once when sorting or filtering changes
|
||||
self.selectors = {} # tab id -> its selector's (options, current) as last read
|
||||
self.status = []
|
||||
self.typed = {} # prompt title -> what was last typed there
|
||||
self.feedback_timer = None
|
||||
@@ -536,6 +578,7 @@ class ProxyTui(App):
|
||||
visible = model.available_tabs(states)
|
||||
status = _safe(status_text, states, fallback=["status unavailable"])
|
||||
rows, summary = model.load_tab(self.tabs[tab_id], states)
|
||||
self.selectors[tab_id] = model.selector_state(self.tabs[tab_id])
|
||||
except Exception as e:
|
||||
# A dead worker would leave the tab as it was, for good; the next refresh tries again.
|
||||
log_trace(f"load {tab_id}")
|
||||
@@ -586,6 +629,11 @@ class ProxyTui(App):
|
||||
widget = self.main.query_one(f"#{tab_id}-summary", Static)
|
||||
_update(widget, Text(printable(summary)))
|
||||
widget.display = bool(summary)
|
||||
if self.tabs[tab_id].selector:
|
||||
state = self.selectors.get(tab_id)
|
||||
widget = self.main.query_one(f"#{tab_id}-selector", Static)
|
||||
_update(widget, selector_markup(self.tabs[tab_id], state) if state else "")
|
||||
widget.display = bool(state)
|
||||
self.rows[tab_id] = {r["key"]: r for r in rows}
|
||||
tab, table = self.tabs[tab_id], self.table(tab_id)
|
||||
keys = [r["key"] for r in rows]
|
||||
@@ -672,10 +720,28 @@ class ProxyTui(App):
|
||||
def action_where(self):
|
||||
self.perform(model.WHERE, None)
|
||||
|
||||
def action_choose(self, value=None):
|
||||
"""The tab's selector: value from a click on its line, else picked from a list."""
|
||||
tab = self.tabs[self.active_tab()]
|
||||
state = self.selectors.get(tab.id)
|
||||
if not tab.selector or not state:
|
||||
self.feedback("Nothing to choose here right now.")
|
||||
return
|
||||
|
||||
def chosen(value):
|
||||
argv = value is not None and model.selector_argv(tab, value)
|
||||
if argv:
|
||||
self.run_argv("run", argv)
|
||||
|
||||
if value is None:
|
||||
self.push_screen(Pick(tab.selector.label, *state), chosen)
|
||||
else:
|
||||
chosen(value)
|
||||
|
||||
def on_data_table_header_selected(self, event):
|
||||
tab_id, name = self.active_tab(), event.column_key.value
|
||||
if self.tabs[tab_id].tree:
|
||||
self.feedback("This list keeps its order: it is the order groups and the top level pick in.")
|
||||
self.feedback("This list keeps its order: the order it is picked or checked in.")
|
||||
return
|
||||
sort = self.sorts.pop(tab_id, None)
|
||||
if not sort or sort[0] != name:
|
||||
@@ -717,7 +783,10 @@ class ProxyTui(App):
|
||||
def action_help(self):
|
||||
tab = self.tabs[self.active_tab()]
|
||||
text = Text()
|
||||
for heading, keys in ((tab.title, model.key_labels(a for a in tab.actions if model.offered(a))), ("Everywhere", GLOBAL_KEYS)):
|
||||
own = model.key_labels(a for a in tab.actions if model.offered(a))
|
||||
if tab.selector:
|
||||
own.append((tab.selector.key, f"choose the {tab.selector.label.lower()}"))
|
||||
for heading, keys in ((tab.title, own), ("Everywhere", GLOBAL_KEYS)):
|
||||
text.append(f"{heading}\n", style="bold")
|
||||
for key, label in keys:
|
||||
text.append(f" {model.display_key(key):<9}", style=ACCENT)
|
||||
|
||||
@@ -2508,6 +2508,10 @@ class WhereTest(EnvTest):
|
||||
}
|
||||
}
|
||||
self.assertEqual(ctl._where_sing_box(config, "rr1.youtube.com"), ("warp", "rule-set yt"))
|
||||
# A runtime routing rule's own rule set reads as the rule.
|
||||
config["route"]["rule_set"][0]["tag"] = "user:videos"
|
||||
config["route"]["rules"][-1]["rule_set"] = ["user:videos"]
|
||||
self.assertEqual(ctl._where_sing_box(config, "rr1.youtube.com"), ("warp", "runtime rule videos"))
|
||||
self.assertEqual(ctl._where_sing_box(config, "a.example.org")[0], "proxy")
|
||||
# A leading dot is subdomains only; nothing else matches, so the final outbound.
|
||||
self.assertEqual(ctl._where_sing_box(config, "example.org")[0], "direct")
|
||||
@@ -2533,6 +2537,163 @@ class WhereTest(EnvTest):
|
||||
)
|
||||
|
||||
|
||||
class RoutingRulesTest(EnvTest):
|
||||
"""proxy rules: the spool proxy-ctl writes, and where each rule lands among the configuration's."""
|
||||
|
||||
SECTIONS = [
|
||||
{"id": "rules", "priority": 100, "label": "routing.rules", "entries": [{"target": "de", "domains": ["c.example"]}]},
|
||||
{"id": "proxy", "priority": 200, "label": "routing.proxy: domains and ips", "entries": [{"target": "proxy", "domains": []}]},
|
||||
{"id": "block", "priority": 300, "label": "routing.block", "entries": [{"target": "block", "domains": ["ads.example"]}]},
|
||||
{"id": "direct", "priority": 400, "label": "routing.direct, private addresses", "entries": [{"target": "direct"}]},
|
||||
]
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
os.makedirs(self.path("routing.d"))
|
||||
geosites = self.path("geo")
|
||||
os.makedirs(geosites)
|
||||
open(os.path.join(geosites, "geosite-netflix.srs"), "w").close()
|
||||
os.environ.update(
|
||||
RUNTIME_ROUTING_DIR=self.path("routing.d"),
|
||||
ROUTING_RULES_DIR=self.path("routing"),
|
||||
ROUTING_RULES_FILE=self.write("buckets.json", {"common": [], "sections": self.SECTIONS}),
|
||||
OUTBOUND_INVENTORY_FILE=self.write("socks/outbounds.json", {"tags": ["de", "proxy"], "groups": {"fast": {}}}),
|
||||
RULE_SETS_FILE=self.write("rulesets.json", [{"name": "blocked", "path": "/x"}]),
|
||||
GEODATA_GEOSITE_DIR=geosites,
|
||||
ROUTE_MODE_STATE_FILE=self.path("no-mode"),
|
||||
)
|
||||
self.applied = 0
|
||||
|
||||
def systemctl(*args, **_):
|
||||
self.applied += args[:2] == ("start", "proxy-suite-routing-apply.service")
|
||||
return 0, ""
|
||||
|
||||
self.patch("systemctl", systemctl)
|
||||
self.patch("svc_exists", lambda unit: True)
|
||||
|
||||
def rules(self):
|
||||
with open(self.path("routing.d/rules.json")) as f:
|
||||
return {r["name"]: r for r in json.load(f)["rules"]}
|
||||
|
||||
def test_matches_as_typed(self):
|
||||
m = ctl._rule_match
|
||||
self.assertEqual(m("Bank.Example"), ("domains", "bank.example"))
|
||||
self.assertEqual(m(".bank.example"), ("domains", "bank.example"))
|
||||
self.assertEqual(m("https://user@WWW.Bank.example:8443/login"), ("domains", "www.bank.example"))
|
||||
self.assertEqual(m("10.1.2.3"), ("ips", "10.1.2.3/32"))
|
||||
self.assertEqual(m("10.1.2.3/8"), ("ips", "10.0.0.0/8"))
|
||||
self.assertEqual(m("2001:db8::1"), ("ips", "2001:db8::1/128"))
|
||||
self.assertEqual(m("geosite:netflix"), ("geosites", "netflix"))
|
||||
self.assertEqual(m("geoip:ru"), ("geoips", "ru")) # no geoip dir here: not checked
|
||||
self.assertEqual(m("ruleset:blocked"), ("ruleSets", "blocked"))
|
||||
for bad in ("geosite:nope", "geosite:../x", "ruleset:other", "a b", "$(id)", "x/y"):
|
||||
with self.subTest(bad=bad):
|
||||
self.assertEqual(run(ctl._rule_match, bad)[0], 1)
|
||||
|
||||
def test_add_extends_the_rule_named_after_its_target(self):
|
||||
ok(ctl.cmd_rules, "add", "direct", "bank.example", "10.0.0.0/8")
|
||||
ok(ctl.cmd_rules, "add", "direct", "bank2.example", "bank.example")
|
||||
ok(ctl.cmd_rules, "add", "fast", "geosite:netflix", "--name", "video", "--priority", "250")
|
||||
rules = self.rules()
|
||||
self.assertEqual(rules["direct"]["domains"], ["bank.example", "bank2.example"])
|
||||
self.assertEqual((rules["direct"]["priority"], rules["direct"]["ips"]), (50, ["10.0.0.0/8"]))
|
||||
self.assertEqual((rules["video"]["target"], rules["video"]["priority"], rules["video"]["geosites"]), ("fast", 250, ["netflix"]))
|
||||
self.assertEqual(self.applied, 3)
|
||||
# Another target under the same name is a mistake, not a silent move.
|
||||
status, _, err = run(ctl.cmd_rules, "add", "proxy", "x.example", "--name", "direct")
|
||||
self.assertEqual(status, 1)
|
||||
self.assertIn("rules target direct proxy", err)
|
||||
self.assertEqual(run(ctl.cmd_rules, "add", "nowhere", "x.example")[0], 1)
|
||||
self.assertEqual(run(ctl.cmd_rules, "add", "proxy", "x.example", "--name", "../x")[0], 1)
|
||||
self.assertEqual(self.applied, 3)
|
||||
|
||||
def test_edits(self):
|
||||
ok(ctl.cmd_rules, "add", "direct", "a.example", "b.example")
|
||||
ok(ctl.cmd_rules, "matches", "direct", "rm", "a.example")
|
||||
ok(ctl.cmd_rules, "matches", "direct", "add", "1.1.1.1")
|
||||
ok(ctl.cmd_rules, "target", "direct", "de")
|
||||
ok(ctl.cmd_rules, "disable", "direct")
|
||||
ok(ctl.cmd_rules, "priority", "direct", "450")
|
||||
rule = self.rules()["direct"]
|
||||
self.assertEqual((rule["domains"], rule["ips"], rule["target"], rule["disabled"], rule["priority"]), (["b.example"], ["1.1.1.1/32"], "de", True, 450))
|
||||
ok(ctl.cmd_rules, "enable", "direct")
|
||||
self.assertFalse(self.rules()["direct"]["disabled"])
|
||||
self.assertEqual(run(ctl.cmd_rules, "priority", "direct", "1.5")[0], 1)
|
||||
self.assertEqual(run(ctl.cmd_rules, "rm", "nope")[0], 1)
|
||||
ok(ctl.cmd_rules, "rm", "direct")
|
||||
self.assertEqual(self.rules(), {})
|
||||
|
||||
def test_up_and_down_step_past_the_configuration(self):
|
||||
ok(ctl.cmd_rules, "add", "direct", "a.example")
|
||||
ok(ctl.cmd_rules, "add", "proxy", "b.example")
|
||||
order = lambda: [r["name"] for r in ctl._routing_rows()] # noqa: E731
|
||||
# Empty sections are no rows: proxy (200) is not there to step past.
|
||||
self.assertEqual(order(), ["direct", "proxy", "routing.rules", "routing.block", "routing.direct, private addresses"])
|
||||
ok(ctl.cmd_rules, "priority", "proxy", "down")
|
||||
self.assertEqual(order(), ["direct", "routing.rules", "proxy", "routing.block", "routing.direct, private addresses"])
|
||||
self.assertEqual(self.rules()["proxy"]["priority"], 110)
|
||||
ok(ctl.cmd_rules, "priority", "direct", "down")
|
||||
# Both after routing.rules now, the one moved first: numbered 10 apart there.
|
||||
self.assertEqual(order()[:3], ["routing.rules", "direct", "proxy"])
|
||||
self.assertEqual({n: r["priority"] for n, r in self.rules().items()}, {"direct": 110, "proxy": 120})
|
||||
ok(ctl.cmd_rules, "priority", "direct", "down")
|
||||
self.assertEqual(order()[:3], ["routing.rules", "proxy", "direct"])
|
||||
ok(ctl.cmd_rules, "priority", "direct", "down")
|
||||
ok(ctl.cmd_rules, "priority", "direct", "down")
|
||||
self.assertEqual(order()[-1], "direct")
|
||||
self.assertIn("already last", ok(ctl.cmd_rules, "priority", "direct", "down"))
|
||||
# Before a section a rule may share its number (runtime first among equals).
|
||||
ok(ctl.cmd_rules, "priority", "proxy", "100")
|
||||
self.assertEqual(order()[:2], ["proxy", "routing.rules"])
|
||||
|
||||
def test_list_and_rows(self):
|
||||
ok(ctl.cmd_rules, "add", "direct", "a.example", "geosite:netflix")
|
||||
self.write("socks/routing-skipped.json", [{"name": "direct", "why": "no such geosite"}])
|
||||
rows = {r["key"]: r for r in ctl._routing_rows()}
|
||||
self.assertEqual(rows["rule:direct"]["matches"], "a.example, geosite:netflix")
|
||||
self.assertEqual(rows["rule:direct"]["notes"], "left out: no such geosite")
|
||||
self.assertEqual((rows["config:block:0"]["source"], rows["config:block:0"]["runtime"]), ("config", False))
|
||||
self.assertEqual(rows["config:direct:0"]["matches"], "private addresses")
|
||||
out = ok(ctl.cmd_rules)
|
||||
self.assertIn("routing.block", out)
|
||||
self.assertIn("-> direct: a.example, geosite:netflix", out)
|
||||
|
||||
def test_a_spool_edited_by_hand_reads_as_root_applies_it(self):
|
||||
"""What routing-render.jq drops is no row, and nothing in the file stops the list."""
|
||||
with open(self.path("routing.d/rules.json"), "w") as f:
|
||||
f.write(
|
||||
'{"rules": [{"name": "inf", "target": "proxy", "priority": Infinity},'
|
||||
' {"name": "nan", "target": "proxy", "priority": NaN},'
|
||||
' {"name": "far", "target": "proxy", "priority": -5e9},'
|
||||
' {"name": "half", "target": "proxy", "priority": -2.5},'
|
||||
' {"name": "half", "target": "direct"},'
|
||||
' {"name": "../x", "target": "proxy"},'
|
||||
' {"name": "ctl", "target": "a\\u0007b"}]}'
|
||||
)
|
||||
rules = {r["name"]: (r["priority"], r["target"]) for r in ctl._runtime_rules()}
|
||||
self.assertEqual(rules, {"inf": (1_000_000, "proxy"), "nan": (50, "proxy"), "far": (-1_000_000, "proxy"), "half": (-3, "proxy")})
|
||||
self.assertIn("inf", ok(ctl.cmd_rules))
|
||||
self.assertIn("priority 7", ok(ctl.cmd_rules, "priority", "half", "007"))
|
||||
|
||||
@unittest.skipIf(os.geteuid() == 0, "root reads anything")
|
||||
def test_a_stranger_sees_what_root_applied(self):
|
||||
"""The spool is the routing scope's; anyone else reads the rendered copy."""
|
||||
ok(ctl.cmd_rules, "add", "direct", "a.example")
|
||||
self.write("routing/rules.json", [{"name": "applied", "target": "proxy", "priority": 5, "domains": ["b.example"]}])
|
||||
os.chmod(self.path("routing.d/rules.json"), 0)
|
||||
self.assertEqual([r["name"] for r in ctl._runtime_rules()], ["applied"])
|
||||
status, _, err = run(ctl.cmd_rules, "add", "direct", "c.example")
|
||||
self.assertEqual(status, 1)
|
||||
self.assertIn("Cannot change", err)
|
||||
|
||||
def test_completion(self):
|
||||
ok(ctl.cmd_rules, "add", "direct", "a.example")
|
||||
self.assertIn("matches", ctl._complete_tree("proxy", "rules"))
|
||||
self.assertEqual(ctl._complete_tree("proxy", "rules", "rm"), {"direct": "-> direct"})
|
||||
targets = ctl._complete_tree("proxy", "rules", "add")
|
||||
self.assertTrue({"proxy", "direct", "block", "de", "fast", "--name"} <= set(targets))
|
||||
|
||||
|
||||
class StatusSnapshotTest(EnvTest):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
|
||||
@@ -154,6 +154,23 @@ class GuiTest(unittest.TestCase):
|
||||
then()
|
||||
self.assertEqual(ran, [(["proxy", "subs", "add", "-"], "https://evil.test/s")])
|
||||
|
||||
def test_selector_runs_only_a_new_choice(self):
|
||||
"""The Routing page's mode drop-down: picking runs proxy-ctl; filling it from a read does not."""
|
||||
routing = next(t for t in model.TABS if t.id == "routing")
|
||||
ran = []
|
||||
win = types.SimpleNamespace(app=types.SimpleNamespace(run_argv=lambda mode, argv, win: ran.append((mode, argv))))
|
||||
page = types.SimpleNamespace(tab=routing, win=win, selector_setting=False, selector_values=["default", *ctl.ROUTE_MODES])
|
||||
drop = lambda index: types.SimpleNamespace(get_selected=lambda: index) # noqa: E731
|
||||
with mock.patch.object(ctl, "_route_mode_current", lambda: "default"):
|
||||
gui.Page.on_selector_changed(page, drop(2), None)
|
||||
self.assertEqual(ran, [("run", ["proxy", "mode", "blacklist"])])
|
||||
gui.Page.on_selector_changed(page, drop(0), None) # the current one
|
||||
gui.Page.on_selector_changed(page, drop(Gtk.INVALID_LIST_POSITION), None)
|
||||
page.selector_setting = True # set from a read
|
||||
gui.Page.on_selector_changed(page, drop(1), None)
|
||||
self.assertEqual(len(ran), 1)
|
||||
self.assertTrue(gui.accelerator(routing.selector.key))
|
||||
|
||||
def test_every_tray_icon_is_drawn(self):
|
||||
here = os.path.join(os.path.dirname(os.path.abspath(__file__)), "icons")
|
||||
with tempfile.TemporaryDirectory() as out:
|
||||
|
||||
@@ -238,6 +238,7 @@ class ModelTest(unittest.TestCase):
|
||||
],
|
||||
"zapret": [{"kind": k} for k in ("learned", "pinned", "excluded")],
|
||||
"autoproxy": [{"kind": k} for k in ("routed", "queued")],
|
||||
"routing": [{"runtime": rt, "disabled": d} for rt in (False, True) for d in (False, True)],
|
||||
}
|
||||
for tab in model.TABS:
|
||||
by_key = {}
|
||||
@@ -271,18 +272,60 @@ class ModelTest(unittest.TestCase):
|
||||
zapret = next(t for t in model.TABS if t.id == "zapret")
|
||||
env = {}
|
||||
with mock.patch.object(ctl, "env", lambda name, default="": env.get(name, default)):
|
||||
self.assertEqual([a.key for a in model.applicable(routing, None)], [])
|
||||
self.assertEqual([a.key for a in model.applicable(routing, None)], ["n"])
|
||||
self.assertEqual([a.key for a in model.applicable(zapret, None)], ["space", "ctrl+r"])
|
||||
with tempfile.NamedTemporaryFile("w", suffix=".json") as f:
|
||||
json.dump([{"name": "ru", "path": "/nonexistent"}], f)
|
||||
f.flush()
|
||||
env.update(RULE_SETS_FILE=f.name, ZAPRET_AUTO_ENABLED="1", ZAPRET_CUTOFF_ENABLED="1")
|
||||
self.assertEqual([a.argv(None, "", {}) for a in model.applicable(routing, None)], [["proxy", "rulesets", "list"], ["proxy", "rulesets", "update"]])
|
||||
self.assertEqual(
|
||||
[a.argv(None, "", {}) for a in model.applicable(routing, None) if a.key != "n"],
|
||||
[["proxy", "rulesets", "list"], ["proxy", "rulesets", "update"]],
|
||||
)
|
||||
self.assertEqual([a.key for a in model.applicable(zapret, None)], ["n", "X", "F", "P", "space", "ctrl+r"])
|
||||
actions = {a.key: a for a in zapret.actions}
|
||||
self.assertEqual(actions["n"].argv(None, "example.com", {}), ["zapret", "auto", "add", "example.com"])
|
||||
self.assertEqual(actions["X"].argv(None, "example.com", {}), ["zapret", "auto", "exclude", "example.com"])
|
||||
|
||||
def test_routing_tab(self):
|
||||
"""Rules in match order, actions on the runtime ones only, and the mode as a selector."""
|
||||
tab = next(t for t in model.TABS if t.id == "routing")
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
spool = os.path.join(tmp, "routing.d")
|
||||
os.makedirs(spool)
|
||||
with open(os.path.join(spool, "rules.json"), "w") as f:
|
||||
json.dump({"rules": [{"name": "work", "target": "de", "priority": 150, "domains": ["work.example"]},
|
||||
{"name": "off", "target": "direct", "priority": 10, "disabled": True}]}, f)
|
||||
buckets = os.path.join(tmp, "buckets.json")
|
||||
with open(buckets, "w") as f:
|
||||
json.dump({"sections": [{"id": "rules", "priority": 100, "label": "routing.rules", "entries": [{"target": "de", "domains": ["c.example"]}]}]}, f)
|
||||
env = {"RUNTIME_ROUTING_DIR": spool, "ROUTING_RULES_FILE": buckets, "OUTBOUND_INVENTORY_FILE": os.path.join(tmp, "none.json")}
|
||||
with mock.patch.object(ctl, "env", lambda name, default="": env.get(name, default)):
|
||||
rows, _ = model.load_tab(tab, {})
|
||||
self.assertEqual([r["key"] for r in rows], ["rule:off", "config:rules:0", "rule:work"])
|
||||
off, config, work = rows
|
||||
self.assertEqual(off["notes"], "disabled")
|
||||
by = lambda row: {a.key: a for a in model.applicable(tab, row)} # noqa: E731
|
||||
self.assertEqual(set(by(config)), {"n"}) # the configuration's: nothing to change here
|
||||
self.assertEqual(by(off)["e"].argv(off, "", {}), ["proxy", "rules", "enable", "off"])
|
||||
self.assertEqual(by(work)["e"].argv(work, "", {}), ["proxy", "rules", "disable", "work"])
|
||||
self.assertEqual(by(work)["plus"].argv(work, "", {}), ["proxy", "rules", "priority", "work", "up"])
|
||||
self.assertEqual(by(work)["a"].argv(work, "a.example 1.1.1.1", {}), ["proxy", "rules", "matches", "work", "add", "a.example", "1.1.1.1"])
|
||||
self.assertEqual(by(work)["t"].argv(work, " proxy ", {}), ["proxy", "rules", "target", "work", "proxy"])
|
||||
self.assertTrue(by(work)["d"].confirm)
|
||||
self.assertEqual(by(None)["n"].argv(None, "direct bank.example --name bank", {}), ["proxy", "rules", "add", "direct", "bank.example", "--name", "bank"])
|
||||
# The mode: a selector over the table, not rows in it.
|
||||
options, current = model.selector_state(tab)
|
||||
self.assertEqual([v for v, _ in options], ["default", *ctl.ROUTE_MODES])
|
||||
self.assertEqual(current, "default")
|
||||
self.assertIsNone(model.selector_argv(tab, "default")) # already
|
||||
self.assertIsNone(model.selector_argv(tab, "nope"))
|
||||
self.assertEqual(model.selector_argv(tab, "all-proxy"), ["proxy", "mode", "all-proxy"])
|
||||
self.assertTrue(model.selector_line(tab).startswith("Mode: ● Default"))
|
||||
self.assertIsNone(model.selector_state(next(t for t in model.TABS if t.id == "services")))
|
||||
# A bare host pasted onto the tab goes through the proxy.
|
||||
self.assertEqual(model.paste_argv("routing", "blocked.example")[0], ["proxy", "rules", "add", "proxy", "blocked.example"])
|
||||
|
||||
def test_tray_menu(self):
|
||||
states = {
|
||||
"proxy-suite-socks": "active",
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
import asyncio
|
||||
import contextlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import tempfile
|
||||
import unittest
|
||||
@@ -285,19 +287,37 @@ class TuiTest(unittest.TestCase):
|
||||
# Declared: nothing removes it here.
|
||||
self.assertNotIn("d", app.screen.active_bindings)
|
||||
|
||||
# On to Routing.
|
||||
# On to Routing: a runtime rule ahead of nothing the configuration has.
|
||||
os.makedirs(f"{self.env['STATE_DIR']}/routing.d")
|
||||
with open(f"{self.env['STATE_DIR']}/routing.d/rules.json", "w") as f:
|
||||
json.dump({"rules": [{"name": "bank", "target": "direct", "domains": ["bank.example"]}]}, f)
|
||||
await pilot.press("right")
|
||||
await self.settle(app, pilot)
|
||||
self.assertEqual((app.active_tab(), app.focused.id), ("routing", "routing-table"))
|
||||
self.assertIn("● [b]Default", str(app.main.query_one("#routing-selector").content))
|
||||
|
||||
# Enter opens the row's actions; arrows and enter pick one.
|
||||
await pilot.press("down", "enter")
|
||||
await pilot.pause()
|
||||
self.assertIsInstance(app.screen, tui.Menu)
|
||||
self.assertEqual(self.menu_labels(app), ["switch to this mode"])
|
||||
await pilot.press("enter")
|
||||
await pilot.pause()
|
||||
self.assertIsInstance(app.screen, tui.Menu)
|
||||
self.assertEqual(self.menu_labels(app)[:2], ["add a rule…", "add domains or addresses to it…"])
|
||||
await pilot.press("escape")
|
||||
await pilot.pause()
|
||||
await pilot.press("minus")
|
||||
self.assertEqual(self.ran.pop(), ["proxy", "rules", "priority", "bank", "down"])
|
||||
|
||||
# m: the mode, picked from a list that starts at the current one.
|
||||
await pilot.press("m")
|
||||
await pilot.pause()
|
||||
self.assertIsInstance(app.screen, tui.Pick)
|
||||
await pilot.press("down", "enter")
|
||||
await pilot.pause()
|
||||
self.assertEqual(self.ran.pop(), ["proxy", "mode", "whitelist"])
|
||||
# Or a click on one in the line above the table.
|
||||
app.action_choose("all-bypass")
|
||||
self.assertEqual(self.ran.pop(), ["proxy", "mode", "all-bypass"])
|
||||
app.action_choose("default") # already: nothing runs
|
||||
self.assertEqual(self.ran, [])
|
||||
|
||||
# Outbounds: letter shortcuts; p pins, and on the pinned row unpins; nothing removes a declared one.
|
||||
await pilot.press("right")
|
||||
|
||||
Reference in new issue
Block a user