Net core: clean restart when the Mac changes networks, instead of a leaky rebind
Re-creating the WireGuard tunnels through a provider reload leaked every old tunnel: on 16.10 the core held 652 UDP sockets to the Amnezia servers and 677 MB, and the servers stopped answering the handshake flood. netctl rebind is now a clean core restart (the move drops the TCP connections anyway), and BroV calls it only when the IPv4 address of a physical adapter actually changed, not on every path update. 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, refresh, rebind (after a network change: re-creates the WireGuard tunnels, which otherwise stay bound to the old address).
|
||||
- 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 (the Mac changed networks: clean core restart — WireGuard tunnels stay bound to the old address, and re-creating them via a provider reload leaked sockets).
|
||||
- `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.
|
||||
|
||||
|
||||
@@ -318,15 +318,42 @@ final class NetCore: ObservableObject {
|
||||
pathMonitor = m
|
||||
}
|
||||
|
||||
/// IPv4 addresses of the physical adapters (en*), sorted: what "another network" means.
|
||||
private var lastAddresses: String?
|
||||
|
||||
private static func physicalAddresses() -> String {
|
||||
var out: [String] = []
|
||||
var ifap: UnsafeMutablePointer<ifaddrs>?
|
||||
guard getifaddrs(&ifap) == 0, let first = ifap else { return "" }
|
||||
defer { freeifaddrs(ifap) }
|
||||
var p: UnsafeMutablePointer<ifaddrs>? = first
|
||||
while let cur = p {
|
||||
let name = String(cString: cur.pointee.ifa_name)
|
||||
if name.hasPrefix("en"), let sa = cur.pointee.ifa_addr, sa.pointee.sa_family == UInt8(AF_INET) {
|
||||
var host = [CChar](repeating: 0, count: Int(NI_MAXHOST))
|
||||
if getnameinfo(sa, socklen_t(sa.pointee.sa_len), &host, socklen_t(host.count), nil, 0, NI_NUMERICHOST) == 0 {
|
||||
out.append(name + "=" + String(cString: host))
|
||||
}
|
||||
}
|
||||
p = cur.pointee.ifa_next
|
||||
}
|
||||
return out.sorted().joined(separator: ",")
|
||||
}
|
||||
|
||||
private func networkChanged() {
|
||||
recheckTask?.cancel()
|
||||
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))
|
||||
let now = Self.physicalAddresses()
|
||||
let moved = lastAddresses != nil && now != lastAddresses && !now.isEmpty
|
||||
lastAddresses = now
|
||||
if moved {
|
||||
// Another network: the WireGuard tunnels (Amnezia, clients) are still bound to
|
||||
// the old address — a clean core restart re-binds them without leaking.
|
||||
_ = await call(["cmd": "rebind"], timeout: 30)
|
||||
try? await Task.sleep(for: .seconds(6))
|
||||
}
|
||||
_ = await call(["cmd": "delay", "group": "auto"], timeout: 15)
|
||||
_ = await call(["cmd": "delay", "group": "amnezia"], timeout: 15)
|
||||
_ = await call(["cmd": "delay", "group": "exit"], timeout: 15)
|
||||
|
||||
+14
-23
@@ -12,8 +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)
|
||||
rebind {} the Mac moved to another network: clean core restart (WireGuard
|
||||
tunnels bind to the new address, nothing leaks)
|
||||
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
|
||||
@@ -419,36 +419,27 @@ def cmd_refresh(_):
|
||||
|
||||
|
||||
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)
|
||||
"""After the Mac moved to another network (its address changed): a clean core restart.
|
||||
mihomo's WireGuard outbounds stay bound to the old address; re-creating them through a
|
||||
provider reload leaked every old tunnel (16.10: 652 UDP sockets, 677 MB, the Amnezia
|
||||
servers stopped answering the handshake flood). A restart leaves nothing behind, and
|
||||
the move has dropped the open TCP connections anyway. TUN comes back as tun.json says;
|
||||
the DNS follows the newly active adapter."""
|
||||
subprocess.run(["/bin/launchctl", "kickstart", "-k", "system/" + CORE_LABEL], capture_output=True, timeout=20)
|
||||
for _ in range(40):
|
||||
time.sleep(0.25)
|
||||
try:
|
||||
api("PUT", "/providers/proxies/" + prov)
|
||||
done.append(prov)
|
||||
api("GET", "/configs", timeout=2)
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
# A new network may run on another adapter (Wi-Fi → Ethernet): its DNS goes into the
|
||||
# core too, while capture is on.
|
||||
try:
|
||||
with open(os.path.join(CORE, "tun.json")) as f:
|
||||
if json.load(f).get("on", True):
|
||||
dns_to_core()
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
return {"ok": True, "rebound": done}
|
||||
return {"ok": True, "restarted": True}
|
||||
|
||||
|
||||
def cmd_hide(r):
|
||||
|
||||
Reference in New Issue
Block a user