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:
@@ -29,7 +29,7 @@ DerivedData must stay outside ~/Documents (iCloud adds Finder attributes and cod
|
||||
|
||||
## Network core (globe 🌐 in the header)
|
||||
- mihomo runs as root: LaunchDaemon `local.maksar.brov.netd`, binary + config + keys + API secret in `/Library/Application Support/BroV/` (root, 0700). Nothing user-writable is read by root.
|
||||
- BroV never sees the config or the API secret: it talks to the narrow root helper `scripts/netcore/netctl.py` (LaunchDaemon `local.maksar.brov.netctl`, socket `/var/run/brov-netctl.sock`, only the installing user) — commands: state, select, delay, tun (on = clean core restart, refused while the AmneziaVPN app is open; also points the Mac DNS into the core), add_key, hide, unhide.
|
||||
- BroV never sees the config or the API secret: it talks to the narrow root helper `scripts/netcore/netctl.py` (LaunchDaemon `local.maksar.brov.netctl`, socket `/var/run/brov-netctl.sock`, only the installing user) — commands: state, select, delay, tun (on = clean core restart, refused while the AmneziaVPN app is open; also points the Mac DNS into the core), add_key, hide, unhide, refresh, rebind (after a network change: re-creates the WireGuard tunnels, which otherwise stay bound to the old address).
|
||||
- `scripts/netcore/gen.py` builds the config (Amnezia keys → provider `keys/amnezia.yaml`, single vless:// links added in BroV → provider `vless-keys` from `keys/vless.txt`, WireGuard clients, VLESS subscription). Install/update: `sudo sh scripts/netcore/install.sh` (verifies the mihomo SHA256, migrates keys). Never commit keys, configs or the guide (`~/.brov-secrets`).
|
||||
- Reloading the whole core config drops every connection (including this chat); group switches and provider reloads don't.
|
||||
|
||||
|
||||
@@ -300,9 +300,10 @@ final class NetCore: ObservableObject {
|
||||
// MARK: Network changes
|
||||
//
|
||||
// Moving between home / Saga / Planet9 Wi-Fi, waking from sleep or AmneziaVPN going on
|
||||
// and off leaves the WireGuard tunnels talking from an address that no longer exists.
|
||||
// Re-test everything a few seconds after the change so "auto" and "exit" re-pick at
|
||||
// once instead of at the next scheduled check.
|
||||
// and off leaves the WireGuard tunnels talking from an address that no longer exists
|
||||
// (seen: Amnezia sockets still on 192.168.68.x after moving to Saga). A few seconds after
|
||||
// the change the tunnels are re-created (netctl rebind), then everything is re-tested so
|
||||
// "auto" and "exit" re-pick at once.
|
||||
|
||||
private var pathMonitor: NWPathMonitor?
|
||||
private var recheckTask: Task<Void, Never>?
|
||||
@@ -322,6 +323,10 @@ final class NetCore: ObservableObject {
|
||||
recheckTask = Task {
|
||||
try? await Task.sleep(for: .seconds(4))
|
||||
guard !Task.isCancelled else { return }
|
||||
// WireGuard tunnels (Amnezia, clients) stay bound to the old network's address:
|
||||
// re-create them first, then re-test.
|
||||
_ = await call(["cmd": "rebind"], timeout: 20)
|
||||
try? await Task.sleep(for: .seconds(2))
|
||||
_ = await call(["cmd": "delay", "group": "auto"], timeout: 15)
|
||||
_ = await call(["cmd": "delay", "group": "amnezia"], timeout: 15)
|
||||
_ = await call(["cmd": "delay", "group": "exit"], timeout: 15)
|
||||
|
||||
+11
-3
@@ -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,
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user