server.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. package server
  2. import (
  3. "context"
  4. "encoding/binary"
  5. "fmt"
  6. "log"
  7. "net"
  8. "time"
  9. "github.com/gravitl/netmaker/nm-proxy/common"
  10. "github.com/gravitl/netmaker/nm-proxy/models"
  11. "github.com/gravitl/netmaker/nm-proxy/packet"
  12. )
  13. var (
  14. NmProxyServer = &ProxyServer{}
  15. )
  16. const (
  17. defaultBodySize = 10000
  18. defaultPort = models.NmProxyPort
  19. )
  20. type Config struct {
  21. Port int
  22. BodySize int
  23. IsRelay bool
  24. Addr net.Addr
  25. }
  26. type ProxyServer struct {
  27. Config Config
  28. Server *net.UDPConn
  29. }
  30. // Proxy.Listen - begins listening for packets
  31. func (p *ProxyServer) Listen(ctx context.Context) {
  32. // Buffer with indicated body size
  33. buffer := make([]byte, 65032)
  34. for {
  35. select {
  36. case <-ctx.Done():
  37. log.Println("--------->### Shutting down Proxy.....")
  38. // clean up proxy connections
  39. for iface, ifaceConf := range common.WgIFaceMap {
  40. log.Println("########------------> CLEANING UP: ", iface)
  41. for _, peerI := range ifaceConf.PeerMap {
  42. peerI.StopConn()
  43. }
  44. }
  45. // close server connection
  46. NmProxyServer.Server.Close()
  47. return
  48. default:
  49. // Read Packet
  50. n, source, err := p.Server.ReadFromUDP(buffer)
  51. if err != nil { // in future log errors?
  52. log.Println("RECV ERROR: ", err)
  53. continue
  54. }
  55. //go func(buffer []byte, source *net.UDPAddr, n int) {
  56. origBufferLen := n
  57. var srcPeerKeyHash, dstPeerKeyHash string
  58. n, srcPeerKeyHash, dstPeerKeyHash = packet.ExtractInfo(buffer, n)
  59. //log.Printf("--------> RECV PKT , [SRCKEYHASH: %s], SourceIP: [%s] \n", srcPeerKeyHash, source.IP.String())
  60. if _, ok := common.WgIfaceKeyMap[dstPeerKeyHash]; !ok {
  61. // if common.IsIngressGateway {
  62. // log.Println("----> fowarding PKT to EXT client...")
  63. // if val, ok := common.PeerKeyHashMap[dstPeerKeyHash]; ok && val.IsAttachedExtClient {
  64. // log.Printf("-------->Forwarding the pkt to extClient [ SourceIP: %s ], [ SourceKeyHash: %s ], [ DstIP: %s ], [ DstHashKey: %s ] \n",
  65. // source.String(), srcPeerKeyHash, val.Endpoint.String(), dstPeerKeyHash)
  66. // _, err = NmProxyServer.Server.WriteToUDP(buffer[:n], val.Endpoint)
  67. // if err != nil {
  68. // log.Println("Failed to send to remote: ", err)
  69. // }
  70. // continue
  71. // }
  72. // }
  73. if common.IsRelay {
  74. log.Println("----------> Relaying######")
  75. // check for routing map and forward to right proxy
  76. if remoteMap, ok := common.RelayPeerMap[srcPeerKeyHash]; ok {
  77. if conf, ok := remoteMap[dstPeerKeyHash]; ok {
  78. log.Printf("--------> Relaying PKT [ SourceIP: %s:%d ], [ SourceKeyHash: %s ], [ DstIP: %s:%d ], [ DstHashKey: %s ] \n",
  79. source.IP.String(), source.Port, srcPeerKeyHash, conf.Endpoint.String(), conf.Endpoint.Port, dstPeerKeyHash)
  80. _, err = NmProxyServer.Server.WriteToUDP(buffer[:n+32], conf.Endpoint)
  81. if err != nil {
  82. log.Println("Failed to send to remote: ", err)
  83. }
  84. //continue
  85. }
  86. } else {
  87. if remoteMap, ok := common.RelayPeerMap[dstPeerKeyHash]; ok {
  88. if conf, ok := remoteMap[dstPeerKeyHash]; ok {
  89. log.Printf("--------> Relaying BACK TO RELAYED NODE PKT [ SourceIP: %s ], [ SourceKeyHash: %s ], [ DstIP: %s ], [ DstHashKey: %s ] \n",
  90. source.String(), srcPeerKeyHash, conf.Endpoint.String(), dstPeerKeyHash)
  91. _, err = NmProxyServer.Server.WriteToUDP(buffer[:n+32], conf.Endpoint)
  92. if err != nil {
  93. log.Println("Failed to send to remote: ", err)
  94. }
  95. //continue
  96. }
  97. }
  98. }
  99. }
  100. }
  101. if peerInfo, ok := common.PeerKeyHashMap[srcPeerKeyHash]; ok {
  102. if ifaceConf, ok := common.WgIFaceMap[peerInfo.Interface]; ok {
  103. if peerI, ok := ifaceConf.PeerMap[peerInfo.PeerKey]; ok {
  104. log.Printf("PROXING TO LOCAL!!!---> %s <<<< %s <<<<<<<< %s [[ RECV PKT [SRCKEYHASH: %s], [DSTKEYHASH: %s], SourceIP: [%s] ]]\n",
  105. peerI.LocalConn.RemoteAddr(), peerI.LocalConn.LocalAddr(),
  106. fmt.Sprintf("%s:%d", source.IP.String(), source.Port), srcPeerKeyHash, dstPeerKeyHash, source.IP.String())
  107. _, err = peerI.LocalConn.Write(buffer[:n])
  108. if err != nil {
  109. log.Println("Failed to proxy to Wg local interface: ", err)
  110. //continue
  111. }
  112. continue
  113. }
  114. }
  115. }
  116. if peerInfo, ok := common.ExtSourceIpMap[source.String()]; ok {
  117. if ifaceConf, ok := common.WgIFaceMap[peerInfo.Interface]; ok {
  118. if peerI, ok := ifaceConf.PeerMap[peerInfo.PeerKey]; ok {
  119. log.Printf("PROXING TO LOCAL!!!---> %s <<<< %s <<<<<<<< %s [[ RECV PKT [SRCKEYHASH: %s], [DSTKEYHASH: %s], SourceIP: [%s] ]]\n",
  120. peerI.LocalConn.RemoteAddr(), peerI.LocalConn.LocalAddr(),
  121. fmt.Sprintf("%s:%d", source.IP.String(), source.Port), srcPeerKeyHash, dstPeerKeyHash, source.IP.String())
  122. _, err = peerI.LocalConn.Write(buffer[:origBufferLen])
  123. if err != nil {
  124. log.Println("Failed to proxy to Wg local interface: ", err)
  125. //continue
  126. }
  127. continue
  128. }
  129. }
  130. }
  131. // unknown peer to proxy -> check if extclient and handle it
  132. // consume handshake message for ext clients
  133. msgType := binary.LittleEndian.Uint32(buffer[:4])
  134. switch msgType {
  135. case packet.MessageInitiationType:
  136. devPriv, devPubkey, err := packet.GetDeviceKeys(common.InterfaceName)
  137. if err == nil {
  138. err := packet.ConsumeHandshakeInitiationMsg(false, buffer[:origBufferLen], source, devPubkey, devPriv)
  139. if err != nil {
  140. log.Println("---------> @@@ failed to decode HS: ", err)
  141. }
  142. } else {
  143. log.Println("failed to get device keys: ", err)
  144. }
  145. }
  146. }
  147. }
  148. }
  149. // Create - creats a proxy listener
  150. // port - port for proxy to listen on localhost
  151. // bodySize - default 10000, leave 0 to use default
  152. // addr - the address for proxy to listen on
  153. // forwards - indicate address to forward to, {"<address:port>",...} format
  154. func (p *ProxyServer) CreateProxyServer(port, bodySize int, addr string) (err error) {
  155. if p == nil {
  156. p = &ProxyServer{}
  157. }
  158. p.Config.Port = port
  159. p.Config.BodySize = bodySize
  160. p.setDefaults()
  161. p.Server, err = net.ListenUDP("udp", &net.UDPAddr{
  162. Port: p.Config.Port,
  163. IP: net.ParseIP(addr),
  164. })
  165. return
  166. }
  167. func (p *ProxyServer) KeepAlive(ip string, port int) {
  168. for {
  169. _, _ = p.Server.WriteToUDP([]byte("hello-proxy"), &net.UDPAddr{
  170. IP: net.ParseIP(ip),
  171. Port: port,
  172. })
  173. //log.Println("Sending MSg: ", ip, port, err)
  174. time.Sleep(time.Second * 5)
  175. }
  176. }
  177. // Proxy.setDefaults - sets all defaults of proxy listener
  178. func (p *ProxyServer) setDefaults() {
  179. p.setDefaultBodySize()
  180. p.setDefaultPort()
  181. }
  182. // Proxy.setDefaultPort - sets default port of Proxy listener if 0
  183. func (p *ProxyServer) setDefaultPort() {
  184. if p.Config.Port == 0 {
  185. p.Config.Port = defaultPort
  186. }
  187. }
  188. // Proxy.setDefaultBodySize - sets default body size of Proxy listener if 0
  189. func (p *ProxyServer) setDefaultBodySize() {
  190. if p.Config.BodySize == 0 {
  191. p.Config.BodySize = defaultBodySize
  192. }
  193. }