handshake_manager.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  1. package nebula
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/rand"
  6. "encoding/binary"
  7. "errors"
  8. "net"
  9. "sync"
  10. "time"
  11. "github.com/rcrowley/go-metrics"
  12. "github.com/sirupsen/logrus"
  13. "github.com/slackhq/nebula/header"
  14. "github.com/slackhq/nebula/iputil"
  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 int
  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. sync.RWMutex
  41. vpnIps map[iputil.VpnIp]*HostInfo
  42. indexes map[uint32]*HostInfo
  43. mainHostMap *HostMap
  44. lightHouse *LightHouse
  45. outside udp.Conn
  46. config HandshakeConfig
  47. OutboundHandshakeTimer *LockingTimerWheel[iputil.VpnIp]
  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 iputil.VpnIp
  55. }
  56. func NewHandshakeManager(l *logrus.Logger, mainHostMap *HostMap, lightHouse *LightHouse, outside udp.Conn, config HandshakeConfig) *HandshakeManager {
  57. return &HandshakeManager{
  58. vpnIps: map[iputil.VpnIp]*HostInfo{},
  59. indexes: map[uint32]*HostInfo{},
  60. mainHostMap: mainHostMap,
  61. lightHouse: lightHouse,
  62. outside: outside,
  63. config: config,
  64. trigger: make(chan iputil.VpnIp, config.triggerBuffer),
  65. OutboundHandshakeTimer: NewLockingTimerWheel[iputil.VpnIp](config.tryInterval, hsTimeout(config.retries, config.tryInterval)),
  66. messageMetrics: config.messageMetrics,
  67. metricInitiated: metrics.GetOrRegisterCounter("handshake_manager.initiated", nil),
  68. metricTimedOut: metrics.GetOrRegisterCounter("handshake_manager.timed_out", nil),
  69. l: l,
  70. }
  71. }
  72. func (c *HandshakeManager) Run(ctx context.Context) {
  73. clockSource := time.NewTicker(c.config.tryInterval)
  74. defer clockSource.Stop()
  75. for {
  76. select {
  77. case <-ctx.Done():
  78. return
  79. case vpnIP := <-c.trigger:
  80. c.handleOutbound(vpnIP, true)
  81. case now := <-clockSource.C:
  82. c.NextOutboundHandshakeTimerTick(now)
  83. }
  84. }
  85. }
  86. func (c *HandshakeManager) NextOutboundHandshakeTimerTick(now time.Time) {
  87. c.OutboundHandshakeTimer.Advance(now)
  88. for {
  89. vpnIp, has := c.OutboundHandshakeTimer.Purge()
  90. if !has {
  91. break
  92. }
  93. c.handleOutbound(vpnIp, false)
  94. }
  95. }
  96. func (c *HandshakeManager) handleOutbound(vpnIp iputil.VpnIp, lighthouseTriggered bool) {
  97. hostinfo := c.QueryVpnIp(vpnIp)
  98. if hostinfo == nil {
  99. return
  100. }
  101. hostinfo.Lock()
  102. defer hostinfo.Unlock()
  103. // We may have raced to completion but now that we have a lock we should ensure we have not yet completed.
  104. if hostinfo.HandshakeComplete {
  105. // Ensure we don't exist in the pending hostmap anymore since we have completed
  106. c.DeleteHostInfo(hostinfo)
  107. return
  108. }
  109. // If we are out of time, clean up
  110. if hostinfo.HandshakeCounter >= c.config.retries {
  111. hostinfo.logger(c.l).WithField("udpAddrs", hostinfo.remotes.CopyAddrs(c.mainHostMap.preferredRanges)).
  112. WithField("initiatorIndex", hostinfo.localIndexId).
  113. WithField("remoteIndex", hostinfo.remoteIndexId).
  114. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  115. WithField("durationNs", time.Since(hostinfo.handshakeStart).Nanoseconds()).
  116. Info("Handshake timed out")
  117. c.metricTimedOut.Inc(1)
  118. c.DeleteHostInfo(hostinfo)
  119. return
  120. }
  121. // Increment the counter to increase our delay, linear backoff
  122. hostinfo.HandshakeCounter++
  123. // Check if we have a handshake packet to transmit yet
  124. if !hostinfo.HandshakeReady {
  125. if !ixHandshakeStage0(c.f, hostinfo) {
  126. c.OutboundHandshakeTimer.Add(vpnIp, c.config.tryInterval*time.Duration(hostinfo.HandshakeCounter))
  127. return
  128. }
  129. }
  130. // Get a remotes object if we don't already have one.
  131. // This is mainly to protect us as this should never be the case
  132. // NB ^ This comment doesn't jive. It's how the thing gets initialized.
  133. // It's the common path. Should it update every time, in case a future LH query/queries give us more info?
  134. if hostinfo.remotes == nil {
  135. hostinfo.remotes = c.lightHouse.QueryCache(vpnIp)
  136. }
  137. remotes := hostinfo.remotes.CopyAddrs(c.mainHostMap.preferredRanges)
  138. remotesHaveChanged := !udp.AddrSlice(remotes).Equal(hostinfo.HandshakeLastRemotes)
  139. // We only care about a lighthouse trigger if we have new remotes to send to.
  140. // This is a very specific optimization for a fast lighthouse reply.
  141. if lighthouseTriggered && !remotesHaveChanged {
  142. // If we didn't return here a lighthouse could cause us to aggressively send handshakes
  143. return
  144. }
  145. hostinfo.HandshakeLastRemotes = remotes
  146. // TODO: this will generate a load of queries for hosts with only 1 ip
  147. // (such as ones registered to the lighthouse with only a private IP)
  148. // So we only do it one time after attempting 5 handshakes already.
  149. if len(remotes) <= 1 && hostinfo.HandshakeCounter == 5 {
  150. // If we only have 1 remote it is highly likely our query raced with the other host registered within the lighthouse
  151. // Our vpnIp here has a tunnel with a lighthouse but has yet to send a host update packet there so we only know about
  152. // the learned public ip for them. Query again to short circuit the promotion counter
  153. c.lightHouse.QueryServer(vpnIp, c.f)
  154. }
  155. // Send the handshake to all known ips, stage 2 takes care of assigning the hostinfo.remote based on the first to reply
  156. var sentTo []*udp.Addr
  157. hostinfo.remotes.ForEach(c.mainHostMap.preferredRanges, func(addr *udp.Addr, _ bool) {
  158. c.messageMetrics.Tx(header.Handshake, header.MessageSubType(hostinfo.HandshakePacket[0][1]), 1)
  159. err := c.outside.WriteTo(hostinfo.HandshakePacket[0], addr)
  160. if err != nil {
  161. hostinfo.logger(c.l).WithField("udpAddr", addr).
  162. WithField("initiatorIndex", hostinfo.localIndexId).
  163. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  164. WithError(err).Error("Failed to send handshake message")
  165. } else {
  166. sentTo = append(sentTo, addr)
  167. }
  168. })
  169. // 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,
  170. // so only log when the list of remotes has changed
  171. if remotesHaveChanged {
  172. hostinfo.logger(c.l).WithField("udpAddrs", sentTo).
  173. WithField("initiatorIndex", hostinfo.localIndexId).
  174. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  175. Info("Handshake message sent")
  176. } else if c.l.IsLevelEnabled(logrus.DebugLevel) {
  177. hostinfo.logger(c.l).WithField("udpAddrs", sentTo).
  178. WithField("initiatorIndex", hostinfo.localIndexId).
  179. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  180. Debug("Handshake message sent")
  181. }
  182. if c.config.useRelays && len(hostinfo.remotes.relays) > 0 {
  183. hostinfo.logger(c.l).WithField("relays", hostinfo.remotes.relays).Info("Attempt to relay through hosts")
  184. // Send a RelayRequest to all known Relay IP's
  185. for _, relay := range hostinfo.remotes.relays {
  186. // Don't relay to myself, and don't relay through the host I'm trying to connect to
  187. if *relay == vpnIp || *relay == c.lightHouse.myVpnIp {
  188. continue
  189. }
  190. relayHostInfo := c.mainHostMap.QueryVpnIp(*relay)
  191. if relayHostInfo == nil || relayHostInfo.remote == nil {
  192. hostinfo.logger(c.l).WithField("relay", relay.String()).Info("Establish tunnel to relay target")
  193. c.f.Handshake(*relay)
  194. continue
  195. }
  196. // Check the relay HostInfo to see if we already established a relay through it
  197. if existingRelay, ok := relayHostInfo.relayState.QueryRelayForByIp(vpnIp); ok {
  198. switch existingRelay.State {
  199. case Established:
  200. hostinfo.logger(c.l).WithField("relay", relay.String()).Info("Send handshake via relay")
  201. c.f.SendVia(relayHostInfo, existingRelay, hostinfo.HandshakePacket[0], make([]byte, 12), make([]byte, mtu), false)
  202. case Requested:
  203. hostinfo.logger(c.l).WithField("relay", relay.String()).Info("Re-send CreateRelay request")
  204. // Re-send the CreateRelay request, in case the previous one was lost.
  205. m := NebulaControl{
  206. Type: NebulaControl_CreateRelayRequest,
  207. InitiatorRelayIndex: existingRelay.LocalIndex,
  208. RelayFromIp: uint32(c.lightHouse.myVpnIp),
  209. RelayToIp: uint32(vpnIp),
  210. }
  211. msg, err := m.Marshal()
  212. if err != nil {
  213. hostinfo.logger(c.l).
  214. WithError(err).
  215. Error("Failed to marshal Control message to create relay")
  216. } else {
  217. // This must send over the hostinfo, not over hm.Hosts[ip]
  218. c.f.SendMessageToHostInfo(header.Control, 0, relayHostInfo, msg, make([]byte, 12), make([]byte, mtu))
  219. c.l.WithFields(logrus.Fields{
  220. "relayFrom": c.lightHouse.myVpnIp,
  221. "relayTo": vpnIp,
  222. "initiatorRelayIndex": existingRelay.LocalIndex,
  223. "relay": *relay}).
  224. Info("send CreateRelayRequest")
  225. }
  226. default:
  227. hostinfo.logger(c.l).
  228. WithField("vpnIp", vpnIp).
  229. WithField("state", existingRelay.State).
  230. WithField("relay", relayHostInfo.vpnIp).
  231. Errorf("Relay unexpected state")
  232. }
  233. } else {
  234. // No relays exist or requested yet.
  235. if relayHostInfo.remote != nil {
  236. idx, err := AddRelay(c.l, relayHostInfo, c.mainHostMap, vpnIp, nil, TerminalType, Requested)
  237. if err != nil {
  238. hostinfo.logger(c.l).WithField("relay", relay.String()).WithError(err).Info("Failed to add relay to hostmap")
  239. }
  240. m := NebulaControl{
  241. Type: NebulaControl_CreateRelayRequest,
  242. InitiatorRelayIndex: idx,
  243. RelayFromIp: uint32(c.lightHouse.myVpnIp),
  244. RelayToIp: uint32(vpnIp),
  245. }
  246. msg, err := m.Marshal()
  247. if err != nil {
  248. hostinfo.logger(c.l).
  249. WithError(err).
  250. Error("Failed to marshal Control message to create relay")
  251. } else {
  252. c.f.SendMessageToHostInfo(header.Control, 0, relayHostInfo, msg, make([]byte, 12), make([]byte, mtu))
  253. c.l.WithFields(logrus.Fields{
  254. "relayFrom": c.lightHouse.myVpnIp,
  255. "relayTo": vpnIp,
  256. "initiatorRelayIndex": idx,
  257. "relay": *relay}).
  258. Info("send CreateRelayRequest")
  259. }
  260. }
  261. }
  262. }
  263. }
  264. // If a lighthouse triggered this attempt then we are still in the timer wheel and do not need to re-add
  265. if !lighthouseTriggered {
  266. c.OutboundHandshakeTimer.Add(vpnIp, c.config.tryInterval*time.Duration(hostinfo.HandshakeCounter))
  267. }
  268. }
  269. // GetOrHandshake will try to find a hostinfo with a fully formed tunnel or start a new handshake if one is not present
  270. // The 2nd argument will be true if the hostinfo is ready to transmit traffic
  271. func (hm *HandshakeManager) GetOrHandshake(vpnIp iputil.VpnIp, cacheCb func(*HostInfo)) (*HostInfo, bool) {
  272. // Check the main hostmap and maintain a read lock if our host is not there
  273. hm.mainHostMap.RLock()
  274. if h, ok := hm.mainHostMap.Hosts[vpnIp]; ok {
  275. hm.mainHostMap.RUnlock()
  276. // Do not attempt promotion if you are a lighthouse
  277. if !hm.lightHouse.amLighthouse {
  278. h.TryPromoteBest(hm.mainHostMap.preferredRanges, hm.f)
  279. }
  280. return h, true
  281. }
  282. defer hm.mainHostMap.RUnlock()
  283. return hm.StartHandshake(vpnIp, cacheCb), false
  284. }
  285. // StartHandshake will ensure a handshake is currently being attempted for the provided vpn ip
  286. func (hm *HandshakeManager) StartHandshake(vpnIp iputil.VpnIp, cacheCb func(*HostInfo)) *HostInfo {
  287. hm.Lock()
  288. defer hm.Unlock()
  289. if hostinfo, ok := hm.vpnIps[vpnIp]; ok {
  290. // We are already trying to handshake with this vpn ip
  291. if cacheCb != nil {
  292. cacheCb(hostinfo)
  293. }
  294. return hostinfo
  295. }
  296. hostinfo := &HostInfo{
  297. vpnIp: vpnIp,
  298. HandshakePacket: make(map[uint8][]byte, 0),
  299. relayState: RelayState{
  300. relays: map[iputil.VpnIp]struct{}{},
  301. relayForByIp: map[iputil.VpnIp]*Relay{},
  302. relayForByIdx: map[uint32]*Relay{},
  303. },
  304. }
  305. hm.vpnIps[vpnIp] = hostinfo
  306. hm.metricInitiated.Inc(1)
  307. hm.OutboundHandshakeTimer.Add(vpnIp, hm.config.tryInterval)
  308. if cacheCb != nil {
  309. cacheCb(hostinfo)
  310. }
  311. // If this is a static host, we don't need to wait for the HostQueryReply
  312. // We can trigger the handshake right now
  313. _, doTrigger := hm.lightHouse.GetStaticHostList()[vpnIp]
  314. if !doTrigger {
  315. // Add any calculated remotes, and trigger early handshake if one found
  316. doTrigger = hm.lightHouse.addCalculatedRemotes(vpnIp)
  317. }
  318. if doTrigger {
  319. select {
  320. case hm.trigger <- vpnIp:
  321. default:
  322. }
  323. }
  324. hm.lightHouse.QueryServer(vpnIp, hm.f)
  325. return hostinfo
  326. }
  327. var (
  328. ErrExistingHostInfo = errors.New("existing hostinfo")
  329. ErrAlreadySeen = errors.New("already seen")
  330. ErrLocalIndexCollision = errors.New("local index collision")
  331. )
  332. // CheckAndComplete checks for any conflicts in the main and pending hostmap
  333. // before adding hostinfo to main. If err is nil, it was added. Otherwise err will be:
  334. //
  335. // ErrAlreadySeen if we already have an entry in the hostmap that has seen the
  336. // exact same handshake packet
  337. //
  338. // ErrExistingHostInfo if we already have an entry in the hostmap for this
  339. // VpnIp and the new handshake was older than the one we currently have
  340. //
  341. // ErrLocalIndexCollision if we already have an entry in the main or pending
  342. // hostmap for the hostinfo.localIndexId.
  343. func (c *HandshakeManager) CheckAndComplete(hostinfo *HostInfo, handshakePacket uint8, f *Interface) (*HostInfo, error) {
  344. c.mainHostMap.Lock()
  345. defer c.mainHostMap.Unlock()
  346. c.Lock()
  347. defer c.Unlock()
  348. // Check if we already have a tunnel with this vpn ip
  349. existingHostInfo, found := c.mainHostMap.Hosts[hostinfo.vpnIp]
  350. if found && existingHostInfo != nil {
  351. testHostInfo := existingHostInfo
  352. for testHostInfo != nil {
  353. // Is it just a delayed handshake packet?
  354. if bytes.Equal(hostinfo.HandshakePacket[handshakePacket], testHostInfo.HandshakePacket[handshakePacket]) {
  355. return testHostInfo, ErrAlreadySeen
  356. }
  357. testHostInfo = testHostInfo.next
  358. }
  359. // Is this a newer handshake?
  360. if existingHostInfo.lastHandshakeTime >= hostinfo.lastHandshakeTime && !existingHostInfo.ConnectionState.initiator {
  361. return existingHostInfo, ErrExistingHostInfo
  362. }
  363. existingHostInfo.logger(c.l).Info("Taking new handshake")
  364. }
  365. existingIndex, found := c.mainHostMap.Indexes[hostinfo.localIndexId]
  366. if found {
  367. // We have a collision, but for a different hostinfo
  368. return existingIndex, ErrLocalIndexCollision
  369. }
  370. existingIndex, found = c.indexes[hostinfo.localIndexId]
  371. if found && existingIndex != hostinfo {
  372. // We have a collision, but for a different hostinfo
  373. return existingIndex, ErrLocalIndexCollision
  374. }
  375. existingRemoteIndex, found := c.mainHostMap.RemoteIndexes[hostinfo.remoteIndexId]
  376. if found && existingRemoteIndex != nil && existingRemoteIndex.vpnIp != hostinfo.vpnIp {
  377. // We have a collision, but this can happen since we can't control
  378. // the remote ID. Just log about the situation as a note.
  379. hostinfo.logger(c.l).
  380. WithField("remoteIndex", hostinfo.remoteIndexId).WithField("collision", existingRemoteIndex.vpnIp).
  381. Info("New host shadows existing host remoteIndex")
  382. }
  383. c.mainHostMap.unlockedAddHostInfo(hostinfo, f)
  384. return existingHostInfo, nil
  385. }
  386. // Complete is a simpler version of CheckAndComplete when we already know we
  387. // won't have a localIndexId collision because we already have an entry in the
  388. // pendingHostMap. An existing hostinfo is returned if there was one.
  389. func (hm *HandshakeManager) Complete(hostinfo *HostInfo, f *Interface) {
  390. hm.mainHostMap.Lock()
  391. defer hm.mainHostMap.Unlock()
  392. hm.Lock()
  393. defer hm.Unlock()
  394. existingRemoteIndex, found := hm.mainHostMap.RemoteIndexes[hostinfo.remoteIndexId]
  395. if found && existingRemoteIndex != nil {
  396. // We have a collision, but this can happen since we can't control
  397. // the remote ID. Just log about the situation as a note.
  398. hostinfo.logger(hm.l).
  399. WithField("remoteIndex", hostinfo.remoteIndexId).WithField("collision", existingRemoteIndex.vpnIp).
  400. Info("New host shadows existing host remoteIndex")
  401. }
  402. // We need to remove from the pending hostmap first to avoid undoing work when after to the main hostmap.
  403. hm.unlockedDeleteHostInfo(hostinfo)
  404. hm.mainHostMap.unlockedAddHostInfo(hostinfo, f)
  405. }
  406. // allocateIndex generates a unique localIndexId for this HostInfo
  407. // and adds it to the pendingHostMap. Will error if we are unable to generate
  408. // a unique localIndexId
  409. func (hm *HandshakeManager) allocateIndex(h *HostInfo) error {
  410. hm.mainHostMap.RLock()
  411. defer hm.mainHostMap.RUnlock()
  412. hm.Lock()
  413. defer hm.Unlock()
  414. for i := 0; i < 32; i++ {
  415. index, err := generateIndex(hm.l)
  416. if err != nil {
  417. return err
  418. }
  419. _, inPending := hm.indexes[index]
  420. _, inMain := hm.mainHostMap.Indexes[index]
  421. if !inMain && !inPending {
  422. h.localIndexId = index
  423. hm.indexes[index] = h
  424. return nil
  425. }
  426. }
  427. return errors.New("failed to generate unique localIndexId")
  428. }
  429. func (c *HandshakeManager) DeleteHostInfo(hostinfo *HostInfo) {
  430. c.Lock()
  431. defer c.Unlock()
  432. c.unlockedDeleteHostInfo(hostinfo)
  433. }
  434. func (c *HandshakeManager) unlockedDeleteHostInfo(hostinfo *HostInfo) {
  435. delete(c.vpnIps, hostinfo.vpnIp)
  436. if len(c.vpnIps) == 0 {
  437. c.vpnIps = map[iputil.VpnIp]*HostInfo{}
  438. }
  439. delete(c.indexes, hostinfo.localIndexId)
  440. if len(c.vpnIps) == 0 {
  441. c.indexes = map[uint32]*HostInfo{}
  442. }
  443. if c.l.Level >= logrus.DebugLevel {
  444. c.l.WithField("hostMap", m{"mapTotalSize": len(c.vpnIps),
  445. "vpnIp": hostinfo.vpnIp, "indexNumber": hostinfo.localIndexId, "remoteIndexNumber": hostinfo.remoteIndexId}).
  446. Debug("Pending hostmap hostInfo deleted")
  447. }
  448. }
  449. func (c *HandshakeManager) QueryVpnIp(vpnIp iputil.VpnIp) *HostInfo {
  450. c.RLock()
  451. defer c.RUnlock()
  452. return c.vpnIps[vpnIp]
  453. }
  454. func (c *HandshakeManager) QueryIndex(index uint32) *HostInfo {
  455. c.RLock()
  456. defer c.RUnlock()
  457. return c.indexes[index]
  458. }
  459. func (c *HandshakeManager) GetPreferredRanges() []*net.IPNet {
  460. return c.mainHostMap.preferredRanges
  461. }
  462. func (c *HandshakeManager) ForEachVpnIp(f controlEach) {
  463. c.RLock()
  464. defer c.RUnlock()
  465. for _, v := range c.vpnIps {
  466. f(v)
  467. }
  468. }
  469. func (c *HandshakeManager) ForEachIndex(f controlEach) {
  470. c.RLock()
  471. defer c.RUnlock()
  472. for _, v := range c.indexes {
  473. f(v)
  474. }
  475. }
  476. func (c *HandshakeManager) EmitStats() {
  477. c.RLock()
  478. hostLen := len(c.vpnIps)
  479. indexLen := len(c.indexes)
  480. c.RUnlock()
  481. metrics.GetOrRegisterGauge("hostmap.pending.hosts", nil).Update(int64(hostLen))
  482. metrics.GetOrRegisterGauge("hostmap.pending.indexes", nil).Update(int64(indexLen))
  483. c.mainHostMap.EmitStats()
  484. }
  485. // Utility functions below
  486. func generateIndex(l *logrus.Logger) (uint32, error) {
  487. b := make([]byte, 4)
  488. // Let zero mean we don't know the ID, so don't generate zero
  489. var index uint32
  490. for index == 0 {
  491. _, err := rand.Read(b)
  492. if err != nil {
  493. l.Errorln(err)
  494. return 0, err
  495. }
  496. index = binary.BigEndian.Uint32(b)
  497. }
  498. if l.Level >= logrus.DebugLevel {
  499. l.WithField("index", index).
  500. Debug("Generated index")
  501. }
  502. return index, nil
  503. }
  504. func hsTimeout(tries int, interval time.Duration) time.Duration {
  505. return time.Duration(tries / 2 * ((2 * int(interval)) + (tries-1)*int(interval)))
  506. }