This commit is contained in:
jdl
2026-06-07 18:12:44 +02:00
parent cad200b9cc
commit b8344a20b9
37 changed files with 568 additions and 981 deletions

View File

@@ -2,7 +2,9 @@ package peer
import (
"log"
"math"
"net/netip"
"time"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
@@ -19,6 +21,7 @@ func (a *App) onAddPeer(p HubPeer) {
IsPublic: p.IsPublic,
Endpoint4: p.EndpointV4,
Endpoint6: p.EndpointV6,
RTT: time.Duration(math.MaxInt64) * time.Nanosecond,
Role: roleFor(a.isPublic, a.vpnIP, p),
}
@@ -58,7 +61,9 @@ func (a *App) onRemovePeer(key wgtypes.Key) {
// switchActiveRelay promotes the lowest-latency relay peer to active.
func (a *App) switchActiveRelay() {
if a.relay != nil {
a.devAddDirect(a.relay, a.relay.WGEndpoint())
// If we have a relay, it's public, so should go back to being a direct
// peer - this will convert it's /24 to a /32.
a.devAddDirect(a.relay, a.relay.PreferredEndpoint())
a.relay = nil
}
@@ -68,7 +73,7 @@ func (a *App) switchActiveRelay() {
continue
}
if best == nil || betterRelay(p, best) {
if best == nil || p.RTT < best.RTT {
best = p
}
}
@@ -77,23 +82,10 @@ func (a *App) switchActiveRelay() {
return
}
a.devSetRelay(best, best.WGEndpoint())
a.devSetRelay(best, best.PreferredEndpoint())
a.relay = best
}
// TODO: Why not < ??
// betterRelay reports whether a is a better relay candidate than b.
// Prefers lower RTT; treats zero RTT (no measurement yet) as worst case.
func betterRelay(a, b *Peer) bool {
if a.RTT == 0 {
return false
}
if b.RTT == 0 {
return true
}
return a.RTT < b.RTT
}
func preferredEndpoint(v4, v6 netip.AddrPort) netip.AddrPort {
if v4.IsValid() {
return v4