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)
|
## 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.
|
- 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`).
|
- `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.
|
- 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
|
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() {
|
private func networkChanged() {
|
||||||
recheckTask?.cancel()
|
recheckTask?.cancel()
|
||||||
recheckTask = Task {
|
recheckTask = Task {
|
||||||
try? await Task.sleep(for: .seconds(4))
|
try? await Task.sleep(for: .seconds(4))
|
||||||
guard !Task.isCancelled else { return }
|
guard !Task.isCancelled else { return }
|
||||||
// WireGuard tunnels (Amnezia, clients) stay bound to the old network's address:
|
let now = Self.physicalAddresses()
|
||||||
// re-create them first, then re-test.
|
let moved = lastAddresses != nil && now != lastAddresses && !now.isEmpty
|
||||||
_ = await call(["cmd": "rebind"], timeout: 20)
|
lastAddresses = now
|
||||||
try? await Task.sleep(for: .seconds(2))
|
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": "auto"], timeout: 15)
|
||||||
_ = await call(["cmd": "delay", "group": "amnezia"], timeout: 15)
|
_ = await call(["cmd": "delay", "group": "amnezia"], timeout: 15)
|
||||||
_ = await call(["cmd": "delay", "group": "exit"], timeout: 15)
|
_ = await call(["cmd": "delay", "group": "exit"], timeout: 15)
|
||||||
|
|||||||
+17
-26
@@ -12,8 +12,8 @@ allows exactly these operations:
|
|||||||
tun {on} traffic capture on (fresh core start) / off; remembered
|
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
|
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
|
refresh {} re-download the VLESS subscription now (new cluster nodes), no reload
|
||||||
rebind {} after a network change: re-create the Amnezia and client WireGuard
|
rebind {} the Mac moved to another network: clean core restart (WireGuard
|
||||||
tunnels so they bind to the new address (other connections stay)
|
tunnels bind to the new address, nothing leaks)
|
||||||
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)
|
||||||
unhide {name} put it back
|
unhide {name} put it back
|
||||||
@@ -419,36 +419,27 @@ def cmd_refresh(_):
|
|||||||
|
|
||||||
|
|
||||||
def cmd_rebind(_):
|
def cmd_rebind(_):
|
||||||
"""mihomo's WireGuard outbounds keep their UDP socket bound to the local address they
|
"""After the Mac moved to another network (its address changed): a clean core restart.
|
||||||
started on: after moving from one Wi-Fi to another (Planet9 → Saga) they keep sending
|
mihomo's WireGuard outbounds stay bound to the old address; re-creating them through a
|
||||||
from the old address and every Amnezia / client tunnel looks dead. A provider whose file
|
provider reload leaked every old tunnel (16.10: 652 UDP sockets, 677 MB, the Amnezia
|
||||||
changed is re-parsed, so its tunnels are created anew and bind to the current address."""
|
servers stopped answering the handshake flood). A restart leaves nothing behind, and
|
||||||
done = []
|
the move has dropped the open TCP connections anyway. TUN comes back as tun.json says;
|
||||||
with gen_lock:
|
the DNS follows the newly active adapter."""
|
||||||
for prov, path in (("amnezia-keys", os.path.join(KEYS, "amnezia.yaml")),
|
subprocess.run(["/bin/launchctl", "kickstart", "-k", "system/" + CORE_LABEL], capture_output=True, timeout=20)
|
||||||
("clients", os.path.join(KEYS, "clients.yaml"))):
|
for _ in range(40):
|
||||||
if not os.path.isfile(path):
|
time.sleep(0.25)
|
||||||
continue
|
try:
|
||||||
body = [l for l in open(path).read().splitlines() if not l.startswith("# rebind ")]
|
api("GET", "/configs", timeout=2)
|
||||||
tmp = path + ".tmp"
|
break
|
||||||
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600)
|
except Exception:
|
||||||
with os.fdopen(fd, "w") as f:
|
pass
|
||||||
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
|
|
||||||
# A new network may run on another adapter (Wi-Fi → Ethernet): its DNS goes into the
|
|
||||||
# core too, while capture is on.
|
|
||||||
try:
|
try:
|
||||||
with open(os.path.join(CORE, "tun.json")) as f:
|
with open(os.path.join(CORE, "tun.json")) as f:
|
||||||
if json.load(f).get("on", True):
|
if json.load(f).get("on", True):
|
||||||
dns_to_core()
|
dns_to_core()
|
||||||
except (OSError, ValueError):
|
except (OSError, ValueError):
|
||||||
pass
|
pass
|
||||||
return {"ok": True, "rebound": done}
|
return {"ok": True, "restarted": True}
|
||||||
|
|
||||||
|
|
||||||
def cmd_hide(r):
|
def cmd_hide(r):
|
||||||
|
|||||||
Reference in New Issue
Block a user