Net core: re-create WireGuard tunnels after a network change (rebind)

mihomo's WireGuard outbounds keep their UDP socket bound to the address they started on:
after moving from Planet9 to Saga the Amnezia sockets were still sending from
192.168.68.x, so every Amnezia (and client) tunnel looked dead while the AmneziaVPN app,
connecting afresh, worked. Client tunnels now live in a file provider (keys/clients.yaml,
groups select them by filter) like the Amnezia keys; netctl rebind touches both files and
reloads the providers, which re-creates the tunnels on the current address without
touching other connections. BroV calls it on every network change before re-testing.
Tested on a scratch core: groups, selection across a rebind, health check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
maksarsanjeev
2026-10-14 15:54:16 +03:00
parent 7c4e9abc46
commit 101a3860a9
4 changed files with 51 additions and 10 deletions
+11 -3
View File
@@ -176,7 +176,12 @@ def main():
with open(os.open(prov, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), "w") as f:
f.write(y({"proxies": awg}) + "\n")
clients = {n: c for n, c in CLIENTS.items() if os.path.exists(os.path.join(SRC, c[0]))}
proxies = [wg(n, f) for n, (f, _, _) in clients.items()]
# Client tunnels live in a provider file too: after a network change BroV re-creates
# them (netctl rebind) so their WireGuard sockets bind to the new address.
client_proxies = [wg(n, f) for n, (f, _, _) in clients.items()]
with open(os.open(os.path.join(KEYS, "clients.yaml"), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), "w") as f:
f.write(y({"proxies": client_proxies}) + "\n")
proxies = []
sub = open(os.path.join(SRC, "vless.sub")).read().strip()
rules = ([] if "home" in clients else [f"IP-CIDR,{HOME_NET},DIRECT,no-resolve"]) + [
@@ -200,6 +205,8 @@ def main():
# Single VLESS links added in BroV: a provider of their own (only when there are any —
# mihomo refuses an empty provider file).
extra_prov = {}
clients_prov = {"clients": {"type": "file", "path": "./keys/clients.yaml",
"health-check": {"enable": False, "url": TEST_URL}}} if clients else {}
vless_file = os.path.join(KEYS, "vless.txt")
if os.path.exists(vless_file) and any(l.strip().startswith("vless://") for l in open(vless_file)):
extra_prov["vless-keys"] = {"type": "file", "path": "./keys/vless.txt",
@@ -223,7 +230,7 @@ def main():
"nameserver": ["https://1.1.1.1/dns-query#exit", "https://8.8.8.8/dns-query#exit"],
"direct-nameserver": ["77.88.8.8", "77.88.8.1"]},
"proxies": proxies,
"proxy-providers": {"amnezia-keys": awg_prov, "vless-cluster": vless, **extra_prov},
"proxy-providers": {"amnezia-keys": awg_prov, "vless-cluster": vless, **extra_prov, **clients_prov},
"proxy-groups": [
# What traffic actually uses: the exit picked in BroV while it answers, "auto"
# when it doesn't (a pinned connection that dies no longer takes the Mac offline).
@@ -246,7 +253,8 @@ def main():
] + [
# Client networks: off (REJECT) until switched on in BroV.
# Client networks: first option = "off" (REJECT, or DIRECT for home).
{"name": f"{n}-sw", "type": "select", "proxies": [off, n]} for n, (_, _, off) in clients.items()
{"name": f"{n}-sw", "type": "select", "proxies": [off], "use": ["clients"], "filter": f"^{n}$"}
for n, (_, _, off) in clients.items()
],
"rules": rules,
}
+31 -3
View File
@@ -12,6 +12,8 @@ allows exactly these operations:
tun {on} traffic capture on (fresh core start) / off; remembered
add_key {text} vpn:// Amnezia key (checked by gen.py) or a vless:// link: stored, core updated
refresh {} re-download the VLESS subscription now (new cluster nodes), no reload
rebind {} after a network change: re-create the Amnezia and client WireGuard
tunnels so they bind to the new address (other connections stay)
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)
unhide {name} put it back
@@ -84,7 +86,7 @@ def cmd_state(_):
for name, p in proxies.items():
keep[name] = {"now": p.get("now"), "all": p.get("all"), "history": (p.get("history") or [])[-1:]}
providers = {}
for prov in ("vless-cluster", "vless-keys", "amnezia-keys"):
for prov in ("vless-cluster", "vless-keys", "amnezia-keys", "clients"):
try:
lst = api("GET", "/providers/proxies/" + prov).get("proxies", [])
except Exception:
@@ -111,7 +113,8 @@ def cmd_delay(r):
return {"ok": True, "delays": api("GET", "/group/%s/delay?%s" % (q(r["group"]), test), timeout=10)}
if r.get("proxy") in CLIENT_TUNNELS:
try:
d = api("GET", "/proxies/%s/delay?%s" % (q(r["proxy"]), test), timeout=10).get("delay", 0)
d = api("GET", "/providers/proxies/clients/%s/healthcheck?%s" % (q(r["proxy"]), test),
timeout=10).get("delay", 0)
except Exception:
d = 0
return {"ok": True, "delays": {r["proxy"]: d}}
@@ -395,6 +398,31 @@ def cmd_refresh(_):
"removed": sorted(before - set(after))}
def cmd_rebind(_):
"""mihomo's WireGuard outbounds keep their UDP socket bound to the local address they
started on: after moving from one Wi-Fi to another (Planet9 → Saga) they keep sending
from the old address and every Amnezia / client tunnel looks dead. A provider whose file
changed is re-parsed, so its tunnels are created anew and bind to the current address."""
done = []
with gen_lock:
for prov, path in (("amnezia-keys", os.path.join(KEYS, "amnezia.yaml")),
("clients", os.path.join(KEYS, "clients.yaml"))):
if not os.path.isfile(path):
continue
body = [l for l in open(path).read().splitlines() if not l.startswith("# rebind ")]
tmp = path + ".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:
f.write("# rebind %d\n" % int(time.time()) + "\n".join(body) + "\n")
os.rename(tmp, path)
try:
api("PUT", "/providers/proxies/" + prov)
done.append(prov)
except Exception:
pass
return {"ok": True, "rebound": done}
def cmd_hide(r):
return change_hidden(r.get("name"), True)
@@ -405,7 +433,7 @@ def cmd_unhide(r):
COMMANDS = {"state": cmd_state, "select": cmd_select, "delay": cmd_delay, "tun": cmd_tun,
"add_key": cmd_add_key, "hide": cmd_hide, "unhide": cmd_unhide,
"refresh": cmd_refresh}
"refresh": cmd_refresh, "rebind": cmd_rebind}
# MARK: - Socket server