hostmap.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865
  1. package nebula
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "log/slog"
  8. "net/netip"
  9. "slices"
  10. "sync"
  11. "sync/atomic"
  12. "time"
  13. "github.com/gaissmai/bart"
  14. "github.com/rcrowley/go-metrics"
  15. "github.com/slackhq/nebula/cert"
  16. "github.com/slackhq/nebula/config"
  17. "github.com/slackhq/nebula/header"
  18. )
  19. const defaultPromoteEvery = 1000 // Count of packets sent before we try moving a tunnel to a preferred underlay ip address
  20. const defaultReQueryEvery = 5000 // Count of packets sent before re-querying a hostinfo to the lighthouse
  21. const defaultReQueryWait = time.Minute // Minimum amount of seconds to wait before re-querying a hostinfo the lighthouse. Evaluated every ReQueryEvery
  22. const MaxRemotes = 10
  23. // MaxHostInfosPerVpnIp is the max number of hostinfos we will track for a given vpn ip
  24. // 5 allows for an initial handshake and each host pair re-handshaking twice
  25. const MaxHostInfosPerVpnIp = 5
  26. // How long we should prevent roaming back to the previous IP.
  27. // This helps prevent flapping due to packets already in flight
  28. const RoamingSuppressSeconds = 2
  29. const (
  30. Requested = iota
  31. PeerRequested
  32. Established
  33. Disestablished
  34. )
  35. const (
  36. Unknowntype = iota
  37. ForwardingType
  38. TerminalType
  39. )
  40. type Relay struct {
  41. Type int
  42. State int
  43. LocalIndex uint32
  44. RemoteIndex uint32
  45. PeerAddr netip.Addr
  46. }
  47. type HostMap struct {
  48. sync.RWMutex //Because we concurrently read and write to our maps
  49. Indexes map[uint32]*HostInfo
  50. Relays map[uint32]*HostInfo // Maps a Relay IDX to a Relay HostInfo object
  51. RemoteIndexes map[uint32]*HostInfo
  52. // Hosts maps a vpn address to its primary hostinfo, one entry per address we hold a tunnel
  53. // for. moreHosts only has an entry while an address is held by 2 or more hostinfos and stores
  54. // the full most-recent-first list; moreHosts[a][0] is always the same hostinfo as Hosts[a].
  55. // Each address gets its own independent list, so a hostinfo owning multiple addresses can
  56. // never corrupt another address's ordering the way the old shared next/prev chain could.
  57. // Entries in moreHosts are only ever written by unlockedSetHostsForAddr; Hosts is written
  58. // directly only in the single-hostinfo fast paths where moreHosts is known to have no entry,
  59. // and unlockedDeleteHostInfo swaps either map for a fresh one when it fully drains.
  60. Hosts map[netip.Addr]*HostInfo
  61. moreHosts map[netip.Addr][]*HostInfo
  62. preferredRanges atomic.Pointer[[]netip.Prefix]
  63. l *slog.Logger
  64. }
  65. // For synchronization, treat the pointed-to Relay struct as immutable. To edit the Relay
  66. // struct, make a copy of an existing value, edit the fileds in the copy, and
  67. // then store a pointer to the new copy in both realyForBy* maps.
  68. type RelayState struct {
  69. sync.RWMutex
  70. relays []netip.Addr // Ordered set of VpnAddrs of Hosts to use as relays to access this peer
  71. // For data race avoidance, the contents of a *Relay are treated immutably. To update a *Relay, copy the existing data,
  72. // modify what needs to be updated, and store the new modified copy in the relayForByIp and relayForByIdx maps (with
  73. // the RelayState Lock held)
  74. relayForByAddr map[netip.Addr]*Relay // Maps vpnAddr of peers for which this HostInfo is a relay to some Relay info
  75. relayForByIdx map[uint32]*Relay // Maps a local index to some Relay info
  76. }
  77. func (rs *RelayState) DeleteRelay(ip netip.Addr) {
  78. rs.Lock()
  79. defer rs.Unlock()
  80. for idx, val := range rs.relays {
  81. if val == ip {
  82. rs.relays = append(rs.relays[:idx], rs.relays[idx+1:]...)
  83. return
  84. }
  85. }
  86. }
  87. func (rs *RelayState) UpdateRelayForByIpState(vpnIp netip.Addr, state int) {
  88. rs.Lock()
  89. defer rs.Unlock()
  90. if r, ok := rs.relayForByAddr[vpnIp]; ok {
  91. newRelay := *r
  92. newRelay.State = state
  93. rs.relayForByAddr[newRelay.PeerAddr] = &newRelay
  94. rs.relayForByIdx[newRelay.LocalIndex] = &newRelay
  95. }
  96. }
  97. func (rs *RelayState) UpdateRelayForByIdxState(idx uint32, state int) {
  98. rs.Lock()
  99. defer rs.Unlock()
  100. if r, ok := rs.relayForByIdx[idx]; ok {
  101. newRelay := *r
  102. newRelay.State = state
  103. rs.relayForByAddr[newRelay.PeerAddr] = &newRelay
  104. rs.relayForByIdx[newRelay.LocalIndex] = &newRelay
  105. }
  106. }
  107. func (rs *RelayState) CopyAllRelayFor() []*Relay {
  108. rs.RLock()
  109. defer rs.RUnlock()
  110. ret := make([]*Relay, 0, len(rs.relayForByIdx))
  111. for _, r := range rs.relayForByIdx {
  112. ret = append(ret, r)
  113. }
  114. return ret
  115. }
  116. func (rs *RelayState) GetRelayForByAddr(addr netip.Addr) (*Relay, bool) {
  117. rs.RLock()
  118. defer rs.RUnlock()
  119. r, ok := rs.relayForByAddr[addr]
  120. return r, ok
  121. }
  122. func (rs *RelayState) InsertRelayTo(ip netip.Addr) {
  123. rs.Lock()
  124. defer rs.Unlock()
  125. if !slices.Contains(rs.relays, ip) {
  126. rs.relays = append(rs.relays, ip)
  127. }
  128. }
  129. func (rs *RelayState) CopyRelayIps() []netip.Addr {
  130. rs.RLock()
  131. defer rs.RUnlock()
  132. ret := make([]netip.Addr, len(rs.relays))
  133. copy(ret, rs.relays)
  134. return ret
  135. }
  136. func (rs *RelayState) CopyRelayForIps() []netip.Addr {
  137. rs.RLock()
  138. defer rs.RUnlock()
  139. currentRelays := make([]netip.Addr, 0, len(rs.relayForByAddr))
  140. for relayIp := range rs.relayForByAddr {
  141. currentRelays = append(currentRelays, relayIp)
  142. }
  143. return currentRelays
  144. }
  145. func (rs *RelayState) CopyRelayForIdxs() []uint32 {
  146. rs.RLock()
  147. defer rs.RUnlock()
  148. ret := make([]uint32, 0, len(rs.relayForByIdx))
  149. for i := range rs.relayForByIdx {
  150. ret = append(ret, i)
  151. }
  152. return ret
  153. }
  154. func (rs *RelayState) CompleteRelayByIP(vpnIp netip.Addr, remoteIdx uint32) bool {
  155. rs.Lock()
  156. defer rs.Unlock()
  157. r, ok := rs.relayForByAddr[vpnIp]
  158. if !ok {
  159. return false
  160. }
  161. newRelay := *r
  162. newRelay.State = Established
  163. newRelay.RemoteIndex = remoteIdx
  164. rs.relayForByIdx[r.LocalIndex] = &newRelay
  165. rs.relayForByAddr[r.PeerAddr] = &newRelay
  166. return true
  167. }
  168. func (rs *RelayState) CompleteRelayByIdx(localIdx uint32, remoteIdx uint32) (*Relay, bool) {
  169. rs.Lock()
  170. defer rs.Unlock()
  171. r, ok := rs.relayForByIdx[localIdx]
  172. if !ok {
  173. return nil, false
  174. }
  175. newRelay := *r
  176. newRelay.State = Established
  177. newRelay.RemoteIndex = remoteIdx
  178. rs.relayForByIdx[r.LocalIndex] = &newRelay
  179. rs.relayForByAddr[r.PeerAddr] = &newRelay
  180. return &newRelay, true
  181. }
  182. func (rs *RelayState) QueryRelayForByIp(vpnIp netip.Addr) (*Relay, bool) {
  183. rs.RLock()
  184. defer rs.RUnlock()
  185. r, ok := rs.relayForByAddr[vpnIp]
  186. return r, ok
  187. }
  188. func (rs *RelayState) QueryRelayForByIdx(idx uint32) (*Relay, bool) {
  189. rs.RLock()
  190. defer rs.RUnlock()
  191. r, ok := rs.relayForByIdx[idx]
  192. return r, ok
  193. }
  194. func (rs *RelayState) InsertRelay(ip netip.Addr, idx uint32, r *Relay) {
  195. rs.Lock()
  196. defer rs.Unlock()
  197. rs.relayForByAddr[ip] = r
  198. rs.relayForByIdx[idx] = r
  199. }
  200. type NetworkType uint8
  201. const (
  202. NetworkTypeUnknown NetworkType = iota
  203. // NetworkTypeVPN is a network that overlaps one or more of the vpnNetworks in our certificate
  204. NetworkTypeVPN
  205. // NetworkTypeVPNPeer is a network that does not overlap one of our networks
  206. NetworkTypeVPNPeer
  207. // NetworkTypeUnsafe is a network from Certificate.UnsafeNetworks()
  208. NetworkTypeUnsafe
  209. )
  210. type HostInfo struct {
  211. remote atomic.Pointer[netip.AddrPort]
  212. remotes *RemoteList
  213. promoteCounter atomic.Uint32
  214. ConnectionState *ConnectionState
  215. remoteIndexId uint32
  216. localIndexId uint32
  217. // vpnAddrs is a list of vpn addresses assigned to this host that are within our own vpn networks
  218. // The host may have other vpn addresses that are outside our
  219. // vpn networks but were removed because they are not usable
  220. vpnAddrs []netip.Addr
  221. // networks is a combination of specific vpn addresses (not prefixes!) and full unsafe networks assigned to this host.
  222. networks *bart.Table[NetworkType]
  223. relayState RelayState
  224. // HandshakePacket records the packets used to create this hostinfo
  225. // We need these to avoid replayed handshake packets creating new hostinfos which causes churn
  226. HandshakePacket map[uint8][]byte
  227. // nextLHQuery is the earliest we can ask the lighthouse for new information.
  228. // This is used to limit lighthouse re-queries in chatty clients
  229. nextLHQuery atomic.Int64
  230. // lastRebindCount is the other side of Interface.rebindCount, if these values don't match then we need to ask LH
  231. // for a punch from the remote end of this tunnel. The goal being to prime their conntrack for our traffic just like
  232. // with a handshake
  233. lastRebindCount int8
  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. //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
  241. in, out, pendingDeletion atomic.Bool
  242. // lastUsed tracks the last time ConnectionManager checked the tunnel and it was in use.
  243. // This value will be behind against actual tunnel utilization in the hot path.
  244. // This should only be used by the ConnectionManagers ticker routine.
  245. lastUsed time.Time
  246. }
  247. type ViaSender struct {
  248. UdpAddr netip.AddrPort
  249. relayHI *HostInfo // relayHI is the host info object of the relay
  250. relay *Relay // relay contains the rest of the relay information, including the PeerIP of the host trying to communicate with us.
  251. IsRelayed bool // IsRelayed is true if the packet was sent through a relay
  252. }
  253. func (v ViaSender) String() string {
  254. if v.IsRelayed {
  255. return fmt.Sprintf("%s (relayed)", v.UdpAddr)
  256. }
  257. return v.UdpAddr.String()
  258. }
  259. func (v ViaSender) MarshalJSON() ([]byte, error) {
  260. if v.IsRelayed {
  261. return json.Marshal(m{"relay": v.UdpAddr})
  262. }
  263. return json.Marshal(m{"direct": v.UdpAddr})
  264. }
  265. type cachedPacket struct {
  266. messageType header.MessageType
  267. messageSubType header.MessageSubType
  268. callback packetCallback
  269. packet []byte
  270. }
  271. type packetCallback func(t header.MessageType, st header.MessageSubType, h *HostInfo, p, nb, out []byte)
  272. type cachedPacketMetrics struct {
  273. sent metrics.Counter
  274. dropped metrics.Counter
  275. }
  276. func NewHostMapFromConfig(l *slog.Logger, c *config.C) *HostMap {
  277. hm := newHostMap(l)
  278. hm.reload(c, true)
  279. c.RegisterReloadCallback(func(c *config.C) {
  280. hm.reload(c, false)
  281. })
  282. l.Info("Main HostMap created", "preferredRanges", hm.GetPreferredRanges())
  283. return hm
  284. }
  285. func newHostMap(l *slog.Logger) *HostMap {
  286. return &HostMap{
  287. Indexes: map[uint32]*HostInfo{},
  288. Relays: map[uint32]*HostInfo{},
  289. RemoteIndexes: map[uint32]*HostInfo{},
  290. Hosts: map[netip.Addr]*HostInfo{},
  291. moreHosts: map[netip.Addr][]*HostInfo{},
  292. l: l,
  293. }
  294. }
  295. func (hm *HostMap) reload(c *config.C, initial bool) {
  296. if initial || c.HasChanged("preferred_ranges") {
  297. var preferredRanges []netip.Prefix
  298. rawPreferredRanges := c.GetStringSlice("preferred_ranges", []string{})
  299. for _, rawPreferredRange := range rawPreferredRanges {
  300. preferredRange, err := netip.ParsePrefix(rawPreferredRange)
  301. if err != nil {
  302. hm.l.Warn("Failed to parse preferred ranges, ignoring",
  303. "error", err,
  304. "range", rawPreferredRanges,
  305. )
  306. continue
  307. }
  308. preferredRanges = append(preferredRanges, preferredRange)
  309. }
  310. oldRanges := hm.preferredRanges.Swap(&preferredRanges)
  311. if !initial {
  312. hm.l.Info("preferred_ranges changed",
  313. "oldPreferredRanges", *oldRanges,
  314. "newPreferredRanges", preferredRanges,
  315. )
  316. }
  317. }
  318. }
  319. // EmitStats reports host, index, and relay counts to the stats collection system
  320. func (hm *HostMap) EmitStats() {
  321. hm.RLock()
  322. hostLen := len(hm.Hosts)
  323. indexLen := len(hm.Indexes)
  324. remoteIndexLen := len(hm.RemoteIndexes)
  325. relaysLen := len(hm.Relays)
  326. hm.RUnlock()
  327. metrics.GetOrRegisterGauge("hostmap.main.hosts", nil).Update(int64(hostLen))
  328. metrics.GetOrRegisterGauge("hostmap.main.indexes", nil).Update(int64(indexLen))
  329. metrics.GetOrRegisterGauge("hostmap.main.remoteIndexes", nil).Update(int64(remoteIndexLen))
  330. metrics.GetOrRegisterGauge("hostmap.main.relayIndexes", nil).Update(int64(relaysLen))
  331. }
  332. // unlockedSetHostsForAddr stores the per-address hostinfo list (list[0] is the primary). An empty
  333. // list removes the address. This is the one place Hosts and moreHosts are written together, keep
  334. // it that way. Callers must hold the write lock.
  335. func (hm *HostMap) unlockedSetHostsForAddr(addr netip.Addr, list []*HostInfo) {
  336. if len(list) == 0 {
  337. delete(hm.Hosts, addr)
  338. delete(hm.moreHosts, addr)
  339. return
  340. }
  341. hm.Hosts[addr] = list[0]
  342. if len(list) > 1 {
  343. hm.moreHosts[addr] = list
  344. } else {
  345. delete(hm.moreHosts, addr)
  346. }
  347. }
  348. // unlockedGetHostList returns every hostinfo holding addr, primary first, or nil if we have no
  349. // tunnel for addr. The common single-hostinfo case builds a fresh one element list, so keep this
  350. // off the packet hot path; the primary is a direct Hosts read. Callers must hold the lock (read
  351. // or write).
  352. func (hm *HostMap) unlockedGetHostList(addr netip.Addr) []*HostInfo {
  353. if list, ok := hm.moreHosts[addr]; ok {
  354. return list
  355. }
  356. if h, ok := hm.Hosts[addr]; ok {
  357. return []*HostInfo{h}
  358. }
  359. return nil
  360. }
  361. // removeHostInfo returns list with hi removed (order preserved), or list unchanged if hi is
  362. // absent. It deletes in place: every mutator holds the hostmap write lock and no reader ever
  363. // retains a slice across a mutation (readers iterate under RLock), so there is no snapshot to
  364. // invalidate.
  365. func removeHostInfo(list []*HostInfo, hi *HostInfo) []*HostInfo {
  366. idx := slices.Index(list, hi)
  367. if idx < 0 {
  368. return list
  369. }
  370. return slices.Delete(list, idx, idx+1)
  371. }
  372. // DeleteHostInfo will fully unlink the hostinfo and return true if no other hostinfo still holds
  373. // any of its vpn addrs, meaning we no longer have a tunnel to the peer
  374. func (hm *HostMap) DeleteHostInfo(hostinfo *HostInfo) bool {
  375. // Delete the host itself, ensuring it's not modified anymore
  376. hm.Lock()
  377. final := hm.unlockedDeleteHostInfo(hostinfo)
  378. hm.Unlock()
  379. return final
  380. }
  381. func (hm *HostMap) MakePrimary(hostinfo *HostInfo) {
  382. hm.Lock()
  383. defer hm.Unlock()
  384. hm.unlockedMakePrimary(hostinfo)
  385. }
  386. // unlockedMakePrimary reports whether hostinfo is (now) the primary for each of its addresses,
  387. // false only when it is no longer in the hostmap at all.
  388. func (hm *HostMap) unlockedMakePrimary(hostinfo *HostInfo) bool {
  389. // A hostinfo that is no longer in the hostmap must not be re-inserted here. Callers can race
  390. // tunnel teardown, deciding to promote under the read lock and only taking the write lock
  391. // after a delete fully unlinked the hostinfo (connection manager swapPrimary, AddRelay). Every
  392. // live hostinfo is registered in Indexes by unlockedAddHostInfo, so this is a membership test.
  393. if hm.Indexes[hostinfo.localIndexId] != hostinfo {
  394. return false
  395. }
  396. // Move hostinfo to the front (primary) of each of its address lists. The lists are
  397. // independent per address, so this can never leave a dangling entry the way promoting
  398. // against a single shared chain could.
  399. for _, addr := range hostinfo.vpnAddrs {
  400. if hm.Hosts[addr] == hostinfo {
  401. // Already primary for this address, the list is already in the right order
  402. continue
  403. }
  404. list := removeHostInfo(hm.unlockedGetHostList(addr), hostinfo)
  405. list = append([]*HostInfo{hostinfo}, list...)
  406. hm.unlockedSetHostsForAddr(addr, list)
  407. }
  408. return true
  409. }
  410. // unlockedDeleteHostInfo removes hostinfo from every one of its address lists and from the index
  411. // maps. It returns true if this was the last hostinfo for all of its addresses (we no longer have
  412. // any tunnel to the peer), which the caller uses to decide whether to clear learned lighthouse
  413. // state and disestablish relays.
  414. func (hm *HostMap) unlockedDeleteHostInfo(hostinfo *HostInfo) bool {
  415. // Remove this hostinfo from each of its address lists. The lists are independent, so a
  416. // sibling is never promoted to an address it does not own and no other list is touched.
  417. final := true
  418. for _, addr := range hostinfo.vpnAddrs {
  419. if list, ok := hm.moreHosts[addr]; ok {
  420. list = removeHostInfo(list, hostinfo)
  421. hm.unlockedSetHostsForAddr(addr, list)
  422. if len(list) > 0 {
  423. final = false
  424. }
  425. } else if existing, ok := hm.Hosts[addr]; ok {
  426. if existing == hostinfo {
  427. // Common case, the only hostinfo for this address. moreHosts has no entry to clean up.
  428. delete(hm.Hosts, addr)
  429. } else {
  430. // We don't hold this address but another hostinfo does, we still have a tunnel to the peer
  431. final = false
  432. }
  433. }
  434. }
  435. // Go maps never shrink their buckets, replace fully drained maps so a node that churned
  436. // through a large peer count gives the memory back. Same idiom as the index maps below.
  437. if len(hm.Hosts) == 0 {
  438. hm.Hosts = map[netip.Addr]*HostInfo{}
  439. }
  440. if len(hm.moreHosts) == 0 {
  441. hm.moreHosts = map[netip.Addr][]*HostInfo{}
  442. }
  443. // The remote index uses index ids outside our control so lets make sure we are only removing
  444. // the remote index pointer here if it points to the hostinfo we are deleting
  445. hostinfo2, ok := hm.RemoteIndexes[hostinfo.remoteIndexId]
  446. if ok && hostinfo2 == hostinfo {
  447. delete(hm.RemoteIndexes, hostinfo.remoteIndexId)
  448. if len(hm.RemoteIndexes) == 0 {
  449. hm.RemoteIndexes = map[uint32]*HostInfo{}
  450. }
  451. }
  452. delete(hm.Indexes, hostinfo.localIndexId)
  453. if len(hm.Indexes) == 0 {
  454. hm.Indexes = map[uint32]*HostInfo{}
  455. }
  456. if hm.l.Enabled(context.Background(), slog.LevelDebug) {
  457. hm.l.Debug("Hostmap hostInfo deleted",
  458. "hostMap", m{"mapTotalSize": len(hm.Hosts),
  459. "vpnAddrs": hostinfo.vpnAddrs, "indexNumber": hostinfo.localIndexId, "remoteIndexNumber": hostinfo.remoteIndexId},
  460. )
  461. }
  462. if final {
  463. // I have lost connectivity to my peers. My relay tunnel is likely broken. Mark the next
  464. // hops as 'Requested' so that new relay tunnels are created in the future.
  465. hm.unlockedDisestablishVpnAddrRelayFor(hostinfo)
  466. }
  467. // Clean up any local relay indexes for which I am acting as a relay hop
  468. for _, localRelayIdx := range hostinfo.relayState.CopyRelayForIdxs() {
  469. delete(hm.Relays, localRelayIdx)
  470. }
  471. return final
  472. }
  473. func (hm *HostMap) QueryIndex(index uint32) *HostInfo {
  474. hm.RLock()
  475. if h, ok := hm.Indexes[index]; ok {
  476. hm.RUnlock()
  477. return h
  478. } else {
  479. hm.RUnlock()
  480. return nil
  481. }
  482. }
  483. func (hm *HostMap) QueryRelayIndex(index uint32) *HostInfo {
  484. hm.RLock()
  485. if h, ok := hm.Relays[index]; ok {
  486. hm.RUnlock()
  487. return h
  488. } else {
  489. hm.RUnlock()
  490. return nil
  491. }
  492. }
  493. func (hm *HostMap) QueryReverseIndex(index uint32) *HostInfo {
  494. hm.RLock()
  495. if h, ok := hm.RemoteIndexes[index]; ok {
  496. hm.RUnlock()
  497. return h
  498. } else {
  499. hm.RUnlock()
  500. return nil
  501. }
  502. }
  503. func (hm *HostMap) QueryVpnAddr(vpnIp netip.Addr) *HostInfo {
  504. return hm.queryVpnAddr(vpnIp, nil)
  505. }
  506. func (hm *HostMap) QueryVpnAddrsRelayFor(targetIps []netip.Addr, relayHostIp netip.Addr) (*HostInfo, *Relay, error) {
  507. hm.RLock()
  508. defer hm.RUnlock()
  509. // This runs per relayed packet, so check the primary with a single map probe and only consult
  510. // moreHosts when the primary can't relay for us.
  511. h, ok := hm.Hosts[relayHostIp]
  512. if !ok {
  513. return nil, nil, errors.New("unable to find host")
  514. }
  515. for _, targetIp := range targetIps {
  516. r, ok := h.relayState.QueryRelayForByIp(targetIp)
  517. if ok && r.State == Established {
  518. return h, r, nil
  519. }
  520. }
  521. if list, ok := hm.moreHosts[relayHostIp]; ok {
  522. // list[0] is the primary we already checked
  523. for _, h := range list[1:] {
  524. for _, targetIp := range targetIps {
  525. r, ok := h.relayState.QueryRelayForByIp(targetIp)
  526. if ok && r.State == Established {
  527. return h, r, nil
  528. }
  529. }
  530. }
  531. }
  532. return nil, nil, errors.New("unable to find host with relay")
  533. }
  534. func (hm *HostMap) unlockedDisestablishVpnAddrRelayFor(hi *HostInfo) {
  535. for _, relayHostIp := range hi.relayState.CopyRelayIps() {
  536. for _, h := range hm.unlockedGetHostList(relayHostIp) {
  537. h.relayState.UpdateRelayForByIpState(hi.vpnAddrs[0], Disestablished)
  538. }
  539. }
  540. for _, rs := range hi.relayState.CopyAllRelayFor() {
  541. if rs.Type == ForwardingType {
  542. for _, h := range hm.unlockedGetHostList(rs.PeerAddr) {
  543. h.relayState.UpdateRelayForByIpState(hi.vpnAddrs[0], Disestablished)
  544. }
  545. }
  546. }
  547. }
  548. func (hm *HostMap) queryVpnAddr(vpnIp netip.Addr, promoteIfce *Interface) *HostInfo {
  549. hm.RLock()
  550. if h, ok := hm.Hosts[vpnIp]; ok {
  551. hm.RUnlock()
  552. // Do not attempt promotion if you are a lighthouse
  553. if promoteIfce != nil && !promoteIfce.lightHouse.amLighthouse {
  554. h.TryPromoteBest(hm.GetPreferredRanges(), promoteIfce)
  555. }
  556. return h
  557. }
  558. hm.RUnlock()
  559. return nil
  560. }
  561. // unlockedAddHostInfo assumes you have a write-lock and will add a hostinfo object to the hostmap Indexes and RemoteIndexes maps.
  562. // If an entry exists for the Hosts table (vpnIp -> hostinfo) then the provided hostinfo will be made primary
  563. func (hm *HostMap) unlockedAddHostInfo(hostinfo *HostInfo, f *Interface) {
  564. if f.dnsServer != nil {
  565. remoteCert := hostinfo.ConnectionState.peerCert
  566. f.dnsServer.Add(remoteCert.Certificate.Name()+".", hostinfo.vpnAddrs)
  567. }
  568. for _, addr := range hostinfo.vpnAddrs {
  569. hm.unlockedInnerAddHostInfo(addr, hostinfo, f)
  570. }
  571. hm.Indexes[hostinfo.localIndexId] = hostinfo
  572. hm.RemoteIndexes[hostinfo.remoteIndexId] = hostinfo
  573. hostinfo.out.Store(true)
  574. if f.connectionManager != nil { // f.connectionManager is only nil in some unit tests
  575. f.connectionManager.trafficTimer.Add(hostinfo.localIndexId, f.connectionManager.checkInterval)
  576. }
  577. if hm.l.Enabled(context.Background(), slog.LevelDebug) {
  578. hm.l.Debug("Hostmap vpnIp added",
  579. "hostMap", m{"vpnAddrs": hostinfo.vpnAddrs, "mapTotalSize": len(hm.Hosts),
  580. "hostinfo": m{"existing": true, "localIndexId": hostinfo.localIndexId, "vpnAddrs": hostinfo.vpnAddrs}},
  581. )
  582. }
  583. }
  584. func (hm *HostMap) unlockedInnerAddHostInfo(vpnAddr netip.Addr, hostinfo *HostInfo, f *Interface) {
  585. existing, ok := hm.Hosts[vpnAddr]
  586. if !ok {
  587. // Common case, the first hostinfo for this address. moreHosts stays empty.
  588. hm.Hosts[vpnAddr] = hostinfo
  589. return
  590. }
  591. // The new hostinfo becomes the primary for this address. Remove any stale copy of it first so
  592. // we never hold a duplicate, then prepend.
  593. list, ok := hm.moreHosts[vpnAddr]
  594. if !ok {
  595. list = []*HostInfo{existing}
  596. }
  597. list = removeHostInfo(list, hostinfo)
  598. list = append([]*HostInfo{hostinfo}, list...)
  599. hm.unlockedSetHostsForAddr(vpnAddr, list)
  600. // Enforce the per-address cap by fully retiring the oldest hostinfo once we exceed it.
  601. // Deleting it removes it from all of its addresses and the index maps, matching prior behavior.
  602. if len(list) > MaxHostInfosPerVpnIp {
  603. hm.unlockedDeleteHostInfo(list[len(list)-1])
  604. }
  605. }
  606. func (hm *HostMap) GetPreferredRanges() []netip.Prefix {
  607. //NOTE: if preferredRanges is ever not stored before a load this will fail to dereference a nil pointer
  608. return *hm.preferredRanges.Load()
  609. }
  610. func (hm *HostMap) ForEachVpnAddr(f controlEach) {
  611. hm.RLock()
  612. defer hm.RUnlock()
  613. for _, v := range hm.Hosts {
  614. f(v)
  615. }
  616. }
  617. func (hm *HostMap) ForEachIndex(f controlEach) {
  618. hm.RLock()
  619. defer hm.RUnlock()
  620. for _, v := range hm.Indexes {
  621. f(v)
  622. }
  623. }
  624. // TryPromoteBest handles re-querying lighthouses and probing for better paths
  625. // NOTE: It is an error to call this if you are a lighthouse since they should not roam clients!
  626. func (i *HostInfo) TryPromoteBest(preferredRanges []netip.Prefix, ifce *Interface) {
  627. c := i.promoteCounter.Add(1)
  628. if c%ifce.tryPromoteEvery.Load() == 0 {
  629. remote := i.GetRemote()
  630. // return early if we are already on a preferred remote
  631. if remote.IsValid() {
  632. rIP := remote.Addr()
  633. for _, l := range preferredRanges {
  634. if l.Contains(rIP) {
  635. return
  636. }
  637. }
  638. }
  639. i.remotes.ForEach(preferredRanges, func(addr netip.AddrPort, preferred bool) {
  640. if remote.IsValid() && (!addr.IsValid() || !preferred) {
  641. return
  642. }
  643. // Try to send a test packet to that host, this should
  644. // cause it to detect a roaming event and switch remotes
  645. ifce.sendTo(header.Test, header.TestRequest, i.ConnectionState, i, addr, []byte(""), make([]byte, 12, 12), make([]byte, mtu))
  646. })
  647. }
  648. // Re query our lighthouses for new remotes occasionally
  649. if c%ifce.reQueryEvery.Load() == 0 && ifce.lightHouse != nil {
  650. now := time.Now().UnixNano()
  651. if now < i.nextLHQuery.Load() {
  652. return
  653. }
  654. i.nextLHQuery.Store(now + ifce.reQueryWait.Load())
  655. ifce.lightHouse.QueryServer(i.vpnAddrs[0])
  656. }
  657. }
  658. func (i *HostInfo) GetCert() *cert.CachedCertificate {
  659. if i.ConnectionState != nil {
  660. return i.ConnectionState.peerCert
  661. }
  662. return nil
  663. }
  664. func (i *HostInfo) GetRemote() netip.AddrPort {
  665. if p := i.remote.Load(); p != nil {
  666. return *p
  667. }
  668. return netip.AddrPort{}
  669. }
  670. // TODO: Maybe use ViaSender here?
  671. func (i *HostInfo) SetRemote(remote netip.AddrPort) {
  672. // We copy here because we likely got this remote from a source that reuses the object
  673. if i.GetRemote() != remote {
  674. i.remote.Store(&remote)
  675. i.remotes.LearnRemote(i.vpnAddrs[0], remote)
  676. }
  677. }
  678. // SetRemoteIfPreferred returns true if the remote was changed. The lastRoam
  679. // time on the HostInfo will also be updated.
  680. func (i *HostInfo) SetRemoteIfPreferred(hm *HostMap, via ViaSender) bool {
  681. if via.IsRelayed {
  682. return false
  683. }
  684. currentRemote := i.GetRemote()
  685. if !currentRemote.IsValid() {
  686. i.SetRemote(via.UdpAddr)
  687. return true
  688. }
  689. // NOTE: We do this loop here instead of calling `isPreferred` in
  690. // remote_list.go so that we only have to loop over preferredRanges once.
  691. newIsPreferred := false
  692. for _, l := range hm.GetPreferredRanges() {
  693. // return early if we are already on a preferred remote
  694. if l.Contains(currentRemote.Addr()) {
  695. return false
  696. }
  697. if l.Contains(via.UdpAddr.Addr()) {
  698. newIsPreferred = true
  699. }
  700. }
  701. if newIsPreferred {
  702. // Consider this a roaming event
  703. i.lastRoam = time.Now()
  704. i.lastRoamRemote = currentRemote
  705. i.SetRemote(via.UdpAddr)
  706. return true
  707. }
  708. return false
  709. }
  710. // buildNetworks fills in the networks field of HostInfo. It accepts a cert.Certificate so you never ever mix the network types up.
  711. func (i *HostInfo) buildNetworks(myVpnNetworksTable *bart.Lite, c cert.Certificate) {
  712. if len(c.Networks()) == 1 && len(c.UnsafeNetworks()) == 0 {
  713. if myVpnNetworksTable.Contains(c.Networks()[0].Addr()) {
  714. return // Simple case, no BART needed
  715. }
  716. }
  717. i.networks = new(bart.Table[NetworkType])
  718. for _, network := range c.Networks() {
  719. nprefix := netip.PrefixFrom(network.Addr(), network.Addr().BitLen())
  720. if myVpnNetworksTable.Contains(network.Addr()) {
  721. i.networks.Insert(nprefix, NetworkTypeVPN)
  722. } else {
  723. i.networks.Insert(nprefix, NetworkTypeVPNPeer)
  724. }
  725. }
  726. for _, network := range c.UnsafeNetworks() {
  727. i.networks.Insert(network, NetworkTypeUnsafe)
  728. }
  729. }
  730. // logger returns a derived slog.Logger with per-hostinfo fields pre-bound.
  731. func (i *HostInfo) logger(l *slog.Logger) *slog.Logger {
  732. if i == nil {
  733. return l
  734. }
  735. li := l.With(
  736. "vpnAddrs", i.vpnAddrs,
  737. "localIndex", i.localIndexId,
  738. "remoteIndex", i.remoteIndexId,
  739. )
  740. if connState := i.ConnectionState; connState != nil {
  741. if peerCert := connState.peerCert; peerCert != nil {
  742. li = li.With("certName", peerCert.Certificate.Name())
  743. }
  744. }
  745. return li
  746. }