1
0

hostmap.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988
  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. }
  245. type ViaSender struct {
  246. UdpAddr netip.AddrPort
  247. relayHI *HostInfo // relayHI is the host info object of the relay
  248. relay *Relay // relay contains the rest of the relay information, including the PeerIP of the host trying to communicate with us.
  249. IsRelayed bool // IsRelayed is true if the packet was sent through a relay
  250. }
  251. func (v ViaSender) String() string {
  252. if v.IsRelayed {
  253. return fmt.Sprintf("%s (relayed)", v.UdpAddr)
  254. }
  255. return v.UdpAddr.String()
  256. }
  257. func (v ViaSender) MarshalJSON() ([]byte, error) {
  258. if v.IsRelayed {
  259. return json.Marshal(m{"relay": v.UdpAddr})
  260. }
  261. return json.Marshal(m{"direct": v.UdpAddr})
  262. }
  263. type cachedPacket struct {
  264. messageType header.MessageType
  265. messageSubType header.MessageSubType
  266. callback packetCallback
  267. packet []byte
  268. }
  269. type packetCallback func(t header.MessageType, st header.MessageSubType, h *HostInfo, p, nb, out []byte)
  270. type cachedPacketMetrics struct {
  271. sent metrics.Counter
  272. dropped metrics.Counter
  273. }
  274. func NewHostMapFromConfig(l *slog.Logger, c *config.C) *HostMap {
  275. hm := newHostMap(l)
  276. hm.reload(c, true)
  277. c.RegisterReloadCallback(func(c *config.C) {
  278. hm.reload(c, false)
  279. })
  280. l.Info("Main HostMap created", "preferredRanges", hm.GetPreferredRanges())
  281. return hm
  282. }
  283. func newHostMap(l *slog.Logger) *HostMap {
  284. return &HostMap{
  285. Indexes: map[uint32]*HostInfo{},
  286. Relays: map[uint32]*HostInfo{},
  287. RemoteIndexes: map[uint32]*HostInfo{},
  288. Hosts: map[netip.Addr]*HostInfo{},
  289. moreHosts: map[netip.Addr][]*HostInfo{},
  290. l: l,
  291. }
  292. }
  293. func (hm *HostMap) reload(c *config.C, initial bool) {
  294. if initial || c.HasChanged("preferred_ranges") {
  295. var preferredRanges []netip.Prefix
  296. rawPreferredRanges := c.GetStringSlice("preferred_ranges", []string{})
  297. for _, rawPreferredRange := range rawPreferredRanges {
  298. preferredRange, err := netip.ParsePrefix(rawPreferredRange)
  299. if err != nil {
  300. hm.l.Warn("Failed to parse preferred ranges, ignoring",
  301. "error", err,
  302. "range", rawPreferredRanges,
  303. )
  304. continue
  305. }
  306. preferredRanges = append(preferredRanges, preferredRange)
  307. }
  308. oldRanges := hm.preferredRanges.Swap(&preferredRanges)
  309. if !initial {
  310. hm.l.Info("preferred_ranges changed",
  311. "oldPreferredRanges", *oldRanges,
  312. "newPreferredRanges", preferredRanges,
  313. )
  314. }
  315. }
  316. }
  317. // EmitStats reports host, index, and relay counts to the stats collection system
  318. func (hm *HostMap) EmitStats() {
  319. hm.RLock()
  320. hostLen := len(hm.Hosts)
  321. indexLen := len(hm.Indexes)
  322. remoteIndexLen := len(hm.RemoteIndexes)
  323. relaysLen := len(hm.Relays)
  324. hm.RUnlock()
  325. metrics.GetOrRegisterGauge("hostmap.main.hosts", nil).Update(int64(hostLen))
  326. metrics.GetOrRegisterGauge("hostmap.main.indexes", nil).Update(int64(indexLen))
  327. metrics.GetOrRegisterGauge("hostmap.main.remoteIndexes", nil).Update(int64(remoteIndexLen))
  328. metrics.GetOrRegisterGauge("hostmap.main.relayIndexes", nil).Update(int64(relaysLen))
  329. }
  330. // unlockedSetHostsForAddr stores the per-address hostinfo list (list[0] is the primary). An empty
  331. // list removes the address. This is the one place Hosts and moreHosts are written together, keep
  332. // it that way. Callers must hold the write lock.
  333. func (hm *HostMap) unlockedSetHostsForAddr(addr netip.Addr, list []*HostInfo) {
  334. if len(list) == 0 {
  335. delete(hm.Hosts, addr)
  336. delete(hm.moreHosts, addr)
  337. return
  338. }
  339. hm.Hosts[addr] = list[0]
  340. if len(list) > 1 {
  341. hm.moreHosts[addr] = list
  342. } else {
  343. delete(hm.moreHosts, addr)
  344. }
  345. }
  346. // unlockedGetHostList returns every hostinfo holding addr, primary first, or nil if we have no
  347. // tunnel for addr. The common single-hostinfo case builds a fresh one element list, so keep this
  348. // off the packet hot path; the primary is a direct Hosts read. Callers must hold the lock (read
  349. // or write).
  350. func (hm *HostMap) unlockedGetHostList(addr netip.Addr) []*HostInfo {
  351. if list, ok := hm.moreHosts[addr]; ok {
  352. return list
  353. }
  354. if h, ok := hm.Hosts[addr]; ok {
  355. return []*HostInfo{h}
  356. }
  357. return nil
  358. }
  359. // removeHostInfo returns list with hi removed (order preserved), or list unchanged if hi is
  360. // absent. It deletes in place: every mutator holds the hostmap write lock and no reader ever
  361. // retains a slice across a mutation (readers iterate under RLock), so there is no snapshot to
  362. // invalidate.
  363. func removeHostInfo(list []*HostInfo, hi *HostInfo) []*HostInfo {
  364. idx := slices.Index(list, hi)
  365. if idx < 0 {
  366. return list
  367. }
  368. return slices.Delete(list, idx, idx+1)
  369. }
  370. // DeleteHostInfo will fully unlink the hostinfo and return true if no other hostinfo still holds
  371. // any of its vpn addrs, meaning we no longer have a tunnel to the peer
  372. func (hm *HostMap) DeleteHostInfo(hostinfo *HostInfo) bool {
  373. // Delete the host itself, ensuring it's not modified anymore
  374. hm.Lock()
  375. final := hm.unlockedDeleteHostInfo(hostinfo)
  376. hm.Unlock()
  377. return final
  378. }
  379. func (hm *HostMap) MakePrimary(hostinfo *HostInfo) {
  380. hm.Lock()
  381. defer hm.Unlock()
  382. hm.unlockedMakePrimary(hostinfo)
  383. }
  384. // unlockedMakePrimary reports whether hostinfo is (now) the primary for each of its addresses,
  385. // false only when it is no longer in the hostmap at all.
  386. func (hm *HostMap) unlockedMakePrimary(hostinfo *HostInfo) bool {
  387. // A hostinfo that is no longer in the hostmap must not be re-inserted here. Callers can race
  388. // tunnel teardown, deciding to promote under the read lock and only taking the write lock
  389. // after a delete fully unlinked the hostinfo (connection manager swapPrimary, AddRelay). Every
  390. // live hostinfo is registered in Indexes by unlockedAddHostInfo, so this is a membership test.
  391. if hm.Indexes[hostinfo.localIndexId] != hostinfo {
  392. return false
  393. }
  394. // Move hostinfo to the front (primary) of each of its address lists. The lists are
  395. // independent per address, so this can never leave a dangling entry the way promoting
  396. // against a single shared chain could.
  397. for _, addr := range hostinfo.vpnAddrs {
  398. if hm.Hosts[addr] == hostinfo {
  399. // Already primary for this address, the list is already in the right order
  400. continue
  401. }
  402. list := removeHostInfo(hm.unlockedGetHostList(addr), hostinfo)
  403. list = append([]*HostInfo{hostinfo}, list...)
  404. hm.unlockedSetHostsForAddr(addr, list)
  405. }
  406. return true
  407. }
  408. // unlockedDeleteHostInfo removes hostinfo from every one of its address lists and from the index
  409. // maps. It returns true if this was the last hostinfo for all of its addresses (we no longer have
  410. // any tunnel to the peer), which the caller uses to decide whether to clear learned lighthouse
  411. // state and disestablish relays.
  412. func (hm *HostMap) unlockedDeleteHostInfo(hostinfo *HostInfo) bool {
  413. // Remove this hostinfo from each of its address lists. The lists are independent, so a
  414. // sibling is never promoted to an address it does not own and no other list is touched.
  415. final := true
  416. for _, addr := range hostinfo.vpnAddrs {
  417. if list, ok := hm.moreHosts[addr]; ok {
  418. list = removeHostInfo(list, hostinfo)
  419. hm.unlockedSetHostsForAddr(addr, list)
  420. if len(list) > 0 {
  421. final = false
  422. }
  423. } else if existing, ok := hm.Hosts[addr]; ok {
  424. if existing == hostinfo {
  425. // Common case, the only hostinfo for this address. moreHosts has no entry to clean up.
  426. delete(hm.Hosts, addr)
  427. } else {
  428. // We don't hold this address but another hostinfo does, we still have a tunnel to the peer
  429. final = false
  430. }
  431. }
  432. }
  433. // Go maps never shrink their buckets, replace fully drained maps so a node that churned
  434. // through a large peer count gives the memory back. Same idiom as the index maps below.
  435. if len(hm.Hosts) == 0 {
  436. hm.Hosts = map[netip.Addr]*HostInfo{}
  437. }
  438. if len(hm.moreHosts) == 0 {
  439. hm.moreHosts = map[netip.Addr][]*HostInfo{}
  440. }
  441. // The remote index uses index ids outside our control so lets make sure we are only removing
  442. // the remote index pointer here if it points to the hostinfo we are deleting
  443. hostinfo2, ok := hm.RemoteIndexes[hostinfo.remoteIndexId]
  444. if ok && hostinfo2 == hostinfo {
  445. delete(hm.RemoteIndexes, hostinfo.remoteIndexId)
  446. if len(hm.RemoteIndexes) == 0 {
  447. hm.RemoteIndexes = map[uint32]*HostInfo{}
  448. }
  449. }
  450. delete(hm.Indexes, hostinfo.localIndexId)
  451. if len(hm.Indexes) == 0 {
  452. hm.Indexes = map[uint32]*HostInfo{}
  453. }
  454. if hm.l.Enabled(context.Background(), slog.LevelDebug) {
  455. hm.l.Debug("Hostmap hostInfo deleted",
  456. "hostMap", m{"mapTotalSize": len(hm.Hosts),
  457. "vpnAddrs": hostinfo.vpnAddrs, "indexNumber": hostinfo.localIndexId, "remoteIndexNumber": hostinfo.remoteIndexId},
  458. )
  459. }
  460. if final {
  461. // I have lost connectivity to my peers. My relay tunnel is likely broken. Mark the next
  462. // hops as 'Requested' so that new relay tunnels are created in the future.
  463. hm.unlockedDisestablishVpnAddrRelayFor(hostinfo)
  464. }
  465. // Clean up any local relay indexes for which I am acting as a relay hop
  466. for _, localRelayIdx := range hostinfo.relayState.CopyRelayForIdxs() {
  467. delete(hm.Relays, localRelayIdx)
  468. }
  469. return final
  470. }
  471. func (hm *HostMap) QueryIndexCached(index uint32, cache map[uint32]*HostInfo) *HostInfo {
  472. if out, ok := cache[index]; ok {
  473. return out
  474. }
  475. out := hm.QueryIndex(index)
  476. if out != nil {
  477. cache[index] = out
  478. }
  479. return out
  480. }
  481. func (hm *HostMap) QueryIndex(index uint32) *HostInfo {
  482. hm.RLock()
  483. if h, ok := hm.Indexes[index]; ok {
  484. hm.RUnlock()
  485. return h
  486. } else {
  487. hm.RUnlock()
  488. return nil
  489. }
  490. }
  491. func (hm *HostMap) QueryRelayIndex(index uint32) *HostInfo {
  492. hm.RLock()
  493. if h, ok := hm.Relays[index]; ok {
  494. hm.RUnlock()
  495. return h
  496. } else {
  497. hm.RUnlock()
  498. return nil
  499. }
  500. }
  501. func (hm *HostMap) QueryReverseIndex(index uint32) *HostInfo {
  502. hm.RLock()
  503. if h, ok := hm.RemoteIndexes[index]; ok {
  504. hm.RUnlock()
  505. return h
  506. } else {
  507. hm.RUnlock()
  508. return nil
  509. }
  510. }
  511. func (hm *HostMap) QueryVpnAddr(vpnIp netip.Addr) *HostInfo {
  512. return hm.queryVpnAddr(vpnIp, nil)
  513. }
  514. func (hm *HostMap) QueryVpnAddrsRelayFor(targetIps []netip.Addr, relayHostIp netip.Addr) (*HostInfo, *Relay, error) {
  515. hm.RLock()
  516. defer hm.RUnlock()
  517. // This runs per relayed packet, so check the primary with a single map probe and only consult
  518. // moreHosts when the primary can't relay for us.
  519. h, ok := hm.Hosts[relayHostIp]
  520. if !ok {
  521. return nil, nil, errors.New("unable to find host")
  522. }
  523. for _, targetIp := range targetIps {
  524. r, ok := h.relayState.QueryRelayForByIp(targetIp)
  525. if ok && r.State == Established {
  526. return h, r, nil
  527. }
  528. }
  529. if list, ok := hm.moreHosts[relayHostIp]; ok {
  530. // list[0] is the primary we already checked
  531. for _, h := range list[1:] {
  532. for _, targetIp := range targetIps {
  533. r, ok := h.relayState.QueryRelayForByIp(targetIp)
  534. if ok && r.State == Established {
  535. return h, r, nil
  536. }
  537. }
  538. }
  539. }
  540. return nil, nil, errors.New("unable to find host with relay")
  541. }
  542. func (hm *HostMap) unlockedDisestablishVpnAddrRelayFor(hi *HostInfo) {
  543. for _, relayHostIp := range hi.relayState.CopyRelayIps() {
  544. for _, h := range hm.unlockedGetHostList(relayHostIp) {
  545. h.relayState.UpdateRelayForByIpState(hi.vpnAddrs[0], Disestablished)
  546. }
  547. }
  548. for _, rs := range hi.relayState.CopyAllRelayFor() {
  549. if rs.Type == ForwardingType {
  550. for _, h := range hm.unlockedGetHostList(rs.PeerAddr) {
  551. h.relayState.UpdateRelayForByIpState(hi.vpnAddrs[0], Disestablished)
  552. }
  553. }
  554. }
  555. }
  556. func (hm *HostMap) queryVpnAddr(vpnIp netip.Addr, promoteIfce *Interface) *HostInfo {
  557. hm.RLock()
  558. if h, ok := hm.Hosts[vpnIp]; ok {
  559. hm.RUnlock()
  560. // Do not attempt promotion if you are a lighthouse
  561. if promoteIfce != nil && !promoteIfce.lightHouse.amLighthouse {
  562. h.TryPromoteBest(hm.GetPreferredRanges(), promoteIfce)
  563. }
  564. return h
  565. }
  566. hm.RUnlock()
  567. return nil
  568. }
  569. // unlockedAddHostInfo assumes you have a write-lock and will add a hostinfo object to the hostmap Indexes and RemoteIndexes maps.
  570. // If an entry exists for the Hosts table (vpnIp -> hostinfo) then the provided hostinfo will be made primary
  571. func (hm *HostMap) unlockedAddHostInfo(hostinfo *HostInfo, f *Interface) {
  572. if f.dnsServer != nil {
  573. remoteCert := hostinfo.ConnectionState.peerCert
  574. f.dnsServer.Add(remoteCert.Certificate.Name()+".", hostinfo.vpnAddrs)
  575. }
  576. for _, addr := range hostinfo.vpnAddrs {
  577. hm.unlockedInnerAddHostInfo(addr, hostinfo, f)
  578. }
  579. hm.Indexes[hostinfo.localIndexId] = hostinfo
  580. hm.RemoteIndexes[hostinfo.remoteIndexId] = hostinfo
  581. hostinfo.markOut(f.rebindEpoch.Load())
  582. if f.connectionManager != nil { // f.connectionManager is only nil in some unit tests
  583. f.connectionManager.trafficTimer.Add(hostinfo.localIndexId, f.connectionManager.checkInterval)
  584. }
  585. if hm.l.Enabled(context.Background(), slog.LevelDebug) {
  586. hm.l.Debug("Hostmap vpnIp added",
  587. "hostMap", m{"vpnAddrs": hostinfo.vpnAddrs, "mapTotalSize": len(hm.Hosts),
  588. "hostinfo": m{"existing": true, "localIndexId": hostinfo.localIndexId, "vpnAddrs": hostinfo.vpnAddrs}},
  589. )
  590. }
  591. }
  592. func (hm *HostMap) unlockedInnerAddHostInfo(vpnAddr netip.Addr, hostinfo *HostInfo, f *Interface) {
  593. existing, ok := hm.Hosts[vpnAddr]
  594. if !ok {
  595. // Common case, the first hostinfo for this address. moreHosts stays empty.
  596. hm.Hosts[vpnAddr] = hostinfo
  597. return
  598. }
  599. // The new hostinfo becomes the primary for this address. Remove any stale copy of it first so
  600. // we never hold a duplicate, then prepend.
  601. list, ok := hm.moreHosts[vpnAddr]
  602. if !ok {
  603. list = []*HostInfo{existing}
  604. }
  605. list = removeHostInfo(list, hostinfo)
  606. list = append([]*HostInfo{hostinfo}, list...)
  607. hm.unlockedSetHostsForAddr(vpnAddr, list)
  608. // Enforce the per-address cap by fully retiring the oldest hostinfo once we exceed it.
  609. // Deleting it removes it from all of its addresses and the index maps, matching prior behavior.
  610. if len(list) > MaxHostInfosPerVpnIp {
  611. hm.unlockedDeleteHostInfo(list[len(list)-1])
  612. }
  613. }
  614. func (hm *HostMap) GetPreferredRanges() []netip.Prefix {
  615. //NOTE: if preferredRanges is ever not stored before a load this will fail to dereference a nil pointer
  616. return *hm.preferredRanges.Load()
  617. }
  618. func (hm *HostMap) ForEachVpnAddr(f controlEach) {
  619. hm.RLock()
  620. defer hm.RUnlock()
  621. for _, v := range hm.Hosts {
  622. f(v)
  623. }
  624. }
  625. func (hm *HostMap) ForEachIndex(f controlEach) {
  626. hm.RLock()
  627. defer hm.RUnlock()
  628. for _, v := range hm.Indexes {
  629. f(v)
  630. }
  631. }
  632. // TryPromoteBest handles re-querying lighthouses and probing for better paths
  633. // NOTE: It is an error to call this if you are a lighthouse since they should not roam clients!
  634. func (i *HostInfo) TryPromoteBest(preferredRanges []netip.Prefix, ifce *Interface) {
  635. c := i.promoteCounter.Add(1)
  636. if c%ifce.tryPromoteEvery.Load() == 0 {
  637. remote := i.GetRemote()
  638. // return early if we are already on a preferred remote
  639. if remote.IsValid() {
  640. rIP := remote.Addr()
  641. for _, l := range preferredRanges {
  642. if l.Contains(rIP) {
  643. return
  644. }
  645. }
  646. }
  647. i.remotes.ForEach(preferredRanges, func(addr netip.AddrPort, preferred bool) {
  648. if remote.IsValid() && (!addr.IsValid() || !preferred) {
  649. return
  650. }
  651. // Try to send a test packet to that host, this should
  652. // cause it to detect a roaming event and switch remotes
  653. ifce.sendTo(header.Test, header.TestRequest, i.ConnectionState, i, addr, []byte(""), make([]byte, 12, 12), make([]byte, mtu))
  654. })
  655. }
  656. // Re query our lighthouses for new remotes occasionally
  657. if c%ifce.reQueryEvery.Load() == 0 && ifce.lightHouse != nil {
  658. now := time.Now().UnixNano()
  659. if now < i.nextLHQuery.Load() {
  660. return
  661. }
  662. i.nextLHQuery.Store(now + ifce.reQueryWait.Load())
  663. ifce.lightHouse.QueryServer(i.vpnAddrs[0])
  664. }
  665. }
  666. // Bits within HostInfo.state, everything above stateEpochShift is the epoch
  667. const (
  668. stateIn uint32 = 1 << iota
  669. stateOut
  670. statePendingDeletion
  671. stateFlags = stateIn | stateOut | statePendingDeletion
  672. // The epoch is the top 29 bits, it would take 2^29 rebinds to wrap and we will never get there
  673. stateEpochShift = 3
  674. )
  675. // markIn records inbound traffic
  676. func (i *HostInfo) markIn() {
  677. if i.state.Load()&stateIn == 0 {
  678. i.state.Or(stateIn)
  679. }
  680. }
  681. // markOut records a send and reports whether the epoch moved, meaning we want a punch from the far side
  682. func (i *HostInfo) markOut(epoch uint32) bool {
  683. e := epoch << stateEpochShift
  684. for {
  685. old := i.state.Load()
  686. if old&stateOut != 0 && old&^stateFlags == e {
  687. return false
  688. }
  689. if i.state.CompareAndSwap(old, old&stateFlags|stateOut|e) {
  690. return old&^stateFlags != e
  691. }
  692. }
  693. }
  694. // markOutOnly records a send without consuming the rebind epoch, for paths that cannot act on a requery
  695. func (i *HostInfo) markOutOnly() {
  696. if i.state.Load()&stateOut == 0 {
  697. i.state.Or(stateOut)
  698. }
  699. }
  700. // takeTraffic clears both traffic bits, leaving the epoch alone, and reports what they were
  701. func (i *HostInfo) takeTraffic() (in bool, out bool) {
  702. old := i.state.And(^(stateIn | stateOut))
  703. return old&stateIn != 0, old&stateOut != 0
  704. }
  705. func (i *HostInfo) setPendingDeletion(v bool) {
  706. if v {
  707. i.state.Or(statePendingDeletion)
  708. } else {
  709. i.state.And(^statePendingDeletion)
  710. }
  711. }
  712. func (i *HostInfo) isPendingDeletion() bool {
  713. return i.state.Load()&statePendingDeletion != 0
  714. }
  715. func (i *HostInfo) GetCert() *cert.CachedCertificate {
  716. if i.ConnectionState != nil {
  717. return i.ConnectionState.peerCert
  718. }
  719. return nil
  720. }
  721. func (i *HostInfo) GetRemote() netip.AddrPort {
  722. if p := i.remote.Load(); p != nil {
  723. return *p
  724. }
  725. return netip.AddrPort{}
  726. }
  727. // TODO: Maybe use ViaSender here?
  728. func (i *HostInfo) SetRemote(remote netip.AddrPort) {
  729. // We copy here because we likely got this remote from a source that reuses the object
  730. if i.GetRemote() != remote {
  731. i.remote.Store(&remote)
  732. i.remotes.LearnRemote(i.vpnAddrs[0], remote)
  733. }
  734. }
  735. // SetRemoteIfPreferred returns true if the remote was changed. The lastRoam
  736. // time on the HostInfo will also be updated.
  737. func (i *HostInfo) SetRemoteIfPreferred(hm *HostMap, via ViaSender) bool {
  738. if via.IsRelayed {
  739. return false
  740. }
  741. currentRemote := i.GetRemote()
  742. if !currentRemote.IsValid() {
  743. i.SetRemote(via.UdpAddr)
  744. return true
  745. }
  746. // NOTE: We do this loop here instead of calling `isPreferred` in
  747. // remote_list.go so that we only have to loop over preferredRanges once.
  748. newIsPreferred := false
  749. for _, l := range hm.GetPreferredRanges() {
  750. // return early if we are already on a preferred remote
  751. if l.Contains(currentRemote.Addr()) {
  752. return false
  753. }
  754. if l.Contains(via.UdpAddr.Addr()) {
  755. newIsPreferred = true
  756. }
  757. }
  758. if newIsPreferred {
  759. // Consider this a roaming event
  760. i.lastRoam = time.Now()
  761. i.lastRoamRemote = currentRemote
  762. i.SetRemote(via.UdpAddr)
  763. return true
  764. }
  765. return false
  766. }
  767. // buildNetworks fills in the networks field of HostInfo. It accepts a cert.Certificate so you never ever mix the network types up.
  768. func (i *HostInfo) buildNetworks(myVpnNetworksTable *bart.Lite, c cert.Certificate) {
  769. if len(c.Networks()) == 1 && len(c.UnsafeNetworks()) == 0 {
  770. if myVpnNetworksTable.Contains(c.Networks()[0].Addr()) {
  771. return // Simple case, no BART needed
  772. }
  773. }
  774. i.networks = new(bart.Table[NetworkType])
  775. for _, network := range c.Networks() {
  776. nprefix := netip.PrefixFrom(network.Addr(), network.Addr().BitLen())
  777. if myVpnNetworksTable.Contains(network.Addr()) {
  778. i.networks.Insert(nprefix, NetworkTypeVPN)
  779. } else {
  780. i.networks.Insert(nprefix, NetworkTypeVPNPeer)
  781. }
  782. }
  783. for _, network := range c.UnsafeNetworks() {
  784. i.networks.Insert(network, NetworkTypeUnsafe)
  785. }
  786. }
  787. // logger returns a derived slog.Logger with per-hostinfo fields pre-bound.
  788. func (i *HostInfo) logger(l *slog.Logger) *slog.Logger {
  789. if i == nil {
  790. return l
  791. }
  792. li := l.With(
  793. "vpnAddrs", i.vpnAddrs,
  794. "localIndex", i.localIndexId,
  795. "remoteIndex", i.remoteIndexId,
  796. )
  797. if connState := i.ConnectionState; connState != nil {
  798. if peerCert := connState.peerCert; peerCert != nil {
  799. li = li.With("certName", peerCert.Certificate.Name())
  800. }
  801. }
  802. return li
  803. }
  804. // Utility functions
  805. func localAddrs(l *slog.Logger, allowList *LocalAllowList) []netip.Addr {
  806. //FIXME: This function is pretty garbage
  807. var finalAddrs []netip.Addr
  808. ifaces, _ := net.Interfaces()
  809. for _, i := range ifaces {
  810. allow := allowList.AllowName(i.Name)
  811. if l.Enabled(context.Background(), logging.LevelTrace) {
  812. l.Log(context.Background(), logging.LevelTrace, "localAllowList.AllowName",
  813. "interfaceName", i.Name,
  814. "allow", allow,
  815. )
  816. }
  817. if !allow {
  818. continue
  819. }
  820. addrs, _ := i.Addrs()
  821. for _, rawAddr := range addrs {
  822. var addr netip.Addr
  823. switch v := rawAddr.(type) {
  824. case *net.IPNet:
  825. //continue
  826. addr, _ = netip.AddrFromSlice(v.IP)
  827. case *net.IPAddr:
  828. addr, _ = netip.AddrFromSlice(v.IP)
  829. }
  830. if !addr.IsValid() {
  831. if l.Enabled(context.Background(), slog.LevelDebug) {
  832. l.Debug("addr was invalid", "localAddr", rawAddr)
  833. }
  834. continue
  835. }
  836. addr = addr.Unmap()
  837. if addr.IsLoopback() == false && addr.IsLinkLocalUnicast() == false {
  838. isAllowed := allowList.Allow(addr)
  839. if l.Enabled(context.Background(), logging.LevelTrace) {
  840. l.Log(context.Background(), logging.LevelTrace, "localAllowList.Allow",
  841. "localAddr", addr,
  842. "allowed", isAllowed,
  843. )
  844. }
  845. if !isAllowed {
  846. continue
  847. }
  848. finalAddrs = append(finalAddrs, addr)
  849. }
  850. }
  851. }
  852. return finalAddrs
  853. }