2
0

handshake_manager.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  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. if hostinfo, ok := hm.vpnIps[vpnIp]; ok {
  289. // We are already trying to handshake with this vpn ip
  290. if cacheCb != nil {
  291. cacheCb(hostinfo)
  292. }
  293. hm.Unlock()
  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.Unlock()
  325. hm.lightHouse.QueryServer(vpnIp, hm.f)
  326. return hostinfo
  327. }
  328. var (
  329. ErrExistingHostInfo = errors.New("existing hostinfo")
  330. ErrAlreadySeen = errors.New("already seen")
  331. ErrLocalIndexCollision = errors.New("local index collision")
  332. )
  333. // CheckAndComplete checks for any conflicts in the main and pending hostmap
  334. // before adding hostinfo to main. If err is nil, it was added. Otherwise err will be:
  335. //
  336. // ErrAlreadySeen if we already have an entry in the hostmap that has seen the
  337. // exact same handshake packet
  338. //
  339. // ErrExistingHostInfo if we already have an entry in the hostmap for this
  340. // VpnIp and the new handshake was older than the one we currently have
  341. //
  342. // ErrLocalIndexCollision if we already have an entry in the main or pending
  343. // hostmap for the hostinfo.localIndexId.
  344. func (c *HandshakeManager) CheckAndComplete(hostinfo *HostInfo, handshakePacket uint8, f *Interface) (*HostInfo, error) {
  345. c.mainHostMap.Lock()
  346. defer c.mainHostMap.Unlock()
  347. c.Lock()
  348. defer c.Unlock()
  349. // Check if we already have a tunnel with this vpn ip
  350. existingHostInfo, found := c.mainHostMap.Hosts[hostinfo.vpnIp]
  351. if found && existingHostInfo != nil {
  352. testHostInfo := existingHostInfo
  353. for testHostInfo != nil {
  354. // Is it just a delayed handshake packet?
  355. if bytes.Equal(hostinfo.HandshakePacket[handshakePacket], testHostInfo.HandshakePacket[handshakePacket]) {
  356. return testHostInfo, ErrAlreadySeen
  357. }
  358. testHostInfo = testHostInfo.next
  359. }
  360. // Is this a newer handshake?
  361. if existingHostInfo.lastHandshakeTime >= hostinfo.lastHandshakeTime && !existingHostInfo.ConnectionState.initiator {
  362. return existingHostInfo, ErrExistingHostInfo
  363. }
  364. existingHostInfo.logger(c.l).Info("Taking new handshake")
  365. }
  366. existingIndex, found := c.mainHostMap.Indexes[hostinfo.localIndexId]
  367. if found {
  368. // We have a collision, but for a different hostinfo
  369. return existingIndex, ErrLocalIndexCollision
  370. }
  371. existingIndex, found = c.indexes[hostinfo.localIndexId]
  372. if found && existingIndex != hostinfo {
  373. // We have a collision, but for a different hostinfo
  374. return existingIndex, ErrLocalIndexCollision
  375. }
  376. existingRemoteIndex, found := c.mainHostMap.RemoteIndexes[hostinfo.remoteIndexId]
  377. if found && existingRemoteIndex != nil && existingRemoteIndex.vpnIp != hostinfo.vpnIp {
  378. // We have a collision, but this can happen since we can't control
  379. // the remote ID. Just log about the situation as a note.
  380. hostinfo.logger(c.l).
  381. WithField("remoteIndex", hostinfo.remoteIndexId).WithField("collision", existingRemoteIndex.vpnIp).
  382. Info("New host shadows existing host remoteIndex")
  383. }
  384. c.mainHostMap.unlockedAddHostInfo(hostinfo, f)
  385. return existingHostInfo, nil
  386. }
  387. // Complete is a simpler version of CheckAndComplete when we already know we
  388. // won't have a localIndexId collision because we already have an entry in the
  389. // pendingHostMap. An existing hostinfo is returned if there was one.
  390. func (hm *HandshakeManager) Complete(hostinfo *HostInfo, f *Interface) {
  391. hm.mainHostMap.Lock()
  392. defer hm.mainHostMap.Unlock()
  393. hm.Lock()
  394. defer hm.Unlock()
  395. existingRemoteIndex, found := hm.mainHostMap.RemoteIndexes[hostinfo.remoteIndexId]
  396. if found && existingRemoteIndex != nil {
  397. // We have a collision, but this can happen since we can't control
  398. // the remote ID. Just log about the situation as a note.
  399. hostinfo.logger(hm.l).
  400. WithField("remoteIndex", hostinfo.remoteIndexId).WithField("collision", existingRemoteIndex.vpnIp).
  401. Info("New host shadows existing host remoteIndex")
  402. }
  403. // We need to remove from the pending hostmap first to avoid undoing work when after to the main hostmap.
  404. hm.unlockedDeleteHostInfo(hostinfo)
  405. hm.mainHostMap.unlockedAddHostInfo(hostinfo, f)
  406. }
  407. // allocateIndex generates a unique localIndexId for this HostInfo
  408. // and adds it to the pendingHostMap. Will error if we are unable to generate
  409. // a unique localIndexId
  410. func (hm *HandshakeManager) allocateIndex(h *HostInfo) error {
  411. hm.mainHostMap.RLock()
  412. defer hm.mainHostMap.RUnlock()
  413. hm.Lock()
  414. defer hm.Unlock()
  415. for i := 0; i < 32; i++ {
  416. index, err := generateIndex(hm.l)
  417. if err != nil {
  418. return err
  419. }
  420. _, inPending := hm.indexes[index]
  421. _, inMain := hm.mainHostMap.Indexes[index]
  422. if !inMain && !inPending {
  423. h.localIndexId = index
  424. hm.indexes[index] = h
  425. return nil
  426. }
  427. }
  428. return errors.New("failed to generate unique localIndexId")
  429. }
  430. func (c *HandshakeManager) DeleteHostInfo(hostinfo *HostInfo) {
  431. c.Lock()
  432. defer c.Unlock()
  433. c.unlockedDeleteHostInfo(hostinfo)
  434. }
  435. func (c *HandshakeManager) unlockedDeleteHostInfo(hostinfo *HostInfo) {
  436. delete(c.vpnIps, hostinfo.vpnIp)
  437. if len(c.vpnIps) == 0 {
  438. c.vpnIps = map[iputil.VpnIp]*HostInfo{}
  439. }
  440. delete(c.indexes, hostinfo.localIndexId)
  441. if len(c.vpnIps) == 0 {
  442. c.indexes = map[uint32]*HostInfo{}
  443. }
  444. if c.l.Level >= logrus.DebugLevel {
  445. c.l.WithField("hostMap", m{"mapTotalSize": len(c.vpnIps),
  446. "vpnIp": hostinfo.vpnIp, "indexNumber": hostinfo.localIndexId, "remoteIndexNumber": hostinfo.remoteIndexId}).
  447. Debug("Pending hostmap hostInfo deleted")
  448. }
  449. }
  450. func (c *HandshakeManager) QueryVpnIp(vpnIp iputil.VpnIp) *HostInfo {
  451. c.RLock()
  452. defer c.RUnlock()
  453. return c.vpnIps[vpnIp]
  454. }
  455. func (c *HandshakeManager) QueryIndex(index uint32) *HostInfo {
  456. c.RLock()
  457. defer c.RUnlock()
  458. return c.indexes[index]
  459. }
  460. func (c *HandshakeManager) GetPreferredRanges() []*net.IPNet {
  461. return c.mainHostMap.preferredRanges
  462. }
  463. func (c *HandshakeManager) ForEachVpnIp(f controlEach) {
  464. c.RLock()
  465. defer c.RUnlock()
  466. for _, v := range c.vpnIps {
  467. f(v)
  468. }
  469. }
  470. func (c *HandshakeManager) ForEachIndex(f controlEach) {
  471. c.RLock()
  472. defer c.RUnlock()
  473. for _, v := range c.indexes {
  474. f(v)
  475. }
  476. }
  477. func (c *HandshakeManager) EmitStats() {
  478. c.RLock()
  479. hostLen := len(c.vpnIps)
  480. indexLen := len(c.indexes)
  481. c.RUnlock()
  482. metrics.GetOrRegisterGauge("hostmap.pending.hosts", nil).Update(int64(hostLen))
  483. metrics.GetOrRegisterGauge("hostmap.pending.indexes", nil).Update(int64(indexLen))
  484. c.mainHostMap.EmitStats()
  485. }
  486. // Utility functions below
  487. func generateIndex(l *logrus.Logger) (uint32, error) {
  488. b := make([]byte, 4)
  489. // Let zero mean we don't know the ID, so don't generate zero
  490. var index uint32
  491. for index == 0 {
  492. _, err := rand.Read(b)
  493. if err != nil {
  494. l.Errorln(err)
  495. return 0, err
  496. }
  497. index = binary.BigEndian.Uint32(b)
  498. }
  499. if l.Level >= logrus.DebugLevel {
  500. l.WithField("index", index).
  501. Debug("Generated index")
  502. }
  503. return index, nil
  504. }
  505. func hsTimeout(tries int, interval time.Duration) time.Duration {
  506. return time.Duration(tries / 2 * ((2 * int(interval)) + (tries-1)*int(interval)))
  507. }