Net core: turning capture on restarts the core cleanly; remember TUN state

After the AmneziaVPN app held the routes, the running core kept Amnezia's utun as its
way out; its own TUN reused the same utun name and sent everything into itself (no
routes, no DNS). "tun on" now refuses while AmneziaVPN is open and restarts the core;
the on/off choice is saved (tun.json) and used on the next start.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
maksarsanjeev
2026-10-10 00:11:54 +03:00
parent bc548d748c
commit 3077404ebf
3 changed files with 53 additions and 12 deletions
+10 -1
View File
@@ -6,6 +6,7 @@ keys/*.vpnkey one vpn:// key per Amnezia connection (AmneziaWG 2/3); BroV
src/saga.conf WireGuard client config -> only 192.168.8.0/24
src/planet9.conf WireGuard client config -> only 192.168.68.0/24
src/vless.sub 3x-ui subscription URL (all VLESS nodes)
tun.json {"on": bool}: traffic capture as the user left it (survives restarts)
hidden.json connections removed in BroV: {"amnezia": [...], "vless": [...]} (proxy
names). Hidden ones stay on disk and can be returned from the panel.
@@ -44,6 +45,14 @@ def hidden():
return {"amnezia": [], "vless": []}
def tun_on():
try:
with open(os.path.join(CORE, "tun.json")) as f:
return bool(json.load(f).get("on", True))
except (OSError, ValueError, AttributeError):
return True
def rx(name):
"""Literal regex for a node name (backslash only before ASCII punctuation: valid in Go
regexp and regexp2 alike)."""
@@ -194,7 +203,7 @@ def main():
"external-controller": "127.0.0.1:9097", "secret": api_secret, "unified-delay": True,
"find-process-mode": "strict",
"profile": {"store-selected": True},
"tun": {"enable": True, "stack": "mixed", "auto-route": True, "auto-detect-interface": True,
"tun": {"enable": tun_on(), "stack": "mixed", "auto-route": True, "auto-detect-interface": True,
"dns-hijack": ["any:53"], "mtu": 1400},
"dns": {"enable": True, "ipv6": False, "enhanced-mode": "fake-ip", "fake-ip-range": "198.18.0.1/16",
"fake-ip-filter": ["*.lan", "*.local", "+.duckdns.org"],
+33 -7
View File
@@ -9,7 +9,7 @@ allows exactly these operations:
state groups, provider nodes with delays, hidden connections, TUN on/off
select {group, name} ai-out / amnezia / saga-sw / planet9-sw / home-sw, name must be a member
delay {group}|{proxy} speed test of exit / ai-out / amnezia, or of a client tunnel
tun {on} traffic capture on/off
tun {on} traffic capture on (fresh core start) / off; remembered
add_key {text} vpn:// Amnezia key: checked by gen.py, stored, provider reloaded
hide {name} take an Amnezia connection or a VLESS node out of the list and
out of "auto" (the key / subscription stay, nothing is deleted)
@@ -26,6 +26,7 @@ import struct
import subprocess
import sys
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
@@ -42,6 +43,7 @@ DELAY_GROUPS = {"exit", "ai-out", "auto", "amnezia"}
CLIENT_TUNNELS = {"saga", "planet9", "home"}
MAX_REQUEST = 64 * 1024
CORE_LABEL = "local.maksar.brov.netd"
HIDDEN = os.path.join(CORE, "hidden.json")
CONFIG = os.path.join(CORE, "config.yaml")
MIHOMO = os.path.join(ROOT, "mihomo")
@@ -115,12 +117,39 @@ def cmd_delay(r):
return {"ok": False, "error": "замер не разрешён"}
def save_tun(on):
tmp = os.path.join(CORE, "tun.json.tmp")
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600)
with os.fdopen(fd, "w") as f:
json.dump({"on": on}, f)
os.rename(tmp, os.path.join(CORE, "tun.json"))
def cmd_tun(r):
"""On = a fresh core start. A core that has been running while the AmneziaVPN app held
the routes keeps treating Amnezia's utun as the way out; its own TUN often gets the same
utun name and then sends everything into itself (no routes, no DNS). A restart forgets
that. The state is saved so the core comes back the same way after a reboot."""
on = r.get("on")
if not isinstance(on, bool):
return {"ok": False, "error": "нужно on: true/false"}
api("PATCH", "/configs", {"tun": {"enable": on}})
return {"ok": True}
if on and subprocess.run(["/usr/bin/pgrep", "-x", "AmneziaVPN"], capture_output=True).returncode == 0:
return {"ok": False, "error": "открыто приложение AmneziaVPN — закрой его (⌘Q), потом включай"}
with gen_lock:
save_tun(on)
gen()
if not on:
api("PATCH", "/configs", {"tun": {"enable": False}})
return {"ok": True}
subprocess.run(["/bin/launchctl", "kickstart", "-k", "system/" + CORE_LABEL], capture_output=True, timeout=20)
for _ in range(40):
time.sleep(0.25)
try:
if api("GET", "/configs", timeout=2).get("tun", {}).get("enable"):
return {"ok": True}
except Exception:
pass
return {"ok": False, "error": "ядро не поднялось после перезапуска"}
def provider_reload_and_test(proxy):
@@ -185,14 +214,11 @@ def awg_key_exists(name):
def reload_core():
"""Full config reload (needed for the VLESS filter): drops open connections for a moment.
The new config is checked first; TUN stays as the user left it."""
The new config is checked first; TUN comes from tun.json, i.e. as the user left it."""
check = subprocess.run([MIHOMO, "-t", "-d", CORE, "-f", CONFIG], capture_output=True, text=True, timeout=30)
if check.returncode != 0:
raise RuntimeError("ядро не приняло новый конфиг")
tun = api("GET", "/configs").get("tun", {}).get("enable", False)
api("PUT", "/configs?force=true", {"path": CONFIG}, timeout=20)
if not tun:
api("PATCH", "/configs", {"tun": {"enable": False}})
def change_hidden(name, hide):