hostmap.go 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126
  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. remotes *RemoteList
  215. promoteCounter atomic.Uint32
  216. ConnectionState *ConnectionState
  217. remoteIndexId uint32
  218. localIndexId uint32
  219. // vpnAddrs is a list of vpn addresses assigned to this host that are within our own vpn networks
  220. // The host may have other vpn addresses that are outside our
  221. // vpn networks but were removed because they are not usable
  222. vpnAddrs []netip.Addr
  223. // networks is a combination of specific vpn addresses (not prefixes!) and full unsafe networks assigned to this host.
  224. networks *bart.Table[NetworkType]
  225. relayState RelayState
  226. // HandshakePacket records the packets used to create this hostinfo
  227. // We need these to avoid replayed handshake packets creating new hostinfos which causes churn
  228. HandshakePacket map[uint8][]byte
  229. // nextLHQuery is the earliest we can ask the lighthouse for new information.
  230. // This is used to limit lighthouse re-queries in chatty clients
  231. nextLHQuery atomic.Int64
  232. // lastRebindCount is the other side of Interface.rebindCount, if these values don't match then we need to ask LH
  233. // for a punch from the remote end of this tunnel. The goal being to prime their conntrack for our traffic just like
  234. // with a handshake
  235. lastRebindCount int8
  236. // lastHandshakeTime records the time the remote side told us about at the stage when the handshake was completed locally
  237. // Stage 1 packet will contain it if I am a responder, stage 2 packet if I am an initiator
  238. // This is used to avoid an attack where a handshake packet is replayed after some time
  239. lastHandshakeTime uint64
  240. lastRoam time.Time
  241. lastRoamRemote netip.AddrPort
  242. //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
  243. in, out, pendingDeletion atomic.Bool
  244. // lastUsed tracks the last time ConnectionManager checked the tunnel and it was in use.
  245. // This value will be behind against actual tunnel utilization in the hot path.
  246. // This should only be used by the ConnectionManagers ticker routine.
  247. lastUsed time.Time
  248. // sockIdx is the index into Interface.writers of the socket every packet
  249. // on this tunnel egresses from (and, for lanes, arrives on). 0 for base
  250. // and vanilla tunnels — the zero value preserves stock behavior.
  251. sockIdx int
  252. // laneIndex is the owner's lane number for a lane tunnel; 0 for base.
  253. laneIndex uint16
  254. // laneOwned is true when we initiated this lane (it carries our TX data).
  255. laneOwned bool
  256. // parent points at the base tunnel a lane hangs off of; nil for base and
  257. // vanilla tunnels. Set before the lane is registered in hostmap.Indexes.
  258. parent *HostInfo
  259. // lanes is allocated on a base tunnel when multiport is enabled and the
  260. // peer advertised lane support; nil otherwise.
  261. lanes *laneState
  262. }
  263. // isLane reports whether this HostInfo is a lane tunnel rather than a base
  264. // (or vanilla) tunnel.
  265. func (i *HostInfo) isLane() bool {
  266. return i.parent != nil
  267. }
  268. // laneState hangs off a base HostInfo and tracks the multiport lane tunnels
  269. // associated with it. txLanes is read lock-free on the TX hot path; the Mutex
  270. // guards everything else.
  271. type laneState struct {
  272. sync.Mutex
  273. // peerPortCount/peerBasePort are the peer's advert from the base
  274. // handshake; lane i targets peerBasePort + (i % peerPortCount).
  275. peerPortCount uint16
  276. peerBasePort uint16
  277. // txLanes[i] is our established, initiator-owned lane for routine i, or
  278. // nil. Index 0 is always nil — the base tunnel is lane 0. A pointer is
  279. // only Stored once the lane's ConnectionState is fully populated, so a
  280. // data-plane routine that Loads non-nil always sees a usable tunnel.
  281. txLanes []atomic.Pointer[HostInfo]
  282. // Under Mutex: per-slot handshake-in-flight flag, consecutive failure
  283. // count, and earliest next attempt, driving ensureLanes' backoff.
  284. txPending []bool
  285. txFails []uint8
  286. txRetryAt []time.Time
  287. // Under Mutex: responder-side records of peer-owned lanes, capped by
  288. // same-laneIndex replacement.
  289. peerLanes []*HostInfo
  290. }
  291. func newLaneState(laneCount int, peerPortCount, peerBasePort uint16) *laneState {
  292. return &laneState{
  293. peerPortCount: peerPortCount,
  294. peerBasePort: peerBasePort,
  295. txLanes: make([]atomic.Pointer[HostInfo], laneCount),
  296. txPending: make([]bool, laneCount),
  297. txFails: make([]uint8, laneCount),
  298. txRetryAt: make([]time.Time, laneCount),
  299. }
  300. }
  301. const (
  302. laneRetryBase = 5 * time.Second
  303. laneRetryMax = 60 * time.Second
  304. )
  305. // noteLaneFailure marks lane slot i as empty and pushes the next attempt out
  306. // with exponential backoff. Called when an owned lane dies or its handshake
  307. // times out.
  308. func (ls *laneState) noteLaneFailure(i int) {
  309. if i < 0 || i >= len(ls.txPending) {
  310. return
  311. }
  312. ls.Lock()
  313. ls.txPending[i] = false
  314. if ls.txFails[i] < 200 { // just avoid wrapping; the delay caps far earlier
  315. ls.txFails[i]++
  316. }
  317. d := laneRetryBase << min(ls.txFails[i], 4)
  318. if d > laneRetryMax {
  319. d = laneRetryMax
  320. }
  321. ls.txRetryAt[i] = time.Now().Add(d)
  322. ls.Unlock()
  323. }
  324. // noteOwnedLaneDeath detaches an established owned lane from its slot
  325. // (identity-checked, so a raced re-establishment is never clobbered) and
  326. // applies failure backoff.
  327. func (ls *laneState) noteOwnedLaneDeath(lane *HostInfo) {
  328. i := int(lane.laneIndex)
  329. if i >= len(ls.txLanes) {
  330. return
  331. }
  332. ls.txLanes[i].CompareAndSwap(lane, nil)
  333. ls.noteLaneFailure(i)
  334. }
  335. // removePeerLane drops a responder-side lane record by identity.
  336. func (ls *laneState) removePeerLane(lane *HostInfo) {
  337. ls.Lock()
  338. for n, h := range ls.peerLanes {
  339. if h == lane {
  340. ls.peerLanes = append(ls.peerLanes[:n], ls.peerLanes[n+1:]...)
  341. break
  342. }
  343. }
  344. ls.Unlock()
  345. }
  346. // snapshotLanes returns every lane hostinfo currently attached, used by the
  347. // base-delete cascade. Taken under the lock and returned as a copy so the
  348. // caller can delete without holding it.
  349. func (ls *laneState) snapshotLanes() []*HostInfo {
  350. ls.Lock()
  351. defer ls.Unlock()
  352. out := make([]*HostInfo, 0, len(ls.txLanes)+len(ls.peerLanes))
  353. for n := range ls.txLanes {
  354. if h := ls.txLanes[n].Load(); h != nil {
  355. out = append(out, h)
  356. }
  357. }
  358. out = append(out, ls.peerLanes...)
  359. return out
  360. }
  361. type ViaSender struct {
  362. UdpAddr netip.AddrPort
  363. relayHI *HostInfo // relayHI is the host info object of the relay
  364. relay *Relay // relay contains the rest of the relay information, including the PeerIP of the host trying to communicate with us.
  365. IsRelayed bool // IsRelayed is true if the packet was sent through a relay
  366. // SockIdx is the local socket (Interface.writers index) the packet
  367. // arrived on. Replies that must originate from the same 4-tuple egress
  368. // f.writers[SockIdx].
  369. SockIdx int
  370. }
  371. func (v ViaSender) String() string {
  372. if v.IsRelayed {
  373. return fmt.Sprintf("%s (relayed)", v.UdpAddr)
  374. }
  375. return v.UdpAddr.String()
  376. }
  377. func (v ViaSender) MarshalJSON() ([]byte, error) {
  378. if v.IsRelayed {
  379. return json.Marshal(m{"relay": v.UdpAddr})
  380. }
  381. return json.Marshal(m{"direct": v.UdpAddr})
  382. }
  383. type cachedPacket struct {
  384. messageType header.MessageType
  385. messageSubType header.MessageSubType
  386. callback packetCallback
  387. packet []byte
  388. }
  389. type packetCallback func(t header.MessageType, st header.MessageSubType, h *HostInfo, p, nb, out []byte)
  390. type cachedPacketMetrics struct {
  391. sent metrics.Counter
  392. dropped metrics.Counter
  393. }
  394. func NewHostMapFromConfig(l *slog.Logger, c *config.C) *HostMap {
  395. hm := newHostMap(l)
  396. hm.reload(c, true)
  397. c.RegisterReloadCallback(func(c *config.C) {
  398. hm.reload(c, false)
  399. })
  400. l.Info("Main HostMap created", "preferredRanges", hm.GetPreferredRanges())
  401. return hm
  402. }
  403. func newHostMap(l *slog.Logger) *HostMap {
  404. return &HostMap{
  405. Indexes: map[uint32]*HostInfo{},
  406. Relays: map[uint32]*HostInfo{},
  407. RemoteIndexes: map[uint32]*HostInfo{},
  408. Hosts: map[netip.Addr]*HostInfo{},
  409. moreHosts: map[netip.Addr][]*HostInfo{},
  410. l: l,
  411. }
  412. }
  413. func (hm *HostMap) reload(c *config.C, initial bool) {
  414. if initial || c.HasChanged("preferred_ranges") {
  415. var preferredRanges []netip.Prefix
  416. rawPreferredRanges := c.GetStringSlice("preferred_ranges", []string{})
  417. for _, rawPreferredRange := range rawPreferredRanges {
  418. preferredRange, err := netip.ParsePrefix(rawPreferredRange)
  419. if err != nil {
  420. hm.l.Warn("Failed to parse preferred ranges, ignoring",
  421. "error", err,
  422. "range", rawPreferredRanges,
  423. )
  424. continue
  425. }
  426. preferredRanges = append(preferredRanges, preferredRange)
  427. }
  428. oldRanges := hm.preferredRanges.Swap(&preferredRanges)
  429. if !initial {
  430. hm.l.Info("preferred_ranges changed",
  431. "oldPreferredRanges", *oldRanges,
  432. "newPreferredRanges", preferredRanges,
  433. )
  434. }
  435. }
  436. }
  437. // EmitStats reports host, index, and relay counts to the stats collection system
  438. func (hm *HostMap) EmitStats() {
  439. hm.RLock()
  440. hostLen := len(hm.Hosts)
  441. indexLen := len(hm.Indexes)
  442. remoteIndexLen := len(hm.RemoteIndexes)
  443. relaysLen := len(hm.Relays)
  444. hm.RUnlock()
  445. metrics.GetOrRegisterGauge("hostmap.main.hosts", nil).Update(int64(hostLen))
  446. metrics.GetOrRegisterGauge("hostmap.main.indexes", nil).Update(int64(indexLen))
  447. metrics.GetOrRegisterGauge("hostmap.main.remoteIndexes", nil).Update(int64(remoteIndexLen))
  448. metrics.GetOrRegisterGauge("hostmap.main.relayIndexes", nil).Update(int64(relaysLen))
  449. }
  450. // unlockedSetHostsForAddr stores the per-address hostinfo list (list[0] is the primary). An empty
  451. // list removes the address. This is the one place Hosts and moreHosts are written together, keep
  452. // it that way. Callers must hold the write lock.
  453. func (hm *HostMap) unlockedSetHostsForAddr(addr netip.Addr, list []*HostInfo) {
  454. if len(list) == 0 {
  455. delete(hm.Hosts, addr)
  456. delete(hm.moreHosts, addr)
  457. return
  458. }
  459. hm.Hosts[addr] = list[0]
  460. if len(list) > 1 {
  461. hm.moreHosts[addr] = list
  462. } else {
  463. delete(hm.moreHosts, addr)
  464. }
  465. }
  466. // unlockedGetHostList returns every hostinfo holding addr, primary first, or nil if we have no
  467. // tunnel for addr. The common single-hostinfo case builds a fresh one element list, so keep this
  468. // off the packet hot path; the primary is a direct Hosts read. Callers must hold the lock (read
  469. // or write).
  470. func (hm *HostMap) unlockedGetHostList(addr netip.Addr) []*HostInfo {
  471. if list, ok := hm.moreHosts[addr]; ok {
  472. return list
  473. }
  474. if h, ok := hm.Hosts[addr]; ok {
  475. return []*HostInfo{h}
  476. }
  477. return nil
  478. }
  479. // removeHostInfo returns list with hi removed (order preserved), or list unchanged if hi is
  480. // absent. It deletes in place: every mutator holds the hostmap write lock and no reader ever
  481. // retains a slice across a mutation (readers iterate under RLock), so there is no snapshot to
  482. // invalidate.
  483. func removeHostInfo(list []*HostInfo, hi *HostInfo) []*HostInfo {
  484. idx := slices.Index(list, hi)
  485. if idx < 0 {
  486. return list
  487. }
  488. return slices.Delete(list, idx, idx+1)
  489. }
  490. // DeleteHostInfo will fully unlink the hostinfo and return true if no other hostinfo still holds
  491. // any of its vpn addrs, meaning we no longer have a tunnel to the peer
  492. func (hm *HostMap) DeleteHostInfo(hostinfo *HostInfo) bool {
  493. // Delete the host itself, ensuring it's not modified anymore
  494. hm.Lock()
  495. final := hm.unlockedDeleteHostInfo(hostinfo)
  496. hm.Unlock()
  497. return final
  498. }
  499. func (hm *HostMap) MakePrimary(hostinfo *HostInfo) {
  500. hm.Lock()
  501. defer hm.Unlock()
  502. hm.unlockedMakePrimary(hostinfo)
  503. }
  504. // unlockedMakePrimary reports whether hostinfo is (now) the primary for each of its addresses,
  505. // false only when it is no longer in the hostmap at all.
  506. func (hm *HostMap) unlockedMakePrimary(hostinfo *HostInfo) bool {
  507. // A lane must never become a Hosts primary: it would start carrying all
  508. // traffic for the peer and become a relay candidate.
  509. if hostinfo.isLane() {
  510. return false
  511. }
  512. // A hostinfo that is no longer in the hostmap must not be re-inserted here. Callers can race
  513. // tunnel teardown, deciding to promote under the read lock and only taking the write lock
  514. // after a delete fully unlinked the hostinfo (connection manager swapPrimary, AddRelay). Every
  515. // live hostinfo is registered in Indexes by unlockedAddHostInfo, so this is a membership test.
  516. if hm.Indexes[hostinfo.localIndexId] != hostinfo {
  517. return false
  518. }
  519. // Move hostinfo to the front (primary) of each of its address lists. The lists are
  520. // independent per address, so this can never leave a dangling entry the way promoting
  521. // against a single shared chain could.
  522. for _, addr := range hostinfo.vpnAddrs {
  523. if hm.Hosts[addr] == hostinfo {
  524. // Already primary for this address, the list is already in the right order
  525. continue
  526. }
  527. list := removeHostInfo(hm.unlockedGetHostList(addr), hostinfo)
  528. list = append([]*HostInfo{hostinfo}, list...)
  529. hm.unlockedSetHostsForAddr(addr, list)
  530. }
  531. return true
  532. }
  533. // unlockedDeleteHostInfo removes hostinfo from every one of its address lists and from the index
  534. // maps. It returns true if this was the last hostinfo for all of its addresses (we no longer have
  535. // any tunnel to the peer), which the caller uses to decide whether to clear learned lighthouse
  536. // state and disestablish relays.
  537. func (hm *HostMap) unlockedDeleteHostInfo(hostinfo *HostInfo) bool {
  538. if hostinfo.isLane() {
  539. return hm.unlockedDeleteLane(hostinfo)
  540. }
  541. // A dying base takes its lanes with it. The peer converges symmetrically
  542. // when it processes the base's CloseTunnel, so lanes need no signaling of
  543. // their own. Depth-1 recursion: lanes have no children.
  544. if hostinfo.lanes != nil {
  545. for _, lane := range hostinfo.lanes.snapshotLanes() {
  546. hm.unlockedDeleteLane(lane)
  547. }
  548. }
  549. // Remove this hostinfo from each of its address lists. The lists are independent, so a
  550. // sibling is never promoted to an address it does not own and no other list is touched.
  551. final := true
  552. for _, addr := range hostinfo.vpnAddrs {
  553. if list, ok := hm.moreHosts[addr]; ok {
  554. list = removeHostInfo(list, hostinfo)
  555. hm.unlockedSetHostsForAddr(addr, list)
  556. if len(list) > 0 {
  557. final = false
  558. }
  559. } else if existing, ok := hm.Hosts[addr]; ok {
  560. if existing == hostinfo {
  561. // Common case, the only hostinfo for this address. moreHosts has no entry to clean up.
  562. delete(hm.Hosts, addr)
  563. } else {
  564. // We don't hold this address but another hostinfo does, we still have a tunnel to the peer
  565. final = false
  566. }
  567. }
  568. }
  569. // Go maps never shrink their buckets, replace fully drained maps so a node that churned
  570. // through a large peer count gives the memory back. Same idiom as the index maps below.
  571. if len(hm.Hosts) == 0 {
  572. hm.Hosts = map[netip.Addr]*HostInfo{}
  573. }
  574. if len(hm.moreHosts) == 0 {
  575. hm.moreHosts = map[netip.Addr][]*HostInfo{}
  576. }
  577. // The remote index uses index ids outside our control so lets make sure we are only removing
  578. // the remote index pointer here if it points to the hostinfo we are deleting
  579. hostinfo2, ok := hm.RemoteIndexes[hostinfo.remoteIndexId]
  580. if ok && hostinfo2 == hostinfo {
  581. delete(hm.RemoteIndexes, hostinfo.remoteIndexId)
  582. if len(hm.RemoteIndexes) == 0 {
  583. hm.RemoteIndexes = map[uint32]*HostInfo{}
  584. }
  585. }
  586. delete(hm.Indexes, hostinfo.localIndexId)
  587. if len(hm.Indexes) == 0 {
  588. hm.Indexes = map[uint32]*HostInfo{}
  589. }
  590. if hm.l.Enabled(context.Background(), slog.LevelDebug) {
  591. hm.l.Debug("Hostmap hostInfo deleted",
  592. "hostMap", m{"mapTotalSize": len(hm.Hosts),
  593. "vpnAddrs": hostinfo.vpnAddrs, "indexNumber": hostinfo.localIndexId, "remoteIndexNumber": hostinfo.remoteIndexId},
  594. )
  595. }
  596. if final {
  597. // I have lost connectivity to my peers. My relay tunnel is likely broken. Mark the next
  598. // hops as 'Requested' so that new relay tunnels are created in the future.
  599. hm.unlockedDisestablishVpnAddrRelayFor(hostinfo)
  600. }
  601. // Clean up any local relay indexes for which I am acting as a relay hop
  602. for _, localRelayIdx := range hostinfo.relayState.CopyRelayForIdxs() {
  603. delete(hm.Relays, localRelayIdx)
  604. }
  605. return final
  606. }
  607. // unlockedDeleteLane removes a lane tunnel from the index maps and detaches it
  608. // from its base. Lanes never live in Hosts and their death never means "no
  609. // tunnel to the peer", so the return is always false (the lighthouse cache and
  610. // relays stay untouched). Idempotent: every step is identity-checked.
  611. func (hm *HostMap) unlockedDeleteLane(lane *HostInfo) bool {
  612. if ls := lane.parent.lanes; ls != nil {
  613. if lane.laneOwned {
  614. ls.noteOwnedLaneDeath(lane)
  615. } else {
  616. ls.removePeerLane(lane)
  617. }
  618. }
  619. if hostinfo2, ok := hm.RemoteIndexes[lane.remoteIndexId]; ok && hostinfo2 == lane {
  620. delete(hm.RemoteIndexes, lane.remoteIndexId)
  621. }
  622. if hostinfo2, ok := hm.Indexes[lane.localIndexId]; ok && hostinfo2 == lane {
  623. delete(hm.Indexes, lane.localIndexId)
  624. }
  625. if hm.l.Enabled(context.Background(), slog.LevelDebug) {
  626. hm.l.Debug("Hostmap lane deleted",
  627. "hostMap", m{"vpnAddrs": lane.vpnAddrs, "laneIndex": lane.laneIndex,
  628. "indexNumber": lane.localIndexId, "remoteIndexNumber": lane.remoteIndexId},
  629. )
  630. }
  631. return false
  632. }
  633. func (hm *HostMap) QueryIndex(index uint32) *HostInfo {
  634. hm.RLock()
  635. if h, ok := hm.Indexes[index]; ok {
  636. hm.RUnlock()
  637. return h
  638. } else {
  639. hm.RUnlock()
  640. return nil
  641. }
  642. }
  643. func (hm *HostMap) QueryRelayIndex(index uint32) *HostInfo {
  644. hm.RLock()
  645. if h, ok := hm.Relays[index]; ok {
  646. hm.RUnlock()
  647. return h
  648. } else {
  649. hm.RUnlock()
  650. return nil
  651. }
  652. }
  653. func (hm *HostMap) QueryReverseIndex(index uint32) *HostInfo {
  654. hm.RLock()
  655. if h, ok := hm.RemoteIndexes[index]; ok {
  656. hm.RUnlock()
  657. return h
  658. } else {
  659. hm.RUnlock()
  660. return nil
  661. }
  662. }
  663. func (hm *HostMap) QueryVpnAddr(vpnIp netip.Addr) *HostInfo {
  664. return hm.queryVpnAddr(vpnIp, nil)
  665. }
  666. func (hm *HostMap) QueryVpnAddrsRelayFor(targetIps []netip.Addr, relayHostIp netip.Addr) (*HostInfo, *Relay, error) {
  667. hm.RLock()
  668. defer hm.RUnlock()
  669. // This runs per relayed packet, so check the primary with a single map probe and only consult
  670. // moreHosts when the primary can't relay for us.
  671. h, ok := hm.Hosts[relayHostIp]
  672. if !ok {
  673. return nil, nil, errors.New("unable to find host")
  674. }
  675. for _, targetIp := range targetIps {
  676. r, ok := h.relayState.QueryRelayForByIp(targetIp)
  677. if ok && r.State == Established {
  678. return h, r, nil
  679. }
  680. }
  681. if list, ok := hm.moreHosts[relayHostIp]; ok {
  682. // list[0] is the primary we already checked
  683. for _, h := range list[1:] {
  684. for _, targetIp := range targetIps {
  685. r, ok := h.relayState.QueryRelayForByIp(targetIp)
  686. if ok && r.State == Established {
  687. return h, r, nil
  688. }
  689. }
  690. }
  691. }
  692. return nil, nil, errors.New("unable to find host with relay")
  693. }
  694. func (hm *HostMap) unlockedDisestablishVpnAddrRelayFor(hi *HostInfo) {
  695. for _, relayHostIp := range hi.relayState.CopyRelayIps() {
  696. for _, h := range hm.unlockedGetHostList(relayHostIp) {
  697. h.relayState.UpdateRelayForByIpState(hi.vpnAddrs[0], Disestablished)
  698. }
  699. }
  700. for _, rs := range hi.relayState.CopyAllRelayFor() {
  701. if rs.Type == ForwardingType {
  702. for _, h := range hm.unlockedGetHostList(rs.PeerAddr) {
  703. h.relayState.UpdateRelayForByIpState(hi.vpnAddrs[0], Disestablished)
  704. }
  705. }
  706. }
  707. }
  708. func (hm *HostMap) queryVpnAddr(vpnIp netip.Addr, promoteIfce *Interface) *HostInfo {
  709. hm.RLock()
  710. if h, ok := hm.Hosts[vpnIp]; ok {
  711. hm.RUnlock()
  712. // Do not attempt promotion if you are a lighthouse
  713. if promoteIfce != nil && !promoteIfce.lightHouse.amLighthouse {
  714. h.TryPromoteBest(hm.GetPreferredRanges(), promoteIfce)
  715. }
  716. return h
  717. }
  718. hm.RUnlock()
  719. return nil
  720. }
  721. // unlockedAddHostInfo assumes you have a write-lock and will add a hostinfo object to the hostmap Indexes and RemoteIndexes maps.
  722. // If an entry exists for the Hosts table (vpnIp -> hostinfo) then the provided hostinfo will be made primary
  723. func (hm *HostMap) unlockedAddHostInfo(hostinfo *HostInfo, f *Interface) {
  724. if f.dnsServer != nil {
  725. remoteCert := hostinfo.ConnectionState.peerCert
  726. f.dnsServer.Add(remoteCert.Certificate.Name()+".", hostinfo.vpnAddrs)
  727. }
  728. for _, addr := range hostinfo.vpnAddrs {
  729. hm.unlockedInnerAddHostInfo(addr, hostinfo, f)
  730. }
  731. hm.Indexes[hostinfo.localIndexId] = hostinfo
  732. hm.RemoteIndexes[hostinfo.remoteIndexId] = hostinfo
  733. hostinfo.out.Store(true)
  734. if f.connectionManager != nil { // f.connectionManager is only nil in some unit tests
  735. f.connectionManager.trafficTimer.Add(hostinfo.localIndexId, f.connectionManager.checkInterval)
  736. }
  737. if hm.l.Enabled(context.Background(), slog.LevelDebug) {
  738. hm.l.Debug("Hostmap vpnIp added",
  739. "hostMap", m{"vpnAddrs": hostinfo.vpnAddrs, "mapTotalSize": len(hm.Hosts),
  740. "hostinfo": m{"existing": true, "localIndexId": hostinfo.localIndexId, "vpnAddrs": hostinfo.vpnAddrs}},
  741. )
  742. }
  743. }
  744. // unlockedAddLane registers a lane tunnel in the index maps (RX demux and
  745. // recv_error need it there) without touching Hosts: lanes are never primary,
  746. // never dns-visible, and never subject to the MaxHostInfosPerVpnIp eviction.
  747. // The connection manager still tracks it for keepalive/death.
  748. func (hm *HostMap) unlockedAddLane(lane *HostInfo, f *Interface) {
  749. hm.Indexes[lane.localIndexId] = lane
  750. hm.RemoteIndexes[lane.remoteIndexId] = lane
  751. lane.out.Store(true)
  752. if f.connectionManager != nil { // f.connectionManager is only nil in some unit tests
  753. f.connectionManager.trafficTimer.Add(lane.localIndexId, f.connectionManager.checkInterval)
  754. }
  755. if hm.l.Enabled(context.Background(), slog.LevelDebug) {
  756. hm.l.Debug("Hostmap lane added",
  757. "hostMap", m{"vpnAddrs": lane.vpnAddrs, "laneIndex": lane.laneIndex,
  758. "indexNumber": lane.localIndexId, "remoteIndexNumber": lane.remoteIndexId},
  759. )
  760. }
  761. }
  762. func (hm *HostMap) unlockedInnerAddHostInfo(vpnAddr netip.Addr, hostinfo *HostInfo, f *Interface) {
  763. existing, ok := hm.Hosts[vpnAddr]
  764. if !ok {
  765. // Common case, the first hostinfo for this address. moreHosts stays empty.
  766. hm.Hosts[vpnAddr] = hostinfo
  767. return
  768. }
  769. // The new hostinfo becomes the primary for this address. Remove any stale copy of it first so
  770. // we never hold a duplicate, then prepend.
  771. list, ok := hm.moreHosts[vpnAddr]
  772. if !ok {
  773. list = []*HostInfo{existing}
  774. }
  775. list = removeHostInfo(list, hostinfo)
  776. list = append([]*HostInfo{hostinfo}, list...)
  777. hm.unlockedSetHostsForAddr(vpnAddr, list)
  778. // Enforce the per-address cap by fully retiring the oldest hostinfo once we exceed it.
  779. // Deleting it removes it from all of its addresses and the index maps, matching prior behavior.
  780. if len(list) > MaxHostInfosPerVpnIp {
  781. hm.unlockedDeleteHostInfo(list[len(list)-1])
  782. }
  783. }
  784. func (hm *HostMap) GetPreferredRanges() []netip.Prefix {
  785. //NOTE: if preferredRanges is ever not stored before a load this will fail to dereference a nil pointer
  786. return *hm.preferredRanges.Load()
  787. }
  788. func (hm *HostMap) ForEachVpnAddr(f controlEach) {
  789. hm.RLock()
  790. defer hm.RUnlock()
  791. for _, v := range hm.Hosts {
  792. f(v)
  793. }
  794. }
  795. func (hm *HostMap) ForEachIndex(f controlEach) {
  796. hm.RLock()
  797. defer hm.RUnlock()
  798. for _, v := range hm.Indexes {
  799. f(v)
  800. }
  801. }
  802. // TryPromoteBest handles re-querying lighthouses and probing for better paths
  803. // NOTE: It is an error to call this if you are a lighthouse since they should not roam clients!
  804. func (i *HostInfo) TryPromoteBest(preferredRanges []netip.Prefix, ifce *Interface) {
  805. c := i.promoteCounter.Add(1)
  806. if c%ifce.tryPromoteEvery.Load() == 0 {
  807. remote := i.GetRemote()
  808. // return early if we are already on a preferred remote
  809. if remote.IsValid() {
  810. rIP := remote.Addr()
  811. for _, l := range preferredRanges {
  812. if l.Contains(rIP) {
  813. return
  814. }
  815. }
  816. }
  817. i.remotes.ForEach(preferredRanges, func(addr netip.AddrPort, preferred bool) {
  818. if remote.IsValid() && (!addr.IsValid() || !preferred) {
  819. return
  820. }
  821. // Try to send a test packet to that host, this should
  822. // cause it to detect a roaming event and switch remotes
  823. ifce.sendTo(header.Test, header.TestRequest, i.ConnectionState, i, addr, []byte(""), make([]byte, 12, 12), make([]byte, mtu))
  824. })
  825. }
  826. // Re query our lighthouses for new remotes occasionally
  827. if c%ifce.reQueryEvery.Load() == 0 && ifce.lightHouse != nil {
  828. now := time.Now().UnixNano()
  829. if now < i.nextLHQuery.Load() {
  830. return
  831. }
  832. i.nextLHQuery.Store(now + ifce.reQueryWait.Load())
  833. ifce.lightHouse.QueryServer(i.vpnAddrs[0])
  834. }
  835. }
  836. func (i *HostInfo) GetCert() *cert.CachedCertificate {
  837. if i.ConnectionState != nil {
  838. return i.ConnectionState.peerCert
  839. }
  840. return nil
  841. }
  842. func (i *HostInfo) GetRemote() netip.AddrPort {
  843. if p := i.remote.Load(); p != nil {
  844. return *p
  845. }
  846. return netip.AddrPort{}
  847. }
  848. // TODO: Maybe use ViaSender here?
  849. func (i *HostInfo) SetRemote(remote netip.AddrPort) {
  850. // We copy here because we likely got this remote from a source that reuses the object
  851. if i.GetRemote() != remote {
  852. i.remote.Store(&remote)
  853. i.remotes.LearnRemote(i.vpnAddrs[0], remote)
  854. }
  855. }
  856. // SetRemoteIfPreferred returns true if the remote was changed. The lastRoam
  857. // time on the HostInfo will also be updated.
  858. func (i *HostInfo) SetRemoteIfPreferred(hm *HostMap, via ViaSender) bool {
  859. if via.IsRelayed {
  860. return false
  861. }
  862. currentRemote := i.GetRemote()
  863. if !currentRemote.IsValid() {
  864. i.SetRemote(via.UdpAddr)
  865. return true
  866. }
  867. // NOTE: We do this loop here instead of calling `isPreferred` in
  868. // remote_list.go so that we only have to loop over preferredRanges once.
  869. newIsPreferred := false
  870. for _, l := range hm.GetPreferredRanges() {
  871. // return early if we are already on a preferred remote
  872. if l.Contains(currentRemote.Addr()) {
  873. return false
  874. }
  875. if l.Contains(via.UdpAddr.Addr()) {
  876. newIsPreferred = true
  877. }
  878. }
  879. if newIsPreferred {
  880. // Consider this a roaming event
  881. i.lastRoam = time.Now()
  882. i.lastRoamRemote = currentRemote
  883. i.SetRemote(via.UdpAddr)
  884. return true
  885. }
  886. return false
  887. }
  888. // buildNetworks fills in the networks field of HostInfo. It accepts a cert.Certificate so you never ever mix the network types up.
  889. func (i *HostInfo) buildNetworks(myVpnNetworksTable *bart.Lite, c cert.Certificate) {
  890. if len(c.Networks()) == 1 && len(c.UnsafeNetworks()) == 0 {
  891. if myVpnNetworksTable.Contains(c.Networks()[0].Addr()) {
  892. return // Simple case, no BART needed
  893. }
  894. }
  895. i.networks = new(bart.Table[NetworkType])
  896. for _, network := range c.Networks() {
  897. nprefix := netip.PrefixFrom(network.Addr(), network.Addr().BitLen())
  898. if myVpnNetworksTable.Contains(network.Addr()) {
  899. i.networks.Insert(nprefix, NetworkTypeVPN)
  900. } else {
  901. i.networks.Insert(nprefix, NetworkTypeVPNPeer)
  902. }
  903. }
  904. for _, network := range c.UnsafeNetworks() {
  905. i.networks.Insert(network, NetworkTypeUnsafe)
  906. }
  907. }
  908. // logger returns a derived slog.Logger with per-hostinfo fields pre-bound.
  909. func (i *HostInfo) logger(l *slog.Logger) *slog.Logger {
  910. if i == nil {
  911. return l
  912. }
  913. li := l.With(
  914. "vpnAddrs", i.vpnAddrs,
  915. "localIndex", i.localIndexId,
  916. "remoteIndex", i.remoteIndexId,
  917. )
  918. if connState := i.ConnectionState; connState != nil {
  919. if peerCert := connState.peerCert; peerCert != nil {
  920. li = li.With("certName", peerCert.Certificate.Name())
  921. }
  922. }
  923. return li
  924. }
  925. // Utility functions
  926. func localAddrs(l *slog.Logger, allowList *LocalAllowList) []netip.Addr {
  927. //FIXME: This function is pretty garbage
  928. var finalAddrs []netip.Addr
  929. ifaces, _ := net.Interfaces()
  930. for _, i := range ifaces {
  931. allow := allowList.AllowName(i.Name)
  932. if l.Enabled(context.Background(), logging.LevelTrace) {
  933. l.Log(context.Background(), logging.LevelTrace, "localAllowList.AllowName",
  934. "interfaceName", i.Name,
  935. "allow", allow,
  936. )
  937. }
  938. if !allow {
  939. continue
  940. }
  941. addrs, _ := i.Addrs()
  942. for _, rawAddr := range addrs {
  943. var addr netip.Addr
  944. switch v := rawAddr.(type) {
  945. case *net.IPNet:
  946. //continue
  947. addr, _ = netip.AddrFromSlice(v.IP)
  948. case *net.IPAddr:
  949. addr, _ = netip.AddrFromSlice(v.IP)
  950. }
  951. if !addr.IsValid() {
  952. if l.Enabled(context.Background(), slog.LevelDebug) {
  953. l.Debug("addr was invalid", "localAddr", rawAddr)
  954. }
  955. continue
  956. }
  957. addr = addr.Unmap()
  958. if addr.IsLoopback() == false && addr.IsLinkLocalUnicast() == false {
  959. isAllowed := allowList.Allow(addr)
  960. if l.Enabled(context.Background(), logging.LevelTrace) {
  961. l.Log(context.Background(), logging.LevelTrace, "localAllowList.Allow",
  962. "localAddr", addr,
  963. "allowed", isAllowed,
  964. )
  965. }
  966. if !isAllowed {
  967. continue
  968. }
  969. finalAddrs = append(finalAddrs, addr)
  970. }
  971. }
  972. }
  973. return finalAddrs
  974. }