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:
@@ -313,15 +313,21 @@ final class NetCore: ObservableObject {
|
|||||||
NSWorkspace.shared.runningApplications.contains { $0.localizedName == "AmneziaVPN" }
|
NSWorkspace.shared.runningApplications.contains { $0.localizedName == "AmneziaVPN" }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Turns traffic capture on/off without a password (the core keeps running).
|
/// Turns traffic capture on/off without a password. On restarts the core cleanly
|
||||||
|
/// (a few seconds): after AmneziaVPN it would otherwise keep using Amnezia's tunnel.
|
||||||
func setTun(_ on: Bool) async {
|
func setTun(_ on: Bool) async {
|
||||||
if on && Self.amneziaRunning {
|
if on && Self.amneziaRunning {
|
||||||
lastError = "Сначала выключи AmneziaVPN — иначе она и ядро подерутся за маршрут."
|
lastError = "Сначала закрой AmneziaVPN (⌘Q) — иначе она и ядро подерутся за маршрут."
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
lastError = nil
|
lastError = nil
|
||||||
tunOn = on
|
tunOn = on
|
||||||
_ = await call(["cmd": "tun", "on": on])
|
busy = true
|
||||||
|
let r = await call(["cmd": "tun", "on": on], timeout: 30)
|
||||||
|
busy = false
|
||||||
|
if r?["ok"] as? Bool != true {
|
||||||
|
lastError = "Не включилось: \(r?["error"] as? String ?? "помощник не ответил")."
|
||||||
|
}
|
||||||
SoundEngine.shared.play(on ? "pop" : "close")
|
SoundEngine.shared.play(on ? "pop" : "close")
|
||||||
try? await Task.sleep(for: .seconds(1))
|
try? await Task.sleep(for: .seconds(1))
|
||||||
await refresh()
|
await refresh()
|
||||||
@@ -426,7 +432,7 @@ struct NetPanel: View {
|
|||||||
.frame(width: 444, alignment: .leading)
|
.frame(width: 444, alignment: .leading)
|
||||||
} else {
|
} else {
|
||||||
NetRow(title: "Ядро перехватывает трафик",
|
NetRow(title: "Ядро перехватывает трафик",
|
||||||
subtitle: net.tunOn ? "весь трафик Мака идёт через BroV" : "выключено — Мак ходит сам (можно включить AmneziaVPN)",
|
subtitle: net.tunOn ? "весь трафик Мака идёт через BroV" : (net.busy ? "перезапускаю ядро…" : "выключено — Мак ходит сам (можно включить AmneziaVPN)"),
|
||||||
delay: nil, isOn: net.tunOn, accent: "#A78BFA") {
|
delay: nil, isOn: net.tunOn, accent: "#A78BFA") {
|
||||||
Task { await net.setTun(!net.tunOn) }
|
Task { await net.setTun(!net.tunOn) }
|
||||||
}
|
}
|
||||||
|
|||||||
+10
-1
@@ -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/saga.conf WireGuard client config -> only 192.168.8.0/24
|
||||||
src/planet9.conf WireGuard client config -> only 192.168.68.0/24
|
src/planet9.conf WireGuard client config -> only 192.168.68.0/24
|
||||||
src/vless.sub 3x-ui subscription URL (all VLESS nodes)
|
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
|
hidden.json connections removed in BroV: {"amnezia": [...], "vless": [...]} (proxy
|
||||||
names). Hidden ones stay on disk and can be returned from the panel.
|
names). Hidden ones stay on disk and can be returned from the panel.
|
||||||
|
|
||||||
@@ -44,6 +45,14 @@ def hidden():
|
|||||||
return {"amnezia": [], "vless": []}
|
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):
|
def rx(name):
|
||||||
"""Literal regex for a node name (backslash only before ASCII punctuation: valid in Go
|
"""Literal regex for a node name (backslash only before ASCII punctuation: valid in Go
|
||||||
regexp and regexp2 alike)."""
|
regexp and regexp2 alike)."""
|
||||||
@@ -194,7 +203,7 @@ def main():
|
|||||||
"external-controller": "127.0.0.1:9097", "secret": api_secret, "unified-delay": True,
|
"external-controller": "127.0.0.1:9097", "secret": api_secret, "unified-delay": True,
|
||||||
"find-process-mode": "strict",
|
"find-process-mode": "strict",
|
||||||
"profile": {"store-selected": True},
|
"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-hijack": ["any:53"], "mtu": 1400},
|
||||||
"dns": {"enable": True, "ipv6": False, "enhanced-mode": "fake-ip", "fake-ip-range": "198.18.0.1/16",
|
"dns": {"enable": True, "ipv6": False, "enhanced-mode": "fake-ip", "fake-ip-range": "198.18.0.1/16",
|
||||||
"fake-ip-filter": ["*.lan", "*.local", "+.duckdns.org"],
|
"fake-ip-filter": ["*.lan", "*.local", "+.duckdns.org"],
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ allows exactly these operations:
|
|||||||
state groups, provider nodes with delays, hidden connections, TUN on/off
|
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
|
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
|
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
|
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
|
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)
|
out of "auto" (the key / subscription stay, nothing is deleted)
|
||||||
@@ -26,6 +26,7 @@ import struct
|
|||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
import threading
|
import threading
|
||||||
|
import time
|
||||||
import urllib.error
|
import urllib.error
|
||||||
import urllib.parse
|
import urllib.parse
|
||||||
import urllib.request
|
import urllib.request
|
||||||
@@ -42,6 +43,7 @@ DELAY_GROUPS = {"exit", "ai-out", "auto", "amnezia"}
|
|||||||
CLIENT_TUNNELS = {"saga", "planet9", "home"}
|
CLIENT_TUNNELS = {"saga", "planet9", "home"}
|
||||||
MAX_REQUEST = 64 * 1024
|
MAX_REQUEST = 64 * 1024
|
||||||
|
|
||||||
|
CORE_LABEL = "local.maksar.brov.netd"
|
||||||
HIDDEN = os.path.join(CORE, "hidden.json")
|
HIDDEN = os.path.join(CORE, "hidden.json")
|
||||||
CONFIG = os.path.join(CORE, "config.yaml")
|
CONFIG = os.path.join(CORE, "config.yaml")
|
||||||
MIHOMO = os.path.join(ROOT, "mihomo")
|
MIHOMO = os.path.join(ROOT, "mihomo")
|
||||||
@@ -115,12 +117,39 @@ def cmd_delay(r):
|
|||||||
return {"ok": False, "error": "замер не разрешён"}
|
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):
|
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")
|
on = r.get("on")
|
||||||
if not isinstance(on, bool):
|
if not isinstance(on, bool):
|
||||||
return {"ok": False, "error": "нужно on: true/false"}
|
return {"ok": False, "error": "нужно on: true/false"}
|
||||||
api("PATCH", "/configs", {"tun": {"enable": on}})
|
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}
|
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):
|
def provider_reload_and_test(proxy):
|
||||||
@@ -185,14 +214,11 @@ def awg_key_exists(name):
|
|||||||
|
|
||||||
def reload_core():
|
def reload_core():
|
||||||
"""Full config reload (needed for the VLESS filter): drops open connections for a moment.
|
"""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)
|
check = subprocess.run([MIHOMO, "-t", "-d", CORE, "-f", CONFIG], capture_output=True, text=True, timeout=30)
|
||||||
if check.returncode != 0:
|
if check.returncode != 0:
|
||||||
raise RuntimeError("ядро не приняло новый конфиг")
|
raise RuntimeError("ядро не приняло новый конфиг")
|
||||||
tun = api("GET", "/configs").get("tun", {}).get("enable", False)
|
|
||||||
api("PUT", "/configs?force=true", {"path": CONFIG}, timeout=20)
|
api("PUT", "/configs?force=true", {"path": CONFIG}, timeout=20)
|
||||||
if not tun:
|
|
||||||
api("PATCH", "/configs", {"tun": {"enable": False}})
|
|
||||||
|
|
||||||
|
|
||||||
def change_hidden(name, hide):
|
def change_hidden(name, hide):
|
||||||
|
|||||||
Reference in New Issue
Block a user