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:
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user