peer.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package peer
  2. import (
  3. "crypto/md5"
  4. "errors"
  5. "fmt"
  6. "log"
  7. "net"
  8. "sync"
  9. "time"
  10. "github.com/gravitl/netmaker/nm-proxy/common"
  11. "github.com/gravitl/netmaker/nm-proxy/models"
  12. "github.com/gravitl/netmaker/nm-proxy/proxy"
  13. "github.com/gravitl/netmaker/nm-proxy/wg"
  14. "golang.zx2c4.com/wireguard/wgctrl/wgtypes"
  15. )
  16. func AddNewPeer(wgInterface *wg.WGIface, peer *wgtypes.PeerConfig, peerAddr string,
  17. isRelayed, isExtClient, isAttachedExtClient bool, relayTo *net.UDPAddr) error {
  18. if peer.PersistentKeepaliveInterval == nil {
  19. d := time.Second * 25
  20. peer.PersistentKeepaliveInterval = &d
  21. }
  22. c := models.ProxyConfig{
  23. LocalKey: wgInterface.Device.PublicKey,
  24. RemoteKey: peer.PublicKey,
  25. WgInterface: wgInterface,
  26. IsExtClient: isExtClient,
  27. PeerConf: peer,
  28. PersistentKeepalive: peer.PersistentKeepaliveInterval,
  29. RecieverChan: make(chan []byte, 1000),
  30. }
  31. p := proxy.NewProxy(c)
  32. peerPort := models.NmProxyPort
  33. if isExtClient && isAttachedExtClient {
  34. peerPort = peer.Endpoint.Port
  35. }
  36. peerEndpointIP := peer.Endpoint.IP
  37. if isRelayed {
  38. //go server.NmProxyServer.KeepAlive(peer.Endpoint.IP.String(), common.NmProxyPort)
  39. if relayTo == nil {
  40. return errors.New("relay endpoint is nil")
  41. }
  42. peerEndpointIP = relayTo.IP
  43. }
  44. peerEndpoint, err := net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", peerEndpointIP, peerPort))
  45. if err != nil {
  46. return err
  47. }
  48. p.Config.PeerEndpoint = peerEndpoint
  49. log.Printf("Starting proxy for Peer: %s\n", peer.PublicKey.String())
  50. err = p.Start()
  51. if err != nil {
  52. return err
  53. }
  54. connConf := models.Conn{
  55. Mutex: &sync.RWMutex{},
  56. Key: peer.PublicKey,
  57. IsRelayed: isRelayed,
  58. RelayedEndpoint: relayTo,
  59. IsAttachedExtClient: isAttachedExtClient,
  60. Config: p.Config,
  61. StopConn: p.Close,
  62. ResetConn: p.Reset,
  63. LocalConn: p.LocalConn,
  64. }
  65. common.WgIfaceMap.PeerMap[peer.PublicKey.String()] = &connConf
  66. common.PeerKeyHashMap[fmt.Sprintf("%x", md5.Sum([]byte(peer.PublicKey.String())))] = models.RemotePeer{
  67. Interface: wgInterface.Name,
  68. PeerKey: peer.PublicKey.String(),
  69. IsExtClient: isExtClient,
  70. Endpoint: peerEndpoint,
  71. IsAttachedExtClient: isAttachedExtClient,
  72. LocalConn: p.LocalConn,
  73. }
  74. return nil
  75. }