handshake_manager.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. package nebula
  2. import (
  3. "crypto/rand"
  4. "encoding/binary"
  5. "fmt"
  6. "net"
  7. "time"
  8. "github.com/sirupsen/logrus"
  9. )
  10. const (
  11. // Total time to try a handshake = sequence of HandshakeTryInterval * HandshakeRetries
  12. // With 100ms interval and 20 retries is 23.5 seconds
  13. DefaultHandshakeTryInterval = time.Millisecond * 100
  14. DefaultHandshakeRetries = 20
  15. // DefaultHandshakeWaitRotation is the number of handshake attempts to do before starting to use other ips addresses
  16. DefaultHandshakeWaitRotation = 5
  17. )
  18. var (
  19. defaultHandshakeConfig = HandshakeConfig{
  20. tryInterval: DefaultHandshakeTryInterval,
  21. retries: DefaultHandshakeRetries,
  22. waitRotation: DefaultHandshakeWaitRotation,
  23. }
  24. )
  25. type HandshakeConfig struct {
  26. tryInterval time.Duration
  27. retries int
  28. waitRotation int
  29. }
  30. type HandshakeManager struct {
  31. pendingHostMap *HostMap
  32. mainHostMap *HostMap
  33. lightHouse *LightHouse
  34. outside *udpConn
  35. config HandshakeConfig
  36. OutboundHandshakeTimer *SystemTimerWheel
  37. InboundHandshakeTimer *SystemTimerWheel
  38. }
  39. func NewHandshakeManager(tunCidr *net.IPNet, preferredRanges []*net.IPNet, mainHostMap *HostMap, lightHouse *LightHouse, outside *udpConn, config HandshakeConfig) *HandshakeManager {
  40. return &HandshakeManager{
  41. pendingHostMap: NewHostMap("pending", tunCidr, preferredRanges),
  42. mainHostMap: mainHostMap,
  43. lightHouse: lightHouse,
  44. outside: outside,
  45. config: config,
  46. OutboundHandshakeTimer: NewSystemTimerWheel(config.tryInterval, config.tryInterval*time.Duration(config.retries)),
  47. InboundHandshakeTimer: NewSystemTimerWheel(config.tryInterval, config.tryInterval*time.Duration(config.retries)),
  48. }
  49. }
  50. func (c *HandshakeManager) Run(f EncWriter) {
  51. clockSource := time.Tick(c.config.tryInterval)
  52. for now := range clockSource {
  53. c.NextOutboundHandshakeTimerTick(now, f)
  54. c.NextInboundHandshakeTimerTick(now)
  55. }
  56. }
  57. func (c *HandshakeManager) NextOutboundHandshakeTimerTick(now time.Time, f EncWriter) {
  58. c.OutboundHandshakeTimer.advance(now)
  59. for {
  60. ep := c.OutboundHandshakeTimer.Purge()
  61. if ep == nil {
  62. break
  63. }
  64. vpnIP := ep.(uint32)
  65. index, err := c.pendingHostMap.GetIndexByVpnIP(vpnIP)
  66. if err != nil {
  67. continue
  68. }
  69. hostinfo, err := c.pendingHostMap.QueryVpnIP(vpnIP)
  70. if err != nil {
  71. continue
  72. }
  73. // If we haven't finished the handshake and we haven't hit max retries, query
  74. // lighthouse and then send the handshake packet again.
  75. if hostinfo.HandshakeCounter < c.config.retries && !hostinfo.HandshakeComplete {
  76. if hostinfo.remote == nil {
  77. // We continue to query the lighthouse because hosts may
  78. // come online during handshake retries. If the query
  79. // succeeds (no error), add the lighthouse info to hostinfo
  80. ips, err := c.lightHouse.Query(vpnIP, f)
  81. if err == nil {
  82. for _, ip := range ips {
  83. hostinfo.AddRemote(ip)
  84. }
  85. hostinfo.ForcePromoteBest(c.mainHostMap.preferredRanges)
  86. }
  87. }
  88. hostinfo.HandshakeCounter++
  89. // We want to use the "best" calculated ip for the first 5 attempts, after that we just blindly rotate through
  90. // all the others until we can stand up a connection.
  91. if hostinfo.HandshakeCounter > c.config.waitRotation {
  92. hostinfo.rotateRemote()
  93. }
  94. // Ensure the handshake is ready to avoid a race in timer tick and stage 0 handshake generation
  95. if hostinfo.HandshakeReady && hostinfo.remote != nil {
  96. err := c.outside.WriteTo(hostinfo.HandshakePacket[0], hostinfo.remote)
  97. if err != nil {
  98. hostinfo.logger().WithField("udpAddr", hostinfo.remote).
  99. WithField("initiatorIndex", hostinfo.localIndexId).
  100. WithField("remoteIndex", hostinfo.remoteIndexId).
  101. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  102. WithError(err).Error("Failed to send handshake message")
  103. } else {
  104. //TODO: this log line is assuming a lot of stuff around the cached stage 0 handshake packet, we should
  105. // keep the real packet struct around for logging purposes
  106. hostinfo.logger().WithField("udpAddr", hostinfo.remote).
  107. WithField("initiatorIndex", hostinfo.localIndexId).
  108. WithField("remoteIndex", hostinfo.remoteIndexId).
  109. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  110. Info("Handshake message sent")
  111. }
  112. }
  113. // Readd to the timer wheel so we continue trying wait HandshakeTryInterval * counter longer for next try
  114. //l.Infoln("Interval: ", HandshakeTryInterval*time.Duration(hostinfo.HandshakeCounter))
  115. c.OutboundHandshakeTimer.Add(vpnIP, c.config.tryInterval*time.Duration(hostinfo.HandshakeCounter))
  116. } else {
  117. c.pendingHostMap.DeleteVpnIP(vpnIP)
  118. c.pendingHostMap.DeleteIndex(index)
  119. }
  120. }
  121. }
  122. func (c *HandshakeManager) NextInboundHandshakeTimerTick(now time.Time) {
  123. c.InboundHandshakeTimer.advance(now)
  124. for {
  125. ep := c.InboundHandshakeTimer.Purge()
  126. if ep == nil {
  127. break
  128. }
  129. index := ep.(uint32)
  130. vpnIP, err := c.pendingHostMap.GetVpnIPByIndex(index)
  131. if err != nil {
  132. continue
  133. }
  134. c.pendingHostMap.DeleteIndex(index)
  135. c.pendingHostMap.DeleteVpnIP(vpnIP)
  136. }
  137. }
  138. func (c *HandshakeManager) AddVpnIP(vpnIP uint32) *HostInfo {
  139. hostinfo := c.pendingHostMap.AddVpnIP(vpnIP)
  140. // We lock here and use an array to insert items to prevent locking the
  141. // main receive thread for very long by waiting to add items to the pending map
  142. c.OutboundHandshakeTimer.Add(vpnIP, c.config.tryInterval)
  143. return hostinfo
  144. }
  145. func (c *HandshakeManager) DeleteVpnIP(vpnIP uint32) {
  146. //l.Debugln("Deleting pending vpn ip :", IntIp(vpnIP))
  147. c.pendingHostMap.DeleteVpnIP(vpnIP)
  148. }
  149. func (c *HandshakeManager) AddIndex(index uint32, ci *ConnectionState) (*HostInfo, error) {
  150. hostinfo, err := c.pendingHostMap.AddIndex(index, ci)
  151. if err != nil {
  152. return nil, fmt.Errorf("Issue adding index: %d", index)
  153. }
  154. //c.mainHostMap.AddIndexHostInfo(index, hostinfo)
  155. c.InboundHandshakeTimer.Add(index, time.Second*10)
  156. return hostinfo, nil
  157. }
  158. func (c *HandshakeManager) AddIndexHostInfo(index uint32, h *HostInfo) {
  159. c.pendingHostMap.AddIndexHostInfo(index, h)
  160. }
  161. func (c *HandshakeManager) DeleteIndex(index uint32) {
  162. //l.Debugln("Deleting pending index :", index)
  163. c.pendingHostMap.DeleteIndex(index)
  164. }
  165. func (c *HandshakeManager) QueryIndex(index uint32) (*HostInfo, error) {
  166. return c.pendingHostMap.QueryIndex(index)
  167. }
  168. func (c *HandshakeManager) EmitStats() {
  169. c.pendingHostMap.EmitStats("pending")
  170. c.mainHostMap.EmitStats("main")
  171. }
  172. // Utility functions below
  173. func generateIndex() (uint32, error) {
  174. b := make([]byte, 4)
  175. _, err := rand.Read(b)
  176. if err != nil {
  177. l.Errorln(err)
  178. return 0, err
  179. }
  180. index := binary.BigEndian.Uint32(b)
  181. if l.Level >= logrus.DebugLevel {
  182. l.WithField("index", index).
  183. Debug("Generated index")
  184. }
  185. return index, nil
  186. }