Files

350 lines
11 KiB
Python

#!/usr/bin/env python3
import argparse
import json
import re
import sys
from pathlib import Path
BUILTIN_ACTIVATION_FALLBACKS = {
"list-instagram.txt": "general",
"list-soundcloud.txt": "general",
"list-twitter.txt": "general",
}
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+--{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:
return _remove_pattern("ipset", stem)
def _mk_family(match_stems: list[str], remove_stems: list[str]) -> dict:
return {
"match": [f"list-{s}.txt" for s in match_stems],
"remove": [_hostlist_remove_pattern(f"list-{s}") for s in remove_stems],
}
FAMILY_PATTERNS = {
"general": _mk_family(["general", "general-user"], ["general", "general-user"]),
"google": _mk_family(["google"], ["google"]),
"instagram": _mk_family(["instagram"], ["instagram"]),
"soundcloud": _mk_family(["soundcloud"], ["soundcloud"]),
"twitter": _mk_family(["twitter"], ["twitter"]),
}
IPSET_PATTERNS = {
"all": {
"match": ["ipset-all.txt"],
"remove": [_ipset_remove_pattern("ipset-all")],
},
}
PROTOCOL_PATTERNS = {
"discord-voice": {
"match": ["--filter-l7=discord,stun"],
},
}
def locate_nfqws_block(lines: list[str]) -> tuple[int, int]:
start = None
for index, line in enumerate(lines):
if line.startswith('NFQWS_OPT="'):
start = index
break
if start is None:
raise ValueError("Could not find NFQWS_OPT block in zapret config")
for index in range(start + 1, len(lines)):
if lines[index] == '"':
return start, index
raise ValueError("Could not find the end of the NFQWS_OPT block in zapret config")
def config_name_key(name: str) -> str:
return re.sub(r"\s+", "", name)
def resolve_config(configs_dir: Path, requested_config: str) -> Path:
selected_config = configs_dir / requested_config
if selected_config.is_file():
return selected_config
requested_key = config_name_key(requested_config)
matches = [
candidate
for candidate in configs_dir.iterdir()
if candidate.is_file() and config_name_key(candidate.name) == requested_key
]
if len(matches) > 1:
matched = ", ".join(str(match) for match in matches)
raise ValueError(
f"zapret config '{requested_config}' is ambiguous after whitespace normalization: {matched}"
)
if not matches:
raise ValueError(f"zapret config '{requested_config}' not found")
return matches[0]
def read_nfqws_lines(config_path: Path) -> list[str]:
lines = config_path.read_text(encoding="utf-8").splitlines()
start, end = locate_nfqws_block(lines)
return lines[start + 1 : end]
def strip_trailing_new(line: str) -> str:
return re.sub(r"(?:\s+--new)+\s*$", "", line.strip())
def normalize_spaces(line: str) -> str:
return re.sub(r"\s+", " ", line).strip()
def add_standard_excludes(line: str, standard_excludes: list[str]) -> str:
for arg in standard_excludes:
if arg not in line:
line = f"{line} {arg}"
return line
def _render_args(
line: str,
option: str,
list_path: str,
standard_excludes: list[str],
*,
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 family is not None:
for pattern in family_patterns[family]["remove"]:
rendered = re.sub(pattern, "", rendered)
else:
rendered = re.sub(rf'\s+--{option}=(?:"[^"]+"|\S+)', "", rendered)
rendered = re.sub(rf'\s+--{other}=(?:"[^"]+"|\S+)', "", rendered)
rendered = normalize_spaces(rendered)
rendered = f'{normalize_spaces(rendered)} --{option}="{list_path}"'
rendered = add_standard_excludes(rendered, standard_excludes)
return f"{normalize_spaces(rendered)} --new"
def render_protocol_clone(line: str) -> str:
return f"{normalize_spaces(strip_trailing_new(line))} --new"
def render_custom_args(
fragment: str,
hostlist_path: str,
standard_excludes: list[str],
) -> str:
return _render_args(fragment, "hostlist", hostlist_path, standard_excludes)
def render_custom_ipset_args(
fragment: str,
ipset_path: str,
standard_excludes: list[str],
) -> str:
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(
existing_lines: list[str],
family: str,
hostlist_path: str,
standard_excludes: list[str],
) -> list[str]:
"""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(
existing_lines: list[str],
family: str,
ipset_path: str,
standard_excludes: list[str],
) -> list[str]:
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]:
return _clone_lines(
existing_lines, PROTOCOL_PATTERNS, family, "Protocol family", render_protocol_clone
)
def activate_builtin_hostlists(
existing_lines: list[str],
hostlists_dir: Path,
standard_excludes: list[str],
) -> list[str]:
generated_lines: list[str] = []
full_text = "\n".join(existing_lines)
for filename, family in BUILTIN_ACTIVATION_FALLBACKS.items():
marker = str(hostlists_dir / filename)
if marker in full_text:
continue
generated_lines.extend(
clone_family_lines(existing_lines, family, marker, standard_excludes)
)
return generated_lines
def main() -> int:
parser = argparse.ArgumentParser(
description="Append proxy-suite custom hostlist rules to a zapret config."
)
parser.add_argument(
"--config", required=True, help="Path to the selected zapret config file"
)
parser.add_argument(
"--spec", required=True, help="JSON file describing custom hostlist rules"
)
args = parser.parse_args()
config_path = Path(args.config)
spec_path = Path(args.spec)
hostlists_dir = config_path.parent / "hostlists"
configs_dir = config_path.parent / "configs"
standard_excludes = [
f'--hostlist-exclude="{hostlists_dir / "list-exclude.txt"}"',
f'--hostlist-exclude="{hostlists_dir / "list-exclude-user.txt"}"',
f'--ipset-exclude="{hostlists_dir / "ipset-exclude.txt"}"',
f'--ipset-exclude="{hostlists_dir / "ipset-exclude-user.txt"}"',
]
lines = config_path.read_text(encoding="utf-8").splitlines()
spec = json.loads(spec_path.read_text(encoding="utf-8"))
entries = spec.get("entries", [])
include_extra_upstream_lists = spec.get("includeExtraUpstreamLists", False)
start, end = locate_nfqws_block(lines)
nfqws_lines = lines[start + 1 : end]
source_config_cache: dict[str, list[str]] = {}
def source_nfqws_lines(config_name: str | None) -> list[str]:
if not config_name:
return nfqws_lines
source_path = resolve_config(configs_dir, config_name)
cache_key = str(source_path)
if cache_key not in source_config_cache:
source_config_cache[cache_key] = read_nfqws_lines(source_path)
return source_config_cache[cache_key]
generated_lines: list[str] = (
activate_builtin_hostlists(nfqws_lines, hostlists_dir, standard_excludes)
if include_extra_upstream_lists
else []
)
for entry in entries:
hostlist_path = str(hostlists_dir / f'list-{entry["name"]}.txt')
ipset_path = str(hostlists_dir / f'ipset-{entry["name"]}.txt')
entry_nfqws_lines = source_nfqws_lines(entry.get("configName"))
presets = entry.get("presets")
if presets is None:
preset = entry.get("preset")
presets = [preset] if preset else []
ipsets = entry.get("ipsets", [])
protocols = entry.get("protocols", [])
has_domains = entry.get("hasDomains", bool(presets))
has_ips = entry.get("hasIps", bool(ipsets))
for preset in presets:
generated_lines.extend(
clone_family_lines(
entry_nfqws_lines, preset, hostlist_path, standard_excludes
)
)
for ipset in ipsets:
generated_lines.extend(
clone_ipset_lines(
entry_nfqws_lines, ipset, ipset_path, standard_excludes
)
)
for protocol in protocols:
generated_lines.extend(clone_protocol_lines(entry_nfqws_lines, protocol))
for fragment in entry.get("nfqwsArgs", []):
if has_domains:
generated_lines.append(
render_custom_args(fragment, hostlist_path, standard_excludes)
)
if has_ips:
generated_lines.append(
render_custom_ipset_args(fragment, ipset_path, standard_excludes)
)
updated_lines = lines[: start + 1] + generated_lines + lines[start + 1 :]
config_path.write_text("\n".join(updated_lines) + "\n", encoding="utf-8")
return 0
if __name__ == "__main__":
try:
raise SystemExit(main())
except ValueError as exc:
print(f"error: {exc}", file=sys.stderr)
raise SystemExit(1) from None