hostmap.go 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169
  1. package nebula
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "hash/fnv"
  8. "log/slog"
  9. "net"
  10. "net/netip"
  11. "slices"
  12. "sync"
  13. "sync/atomic"
  14. "time"
  15. "github.com/gaissmai/bart"
  16. "github.com/rcrowley/go-metrics"
  17. "github.com/slackhq/nebula/cert"
  18. "github.com/slackhq/nebula/config"
  19. "github.com/slackhq/nebula/header"
  20. "github.com/slackhq/nebula/logging"
  21. )
  22. const defaultPromoteEvery = 1000 // Count of packets sent before we try moving a tunnel to a preferred underlay ip address
  23. const defaultReQueryEvery = 5000 // Count of packets sent before re-querying a hostinfo to the lighthouse
  24. const defaultReQueryWait = time.Minute // Minimum amount of seconds to wait before re-querying a hostinfo the lighthouse. Evaluated every ReQueryEvery
  25. const MaxRemotes = 10
  26. // MaxHostInfosPerVpnIp is the max number of hostinfos we will track for a given vpn ip
  27. // 5 allows for an initial handshake and each host pair re-handshaking twice
  28. const MaxHostInfosPerVpnIp = 5
  29. // How long we should prevent roaming back to the previous IP.
  30. // This helps prevent flapping due to packets already in flight
  31. const RoamingSuppressSeconds = 2
  32. const (
  33. Requested = iota
  34. PeerRequested
  35. Established
  36. Disestablished
  37. )
  38. const (
  39. Unknowntype = iota
  40. ForwardingType
  41. TerminalType
  42. )
  43. type Relay struct {
  44. Type int
  45. State int
  46. LocalIndex uint32
  47. RemoteIndex uint32
  48. PeerAddr netip.Addr
  49. }
  50. type HostMap struct {
  51. sync.RWMutex //Because we concurrently read and write to our maps
  52. Indexes map[uint32]*HostInfo
  53. Relays map[uint32]*HostInfo // Maps a Relay IDX to a Relay HostInfo object
  54. RemoteIndexes map[uint32]*HostInfo
  55. // Hosts maps a vpn address to its primary hostinfo, one entry per address we hold a tunnel
  56. // for. moreHosts only has an entry while an address is held by 2 or more hostinfos and stores
  57. // the full most-recent-first list; moreHosts[a][0] is always the same hostinfo as Hosts[a].
  58. // Each address gets its own independent list, so a hostinfo owning multiple addresses can
  59. // never corrupt another address's ordering the way the old shared next/prev chain could.
  60. // Entries in moreHosts are only ever written by unlockedSetHostsForAddr; Hosts is written
  61. // directly only in the single-hostinfo fast paths where moreHosts is known to have no entry,
  62. // and unlockedDeleteHostInfo swaps either map for a fresh one when it fully drains.
  63. Hosts map[netip.Addr]*HostInfo
  64. moreHosts map[netip.Addr][]*HostInfo
  65. preferredRanges atomic.Pointer[[]netip.Prefix]
  66. l *slog.Logger
  67. }
  68. // For synchronization, treat the pointed-to Relay struct as immutable. To edit the Relay
  69. // struct, make a copy of an existing value, edit the fileds in the copy, and
  70. // then store a pointer to the new copy in both realyForBy* maps.
  71. type RelayState struct {
  72. sync.RWMutex
  73. relays []netip.Addr // Ordered set of VpnAddrs of Hosts to use as relays to access this peer
  74. // For data race avoidance, the contents of a *Relay are treated immutably. To update a *Relay, copy the existing data,
  75. // modify what needs to be updated, and store the new modified copy in the relayForByIp and relayForByIdx maps (with
  76. // the RelayState Lock held)
  77. relayForByAddr map[netip.Addr]*Relay // Maps vpnAddr of peers for which this HostInfo is a relay to some Relay info
  78. relayForByIdx map[uint32]*Relay // Maps a local index to some Relay info
  79. }
  80. func (rs *RelayState) DeleteRelay(ip netip.Addr) {
  81. rs.Lock()
  82. defer rs.Unlock()
  83. for idx, val := range rs.relays {
  84. if val == ip {
  85. rs.relays = append(rs.relays[:idx], rs.relays[idx+1:]...)
  86. return
  87. }
  88. }
  89. }
  90. func (rs *RelayState) UpdateRelayForByIpState(vpnIp netip.Addr, state int) {
  91. rs.Lock()
  92. defer rs.Unlock()
  93. if r, ok := rs.relayForByAddr[vpnIp]; ok {
  94. newRelay := *r
  95. newRelay.State = state
  96. rs.relayForByAddr[newRelay.PeerAddr] = &newRelay
  97. rs.relayForByIdx[newRelay.LocalIndex] = &newRelay
  98. }
  99. }
  100. func (rs *RelayState) UpdateRelayForByIdxState(idx uint32, state int) {
  101. rs.Lock()
  102. defer rs.Unlock()
  103. if r, ok := rs.relayForByIdx[idx]; ok {
  104. newRelay := *r
  105. newRelay.State = state
  106. rs.relayForByAddr[newRelay.PeerAddr] = &newRelay
  107. rs.relayForByIdx[newRelay.LocalIndex] = &newRelay
  108. }
  109. }
  110. func (rs *RelayState) CopyAllRelayFor() []*Relay {
  111. rs.RLock()
  112. defer rs.RUnlock()
  113. ret := make([]*Relay, 0, len(rs.relayForByIdx))
  114. for _, r := range rs.relayForByIdx {
  115. ret = append(ret, r)
  116. }
  117. return ret
  118. }
  119. func (rs *RelayState) GetRelayForByAddr(addr netip.Addr) (*Relay, bool) {
  120. rs.RLock()
  121. defer rs.RUnlock()
  122. r, ok := rs.relayForByAddr[addr]
  123. return r, ok
  124. }
  125. func (rs *RelayState) InsertRelayTo(ip netip.Addr) {
  126. rs.Lock()
  127. defer rs.Unlock()
  128. if !slices.Contains(rs.relays, ip) {
  129. rs.relays = append(rs.relays, ip)
  130. }
  131. }
  132. func (rs *RelayState) CopyRelayIps() []netip.Addr {
  133. rs.RLock()
  134. defer rs.RUnlock()
  135. ret := make([]netip.Addr, len(rs.relays))
  136. copy(ret, rs.relays)
  137. return ret
  138. }
  139. func (rs *RelayState) CopyRelayForIps() []netip.Addr {
  140. rs.RLock()
  141. defer rs.RUnlock()
  142. currentRelays := make([]netip.Addr, 0, len(rs.relayForByAddr))
  143. for relayIp := range rs.relayForByAddr {
  144. currentRelays = append(currentRelays, relayIp)
  145. }
  146. return currentRelays
  147. }
  148. func (rs *RelayState) CopyRelayForIdxs() []uint32 {
  149. rs.RLock()
  150. defer rs.RUnlock()
  151. ret := make([]uint32, 0, len(rs.relayForByIdx))
  152. for i := range rs.relayForByIdx {
  153. ret = append(ret, i)
  154. }
  155. return ret
  156. }
  157. func (rs *RelayState) CompleteRelayByIP(vpnIp netip.Addr, remoteIdx uint32) bool {
  158. rs.Lock()
  159. defer rs.Unlock()
  160. r, ok := rs.relayForByAddr[vpnIp]
  161. if !ok {
  162. return false
  163. }
  164. newRelay := *r
  165. newRelay.State = Established
  166. newRelay.RemoteIndex = remoteIdx
  167. rs.relayForByIdx[r.LocalIndex] = &newRelay
  168. rs.relayForByAddr[r.PeerAddr] = &newRelay
  169. return true
  170. }
  171. func (rs *RelayState) CompleteRelayByIdx(localIdx uint32, remoteIdx uint32) (*Relay, bool) {
  172. rs.Lock()
  173. defer rs.Unlock()
  174. r, ok := rs.relayForByIdx[localIdx]
  175. if !ok {
  176. return nil, false
  177. }
  178. newRelay := *r
  179. newRelay.State = Established
  180. newRelay.RemoteIndex = remoteIdx
  181. rs.relayForByIdx[r.LocalIndex] = &newRelay
  182. rs.relayForByAddr[r.PeerAddr] = &newRelay
  183. return &newRelay, true
  184. }
  185. func (rs *RelayState) QueryRelayForByIp(vpnIp netip.Addr) (*Relay, bool) {
  186. rs.RLock()
  187. defer rs.RUnlock()
  188. r, ok := rs.relayForByAddr[vpnIp]
  189. return r, ok
  190. }
  191. func (rs *RelayState) QueryRelayForByIdx(idx uint32) (*Relay, bool) {
  192. rs.RLock()
  193. defer rs.RUnlock()
  194. r, ok := rs.relayForByIdx[idx]
  195. return r, ok
  196. }
  197. func (rs *RelayState) InsertRelay(ip netip.Addr, idx uint32, r *Relay) {
  198. rs.Lock()
  199. defer rs.Unlock()
  200. rs.relayForByAddr[ip] = r
  201. rs.relayForByIdx[idx] = r
  202. }
  203. type NetworkType uint8
  204. const (
  205. NetworkTypeUnknown NetworkType = iota
  206. // NetworkTypeVPN is a network that overlaps one or more of the vpnNetworks in our certificate
  207. NetworkTypeVPN
  208. // NetworkTypeVPNPeer is a network that does not overlap one of our networks
  209. NetworkTypeVPNPeer
  210. // NetworkTypeUnsafe is a network from Certificate.UnsafeNetworks()
  211. NetworkTypeUnsafe
  212. )
  213. type HostInfo struct {
  214. remote atomic.Pointer[netip.AddrPort]
  215. remotes *RemoteList
  216. promoteCounter atomic.Uint32
  217. ConnectionState *ConnectionState
  218. remoteIndexId uint32
  219. localIndexId uint32
  220. // vpnAddrs is a list of vpn addresses assigned to this host that are within our own vpn networks
  221. // The host may have other vpn addresses that are outside our
  222. // vpn networks but were removed because they are not usable
  223. vpnAddrs []netip.Addr
  224. // networks is a combination of specific vpn addresses (not prefixes!) and full unsafe networks assigned to this host.
  225. networks *bart.Table[NetworkType]
  226. relayState RelayState
  227. // HandshakePacket records the packets used to create this hostinfo
  228. // We need these to avoid replayed handshake packets creating new hostinfos which causes churn
  229. HandshakePacket map[uint8][]byte
  230. // nextLHQuery is the earliest we can ask the lighthouse for new information.
  231. // This is used to limit lighthouse re-queries in chatty clients
  232. nextLHQuery atomic.Int64
  233. // lastRebindCount is the other side of Interface.rebindCount, if these values don't match then we need to ask LH
  234. // for a punch from the remote end of this tunnel. The goal being to prime their conntrack for our traffic just like
  235. // with a handshake
  236. lastRebindCount int8
  237. // lastHandshakeTime records the time the remote side told us about at the stage when the handshake was completed locally
  238. // Stage 1 packet will contain it if I am a responder, stage 2 packet if I am an initiator
  239. // This is used to avoid an attack where a handshake packet is replayed after some time
  240. lastHandshakeTime uint64
  241. lastRoam time.Time
  242. lastRoamRemote netip.AddrPort
  243. //TODO: in, out, and others might benefit from being an atomic.Int32. We could collapse connectionManager pendingDeletion, relayUsed, and in/out into this 1 thing
  244. in, out, pendingDeletion atomic.Bool
  245. // lastUsed tracks the last time ConnectionManager checked the tunnel and it was in use.
  246. // This value will be behind against actual tunnel utilization in the hot path.
  247. // This should only be used by the ConnectionManagers ticker routine.
  248. lastUsed time.Time
  249. // sockIdx is the index into Interface.writers of the socket every packet
  250. // on this tunnel egresses from (and, for lanes, arrives on). 0 for base
  251. // and vanilla tunnels — the zero value preserves stock behavior.
  252. sockIdx int
  253. // laneIndex is the owner's lane number for a lane tunnel; 0 for base.
  254. laneIndex uint16
  255. // laneOwned is true when we initiated this lane (it carries our TX data).
  256. laneOwned bool
  257. // parent points at the base tunnel a lane hangs off of; nil for base and
  258. // vanilla tunnels. Set before the lane is registered in hostmap.Indexes.
  259. parent *HostInfo
  260. // lanes is allocated on a base tunnel when multiport is enabled and the
  261. // peer advertised lane support; nil otherwise.
  262. lanes *laneState
  263. }
  264. // isLane reports whether this HostInfo is a lane tunnel rather than a base
  265. // (or vanilla) tunnel.
  266. func (i *HostInfo) isLane() bool {
  267. return i.parent != nil
  268. }
  269. // laneState hangs off a base HostInfo and tracks the multiport lane tunnels
  270. // associated with it. txLanes is read lock-free on the TX hot path; the Mutex
  271. // guards everything else.
  272. type laneState struct {
  273. sync.Mutex
  274. // peerPortCount/peerBasePort are the peer's advert from the base
  275. // handshake; portOffset is the per-pair rotation from lanePortOffset.
  276. // Lane i targets peerBasePort + ((i + portOffset) % peerPortCount).
  277. peerPortCount uint16
  278. peerBasePort uint16
  279. portOffset uint16
  280. // txLanes[i] is our established, initiator-owned lane for routine i, or
  281. // nil. Index 0 is always nil — the base tunnel is lane 0. A pointer is
  282. // only Stored once the lane's ConnectionState is fully populated, so a
  283. // data-plane routine that Loads non-nil always sees a usable tunnel.
  284. txLanes []atomic.Pointer[HostInfo]
  285. // Under Mutex: per-slot handshake-in-flight flag, consecutive failure
  286. // count, and earliest next attempt, driving ensureLanes' backoff.
  287. txPending []bool
  288. txFails []uint8
  289. txRetryAt []time.Time
  290. // Under Mutex: responder-side records of peer-owned lanes, capped by
  291. // same-laneIndex replacement.
  292. peerLanes []*HostInfo
  293. }
  294. func newLaneState(laneCount int, peerPortCount, peerBasePort, portOffset uint16) *laneState {
  295. return &laneState{
  296. peerPortCount: peerPortCount,
  297. peerBasePort: peerBasePort,
  298. portOffset: portOffset,
  299. txLanes: make([]atomic.Pointer[HostInfo], laneCount),
  300. txPending: make([]bool, laneCount),
  301. txFails: make([]uint8, laneCount),
  302. txRetryAt: make([]time.Time, laneCount),
  303. }
  304. }
  305. // laneTargetPort returns the peer port that owned lane i handshakes to and
  306. // egresses toward. The caller must ensure peerPortCount != 0.
  307. func (ls *laneState) laneTargetPort(i int) uint16 {
  308. return ls.peerBasePort + uint16((i+int(ls.portOffset))%int(ls.peerPortCount))
  309. }
  310. // lanePortOffset returns the rotation applied to this pair's lane target
  311. // ports, in [0, peerPortCount). Without it every low-routine peer would aim
  312. // its few lanes at a big peer's first few ports, concentrating the big
  313. // peer's receive work on a couple of sockets; the hash spreads pairs across
  314. // the whole advertised range.
  315. //
  316. // Both sides hash the same sorted vpn-address pair and the higher address
  317. // negates the result, so when port counts match the two sides' rotations
  318. // cancel: our lane i's 4-tuple is still the reverse of a peer-owned lane's,
  319. // and each outbound lane handshake opens the conntrack entry its partner
  320. // arrives through. (The one lane a nonzero rotation lands on the peer's base
  321. // port has no partner lane; behind a port-restricted NAT it may not form and
  322. // its routine rides the base tunnel — the standard lane fallback.)
  323. func lanePortOffset(myAddr, peerAddr netip.Addr, peerPortCount uint16) uint16 {
  324. if peerPortCount == 0 {
  325. return 0
  326. }
  327. lo, hi := myAddr, peerAddr
  328. if hi.Less(lo) {
  329. lo, hi = hi, lo
  330. }
  331. h := fnv.New32a()
  332. b := lo.As16()
  333. h.Write(b[:])
  334. b = hi.As16()
  335. h.Write(b[:])
  336. o := uint16(h.Sum32() % uint32(peerPortCount))
  337. if myAddr == hi {
  338. o = (peerPortCount - o) % peerPortCount
  339. }
  340. return o
  341. }
  342. const (
  343. laneRetryBase = 5 * time.Second
  344. laneRetryMax = 60 * time.Second
  345. )
  346. // noteLaneFailure marks lane slot i as empty and pushes the next attempt out
  347. // with exponential backoff. Called when an owned lane dies or its handshake
  348. // times out.
  349. func (ls *laneState) noteLaneFailure(i int) {
  350. if i < 0 || i >= len(ls.txPending) {
  351. return
  352. }
  353. ls.Lock()
  354. ls.txPending[i] = false
  355. if ls.txFails[i] < 200 { // just avoid wrapping; the delay caps far earlier
  356. ls.txFails[i]++
  357. }
  358. d := laneRetryBase << min(ls.txFails[i], 4)
  359. if d > laneRetryMax {
  360. d = laneRetryMax
  361. }
  362. ls.txRetryAt[i] = time.Now().Add(d)
  363. ls.Unlock()
  364. }
  365. // noteOwnedLaneDeath detaches an established owned lane from its slot
  366. // (identity-checked, so a raced re-establishment is never clobbered) and
  367. // applies failure backoff.
  368. func (ls *laneState) noteOwnedLaneDeath(lane *HostInfo) {
  369. i := int(lane.laneIndex)
  370. if i >= len(ls.txLanes) {
  371. return
  372. }
  373. ls.txLanes[i].CompareAndSwap(lane, nil)
  374. ls.noteLaneFailure(i)
  375. }
  376. // removePeerLane drops a responder-side lane record by identity.
  377. func (ls *laneState) removePeerLane(lane *HostInfo) {
  378. ls.Lock()
  379. for n, h := range ls.peerLanes {
  380. if h == lane {
  381. ls.peerLanes = append(ls.peerLanes[:n], ls.peerLanes[n+1:]...)
  382. break
  383. }
  384. }
  385. ls.Unlock()
  386. }
  387. // snapshotLanes returns every lane hostinfo currently attached, used by the
  388. // base-delete cascade. Taken under the lock and returned as a copy so the
  389. // caller can delete without holding it.
  390. func (ls *laneState) snapshotLanes() []*HostInfo {
  391. ls.Lock()
  392. defer ls.Unlock()
  393. out := make([]*HostInfo, 0, len(ls.txLanes)+len(ls.peerLanes))
  394. for n := range ls.txLanes {
  395. if h := ls.txLanes[n].Load(); h != nil {
  396. out = append(out, h)
  397. }
  398. }
  399. out = append(out, ls.peerLanes...)
  400. return out
  401. }
  402. type ViaSender struct {
  403. UdpAddr netip.AddrPort
  404. relayHI *HostInfo // relayHI is the host info object of the relay
  405. relay *Relay // relay contains the rest of the relay information, including the PeerIP of the host trying to communicate with us.
  406. IsRelayed bool // IsRelayed is true if the packet was sent through a relay
  407. // SockIdx is the local socket (Interface.writers index) the packet
  408. // arrived on. Replies that must originate from the same 4-tuple egress
  409. // f.writers[SockIdx].
  410. SockIdx int
  411. }
  412. func (v ViaSender) String() string {
  413. if v.IsRelayed {
  414. return fmt.Sprintf("%s (relayed)", v.UdpAddr)
  415. }
  416. return v.UdpAddr.String()
  417. }
  418. func (v ViaSender) MarshalJSON() ([]byte, error) {
  419. if v.IsRelayed {
  420. return json.Marshal(m{"relay": v.UdpAddr})
  421. }
  422. return json.Marshal(m{"direct": v.UdpAddr})
  423. }
  424. type cachedPacket struct {
  425. messageType header.MessageType
  426. messageSubType header.MessageSubType
  427. callback packetCallback
  428. packet []byte
  429. }
  430. type packetCallback func(t header.MessageType, st header.MessageSubType, h *HostInfo, p, nb, out []byte)
  431. type cachedPacketMetrics struct {
  432. sent metrics.Counter
  433. dropped metrics.Counter
  434. }
  435. func NewHostMapFromConfig(l *slog.Logger, c *config.C) *HostMap {
  436. hm := newHostMap(l)
  437. hm.reload(c, true)
  438. c.RegisterReloadCallback(func(c *config.C) {
  439. hm.reload(c, false)
  440. })
  441. l.Info("Main HostMap created", "preferredRanges", hm.GetPreferredRanges())
  442. return hm
  443. }
  444. func newHostMap(l *slog.Logger) *HostMap {
  445. return &HostMap{
  446. Indexes: map[uint32]*HostInfo{},
  447. Relays: map[uint32]*HostInfo{},
  448. RemoteIndexes: map[uint32]*HostInfo{},
  449. Hosts: map[netip.Addr]*HostInfo{},
  450. moreHosts: map[netip.Addr][]*HostInfo{},
  451. l: l,
  452. }
  453. }
  454. func (hm *HostMap) reload(c *config.C, initial bool) {
  455. if initial || c.HasChanged("preferred_ranges") {
  456. var preferredRanges []netip.Prefix
  457. rawPreferredRanges := c.GetStringSlice("preferred_ranges", []string{})
  458. for _, rawPreferredRange := range rawPreferredRanges {
  459. preferredRange, err := netip.ParsePrefix(rawPreferredRange)
  460. if err != nil {
  461. hm.l.Warn("Failed to parse preferred ranges, ignoring",
  462. "error", err,
  463. "range", rawPreferredRanges,
  464. )
  465. continue
  466. }
  467. preferredRanges = append(preferredRanges, preferredRange)
  468. }
  469. oldRanges := hm.preferredRanges.Swap(&preferredRanges)
  470. if !initial {
  471. hm.l.Info("preferred_ranges changed",
  472. "oldPreferredRanges", *oldRanges,
  473. "newPreferredRanges", preferredRanges,
  474. )
  475. }
  476. }
  477. }
  478. // EmitStats reports host, index, and relay counts to the stats collection system
  479. func (hm *HostMap) EmitStats() {
  480. hm.RLock()
  481. hostLen := len(hm.Hosts)
  482. indexLen := len(hm.Indexes)
  483. remoteIndexLen := len(hm.RemoteIndexes)
  484. relaysLen := len(hm.Relays)
  485. hm.RUnlock()
  486. metrics.GetOrRegisterGauge("hostmap.main.hosts", nil).Update(int64(hostLen))
  487. metrics.GetOrRegisterGauge("hostmap.main.indexes", nil).Update(int64(indexLen))
  488. metrics.GetOrRegisterGauge("hostmap.main.remoteIndexes", nil).Update(int64(remoteIndexLen))
  489. metrics.GetOrRegisterGauge("hostmap.main.relayIndexes", nil).Update(int64(relaysLen))
  490. }
  491. // unlockedSetHostsForAddr stores the per-address hostinfo list (list[0] is the primary). An empty
  492. // list removes the address. This is the one place Hosts and moreHosts are written together, keep
  493. // it that way. Callers must hold the write lock.
  494. func (hm *HostMap) unlockedSetHostsForAddr(addr netip.Addr, list []*HostInfo) {
  495. if len(list) == 0 {
  496. delete(hm.Hosts, addr)
  497. delete(hm.moreHosts, addr)
  498. return
  499. }
  500. hm.Hosts[addr] = list[0]
  501. if len(list) > 1 {
  502. hm.moreHosts[addr] = list
  503. } else {
  504. delete(hm.moreHosts, addr)
  505. }
  506. }
  507. // unlockedGetHostList returns every hostinfo holding addr, primary first, or nil if we have no
  508. // tunnel for addr. The common single-hostinfo case builds a fresh one element list, so keep this
  509. // off the packet hot path; the primary is a direct Hosts read. Callers must hold the lock (read
  510. // or write).
  511. func (hm *HostMap) unlockedGetHostList(addr netip.Addr) []*HostInfo {
  512. if list, ok := hm.moreHosts[addr]; ok {
  513. return list
  514. }
  515. if h, ok := hm.Hosts[addr]; ok {
  516. return []*HostInfo{h}
  517. }
  518. return nil
  519. }
  520. // removeHostInfo returns list with hi removed (order preserved), or list unchanged if hi is
  521. // absent. It deletes in place: every mutator holds the hostmap write lock and no reader ever
  522. // retains a slice across a mutation (readers iterate under RLock), so there is no snapshot to
  523. // invalidate.
  524. func removeHostInfo(list []*HostInfo, hi *HostInfo) []*HostInfo {
  525. idx := slices.Index(list, hi)
  526. if idx < 0 {
  527. return list
  528. }
  529. return slices.Delete(list, idx, idx+1)
  530. }
  531. // DeleteHostInfo will fully unlink the hostinfo and return true if no other hostinfo still holds
  532. // any of its vpn addrs, meaning we no longer have a tunnel to the peer
  533. func (hm *HostMap) DeleteHostInfo(hostinfo *HostInfo) bool {
  534. // Delete the host itself, ensuring it's not modified anymore
  535. hm.Lock()
  536. final := hm.unlockedDeleteHostInfo(hostinfo)
  537. hm.Unlock()
  538. return final
  539. }
  540. func (hm *HostMap) MakePrimary(hostinfo *HostInfo) {
  541. hm.Lock()
  542. defer hm.Unlock()
  543. hm.unlockedMakePrimary(hostinfo)
  544. }
  545. // unlockedMakePrimary reports whether hostinfo is (now) the primary for each of its addresses,
  546. // false only when it is no longer in the hostmap at all.
  547. func (hm *HostMap) unlockedMakePrimary(hostinfo *HostInfo) bool {
  548. // A lane must never become a Hosts primary: it would start carrying all
  549. // traffic for the peer and become a relay candidate.
  550. if hostinfo.isLane() {
  551. return false
  552. }
  553. // A hostinfo that is no longer in the hostmap must not be re-inserted here. Callers can race
  554. // tunnel teardown, deciding to promote under the read lock and only taking the write lock
  555. // after a delete fully unlinked the hostinfo (connection manager swapPrimary, AddRelay). Every
  556. // live hostinfo is registered in Indexes by unlockedAddHostInfo, so this is a membership test.
  557. if hm.Indexes[hostinfo.localIndexId] != hostinfo {
  558. return false
  559. }
  560. // Move hostinfo to the front (primary) of each of its address lists. The lists are
  561. // independent per address, so this can never leave a dangling entry the way promoting
  562. // against a single shared chain could.
  563. for _, addr := range hostinfo.vpnAddrs {
  564. if hm.Hosts[addr] == hostinfo {
  565. // Already primary for this address, the list is already in the right order
  566. continue
  567. }
  568. list := removeHostInfo(hm.unlockedGetHostList(addr), hostinfo)
  569. list = append([]*HostInfo{hostinfo}, list...)
  570. hm.unlockedSetHostsForAddr(addr, list)
  571. }
  572. return true
  573. }
  574. // unlockedDeleteHostInfo removes hostinfo from every one of its address lists and from the index
  575. // maps. It returns true if this was the last hostinfo for all of its addresses (we no longer have
  576. // any tunnel to the peer), which the caller uses to decide whether to clear learned lighthouse
  577. // state and disestablish relays.
  578. func (hm *HostMap) unlockedDeleteHostInfo(hostinfo *HostInfo) bool {
  579. if hostinfo.isLane() {
  580. return hm.unlockedDeleteLane(hostinfo)
  581. }
  582. // A dying base takes its lanes with it. The peer converges symmetrically
  583. // when it processes the base's CloseTunnel, so lanes need no signaling of
  584. // their own. Depth-1 recursion: lanes have no children.
  585. if hostinfo.lanes != nil {
  586. for _, lane := range hostinfo.lanes.snapshotLanes() {
  587. hm.unlockedDeleteLane(lane)
  588. }
  589. }
  590. // Remove this hostinfo from each of its address lists. The lists are independent, so a
  591. // sibling is never promoted to an address it does not own and no other list is touched.
  592. final := true
  593. for _, addr := range hostinfo.vpnAddrs {
  594. if list, ok := hm.moreHosts[addr]; ok {
  595. list = removeHostInfo(list, hostinfo)
  596. hm.unlockedSetHostsForAddr(addr, list)
  597. if len(list) > 0 {
  598. final = false
  599. }
  600. } else if existing, ok := hm.Hosts[addr]; ok {
  601. if existing == hostinfo {
  602. // Common case, the only hostinfo for this address. moreHosts has no entry to clean up.
  603. delete(hm.Hosts, addr)
  604. } else {
  605. // We don't hold this address but another hostinfo does, we still have a tunnel to the peer
  606. final = false
  607. }
  608. }
  609. }
  610. // Go maps never shrink their buckets, replace fully drained maps so a node that churned
  611. // through a large peer count gives the memory back. Same idiom as the index maps below.
  612. if len(hm.Hosts) == 0 {
  613. hm.Hosts = map[netip.Addr]*HostInfo{}
  614. }
  615. if len(hm.moreHosts) == 0 {
  616. hm.moreHosts = map[netip.Addr][]*HostInfo{}
  617. }
  618. // The remote index uses index ids outside our control so lets make sure we are only removing
  619. // the remote index pointer here if it points to the hostinfo we are deleting
  620. hostinfo2, ok := hm.RemoteIndexes[hostinfo.remoteIndexId]
  621. if ok && hostinfo2 == hostinfo {
  622. delete(hm.RemoteIndexes, hostinfo.remoteIndexId)
  623. if len(hm.RemoteIndexes) == 0 {
  624. hm.RemoteIndexes = map[uint32]*HostInfo{}
  625. }
  626. }
  627. delete(hm.Indexes, hostinfo.localIndexId)
  628. if len(hm.Indexes) == 0 {
  629. hm.Indexes = map[uint32]*HostInfo{}
  630. }
  631. if hm.l.Enabled(context.Background(), slog.LevelDebug) {
  632. hm.l.Debug("Hostmap hostInfo deleted",
  633. "hostMap", m{"mapTotalSize": len(hm.Hosts),
  634. "vpnAddrs": hostinfo.vpnAddrs, "indexNumber": hostinfo.localIndexId, "remoteIndexNumber": hostinfo.remoteIndexId},
  635. )
  636. }
  637. if final {
  638. // I have lost connectivity to my peers. My relay tunnel is likely broken. Mark the next
  639. // hops as 'Requested' so that new relay tunnels are created in the future.
  640. hm.unlockedDisestablishVpnAddrRelayFor(hostinfo)
  641. }
  642. // Clean up any local relay indexes for which I am acting as a relay hop
  643. for _, localRelayIdx := range hostinfo.relayState.CopyRelayForIdxs() {
  644. delete(hm.Relays, localRelayIdx)
  645. }
  646. return final
  647. }
  648. // unlockedDeleteLane removes a lane tunnel from the index maps and detaches it
  649. // from its base. Lanes never live in Hosts and their death never means "no
  650. // tunnel to the peer", so the return is always false (the lighthouse cache and
  651. // relays stay untouched). Idempotent: every step is identity-checked.
  652. func (hm *HostMap) unlockedDeleteLane(lane *HostInfo) bool {
  653. if ls := lane.parent.lanes; ls != nil {
  654. if lane.laneOwned {
  655. ls.noteOwnedLaneDeath(lane)
  656. } else {
  657. ls.removePeerLane(lane)
  658. }
  659. }
  660. if hostinfo2, ok := hm.RemoteIndexes[lane.remoteIndexId]; ok && hostinfo2 == lane {
  661. delete(hm.RemoteIndexes, lane.remoteIndexId)
  662. }
  663. if hostinfo2, ok := hm.Indexes[lane.localIndexId]; ok && hostinfo2 == lane {
  664. delete(hm.Indexes, lane.localIndexId)
  665. }
  666. if hm.l.Enabled(context.Background(), slog.LevelDebug) {
  667. hm.l.Debug("Hostmap lane deleted",
  668. "hostMap", m{"vpnAddrs": lane.vpnAddrs, "laneIndex": lane.laneIndex,
  669. "indexNumber": lane.localIndexId, "remoteIndexNumber": lane.remoteIndexId},
  670. )
  671. }
  672. return false
  673. }
  674. func (hm *HostMap) QueryIndex(index uint32) *HostInfo {
  675. hm.RLock()
  676. if h, ok := hm.Indexes[index]; ok {
  677. hm.RUnlock()
  678. return h
  679. } else {
  680. hm.RUnlock()
  681. return nil
  682. }
  683. }
  684. func (hm *HostMap) QueryRelayIndex(index uint32) *HostInfo {
  685. hm.RLock()
  686. if h, ok := hm.Relays[index]; ok {
  687. hm.RUnlock()
  688. return h
  689. } else {
  690. hm.RUnlock()
  691. return nil
  692. }
  693. }
  694. func (hm *HostMap) QueryReverseIndex(index uint32) *HostInfo {
  695. hm.RLock()
  696. if h, ok := hm.RemoteIndexes[index]; ok {
  697. hm.RUnlock()
  698. return h
  699. } else {
  700. hm.RUnlock()
  701. return nil
  702. }
  703. }
  704. func (hm *HostMap) QueryVpnAddr(vpnIp netip.Addr) *HostInfo {
  705. return hm.queryVpnAddr(vpnIp, nil)
  706. }
  707. func (hm *HostMap) QueryVpnAddrsRelayFor(targetIps []netip.Addr, relayHostIp netip.Addr) (*HostInfo, *Relay, error) {
  708. hm.RLock()
  709. defer hm.RUnlock()
  710. // This runs per relayed packet, so check the primary with a single map probe and only consult
  711. // moreHosts when the primary can't relay for us.
  712. h, ok := hm.Hosts[relayHostIp]
  713. if !ok {
  714. return nil, nil, errors.New("unable to find host")
  715. }
  716. for _, targetIp := range targetIps {
  717. r, ok := h.relayState.QueryRelayForByIp(targetIp)
  718. if ok && r.State == Established {
  719. return h, r, nil
  720. }
  721. }
  722. if list, ok := hm.moreHosts[relayHostIp]; ok {
  723. // list[0] is the primary we already checked
  724. for _, h := range list[1:] {
  725. for _, targetIp := range targetIps {
  726. r, ok := h.relayState.QueryRelayForByIp(targetIp)
  727. if ok && r.State == Established {
  728. return h, r, nil
  729. }
  730. }
  731. }
  732. }
  733. return nil, nil, errors.New("unable to find host with relay")
  734. }
  735. func (hm *HostMap) unlockedDisestablishVpnAddrRelayFor(hi *HostInfo) {
  736. for _, relayHostIp := range hi.relayState.CopyRelayIps() {
  737. for _, h := range hm.unlockedGetHostList(relayHostIp) {
  738. h.relayState.UpdateRelayForByIpState(hi.vpnAddrs[0], Disestablished)
  739. }
  740. }
  741. for _, rs := range hi.relayState.CopyAllRelayFor() {
  742. if rs.Type == ForwardingType {
  743. for _, h := range hm.unlockedGetHostList(rs.PeerAddr) {
  744. h.relayState.UpdateRelayForByIpState(hi.vpnAddrs[0], Disestablished)
  745. }
  746. }
  747. }
  748. }
  749. func (hm *HostMap) queryVpnAddr(vpnIp netip.Addr, promoteIfce *Interface) *HostInfo {
  750. hm.RLock()
  751. if h, ok := hm.Hosts[vpnIp]; ok {
  752. hm.RUnlock()
  753. // Do not attempt promotion if you are a lighthouse
  754. if promoteIfce != nil && !promoteIfce.lightHouse.amLighthouse {
  755. h.TryPromoteBest(hm.GetPreferredRanges(), promoteIfce)
  756. }
  757. return h
  758. }
  759. hm.RUnlock()
  760. return nil
  761. }
  762. // unlockedAddHostInfo assumes you have a write-lock and will add a hostinfo object to the hostmap Indexes and RemoteIndexes maps.
  763. // If an entry exists for the Hosts table (vpnIp -> hostinfo) then the provided hostinfo will be made primary
  764. func (hm *HostMap) unlockedAddHostInfo(hostinfo *HostInfo, f *Interface) {
  765. if f.dnsServer != nil {
  766. remoteCert := hostinfo.ConnectionState.peerCert
  767. f.dnsServer.Add(remoteCert.Certificate.Name()+".", hostinfo.vpnAddrs)
  768. }
  769. for _, addr := range hostinfo.vpnAddrs {
  770. hm.unlockedInnerAddHostInfo(addr, hostinfo, f)
  771. }
  772. hm.Indexes[hostinfo.localIndexId] = hostinfo
  773. hm.RemoteIndexes[hostinfo.remoteIndexId] = hostinfo
  774. hostinfo.out.Store(true)
  775. if f.connectionManager != nil { // f.connectionManager is only nil in some unit tests
  776. f.connectionManager.trafficTimer.Add(hostinfo.localIndexId, f.connectionManager.checkInterval)
  777. }
  778. if hm.l.Enabled(context.Background(), slog.LevelDebug) {
  779. hm.l.Debug("Hostmap vpnIp added",
  780. "hostMap", m{"vpnAddrs": hostinfo.vpnAddrs, "mapTotalSize": len(hm.Hosts),
  781. "hostinfo": m{"existing": true, "localIndexId": hostinfo.localIndexId, "vpnAddrs": hostinfo.vpnAddrs}},
  782. )
  783. }
  784. }
  785. // unlockedAddLane registers a lane tunnel in the index maps (RX demux and
  786. // recv_error need it there) without touching Hosts: lanes are never primary,
  787. // never dns-visible, and never subject to the MaxHostInfosPerVpnIp eviction.
  788. // The connection manager still tracks it for keepalive/death.
  789. func (hm *HostMap) unlockedAddLane(lane *HostInfo, f *Interface) {
  790. hm.Indexes[lane.localIndexId] = lane
  791. hm.RemoteIndexes[lane.remoteIndexId] = lane
  792. lane.out.Store(true)
  793. if f.connectionManager != nil { // f.connectionManager is only nil in some unit tests
  794. f.connectionManager.trafficTimer.Add(lane.localIndexId, f.connectionManager.checkInterval)
  795. }
  796. if hm.l.Enabled(context.Background(), slog.LevelDebug) {
  797. hm.l.Debug("Hostmap lane added",
  798. "hostMap", m{"vpnAddrs": lane.vpnAddrs, "laneIndex": lane.laneIndex,
  799. "indexNumber": lane.localIndexId, "remoteIndexNumber": lane.remoteIndexId},
  800. )
  801. }
  802. }
  803. func (hm *HostMap) unlockedInnerAddHostInfo(vpnAddr netip.Addr, hostinfo *HostInfo, f *Interface) {
  804. existing, ok := hm.Hosts[vpnAddr]
  805. if !ok {
  806. // Common case, the first hostinfo for this address. moreHosts stays empty.
  807. hm.Hosts[vpnAddr] = hostinfo
  808. return
  809. }
  810. // The new hostinfo becomes the primary for this address. Remove any stale copy of it first so
  811. // we never hold a duplicate, then prepend.
  812. list, ok := hm.moreHosts[vpnAddr]
  813. if !ok {
  814. list = []*HostInfo{existing}
  815. }
  816. list = removeHostInfo(list, hostinfo)
  817. list = append([]*HostInfo{hostinfo}, list...)
  818. hm.unlockedSetHostsForAddr(vpnAddr, list)
  819. // Enforce the per-address cap by fully retiring the oldest hostinfo once we exceed it.
  820. // Deleting it removes it from all of its addresses and the index maps, matching prior behavior.
  821. if len(list) > MaxHostInfosPerVpnIp {
  822. hm.unlockedDeleteHostInfo(list[len(list)-1])
  823. }
  824. }
  825. func (hm *HostMap) GetPreferredRanges() []netip.Prefix {
  826. //NOTE: if preferredRanges is ever not stored before a load this will fail to dereference a nil pointer
  827. return *hm.preferredRanges.Load()
  828. }
  829. func (hm *HostMap) ForEachVpnAddr(f controlEach) {
  830. hm.RLock()
  831. defer hm.RUnlock()
  832. for _, v := range hm.Hosts {
  833. f(v)
  834. }
  835. }
  836. func (hm *HostMap) ForEachIndex(f controlEach) {
  837. hm.RLock()
  838. defer hm.RUnlock()
  839. for _, v := range hm.Indexes {
  840. f(v)
  841. }
  842. }
  843. // TryPromoteBest handles re-querying lighthouses and probing for better paths
  844. // NOTE: It is an error to call this if you are a lighthouse since they should not roam clients!
  845. func (i *HostInfo) TryPromoteBest(preferredRanges []netip.Prefix, ifce *Interface) {
  846. c := i.promoteCounter.Add(1)
  847. if c%ifce.tryPromoteEvery.Load() == 0 {
  848. remote := i.GetRemote()
  849. // return early if we are already on a preferred remote
  850. if remote.IsValid() {
  851. rIP := remote.Addr()
  852. for _, l := range preferredRanges {
  853. if l.Contains(rIP) {
  854. return
  855. }
  856. }
  857. }
  858. i.remotes.ForEach(preferredRanges, func(addr netip.AddrPort, preferred bool) {
  859. if remote.IsValid() && (!addr.IsValid() || !preferred) {
  860. return
  861. }
  862. // Try to send a test packet to that host, this should
  863. // cause it to detect a roaming event and switch remotes
  864. ifce.sendTo(header.Test, header.TestRequest, i.ConnectionState, i, addr, []byte(""), make([]byte, 12, 12), make([]byte, mtu))
  865. })
  866. }
  867. // Re query our lighthouses for new remotes occasionally
  868. if c%ifce.reQueryEvery.Load() == 0 && ifce.lightHouse != nil {
  869. now := time.Now().UnixNano()
  870. if now < i.nextLHQuery.Load() {
  871. return
  872. }
  873. i.nextLHQuery.Store(now + ifce.reQueryWait.Load())
  874. ifce.lightHouse.QueryServer(i.vpnAddrs[0])
  875. }
  876. }
  877. func (i *HostInfo) GetCert() *cert.CachedCertificate {
  878. if i.ConnectionState != nil {
  879. return i.ConnectionState.peerCert
  880. }
  881. return nil
  882. }
  883. func (i *HostInfo) GetRemote() netip.AddrPort {
  884. if p := i.remote.Load(); p != nil {
  885. return *p
  886. }
  887. return netip.AddrPort{}
  888. }
  889. // TODO: Maybe use ViaSender here?
  890. func (i *HostInfo) SetRemote(remote netip.AddrPort) {
  891. // We copy here because we likely got this remote from a source that reuses the object
  892. if i.GetRemote() != remote {
  893. i.remote.Store(&remote)
  894. i.remotes.LearnRemote(i.vpnAddrs[0], remote)
  895. }
  896. }
  897. // SetRemoteIfPreferred returns true if the remote was changed. The lastRoam
  898. // time on the HostInfo will also be updated.
  899. func (i *HostInfo) SetRemoteIfPreferred(hm *HostMap, via ViaSender) bool {
  900. if via.IsRelayed {
  901. return false
  902. }
  903. currentRemote := i.GetRemote()
  904. if !currentRemote.IsValid() {
  905. i.SetRemote(via.UdpAddr)
  906. return true
  907. }
  908. // NOTE: We do this loop here instead of calling `isPreferred` in
  909. // remote_list.go so that we only have to loop over preferredRanges once.
  910. newIsPreferred := false
  911. for _, l := range hm.GetPreferredRanges() {
  912. // return early if we are already on a preferred remote
  913. if l.Contains(currentRemote.Addr()) {
  914. return false
  915. }
  916. if l.Contains(via.UdpAddr.Addr()) {
  917. newIsPreferred = true
  918. }
  919. }
  920. if newIsPreferred {
  921. // Consider this a roaming event
  922. i.lastRoam = time.Now()
  923. i.lastRoamRemote = currentRemote
  924. i.SetRemote(via.UdpAddr)
  925. return true
  926. }
  927. return false
  928. }
  929. // buildNetworks fills in the networks field of HostInfo. It accepts a cert.Certificate so you never ever mix the network types up.
  930. func (i *HostInfo) buildNetworks(myVpnNetworksTable *bart.Lite, c cert.Certificate) {
  931. if len(c.Networks()) == 1 && len(c.UnsafeNetworks()) == 0 {
  932. if myVpnNetworksTable.Contains(c.Networks()[0].Addr()) {
  933. return // Simple case, no BART needed
  934. }
  935. }
  936. i.networks = new(bart.Table[NetworkType])
  937. for _, network := range c.Networks() {
  938. nprefix := netip.PrefixFrom(network.Addr(), network.Addr().BitLen())
  939. if myVpnNetworksTable.Contains(network.Addr()) {
  940. i.networks.Insert(nprefix, NetworkTypeVPN)
  941. } else {
  942. i.networks.Insert(nprefix, NetworkTypeVPNPeer)
  943. }
  944. }
  945. for _, network := range c.UnsafeNetworks() {
  946. i.networks.Insert(network, NetworkTypeUnsafe)
  947. }
  948. }
  949. // logger returns a derived slog.Logger with per-hostinfo fields pre-bound.
  950. func (i *HostInfo) logger(l *slog.Logger) *slog.Logger {
  951. if i == nil {
  952. return l
  953. }
  954. li := l.With(
  955. "vpnAddrs", i.vpnAddrs,
  956. "localIndex", i.localIndexId,
  957. "remoteIndex", i.remoteIndexId,
  958. )
  959. if connState := i.ConnectionState; connState != nil {
  960. if peerCert := connState.peerCert; peerCert != nil {
  961. li = li.With("certName", peerCert.Certificate.Name())
  962. }
  963. }
  964. return li
  965. }
  966. // Utility functions
  967. func localAddrs(l *slog.Logger, allowList *LocalAllowList) []netip.Addr {
  968. //FIXME: This function is pretty garbage
  969. var finalAddrs []netip.Addr
  970. ifaces, _ := net.Interfaces()
  971. for _, i := range ifaces {
  972. allow := allowList.AllowName(i.Name)
  973. if l.Enabled(context.Background(), logging.LevelTrace) {
  974. l.Log(context.Background(), logging.LevelTrace, "localAllowList.AllowName",
  975. "interfaceName", i.Name,
  976. "allow", allow,
  977. )
  978. }
  979. if !allow {
  980. continue
  981. }
  982. addrs, _ := i.Addrs()
  983. for _, rawAddr := range addrs {
  984. var addr netip.Addr
  985. switch v := rawAddr.(type) {
  986. case *net.IPNet:
  987. //continue
  988. addr, _ = netip.AddrFromSlice(v.IP)
  989. case *net.IPAddr:
  990. addr, _ = netip.AddrFromSlice(v.IP)
  991. }
  992. if !addr.IsValid() {
  993. if l.Enabled(context.Background(), slog.LevelDebug) {
  994. l.Debug("addr was invalid", "localAddr", rawAddr)
  995. }
  996. continue
  997. }
  998. addr = addr.Unmap()
  999. if addr.IsLoopback() == false && addr.IsLinkLocalUnicast() == false {
  1000. isAllowed := allowList.Allow(addr)
  1001. if l.Enabled(context.Background(), logging.LevelTrace) {
  1002. l.Log(context.Background(), logging.LevelTrace, "localAllowList.Allow",
  1003. "localAddr", addr,
  1004. "allowed", isAllowed,
  1005. )
  1006. }
  1007. if !isAllowed {
  1008. continue
  1009. }
  1010. finalAddrs = append(finalAddrs, addr)
  1011. }
  1012. }
  1013. }
  1014. return finalAddrs
  1015. }