handshake_manager.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  1. package nebula
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/rand"
  6. "encoding/binary"
  7. "errors"
  8. "net/netip"
  9. "slices"
  10. "sync"
  11. "time"
  12. "github.com/rcrowley/go-metrics"
  13. "github.com/sirupsen/logrus"
  14. "github.com/slackhq/nebula/cert"
  15. "github.com/slackhq/nebula/header"
  16. "github.com/slackhq/nebula/udp"
  17. )
  18. const (
  19. DefaultHandshakeTryInterval = time.Millisecond * 100
  20. DefaultHandshakeRetries = 10
  21. DefaultHandshakeTriggerBuffer = 64
  22. DefaultUseRelays = true
  23. )
  24. var (
  25. defaultHandshakeConfig = HandshakeConfig{
  26. tryInterval: DefaultHandshakeTryInterval,
  27. retries: DefaultHandshakeRetries,
  28. triggerBuffer: DefaultHandshakeTriggerBuffer,
  29. useRelays: DefaultUseRelays,
  30. }
  31. )
  32. type HandshakeConfig struct {
  33. tryInterval time.Duration
  34. retries int64
  35. triggerBuffer int
  36. useRelays bool
  37. messageMetrics *MessageMetrics
  38. }
  39. type HandshakeManager struct {
  40. // Mutex for interacting with the vpnIps and indexes maps
  41. sync.RWMutex
  42. vpnIps map[netip.Addr]*HandshakeHostInfo
  43. indexes map[uint32]*HandshakeHostInfo
  44. mainHostMap *HostMap
  45. lightHouse *LightHouse
  46. outside udp.Conn
  47. config HandshakeConfig
  48. OutboundHandshakeTimer *LockingTimerWheel[netip.Addr]
  49. messageMetrics *MessageMetrics
  50. metricInitiated metrics.Counter
  51. metricTimedOut metrics.Counter
  52. f *Interface
  53. l *logrus.Logger
  54. // can be used to trigger outbound handshake for the given vpnIp
  55. trigger chan netip.Addr
  56. }
  57. type HandshakeHostInfo struct {
  58. sync.Mutex
  59. startTime time.Time // Time that we first started trying with this handshake
  60. ready bool // Is the handshake ready
  61. counter int64 // How many attempts have we made so far
  62. lastRemotes []netip.AddrPort // Remotes that we sent to during the previous attempt
  63. packetStore []*cachedPacket // A set of packets to be transmitted once the handshake completes
  64. hostinfo *HostInfo
  65. }
  66. func (hh *HandshakeHostInfo) cachePacket(l *logrus.Logger, t header.MessageType, st header.MessageSubType, packet []byte, f packetCallback, m *cachedPacketMetrics) {
  67. if len(hh.packetStore) < 100 {
  68. tempPacket := make([]byte, len(packet))
  69. copy(tempPacket, packet)
  70. hh.packetStore = append(hh.packetStore, &cachedPacket{t, st, f, tempPacket})
  71. if l.Level >= logrus.DebugLevel {
  72. hh.hostinfo.logger(l).
  73. WithField("length", len(hh.packetStore)).
  74. WithField("stored", true).
  75. Debugf("Packet store")
  76. }
  77. } else {
  78. m.dropped.Inc(1)
  79. if l.Level >= logrus.DebugLevel {
  80. hh.hostinfo.logger(l).
  81. WithField("length", len(hh.packetStore)).
  82. WithField("stored", false).
  83. Debugf("Packet store")
  84. }
  85. }
  86. }
  87. func NewHandshakeManager(l *logrus.Logger, mainHostMap *HostMap, lightHouse *LightHouse, outside udp.Conn, config HandshakeConfig) *HandshakeManager {
  88. return &HandshakeManager{
  89. vpnIps: map[netip.Addr]*HandshakeHostInfo{},
  90. indexes: map[uint32]*HandshakeHostInfo{},
  91. mainHostMap: mainHostMap,
  92. lightHouse: lightHouse,
  93. outside: outside,
  94. config: config,
  95. trigger: make(chan netip.Addr, config.triggerBuffer),
  96. OutboundHandshakeTimer: NewLockingTimerWheel[netip.Addr](config.tryInterval, hsTimeout(config.retries, config.tryInterval)),
  97. messageMetrics: config.messageMetrics,
  98. metricInitiated: metrics.GetOrRegisterCounter("handshake_manager.initiated", nil),
  99. metricTimedOut: metrics.GetOrRegisterCounter("handshake_manager.timed_out", nil),
  100. l: l,
  101. }
  102. }
  103. func (hm *HandshakeManager) Run(ctx context.Context) {
  104. clockSource := time.NewTicker(hm.config.tryInterval)
  105. defer clockSource.Stop()
  106. for {
  107. select {
  108. case <-ctx.Done():
  109. return
  110. case vpnIP := <-hm.trigger:
  111. hm.handleOutbound(vpnIP, true)
  112. case now := <-clockSource.C:
  113. hm.NextOutboundHandshakeTimerTick(now)
  114. }
  115. }
  116. }
  117. func (hm *HandshakeManager) HandleIncoming(addr netip.AddrPort, via *ViaSender, packet []byte, h *header.H) {
  118. // First remote allow list check before we know the vpnIp
  119. if addr.IsValid() {
  120. if !hm.lightHouse.GetRemoteAllowList().AllowUnknownVpnAddr(addr.Addr()) {
  121. hm.l.WithField("udpAddr", addr).Debug("lighthouse.remote_allow_list denied incoming handshake")
  122. return
  123. }
  124. }
  125. switch h.Subtype {
  126. case header.HandshakeIXPSK0:
  127. switch h.MessageCounter {
  128. case 1:
  129. ixHandshakeStage1(hm.f, addr, via, packet, h)
  130. case 2:
  131. newHostinfo := hm.queryIndex(h.RemoteIndex)
  132. tearDown := ixHandshakeStage2(hm.f, addr, via, newHostinfo, packet, h)
  133. if tearDown && newHostinfo != nil {
  134. hm.DeleteHostInfo(newHostinfo.hostinfo)
  135. }
  136. }
  137. }
  138. }
  139. func (hm *HandshakeManager) NextOutboundHandshakeTimerTick(now time.Time) {
  140. hm.OutboundHandshakeTimer.Advance(now)
  141. for {
  142. vpnIp, has := hm.OutboundHandshakeTimer.Purge()
  143. if !has {
  144. break
  145. }
  146. hm.handleOutbound(vpnIp, false)
  147. }
  148. }
  149. func (hm *HandshakeManager) handleOutbound(vpnIp netip.Addr, lighthouseTriggered bool) {
  150. hh := hm.queryVpnIp(vpnIp)
  151. if hh == nil {
  152. return
  153. }
  154. hh.Lock()
  155. defer hh.Unlock()
  156. hostinfo := hh.hostinfo
  157. // If we are out of time, clean up
  158. if hh.counter >= hm.config.retries {
  159. hh.hostinfo.logger(hm.l).WithField("udpAddrs", hh.hostinfo.remotes.CopyAddrs(hm.mainHostMap.GetPreferredRanges())).
  160. WithField("initiatorIndex", hh.hostinfo.localIndexId).
  161. WithField("remoteIndex", hh.hostinfo.remoteIndexId).
  162. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  163. WithField("durationNs", time.Since(hh.startTime).Nanoseconds()).
  164. Info("Handshake timed out")
  165. hm.metricTimedOut.Inc(1)
  166. hm.DeleteHostInfo(hostinfo)
  167. return
  168. }
  169. // Increment the counter to increase our delay, linear backoff
  170. hh.counter++
  171. // Check if we have a handshake packet to transmit yet
  172. if !hh.ready {
  173. if !ixHandshakeStage0(hm.f, hh) {
  174. hm.OutboundHandshakeTimer.Add(vpnIp, hm.config.tryInterval*time.Duration(hh.counter))
  175. return
  176. }
  177. }
  178. // Get a remotes object if we don't already have one.
  179. // This is mainly to protect us as this should never be the case
  180. // NB ^ This comment doesn't jive. It's how the thing gets initialized.
  181. // It's the common path. Should it update every time, in case a future LH query/queries give us more info?
  182. if hostinfo.remotes == nil {
  183. hostinfo.remotes = hm.lightHouse.QueryCache([]netip.Addr{vpnIp})
  184. }
  185. remotes := hostinfo.remotes.CopyAddrs(hm.mainHostMap.GetPreferredRanges())
  186. remotesHaveChanged := !slices.Equal(remotes, hh.lastRemotes)
  187. // We only care about a lighthouse trigger if we have new remotes to send to.
  188. // This is a very specific optimization for a fast lighthouse reply.
  189. if lighthouseTriggered && !remotesHaveChanged {
  190. // If we didn't return here a lighthouse could cause us to aggressively send handshakes
  191. return
  192. }
  193. hh.lastRemotes = remotes
  194. // This will generate a load of queries for hosts with only 1 ip
  195. // (such as ones registered to the lighthouse with only a private IP)
  196. // So we only do it one time after attempting 5 handshakes already.
  197. if len(remotes) <= 1 && hh.counter == 5 {
  198. // If we only have 1 remote it is highly likely our query raced with the other host registered within the lighthouse
  199. // Our vpnIp here has a tunnel with a lighthouse but has yet to send a host update packet there so we only know about
  200. // the learned public ip for them. Query again to short circuit the promotion counter
  201. hm.lightHouse.QueryServer(vpnIp)
  202. }
  203. // Send the handshake to all known ips, stage 2 takes care of assigning the hostinfo.remote based on the first to reply
  204. var sentTo []netip.AddrPort
  205. hostinfo.remotes.ForEach(hm.mainHostMap.GetPreferredRanges(), func(addr netip.AddrPort, _ bool) {
  206. hm.messageMetrics.Tx(header.Handshake, header.MessageSubType(hostinfo.HandshakePacket[0][1]), 1)
  207. err := hm.outside.WriteTo(hostinfo.HandshakePacket[0], addr)
  208. if err != nil {
  209. hostinfo.logger(hm.l).WithField("udpAddr", addr).
  210. WithField("initiatorIndex", hostinfo.localIndexId).
  211. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  212. WithError(err).Error("Failed to send handshake message")
  213. } else {
  214. sentTo = append(sentTo, addr)
  215. }
  216. })
  217. // Don't be too noisy or confusing if we fail to send a handshake - if we don't get through we'll eventually log a timeout,
  218. // so only log when the list of remotes has changed
  219. if remotesHaveChanged {
  220. hostinfo.logger(hm.l).WithField("udpAddrs", sentTo).
  221. WithField("initiatorIndex", hostinfo.localIndexId).
  222. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  223. Info("Handshake message sent")
  224. } else if hm.l.IsLevelEnabled(logrus.DebugLevel) {
  225. hostinfo.logger(hm.l).WithField("udpAddrs", sentTo).
  226. WithField("initiatorIndex", hostinfo.localIndexId).
  227. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  228. Debug("Handshake message sent")
  229. }
  230. if hm.config.useRelays && len(hostinfo.remotes.relays) > 0 {
  231. hostinfo.logger(hm.l).WithField("relays", hostinfo.remotes.relays).Info("Attempt to relay through hosts")
  232. // Send a RelayRequest to all known Relay IP's
  233. for _, relay := range hostinfo.remotes.relays {
  234. // Don't relay to myself
  235. if relay == vpnIp {
  236. continue
  237. }
  238. // Don't relay through the host I'm trying to connect to
  239. _, found := hm.f.myVpnAddrsTable.Lookup(relay)
  240. if found {
  241. continue
  242. }
  243. relayHostInfo := hm.mainHostMap.QueryVpnAddr(relay)
  244. if relayHostInfo == nil || !relayHostInfo.remote.IsValid() {
  245. hostinfo.logger(hm.l).WithField("relay", relay.String()).Info("Establish tunnel to relay target")
  246. hm.f.Handshake(relay)
  247. continue
  248. }
  249. // Check the relay HostInfo to see if we already established a relay through
  250. existingRelay, ok := relayHostInfo.relayState.QueryRelayForByIp(vpnIp)
  251. if !ok {
  252. // No relays exist or requested yet.
  253. if relayHostInfo.remote.IsValid() {
  254. idx, err := AddRelay(hm.l, relayHostInfo, hm.mainHostMap, vpnIp, nil, TerminalType, Requested)
  255. if err != nil {
  256. hostinfo.logger(hm.l).WithField("relay", relay.String()).WithError(err).Info("Failed to add relay to hostmap")
  257. }
  258. m := NebulaControl{
  259. Type: NebulaControl_CreateRelayRequest,
  260. InitiatorRelayIndex: idx,
  261. }
  262. switch relayHostInfo.GetCert().Certificate.Version() {
  263. case cert.Version1:
  264. if !hm.f.myVpnAddrs[0].Is4() {
  265. hostinfo.logger(hm.l).Error("can not establish v1 relay with a v6 network because the relay is not running a current nebula version")
  266. continue
  267. }
  268. if !vpnIp.Is4() {
  269. hostinfo.logger(hm.l).Error("can not establish v1 relay with a v6 remote network because the relay is not running a current nebula version")
  270. continue
  271. }
  272. b := hm.f.myVpnAddrs[0].As4()
  273. m.OldRelayFromAddr = binary.BigEndian.Uint32(b[:])
  274. b = vpnIp.As4()
  275. m.OldRelayToAddr = binary.BigEndian.Uint32(b[:])
  276. case cert.Version2:
  277. m.RelayFromAddr = netAddrToProtoAddr(hm.f.myVpnAddrs[0])
  278. m.RelayToAddr = netAddrToProtoAddr(vpnIp)
  279. default:
  280. hostinfo.logger(hm.l).Error("Unknown certificate version found while creating relay")
  281. continue
  282. }
  283. msg, err := m.Marshal()
  284. if err != nil {
  285. hostinfo.logger(hm.l).
  286. WithError(err).
  287. Error("Failed to marshal Control message to create relay")
  288. } else {
  289. hm.f.SendMessageToHostInfo(header.Control, 0, relayHostInfo, msg, make([]byte, 12), make([]byte, mtu))
  290. hm.l.WithFields(logrus.Fields{
  291. "relayFrom": hm.f.myVpnAddrs[0],
  292. "relayTo": vpnIp,
  293. "initiatorRelayIndex": idx,
  294. "relay": relay}).
  295. Info("send CreateRelayRequest")
  296. }
  297. }
  298. continue
  299. }
  300. switch existingRelay.State {
  301. case Established:
  302. hostinfo.logger(hm.l).WithField("relay", relay.String()).Info("Send handshake via relay")
  303. hm.f.SendVia(relayHostInfo, existingRelay, hostinfo.HandshakePacket[0], make([]byte, 12), make([]byte, mtu), false)
  304. case Disestablished:
  305. // Mark this relay as 'requested'
  306. relayHostInfo.relayState.UpdateRelayForByIpState(vpnIp, Requested)
  307. fallthrough
  308. case Requested:
  309. hostinfo.logger(hm.l).WithField("relay", relay.String()).Info("Re-send CreateRelay request")
  310. // Re-send the CreateRelay request, in case the previous one was lost.
  311. m := NebulaControl{
  312. Type: NebulaControl_CreateRelayRequest,
  313. InitiatorRelayIndex: existingRelay.LocalIndex,
  314. }
  315. switch relayHostInfo.GetCert().Certificate.Version() {
  316. case cert.Version1:
  317. if !hm.f.myVpnAddrs[0].Is4() {
  318. hostinfo.logger(hm.l).Error("can not establish v1 relay with a v6 network because the relay is not running a current nebula version")
  319. continue
  320. }
  321. if !vpnIp.Is4() {
  322. hostinfo.logger(hm.l).Error("can not establish v1 relay with a v6 remote network because the relay is not running a current nebula version")
  323. continue
  324. }
  325. b := hm.f.myVpnAddrs[0].As4()
  326. m.OldRelayFromAddr = binary.BigEndian.Uint32(b[:])
  327. b = vpnIp.As4()
  328. m.OldRelayToAddr = binary.BigEndian.Uint32(b[:])
  329. case cert.Version2:
  330. m.RelayFromAddr = netAddrToProtoAddr(hm.f.myVpnAddrs[0])
  331. m.RelayToAddr = netAddrToProtoAddr(vpnIp)
  332. default:
  333. hostinfo.logger(hm.l).Error("Unknown certificate version found while creating relay")
  334. continue
  335. }
  336. msg, err := m.Marshal()
  337. if err != nil {
  338. hostinfo.logger(hm.l).
  339. WithError(err).
  340. Error("Failed to marshal Control message to create relay")
  341. } else {
  342. // This must send over the hostinfo, not over hm.Hosts[ip]
  343. hm.f.SendMessageToHostInfo(header.Control, 0, relayHostInfo, msg, make([]byte, 12), make([]byte, mtu))
  344. hm.l.WithFields(logrus.Fields{
  345. "relayFrom": hm.f.myVpnAddrs[0],
  346. "relayTo": vpnIp,
  347. "initiatorRelayIndex": existingRelay.LocalIndex,
  348. "relay": relay}).
  349. Info("send CreateRelayRequest")
  350. }
  351. case PeerRequested:
  352. // PeerRequested only occurs in Forwarding relays, not Terminal relays, and this is a Terminal relay case.
  353. fallthrough
  354. default:
  355. hostinfo.logger(hm.l).
  356. WithField("vpnIp", vpnIp).
  357. WithField("state", existingRelay.State).
  358. WithField("relay", relay).
  359. Errorf("Relay unexpected state")
  360. }
  361. }
  362. }
  363. // If a lighthouse triggered this attempt then we are still in the timer wheel and do not need to re-add
  364. if !lighthouseTriggered {
  365. hm.OutboundHandshakeTimer.Add(vpnIp, hm.config.tryInterval*time.Duration(hh.counter))
  366. }
  367. }
  368. // GetOrHandshake will try to find a hostinfo with a fully formed tunnel or start a new handshake if one is not present
  369. // The 2nd argument will be true if the hostinfo is ready to transmit traffic
  370. func (hm *HandshakeManager) GetOrHandshake(vpnIp netip.Addr, cacheCb func(*HandshakeHostInfo)) (*HostInfo, bool) {
  371. hm.mainHostMap.RLock()
  372. h, ok := hm.mainHostMap.Hosts[vpnIp]
  373. hm.mainHostMap.RUnlock()
  374. if ok {
  375. // Do not attempt promotion if you are a lighthouse
  376. if !hm.lightHouse.amLighthouse {
  377. h.TryPromoteBest(hm.mainHostMap.GetPreferredRanges(), hm.f)
  378. }
  379. return h, true
  380. }
  381. return hm.StartHandshake(vpnIp, cacheCb), false
  382. }
  383. // StartHandshake will ensure a handshake is currently being attempted for the provided vpn ip
  384. func (hm *HandshakeManager) StartHandshake(vpnAddr netip.Addr, cacheCb func(*HandshakeHostInfo)) *HostInfo {
  385. hm.Lock()
  386. if hh, ok := hm.vpnIps[vpnAddr]; ok {
  387. // We are already trying to handshake with this vpn ip
  388. if cacheCb != nil {
  389. cacheCb(hh)
  390. }
  391. hm.Unlock()
  392. return hh.hostinfo
  393. }
  394. hostinfo := &HostInfo{
  395. vpnAddrs: []netip.Addr{vpnAddr},
  396. HandshakePacket: make(map[uint8][]byte, 0),
  397. relayState: RelayState{
  398. relays: map[netip.Addr]struct{}{},
  399. relayForByAddr: map[netip.Addr]*Relay{},
  400. relayForByIdx: map[uint32]*Relay{},
  401. },
  402. }
  403. hh := &HandshakeHostInfo{
  404. hostinfo: hostinfo,
  405. startTime: time.Now(),
  406. }
  407. hm.vpnIps[vpnAddr] = hh
  408. hm.metricInitiated.Inc(1)
  409. hm.OutboundHandshakeTimer.Add(vpnAddr, hm.config.tryInterval)
  410. if cacheCb != nil {
  411. cacheCb(hh)
  412. }
  413. // If this is a static host, we don't need to wait for the HostQueryReply
  414. // We can trigger the handshake right now
  415. _, doTrigger := hm.lightHouse.GetStaticHostList()[vpnAddr]
  416. if !doTrigger {
  417. // Add any calculated remotes, and trigger early handshake if one found
  418. doTrigger = hm.lightHouse.addCalculatedRemotes(vpnAddr)
  419. }
  420. if doTrigger {
  421. select {
  422. case hm.trigger <- vpnAddr:
  423. default:
  424. }
  425. }
  426. hm.Unlock()
  427. hm.lightHouse.QueryServer(vpnAddr)
  428. return hostinfo
  429. }
  430. var (
  431. ErrExistingHostInfo = errors.New("existing hostinfo")
  432. ErrAlreadySeen = errors.New("already seen")
  433. ErrLocalIndexCollision = errors.New("local index collision")
  434. )
  435. // CheckAndComplete checks for any conflicts in the main and pending hostmap
  436. // before adding hostinfo to main. If err is nil, it was added. Otherwise err will be:
  437. //
  438. // ErrAlreadySeen if we already have an entry in the hostmap that has seen the
  439. // exact same handshake packet
  440. //
  441. // ErrExistingHostInfo if we already have an entry in the hostmap for this
  442. // VpnIp and the new handshake was older than the one we currently have
  443. //
  444. // ErrLocalIndexCollision if we already have an entry in the main or pending
  445. // hostmap for the hostinfo.localIndexId.
  446. func (hm *HandshakeManager) CheckAndComplete(hostinfo *HostInfo, handshakePacket uint8, f *Interface) (*HostInfo, error) {
  447. hm.mainHostMap.Lock()
  448. defer hm.mainHostMap.Unlock()
  449. hm.Lock()
  450. defer hm.Unlock()
  451. // Check if we already have a tunnel with this vpn ip
  452. existingHostInfo, found := hm.mainHostMap.Hosts[hostinfo.vpnAddrs[0]]
  453. if found && existingHostInfo != nil {
  454. testHostInfo := existingHostInfo
  455. for testHostInfo != nil {
  456. // Is it just a delayed handshake packet?
  457. if bytes.Equal(hostinfo.HandshakePacket[handshakePacket], testHostInfo.HandshakePacket[handshakePacket]) {
  458. return testHostInfo, ErrAlreadySeen
  459. }
  460. testHostInfo = testHostInfo.next
  461. }
  462. // Is this a newer handshake?
  463. if existingHostInfo.lastHandshakeTime >= hostinfo.lastHandshakeTime && !existingHostInfo.ConnectionState.initiator {
  464. return existingHostInfo, ErrExistingHostInfo
  465. }
  466. existingHostInfo.logger(hm.l).Info("Taking new handshake")
  467. }
  468. existingIndex, found := hm.mainHostMap.Indexes[hostinfo.localIndexId]
  469. if found {
  470. // We have a collision, but for a different hostinfo
  471. return existingIndex, ErrLocalIndexCollision
  472. }
  473. existingPendingIndex, found := hm.indexes[hostinfo.localIndexId]
  474. if found && existingPendingIndex.hostinfo != hostinfo {
  475. // We have a collision, but for a different hostinfo
  476. return existingPendingIndex.hostinfo, ErrLocalIndexCollision
  477. }
  478. existingRemoteIndex, found := hm.mainHostMap.RemoteIndexes[hostinfo.remoteIndexId]
  479. if found && existingRemoteIndex != nil && existingRemoteIndex.vpnAddrs[0] != hostinfo.vpnAddrs[0] {
  480. // We have a collision, but this can happen since we can't control
  481. // the remote ID. Just log about the situation as a note.
  482. hostinfo.logger(hm.l).
  483. WithField("remoteIndex", hostinfo.remoteIndexId).WithField("collision", existingRemoteIndex.vpnAddrs).
  484. Info("New host shadows existing host remoteIndex")
  485. }
  486. hm.mainHostMap.unlockedAddHostInfo(hostinfo, f)
  487. return existingHostInfo, nil
  488. }
  489. // Complete is a simpler version of CheckAndComplete when we already know we
  490. // won't have a localIndexId collision because we already have an entry in the
  491. // pendingHostMap. An existing hostinfo is returned if there was one.
  492. func (hm *HandshakeManager) Complete(hostinfo *HostInfo, f *Interface) {
  493. hm.mainHostMap.Lock()
  494. defer hm.mainHostMap.Unlock()
  495. hm.Lock()
  496. defer hm.Unlock()
  497. existingRemoteIndex, found := hm.mainHostMap.RemoteIndexes[hostinfo.remoteIndexId]
  498. if found && existingRemoteIndex != nil {
  499. // We have a collision, but this can happen since we can't control
  500. // the remote ID. Just log about the situation as a note.
  501. hostinfo.logger(hm.l).
  502. WithField("remoteIndex", hostinfo.remoteIndexId).WithField("collision", existingRemoteIndex.vpnAddrs).
  503. Info("New host shadows existing host remoteIndex")
  504. }
  505. // We need to remove from the pending hostmap first to avoid undoing work when after to the main hostmap.
  506. hm.unlockedDeleteHostInfo(hostinfo)
  507. hm.mainHostMap.unlockedAddHostInfo(hostinfo, f)
  508. }
  509. // allocateIndex generates a unique localIndexId for this HostInfo
  510. // and adds it to the pendingHostMap. Will error if we are unable to generate
  511. // a unique localIndexId
  512. func (hm *HandshakeManager) allocateIndex(hh *HandshakeHostInfo) error {
  513. hm.mainHostMap.RLock()
  514. defer hm.mainHostMap.RUnlock()
  515. hm.Lock()
  516. defer hm.Unlock()
  517. for i := 0; i < 32; i++ {
  518. index, err := generateIndex(hm.l)
  519. if err != nil {
  520. return err
  521. }
  522. _, inPending := hm.indexes[index]
  523. _, inMain := hm.mainHostMap.Indexes[index]
  524. if !inMain && !inPending {
  525. hh.hostinfo.localIndexId = index
  526. hm.indexes[index] = hh
  527. return nil
  528. }
  529. }
  530. return errors.New("failed to generate unique localIndexId")
  531. }
  532. func (hm *HandshakeManager) DeleteHostInfo(hostinfo *HostInfo) {
  533. hm.Lock()
  534. defer hm.Unlock()
  535. hm.unlockedDeleteHostInfo(hostinfo)
  536. }
  537. func (hm *HandshakeManager) unlockedDeleteHostInfo(hostinfo *HostInfo) {
  538. for _, addr := range hostinfo.vpnAddrs {
  539. delete(hm.vpnIps, addr)
  540. }
  541. if len(hm.vpnIps) == 0 {
  542. hm.vpnIps = map[netip.Addr]*HandshakeHostInfo{}
  543. }
  544. delete(hm.indexes, hostinfo.localIndexId)
  545. if len(hm.indexes) == 0 {
  546. hm.indexes = map[uint32]*HandshakeHostInfo{}
  547. }
  548. if hm.l.Level >= logrus.DebugLevel {
  549. hm.l.WithField("hostMap", m{"mapTotalSize": len(hm.vpnIps),
  550. "vpnAddrs": hostinfo.vpnAddrs, "indexNumber": hostinfo.localIndexId, "remoteIndexNumber": hostinfo.remoteIndexId}).
  551. Debug("Pending hostmap hostInfo deleted")
  552. }
  553. }
  554. func (hm *HandshakeManager) QueryVpnAddr(vpnIp netip.Addr) *HostInfo {
  555. hh := hm.queryVpnIp(vpnIp)
  556. if hh != nil {
  557. return hh.hostinfo
  558. }
  559. return nil
  560. }
  561. func (hm *HandshakeManager) queryVpnIp(vpnIp netip.Addr) *HandshakeHostInfo {
  562. hm.RLock()
  563. defer hm.RUnlock()
  564. return hm.vpnIps[vpnIp]
  565. }
  566. func (hm *HandshakeManager) QueryIndex(index uint32) *HostInfo {
  567. hh := hm.queryIndex(index)
  568. if hh != nil {
  569. return hh.hostinfo
  570. }
  571. return nil
  572. }
  573. func (hm *HandshakeManager) queryIndex(index uint32) *HandshakeHostInfo {
  574. hm.RLock()
  575. defer hm.RUnlock()
  576. return hm.indexes[index]
  577. }
  578. func (hm *HandshakeManager) GetPreferredRanges() []netip.Prefix {
  579. return hm.mainHostMap.GetPreferredRanges()
  580. }
  581. func (hm *HandshakeManager) ForEachVpnAddr(f controlEach) {
  582. hm.RLock()
  583. defer hm.RUnlock()
  584. for _, v := range hm.vpnIps {
  585. f(v.hostinfo)
  586. }
  587. }
  588. func (hm *HandshakeManager) ForEachIndex(f controlEach) {
  589. hm.RLock()
  590. defer hm.RUnlock()
  591. for _, v := range hm.indexes {
  592. f(v.hostinfo)
  593. }
  594. }
  595. func (hm *HandshakeManager) EmitStats() {
  596. hm.RLock()
  597. hostLen := len(hm.vpnIps)
  598. indexLen := len(hm.indexes)
  599. hm.RUnlock()
  600. metrics.GetOrRegisterGauge("hostmap.pending.hosts", nil).Update(int64(hostLen))
  601. metrics.GetOrRegisterGauge("hostmap.pending.indexes", nil).Update(int64(indexLen))
  602. hm.mainHostMap.EmitStats()
  603. }
  604. // Utility functions below
  605. func generateIndex(l *logrus.Logger) (uint32, error) {
  606. b := make([]byte, 4)
  607. // Let zero mean we don't know the ID, so don't generate zero
  608. var index uint32
  609. for index == 0 {
  610. _, err := rand.Read(b)
  611. if err != nil {
  612. l.Errorln(err)
  613. return 0, err
  614. }
  615. index = binary.BigEndian.Uint32(b)
  616. }
  617. if l.Level >= logrus.DebugLevel {
  618. l.WithField("index", index).
  619. Debug("Generated index")
  620. }
  621. return index, nil
  622. }
  623. func hsTimeout(tries int64, interval time.Duration) time.Duration {
  624. return time.Duration(tries / 2 * ((2 * int64(interval)) + (tries-1)*int64(interval)))
  625. }