1
0

hostmap.go 36 KB

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