refactor: remove duplication
This commit is contained in:
109 files changed
+2206
-3078
No files matched your search
@@ -13,14 +13,18 @@ BUILTIN_ACTIVATION_FALLBACKS = {
|
||||
}
|
||||
|
||||
|
||||
def _hostlist_remove_pattern(stem: str) -> str:
|
||||
def _remove_pattern(option: str, stem: str) -> str:
|
||||
"""Matches --hostlist=/--ipset= pointing at one of the config's own list files."""
|
||||
escaped = re.escape(stem)
|
||||
return rf'\s+--hostlist=(?:"[^"]*/hostlists/{escaped}\.txt"|[^ ]*/hostlists/{escaped}\.txt)'
|
||||
return rf'\s+--{option}=(?:"[^"]*/hostlists/{escaped}\.txt"|[^ ]*/hostlists/{escaped}\.txt)'
|
||||
|
||||
|
||||
def _hostlist_remove_pattern(stem: str) -> str:
|
||||
return _remove_pattern("hostlist", stem)
|
||||
|
||||
|
||||
def _ipset_remove_pattern(stem: str) -> str:
|
||||
escaped = re.escape(stem)
|
||||
return rf'\s+--ipset=(?:"[^"]*/hostlists/{escaped}\.txt"|[^ ]*/hostlists/{escaped}\.txt)'
|
||||
return _remove_pattern("ipset", stem)
|
||||
|
||||
|
||||
def _mk_family(match_stems: list[str], remove_stems: list[str]) -> dict:
|
||||
@@ -117,40 +121,28 @@ def add_standard_excludes(line: str, standard_excludes: list[str]) -> str:
|
||||
|
||||
def _render_args(
|
||||
line: str,
|
||||
hostlist_path: str,
|
||||
option: str,
|
||||
list_path: str,
|
||||
standard_excludes: list[str],
|
||||
*,
|
||||
preset_family: str | None = None,
|
||||
family_patterns: dict | None = None,
|
||||
family: str | None = None,
|
||||
) -> str:
|
||||
"""The line with its own list arguments dropped and list_path put in their place.
|
||||
|
||||
`option` is "hostlist" or "ipset": the other kind is always removed, and the named
|
||||
family's own patterns are removed instead of every argument when cloning a preset.
|
||||
"""
|
||||
other = "ipset" if option == "hostlist" else "hostlist"
|
||||
rendered = strip_trailing_new(line)
|
||||
if preset_family is not None:
|
||||
for pattern in FAMILY_PATTERNS[preset_family]["remove"]:
|
||||
if family is not None:
|
||||
for pattern in family_patterns[family]["remove"]:
|
||||
rendered = re.sub(pattern, "", rendered)
|
||||
else:
|
||||
rendered = re.sub(r'\s+--hostlist=(?:"[^"]+"|\S+)', "", rendered)
|
||||
rendered = re.sub(r'\s+--ipset=(?:"[^"]+"|\S+)', "", rendered)
|
||||
rendered = re.sub(rf'\s+--{option}=(?:"[^"]+"|\S+)', "", rendered)
|
||||
rendered = re.sub(rf'\s+--{other}=(?:"[^"]+"|\S+)', "", rendered)
|
||||
rendered = normalize_spaces(rendered)
|
||||
rendered = f'{rendered} --hostlist="{hostlist_path}"'
|
||||
rendered = add_standard_excludes(rendered, standard_excludes)
|
||||
return f"{normalize_spaces(rendered)} --new"
|
||||
|
||||
|
||||
def _render_ipset_args(
|
||||
line: str,
|
||||
ipset_path: str,
|
||||
standard_excludes: list[str],
|
||||
*,
|
||||
ipset_family: str | None = None,
|
||||
) -> str:
|
||||
rendered = strip_trailing_new(line)
|
||||
if ipset_family is not None:
|
||||
for pattern in IPSET_PATTERNS[ipset_family]["remove"]:
|
||||
rendered = re.sub(pattern, "", rendered)
|
||||
else:
|
||||
rendered = re.sub(r'\s+--ipset=(?:"[^"]+"|\S+)', "", rendered)
|
||||
rendered = re.sub(r'\s+--hostlist=(?:"[^"]+"|\S+)', "", rendered)
|
||||
rendered = normalize_spaces(rendered)
|
||||
rendered = f'{rendered} --ipset="{ipset_path}"'
|
||||
rendered = f'{normalize_spaces(rendered)} --{option}="{list_path}"'
|
||||
rendered = add_standard_excludes(rendered, standard_excludes)
|
||||
return f"{normalize_spaces(rendered)} --new"
|
||||
|
||||
@@ -159,30 +151,12 @@ def render_protocol_clone(line: str) -> str:
|
||||
return f"{normalize_spaces(strip_trailing_new(line))} --new"
|
||||
|
||||
|
||||
def render_preset_clone(
|
||||
line: str,
|
||||
family: str,
|
||||
hostlist_path: str,
|
||||
standard_excludes: list[str],
|
||||
) -> str:
|
||||
return _render_args(line, hostlist_path, standard_excludes, preset_family=family)
|
||||
|
||||
|
||||
def render_custom_args(
|
||||
fragment: str,
|
||||
hostlist_path: str,
|
||||
standard_excludes: list[str],
|
||||
) -> str:
|
||||
return _render_args(fragment, hostlist_path, standard_excludes)
|
||||
|
||||
|
||||
def render_ipset_clone(
|
||||
line: str,
|
||||
family: str,
|
||||
ipset_path: str,
|
||||
standard_excludes: list[str],
|
||||
) -> str:
|
||||
return _render_ipset_args(line, ipset_path, standard_excludes, ipset_family=family)
|
||||
return _render_args(fragment, "hostlist", hostlist_path, standard_excludes)
|
||||
|
||||
|
||||
def render_custom_ipset_args(
|
||||
@@ -190,7 +164,21 @@ def render_custom_ipset_args(
|
||||
ipset_path: str,
|
||||
standard_excludes: list[str],
|
||||
) -> str:
|
||||
return _render_ipset_args(fragment, ipset_path, standard_excludes)
|
||||
return _render_args(fragment, "ipset", ipset_path, standard_excludes)
|
||||
|
||||
|
||||
def _clone_lines(
|
||||
existing_lines: list[str], patterns: dict, family: str, what: str, render
|
||||
) -> list[str]:
|
||||
"""Every line of the config carrying the family's marker, rendered anew."""
|
||||
if family not in patterns:
|
||||
raise ValueError(f"{what} '{family}' is unknown")
|
||||
matches = [
|
||||
line for line in existing_lines if any(m in line for m in patterns[family]["match"])
|
||||
]
|
||||
if not matches:
|
||||
raise ValueError(f"{what} '{family}' is not present in the selected zapret config")
|
||||
return [render(line) for line in matches]
|
||||
|
||||
|
||||
def clone_family_lines(
|
||||
@@ -199,19 +187,21 @@ def clone_family_lines(
|
||||
hostlist_path: str,
|
||||
standard_excludes: list[str],
|
||||
) -> list[str]:
|
||||
matches = [
|
||||
line
|
||||
for line in existing_lines
|
||||
if any(marker in line for marker in FAMILY_PATTERNS[family]["match"])
|
||||
]
|
||||
if not matches:
|
||||
raise ValueError(
|
||||
f"Preset family '{family}' is not present in the selected zapret config"
|
||||
)
|
||||
return [
|
||||
render_preset_clone(line, family, hostlist_path, standard_excludes)
|
||||
for line in matches
|
||||
]
|
||||
"""The preset family's rules, pointed at this entry's own hostlist."""
|
||||
return _clone_lines(
|
||||
existing_lines,
|
||||
FAMILY_PATTERNS,
|
||||
family,
|
||||
"Preset family",
|
||||
lambda line: _render_args(
|
||||
line,
|
||||
"hostlist",
|
||||
hostlist_path,
|
||||
standard_excludes,
|
||||
family_patterns=FAMILY_PATTERNS,
|
||||
family=family,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def clone_ipset_lines(
|
||||
@@ -220,32 +210,26 @@ def clone_ipset_lines(
|
||||
ipset_path: str,
|
||||
standard_excludes: list[str],
|
||||
) -> list[str]:
|
||||
matches = [
|
||||
line
|
||||
for line in existing_lines
|
||||
if any(marker in line for marker in IPSET_PATTERNS[family]["match"])
|
||||
]
|
||||
if not matches:
|
||||
raise ValueError(
|
||||
f"IP set family '{family}' is not present in the selected zapret config"
|
||||
)
|
||||
return [
|
||||
render_ipset_clone(line, family, ipset_path, standard_excludes)
|
||||
for line in matches
|
||||
]
|
||||
return _clone_lines(
|
||||
existing_lines,
|
||||
IPSET_PATTERNS,
|
||||
family,
|
||||
"IP set family",
|
||||
lambda line: _render_args(
|
||||
line,
|
||||
"ipset",
|
||||
ipset_path,
|
||||
standard_excludes,
|
||||
family_patterns=IPSET_PATTERNS,
|
||||
family=family,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def clone_protocol_lines(existing_lines: list[str], family: str) -> list[str]:
|
||||
matches = [
|
||||
line
|
||||
for line in existing_lines
|
||||
if any(marker in line for marker in PROTOCOL_PATTERNS[family]["match"])
|
||||
]
|
||||
if not matches:
|
||||
raise ValueError(
|
||||
f"Protocol family '{family}' is not present in the selected zapret config"
|
||||
)
|
||||
return [render_protocol_clone(line) for line in matches]
|
||||
return _clone_lines(
|
||||
existing_lines, PROTOCOL_PATTERNS, family, "Protocol family", render_protocol_clone
|
||||
)
|
||||
|
||||
|
||||
def activate_builtin_hostlists(
|
||||
|
||||
+53
-55
@@ -286,6 +286,46 @@ def _subscription_tag(line: str, tag_prefix: str, index: int, seen_tags: set[str
|
||||
return _unique_tag(make_tag(tag_prefix, _remark_from_line(line), index), seen_tags)
|
||||
|
||||
|
||||
def _walk_subscription(
|
||||
lines: list[str],
|
||||
tag_prefix: str,
|
||||
routing_mark: int | None,
|
||||
backends: list[str],
|
||||
links: dict[str, str] | None,
|
||||
keep,
|
||||
) -> None:
|
||||
"""Parses every supported line, trying each backend in turn, and hands the result to keep.
|
||||
|
||||
A line no backend accepts is reported with every backend's complaint and skipped.
|
||||
"""
|
||||
seen_tags: set[str] = set()
|
||||
|
||||
for index, line in enumerate(lines):
|
||||
scheme = detect_scheme(line)
|
||||
if scheme not in PARSERS:
|
||||
continue
|
||||
|
||||
tag = _subscription_tag(line, tag_prefix, index, seen_tags)
|
||||
errors = []
|
||||
for backend in backends:
|
||||
try:
|
||||
outbound = build_outbound(line, tag, routing_mark, backend)
|
||||
except Exception as exc:
|
||||
errors.append(f"{backend}: {exc}" if len(backends) > 1 else str(exc))
|
||||
continue
|
||||
|
||||
seen_tags.add(tag)
|
||||
keep(backend, outbound)
|
||||
if links is not None:
|
||||
links[tag] = line
|
||||
break
|
||||
else:
|
||||
print(
|
||||
f"warning: skipping entry {index} ({scheme}): " + "; ".join(errors),
|
||||
file=sys.stderr,
|
||||
)
|
||||
|
||||
|
||||
def parse_subscription(
|
||||
lines: list[str],
|
||||
tag_prefix: str,
|
||||
@@ -294,66 +334,24 @@ def parse_subscription(
|
||||
links: dict[str, str] | None = None,
|
||||
) -> list[dict]:
|
||||
"""links, when given, collects tag -> the line it came from, to share it back."""
|
||||
outbounds = []
|
||||
seen_tags: set[str] = set()
|
||||
|
||||
for index, line in enumerate(lines):
|
||||
scheme = detect_scheme(line)
|
||||
if scheme not in PARSERS:
|
||||
continue
|
||||
|
||||
tag = _subscription_tag(line, tag_prefix, index, seen_tags)
|
||||
|
||||
try:
|
||||
outbound = build_outbound(line, tag, routing_mark, backend)
|
||||
except Exception as exc:
|
||||
print(f"warning: skipping entry {index} ({scheme}): {exc}", file=sys.stderr)
|
||||
continue
|
||||
|
||||
seen_tags.add(tag)
|
||||
outbounds.append(outbound)
|
||||
if links is not None:
|
||||
links[tag] = line
|
||||
|
||||
outbounds: list[dict] = []
|
||||
_walk_subscription(
|
||||
lines, tag_prefix, routing_mark, [backend], links, lambda _, ob: outbounds.append(ob)
|
||||
)
|
||||
return outbounds
|
||||
|
||||
|
||||
def parse_hybrid_subscription(
|
||||
lines: list[str], tag_prefix: str, routing_mark: int | None = None, links: dict[str, str] | None = None
|
||||
) -> dict[str, list[dict]]:
|
||||
"""Each line goes to whichever backend can dial it, sing-box first."""
|
||||
outbounds: dict[str, list[dict]] = {"singBox": [], "xray": []}
|
||||
seen_tags: set[str] = set()
|
||||
|
||||
for index, line in enumerate(lines):
|
||||
scheme = detect_scheme(line)
|
||||
if scheme not in PARSERS:
|
||||
continue
|
||||
|
||||
tag = _subscription_tag(line, tag_prefix, index, seen_tags)
|
||||
|
||||
try:
|
||||
outbound = build_outbound(line, tag, routing_mark, "sing-box")
|
||||
outbounds["singBox"].append(outbound)
|
||||
seen_tags.add(tag)
|
||||
if links is not None:
|
||||
links[tag] = line
|
||||
continue
|
||||
except Exception as sing_box_exc:
|
||||
sing_box_error = sing_box_exc
|
||||
|
||||
try:
|
||||
outbound = build_outbound(line, tag, routing_mark, "xray")
|
||||
except Exception as xray_exc:
|
||||
print(
|
||||
f"warning: skipping entry {index} ({scheme}): "
|
||||
f"sing-box: {sing_box_error}; xray: {xray_exc}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
continue
|
||||
|
||||
outbounds["xray"].append(outbound)
|
||||
seen_tags.add(tag)
|
||||
if links is not None:
|
||||
links[tag] = line
|
||||
|
||||
_walk_subscription(
|
||||
lines,
|
||||
tag_prefix,
|
||||
routing_mark,
|
||||
["sing-box", "xray"],
|
||||
links,
|
||||
lambda backend, ob: outbounds["singBox" if backend == "sing-box" else "xray"].append(ob),
|
||||
)
|
||||
return outbounds
|
||||
@@ -209,6 +209,15 @@ def _mk_auth(userinfo: str) -> "tuple[str | None, str | None]":
|
||||
return urllib.parse.unquote(username), urllib.parse.unquote(password) if separator else None
|
||||
|
||||
|
||||
def _set_auth(ob: dict, userinfo: str) -> None:
|
||||
"""Copies userinfo onto the outbound, password only when it is there."""
|
||||
username, password = _mk_auth(userinfo)
|
||||
if username is not None:
|
||||
ob["username"] = username
|
||||
if password is not None:
|
||||
ob["password"] = password
|
||||
|
||||
|
||||
def parse_vless(url: str, tag: str, backend: str = "sing-box") -> dict:
|
||||
userinfo, host, port, params = _parse_url_parts(url, "vless")
|
||||
security = _param(params, "security", "none")
|
||||
@@ -478,52 +487,37 @@ def parse_naive(url: str, tag: str) -> dict:
|
||||
"server_port": _port(port),
|
||||
"tls": {"enabled": True, "server_name": params.get("sni") or host},
|
||||
}
|
||||
username, password = _mk_auth(userinfo)
|
||||
if username is not None:
|
||||
ob["username"] = username
|
||||
if password is not None:
|
||||
ob["password"] = password
|
||||
_set_auth(ob, userinfo)
|
||||
if scheme == "naive+quic":
|
||||
ob["quic"] = True
|
||||
return ob
|
||||
|
||||
|
||||
def parse_socks(url: str, tag: str) -> dict:
|
||||
scheme = url.split("://")[0].lower()
|
||||
version = "4" if scheme.startswith("socks4") else "5"
|
||||
userinfo, host, port, _ = _parse_url_parts(url, scheme)
|
||||
|
||||
ob: dict = {"type": "socks", "tag": tag, "version": version}
|
||||
username, password = _mk_auth(userinfo)
|
||||
if username is not None:
|
||||
ob["username"] = username
|
||||
if password is not None:
|
||||
ob["password"] = password
|
||||
ob["server"] = host
|
||||
ob["server_port"] = _port(port)
|
||||
|
||||
return ob
|
||||
|
||||
|
||||
def parse_http_proxy(url: str, tag: str) -> dict:
|
||||
def _parse_plain_proxy(url: str, tag: str, kind: str) -> dict:
|
||||
"""socks:// and http(s)://: host, port and optional credentials, nothing else."""
|
||||
scheme = url.split("://")[0].lower()
|
||||
userinfo, host, port, _ = _parse_url_parts(url, scheme)
|
||||
|
||||
ob: dict = {"type": "http", "tag": tag}
|
||||
username, password = _mk_auth(userinfo)
|
||||
if username is not None:
|
||||
ob["username"] = username
|
||||
if password is not None:
|
||||
ob["password"] = password
|
||||
ob: dict = {"type": kind, "tag": tag}
|
||||
if kind == "socks":
|
||||
ob["version"] = "4" if scheme.startswith("socks4") else "5"
|
||||
_set_auth(ob, userinfo)
|
||||
ob["server"] = host
|
||||
ob["server_port"] = _port(port)
|
||||
|
||||
if scheme == "https":
|
||||
if kind == "http" and scheme == "https":
|
||||
ob["tls"] = {"enabled": True, "server_name": host}
|
||||
|
||||
return ob
|
||||
|
||||
|
||||
def parse_socks(url: str, tag: str) -> dict:
|
||||
return _parse_plain_proxy(url, tag, "socks")
|
||||
|
||||
|
||||
def parse_http_proxy(url: str, tag: str) -> dict:
|
||||
return _parse_plain_proxy(url, tag, "http")
|
||||
|
||||
|
||||
PARSERS = {
|
||||
"vless": parse_vless,
|
||||
"vmess": parse_vmess,
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
#!/usr/bin/env python3
|
||||
"""patch-zapret-config.py: the NFQWS_OPT rewrites, on strings only."""
|
||||
|
||||
import importlib.util
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"patch_zapret_config", Path(__file__).with_name("patch-zapret-config.py")
|
||||
)
|
||||
patch = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(patch)
|
||||
|
||||
HOSTLISTS = "/opt/zapret/hostlists"
|
||||
EXCLUDES = [
|
||||
f'--hostlist-exclude="{HOSTLISTS}/list-exclude.txt"',
|
||||
f'--ipset-exclude="{HOSTLISTS}/ipset-exclude.txt"',
|
||||
]
|
||||
GENERAL = (
|
||||
f'--filter-tcp=443 --hostlist="{HOSTLISTS}/list-general.txt" '
|
||||
"--dpi-desync=fake --dpi-desync-ttl=6 --new"
|
||||
)
|
||||
IPSET_ALL = f'--filter-udp=443 --ipset="{HOSTLISTS}/ipset-all.txt" --dpi-desync=fake --new'
|
||||
DISCORD = "--filter-l7=discord,stun --dpi-desync=fake --new"
|
||||
|
||||
|
||||
class CloneTests(unittest.TestCase):
|
||||
def test_family_clone_repoints_the_hostlist_and_keeps_the_strategy(self):
|
||||
(line,) = patch.clone_family_lines([GENERAL], "general", "/run/mine.txt", EXCLUDES)
|
||||
self.assertIn('--hostlist="/run/mine.txt"', line)
|
||||
self.assertNotIn("list-general.txt", line)
|
||||
self.assertIn("--dpi-desync=fake", line)
|
||||
self.assertIn("--dpi-desync-ttl=6", line)
|
||||
self.assertTrue(line.endswith("--new"))
|
||||
self.assertEqual(line.count("--new"), 1)
|
||||
for exclude in EXCLUDES:
|
||||
self.assertIn(exclude, line)
|
||||
|
||||
def test_ipset_clone_repoints_the_ipset(self):
|
||||
(line,) = patch.clone_ipset_lines([IPSET_ALL], "all", "/run/mine-ips.txt", EXCLUDES)
|
||||
self.assertIn('--ipset="/run/mine-ips.txt"', line)
|
||||
self.assertNotIn("ipset-all.txt", line)
|
||||
self.assertNotIn("--hostlist=", line)
|
||||
self.assertTrue(line.endswith("--new"))
|
||||
|
||||
def test_protocol_clone_keeps_the_line_as_is(self):
|
||||
(line,) = patch.clone_protocol_lines([DISCORD], "discord-voice")
|
||||
self.assertEqual(line, DISCORD)
|
||||
|
||||
def test_a_missing_family_is_an_error(self):
|
||||
for call in (
|
||||
lambda: patch.clone_family_lines([IPSET_ALL], "google", "/run/x.txt", EXCLUDES),
|
||||
lambda: patch.clone_ipset_lines([GENERAL], "all", "/run/x.txt", EXCLUDES),
|
||||
lambda: patch.clone_protocol_lines([GENERAL], "discord-voice"),
|
||||
):
|
||||
with self.assertRaises(ValueError):
|
||||
call()
|
||||
|
||||
def test_custom_args_get_one_hostlist_and_one_ipset_form(self):
|
||||
fragment = "--filter-tcp=80 --dpi-desync=split2"
|
||||
host = patch.render_custom_args(fragment, "/run/mine.txt", EXCLUDES)
|
||||
ips = patch.render_custom_ipset_args(fragment, "/run/mine-ips.txt", EXCLUDES)
|
||||
self.assertIn('--hostlist="/run/mine.txt"', host)
|
||||
self.assertNotIn("--ipset=", host)
|
||||
self.assertIn('--ipset="/run/mine-ips.txt"', ips)
|
||||
self.assertNotIn("--hostlist=", ips)
|
||||
|
||||
def test_builtin_activation_only_adds_missing_lists(self):
|
||||
instagram = f'--filter-tcp=443 --hostlist="{HOSTLISTS}/list-instagram.txt" --new'
|
||||
added = patch.activate_builtin_hostlists(
|
||||
[GENERAL, instagram], Path(HOSTLISTS), EXCLUDES
|
||||
)
|
||||
joined = "\n".join(added)
|
||||
self.assertNotIn("list-instagram.txt", joined)
|
||||
self.assertIn("list-soundcloud.txt", joined)
|
||||
self.assertIn("list-twitter.txt", joined)
|
||||
|
||||
|
||||
class BlockTests(unittest.TestCase):
|
||||
def test_locate_nfqws_block(self):
|
||||
lines = ['OTHER=1', 'NFQWS_OPT="', GENERAL, '"', "TAIL=2"]
|
||||
start, end = patch.locate_nfqws_block(lines)
|
||||
self.assertEqual((start, end), (1, 3))
|
||||
|
||||
def test_a_config_without_the_block_is_an_error(self):
|
||||
with self.assertRaises(ValueError):
|
||||
patch.locate_nfqws_block(["OTHER=1"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user