Files
proxy-suite-flake/scripts/patch-zapret-config.py
T

340 lines
10 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 _hostlist_remove_pattern(stem: str) -> str:
escaped = re.escape(stem)
return rf'\s+--hostlist=(?:"[^"]*/hostlists/{escaped}\.txt"|[^ ]*/hostlists/{escaped}\.txt)'
def _ipset_remove_pattern(stem: str) -> str:
escaped = re.escape(stem)
return rf'\s+--ipset=(?:"[^"]*/hostlists/{escaped}\.txt"|[^ ]*/hostlists/{escaped}\.txt)'
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")],
},
}
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,
hostlist_path: str,
standard_excludes: list[str],
*,
preset_family: str | None = None,
) -> str:
rendered = strip_trailing_new(line)
if preset_family is not None:
for pattern in FAMILY_PATTERNS[preset_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 = 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 = add_standard_excludes(rendered, standard_excludes)
return f"{normalize_spaces(rendered)} --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)
def render_custom_ipset_args(
fragment: str,
ipset_path: str,
standard_excludes: list[str],
) -> str:
return _render_ipset_args(fragment, ipset_path, standard_excludes)
def clone_family_lines(
existing_lines: list[str],
family: str,
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
]
def clone_ipset_lines(
existing_lines: list[str],
family: str,
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
]
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", [])
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 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[:end] + generated_lines + lines[end:]
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)