handshake_manager.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  1. package nebula
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/rand"
  6. "encoding/binary"
  7. "errors"
  8. "net/netip"
  9. "slices"
  10. "time"
  11. "github.com/rcrowley/go-metrics"
  12. "github.com/sirupsen/logrus"
  13. "github.com/slackhq/nebula/cert"
  14. "github.com/slackhq/nebula/header"
  15. "github.com/slackhq/nebula/udp"
  16. )
  17. const (
  18. DefaultHandshakeTryInterval = time.Millisecond * 100
  19. DefaultHandshakeRetries = 10
  20. DefaultHandshakeTriggerBuffer = 64
  21. DefaultUseRelays = true
  22. )
  23. var (
  24. defaultHandshakeConfig = HandshakeConfig{
  25. tryInterval: DefaultHandshakeTryInterval,
  26. retries: DefaultHandshakeRetries,
  27. triggerBuffer: DefaultHandshakeTriggerBuffer,
  28. useRelays: DefaultUseRelays,
  29. }
  30. )
  31. type HandshakeConfig struct {
  32. tryInterval time.Duration
  33. retries int64
  34. triggerBuffer int
  35. useRelays bool
  36. messageMetrics *MessageMetrics
  37. }
  38. type HandshakeManager struct {
  39. // Mutex for interacting with the vpnIps and indexes maps
  40. syncRWMutex
  41. vpnIps map[netip.Addr]*HandshakeHostInfo
  42. indexes map[uint32]*HandshakeHostInfo
  43. mainHostMap *HostMap
  44. lightHouse *LightHouse
  45. outside udp.Conn
  46. config HandshakeConfig
  47. OutboundHandshakeTimer *LockingTimerWheel[netip.Addr]
  48. messageMetrics *MessageMetrics
  49. metricInitiated metrics.Counter
  50. metricTimedOut metrics.Counter
  51. f *Interface
  52. l *logrus.Logger
  53. // can be used to trigger outbound handshake for the given vpnIp
  54. trigger chan netip.Addr
  55. }
  56. type HandshakeHostInfo struct {
  57. syncMutex
  58. startTime time.Time // Time that we first started trying with this handshake
  59. ready bool // Is the handshake ready
  60. counter int64 // How many attempts have we made so far
  61. lastRemotes []netip.AddrPort // Remotes that we sent to during the previous attempt
  62. packetStore []*cachedPacket // A set of packets to be transmitted once the handshake completes
  63. hostinfo *HostInfo
  64. }
  65. func (hh *HandshakeHostInfo) cachePacket(l *logrus.Logger, t header.MessageType, st header.MessageSubType, packet []byte, f packetCallback, m *cachedPacketMetrics) {
  66. if len(hh.packetStore) < 100 {
  67. tempPacket := make([]byte, len(packet))
  68. copy(tempPacket, packet)
  69. hh.packetStore = append(hh.packetStore, &cachedPacket{t, st, f, tempPacket})
  70. if l.Level >= logrus.DebugLevel {
  71. hh.hostinfo.logger(l).
  72. WithField("length", len(hh.packetStore)).
  73. WithField("stored", true).
  74. Debugf("Packet store")
  75. }
  76. } else {
  77. m.dropped.Inc(1)
  78. if l.Level >= logrus.DebugLevel {
  79. hh.hostinfo.logger(l).
  80. WithField("length", len(hh.packetStore)).
  81. WithField("stored", false).
  82. Debugf("Packet store")
  83. }
  84. }
  85. }
  86. func NewHandshakeManager(l *logrus.Logger, mainHostMap *HostMap, lightHouse *LightHouse, outside udp.Conn, config HandshakeConfig) *HandshakeManager {
  87. return &HandshakeManager{
  88. syncRWMutex: newSyncRWMutex("handshake-manager"),
  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]("handshake-manager-timer", 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.Level >= 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. syncRWMutex: newSyncRWMutex("hostinfo"),
  396. vpnAddrs: []netip.Addr{vpnAddr},
  397. HandshakePacket: make(map[uint8][]byte, 0),
  398. relayState: RelayState{
  399. syncRWMutex: newSyncRWMutex("relay-state"),
  400. relays: map[netip.Addr]struct{}{},
  401. relayForByAddr: map[netip.Addr]*Relay{},
  402. relayForByIdx: map[uint32]*Relay{},
  403. },
  404. }
  405. hh := &HandshakeHostInfo{
  406. syncMutex: newSyncMutex("handshake-hostinfo"),
  407. hostinfo: hostinfo,
  408. startTime: time.Now(),
  409. }
  410. hm.vpnIps[vpnAddr] = hh
  411. hm.metricInitiated.Inc(1)
  412. hm.OutboundHandshakeTimer.Add(vpnAddr, hm.config.tryInterval)
  413. if cacheCb != nil {
  414. cacheCb(hh)
  415. }
  416. // If this is a static host, we don't need to wait for the HostQueryReply
  417. // We can trigger the handshake right now
  418. _, doTrigger := hm.lightHouse.GetStaticHostList()[vpnAddr]
  419. if !doTrigger {
  420. // Add any calculated remotes, and trigger early handshake if one found
  421. doTrigger = hm.lightHouse.addCalculatedRemotes(vpnAddr)
  422. }
  423. if doTrigger {
  424. select {
  425. case hm.trigger <- vpnAddr:
  426. default:
  427. }
  428. }
  429. hm.Unlock()
  430. hm.lightHouse.QueryServer(vpnAddr)
  431. return hostinfo
  432. }
  433. var (
  434. ErrExistingHostInfo = errors.New("existing hostinfo")
  435. ErrAlreadySeen = errors.New("already seen")
  436. ErrLocalIndexCollision = errors.New("local index collision")
  437. )
  438. // CheckAndComplete checks for any conflicts in the main and pending hostmap
  439. // before adding hostinfo to main. If err is nil, it was added. Otherwise err will be:
  440. //
  441. // ErrAlreadySeen if we already have an entry in the hostmap that has seen the
  442. // exact same handshake packet
  443. //
  444. // ErrExistingHostInfo if we already have an entry in the hostmap for this
  445. // VpnIp and the new handshake was older than the one we currently have
  446. //
  447. // ErrLocalIndexCollision if we already have an entry in the main or pending
  448. // hostmap for the hostinfo.localIndexId.
  449. func (hm *HandshakeManager) CheckAndComplete(hostinfo *HostInfo, handshakePacket uint8, f *Interface) (*HostInfo, error) {
  450. hm.mainHostMap.Lock()
  451. defer hm.mainHostMap.Unlock()
  452. hm.Lock()
  453. defer hm.Unlock()
  454. // Check if we already have a tunnel with this vpn ip
  455. existingHostInfo, found := hm.mainHostMap.Hosts[hostinfo.vpnAddrs[0]]
  456. if found && existingHostInfo != nil {
  457. testHostInfo := existingHostInfo
  458. for testHostInfo != nil {
  459. // Is it just a delayed handshake packet?
  460. if bytes.Equal(hostinfo.HandshakePacket[handshakePacket], testHostInfo.HandshakePacket[handshakePacket]) {
  461. return testHostInfo, ErrAlreadySeen
  462. }
  463. testHostInfo = testHostInfo.next
  464. }
  465. // Is this a newer handshake?
  466. if existingHostInfo.lastHandshakeTime >= hostinfo.lastHandshakeTime && !existingHostInfo.ConnectionState.initiator {
  467. return existingHostInfo, ErrExistingHostInfo
  468. }
  469. existingHostInfo.logger(hm.l).Info("Taking new handshake")
  470. }
  471. existingIndex, found := hm.mainHostMap.Indexes[hostinfo.localIndexId]
  472. if found {
  473. // We have a collision, but for a different hostinfo
  474. return existingIndex, ErrLocalIndexCollision
  475. }
  476. existingPendingIndex, found := hm.indexes[hostinfo.localIndexId]
  477. if found && existingPendingIndex.hostinfo != hostinfo {
  478. // We have a collision, but for a different hostinfo
  479. return existingPendingIndex.hostinfo, ErrLocalIndexCollision
  480. }
  481. existingRemoteIndex, found := hm.mainHostMap.RemoteIndexes[hostinfo.remoteIndexId]
  482. if found && existingRemoteIndex != nil && existingRemoteIndex.vpnAddrs[0] != hostinfo.vpnAddrs[0] {
  483. // We have a collision, but this can happen since we can't control
  484. // the remote ID. Just log about the situation as a note.
  485. hostinfo.logger(hm.l).
  486. WithField("remoteIndex", hostinfo.remoteIndexId).WithField("collision", existingRemoteIndex.vpnAddrs).
  487. Info("New host shadows existing host remoteIndex")
  488. }
  489. hm.mainHostMap.unlockedAddHostInfo(hostinfo, f)
  490. return existingHostInfo, nil
  491. }
  492. // Complete is a simpler version of CheckAndComplete when we already know we
  493. // won't have a localIndexId collision because we already have an entry in the
  494. // pendingHostMap. An existing hostinfo is returned if there was one.
  495. func (hm *HandshakeManager) Complete(hostinfo *HostInfo, f *Interface) {
  496. hm.mainHostMap.Lock()
  497. defer hm.mainHostMap.Unlock()
  498. hm.Lock()
  499. defer hm.Unlock()
  500. existingRemoteIndex, found := hm.mainHostMap.RemoteIndexes[hostinfo.remoteIndexId]
  501. if found && existingRemoteIndex != nil {
  502. // We have a collision, but this can happen since we can't control
  503. // the remote ID. Just log about the situation as a note.
  504. hostinfo.logger(hm.l).
  505. WithField("remoteIndex", hostinfo.remoteIndexId).WithField("collision", existingRemoteIndex.vpnAddrs).
  506. Info("New host shadows existing host remoteIndex")
  507. }
  508. // We need to remove from the pending hostmap first to avoid undoing work when after to the main hostmap.
  509. hm.unlockedDeleteHostInfo(hostinfo)
  510. hm.mainHostMap.unlockedAddHostInfo(hostinfo, f)
  511. }
  512. // allocateIndex generates a unique localIndexId for this HostInfo
  513. // and adds it to the pendingHostMap. Will error if we are unable to generate
  514. // a unique localIndexId
  515. func (hm *HandshakeManager) allocateIndex(hh *HandshakeHostInfo) error {
  516. hm.mainHostMap.RLock()
  517. defer hm.mainHostMap.RUnlock()
  518. hm.Lock()
  519. defer hm.Unlock()
  520. for i := 0; i < 32; i++ {
  521. index, err := generateIndex(hm.l)
  522. if err != nil {
  523. return err
  524. }
  525. _, inPending := hm.indexes[index]
  526. _, inMain := hm.mainHostMap.Indexes[index]
  527. if !inMain && !inPending {
  528. hh.hostinfo.localIndexId = index
  529. hm.indexes[index] = hh
  530. return nil
  531. }
  532. }
  533. return errors.New("failed to generate unique localIndexId")
  534. }
  535. func (hm *HandshakeManager) DeleteHostInfo(hostinfo *HostInfo) {
  536. hm.Lock()
  537. defer hm.Unlock()
  538. hm.unlockedDeleteHostInfo(hostinfo)
  539. }
  540. func (hm *HandshakeManager) unlockedDeleteHostInfo(hostinfo *HostInfo) {
  541. for _, addr := range hostinfo.vpnAddrs {
  542. delete(hm.vpnIps, addr)
  543. }
  544. if len(hm.vpnIps) == 0 {
  545. hm.vpnIps = map[netip.Addr]*HandshakeHostInfo{}
  546. }
  547. delete(hm.indexes, hostinfo.localIndexId)
  548. if len(hm.indexes) == 0 {
  549. hm.indexes = map[uint32]*HandshakeHostInfo{}
  550. }
  551. if hm.l.Level >= logrus.DebugLevel {
  552. hm.l.WithField("hostMap", m{"mapTotalSize": len(hm.vpnIps),
  553. "vpnAddrs": hostinfo.vpnAddrs, "indexNumber": hostinfo.localIndexId, "remoteIndexNumber": hostinfo.remoteIndexId}).
  554. Debug("Pending hostmap hostInfo deleted")
  555. }
  556. }
  557. func (hm *HandshakeManager) QueryVpnAddr(vpnIp netip.Addr) *HostInfo {
  558. hh := hm.queryVpnIp(vpnIp)
  559. if hh != nil {
  560. return hh.hostinfo
  561. }
  562. return nil
  563. }
  564. func (hm *HandshakeManager) queryVpnIp(vpnIp netip.Addr) *HandshakeHostInfo {
  565. hm.RLock()
  566. defer hm.RUnlock()
  567. return hm.vpnIps[vpnIp]
  568. }
  569. func (hm *HandshakeManager) QueryIndex(index uint32) *HostInfo {
  570. hh := hm.queryIndex(index)
  571. if hh != nil {
  572. return hh.hostinfo
  573. }
  574. return nil
  575. }
  576. func (hm *HandshakeManager) queryIndex(index uint32) *HandshakeHostInfo {
  577. hm.RLock()
  578. defer hm.RUnlock()
  579. return hm.indexes[index]
  580. }
  581. func (hm *HandshakeManager) GetPreferredRanges() []netip.Prefix {
  582. return hm.mainHostMap.GetPreferredRanges()
  583. }
  584. func (hm *HandshakeManager) ForEachVpnAddr(f controlEach) {
  585. hm.RLock()
  586. defer hm.RUnlock()
  587. for _, v := range hm.vpnIps {
  588. f(v.hostinfo)
  589. }
  590. }
  591. func (hm *HandshakeManager) ForEachIndex(f controlEach) {
  592. hm.RLock()
  593. defer hm.RUnlock()
  594. for _, v := range hm.indexes {
  595. f(v.hostinfo)
  596. }
  597. }
  598. func (hm *HandshakeManager) EmitStats() {
  599. hm.RLock()
  600. hostLen := len(hm.vpnIps)
  601. indexLen := len(hm.indexes)
  602. hm.RUnlock()
  603. metrics.GetOrRegisterGauge("hostmap.pending.hosts", nil).Update(int64(hostLen))
  604. metrics.GetOrRegisterGauge("hostmap.pending.indexes", nil).Update(int64(indexLen))
  605. hm.mainHostMap.EmitStats()
  606. }
  607. // Utility functions below
  608. func generateIndex(l *logrus.Logger) (uint32, error) {
  609. b := make([]byte, 4)
  610. // Let zero mean we don't know the ID, so don't generate zero
  611. var index uint32
  612. for index == 0 {
  613. _, err := rand.Read(b)
  614. if err != nil {
  615. l.Errorln(err)
  616. return 0, err
  617. }
  618. index = binary.BigEndian.Uint32(b)
  619. }
  620. if l.Level >= logrus.DebugLevel {
  621. l.WithField("index", index).
  622. Debug("Generated index")
  623. }
  624. return index, nil
  625. }
  626. func hsTimeout(tries int64, interval time.Duration) time.Duration {
  627. return time.Duration(tries / 2 * ((2 * int64(interval)) + (tries-1)*int64(interval)))
  628. }