handshake_manager.go 20 KB

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