turnserver.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package turnserver
  2. import (
  3. "context"
  4. "log"
  5. "net"
  6. "strconv"
  7. "sync"
  8. "time"
  9. "github.com/gravitl/netmaker/logger"
  10. "github.com/gravitl/netmaker/servercfg"
  11. "github.com/pion/turn/v2"
  12. )
  13. var (
  14. UsersMap = make(map[string][]byte)
  15. )
  16. func RegisterNewHostWithTurn(hostID, hostPass string) {
  17. UsersMap[hostID] = turn.GenerateAuthKey(hostID, servercfg.GetTurnHost(), hostPass)
  18. }
  19. func Start(wg *sync.WaitGroup, ctx context.Context) {
  20. defer wg.Done()
  21. // Create a UDP listener to pass into pion/turn
  22. // pion/turn itself doesn't allocate any UDP sockets, but lets the user pass them in
  23. // this allows us to add logging, storage or modify inbound/outbound traffic
  24. udpListener, err := net.ListenPacket("udp4", "0.0.0.0:"+strconv.Itoa(servercfg.GetTurnPort()))
  25. if err != nil {
  26. log.Panicf("Failed to create TURN server listener: %s", err)
  27. }
  28. s, err := turn.NewServer(turn.ServerConfig{
  29. Realm: servercfg.GetTurnHost(),
  30. // Set AuthHandler callback
  31. // This is called every time a user tries to authenticate with the TURN server
  32. // Return the key for that user, or false when no user is found
  33. AuthHandler: func(username string, realm string, srcAddr net.Addr) ([]byte, bool) {
  34. if key, ok := UsersMap[username]; ok {
  35. return key, true
  36. }
  37. return nil, false
  38. },
  39. // PacketConnConfigs is a list of UDP Listeners and the configuration around them
  40. PacketConnConfigs: []turn.PacketConnConfig{
  41. {
  42. PacketConn: udpListener,
  43. RelayAddressGenerator: &turn.RelayAddressGeneratorStatic{
  44. RelayAddress: net.ParseIP("64.227.178.89"), // Claim that we are listening on IP passed by user (This should be your Public IP)
  45. Address: "0.0.0.0", // But actually be listening on every interface
  46. },
  47. },
  48. },
  49. })
  50. if err != nil {
  51. log.Panic(err)
  52. }
  53. go func() {
  54. for {
  55. time.Sleep(time.Second * 10)
  56. log.Print(s.AllocationCount())
  57. }
  58. }()
  59. // Block until user sends SIGINT or SIGTERM
  60. <-ctx.Done()
  61. logger.Log(0, "## Stopping Turn Server...")
  62. if err = s.Close(); err != nil {
  63. log.Panic(err)
  64. }
  65. }