proxy.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. package proxy
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "net"
  7. "github.com/gravitl/netmaker/nm-proxy/common"
  8. "github.com/gravitl/netmaker/nm-proxy/wg"
  9. "golang.zx2c4.com/wireguard/wgctrl/wgtypes"
  10. )
  11. const (
  12. defaultBodySize = 10000
  13. defaultPort = 51722
  14. )
  15. type Config struct {
  16. Port int
  17. BodySize int
  18. Addr string
  19. RemoteKey string
  20. LocalKey string
  21. WgInterface *wg.WGIface
  22. AllowedIps []net.IPNet
  23. PreSharedKey *wgtypes.Key
  24. }
  25. // Proxy - WireguardProxy proxies
  26. type Proxy struct {
  27. Ctx context.Context
  28. Cancel context.CancelFunc
  29. Config Config
  30. RemoteConn *net.UDPAddr
  31. LocalConn net.Conn
  32. }
  33. func GetInterfaceIpv4Addr(interfaceName string) (addr string, err error) {
  34. var (
  35. ief *net.Interface
  36. addrs []net.Addr
  37. ipv4Addr net.IP
  38. )
  39. if ief, err = net.InterfaceByName(interfaceName); err != nil { // get interface
  40. return
  41. }
  42. if addrs, err = ief.Addrs(); err != nil { // get addresses
  43. return
  44. }
  45. for _, addr := range addrs { // get ipv4 address
  46. if ipv4Addr = addr.(*net.IPNet).IP.To4(); ipv4Addr != nil {
  47. break
  48. }
  49. }
  50. if ipv4Addr == nil {
  51. return "", errors.New(fmt.Sprintf("interface %s don't have an ipv4 address\n", interfaceName))
  52. }
  53. return ipv4Addr.String(), nil
  54. }
  55. func GetInterfaceListenAddr(port int) (*net.UDPAddr, error) {
  56. locallistenAddr := "127.0.0.1"
  57. udpAddr, err := net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", locallistenAddr, port))
  58. if err != nil {
  59. return udpAddr, err
  60. }
  61. if !common.IsHostNetwork {
  62. addrs, err := getBoardCastAddress()
  63. if err != nil {
  64. return udpAddr, err
  65. }
  66. for _, addr := range addrs {
  67. if liAddr := addr.(*net.IPNet).IP; liAddr != nil {
  68. udpAddr.IP = liAddr
  69. break
  70. }
  71. }
  72. }
  73. return udpAddr, nil
  74. }
  75. func getBoardCastAddress() ([]net.Addr, error) {
  76. localnets, err := net.Interfaces()
  77. if err != nil {
  78. return nil, err
  79. }
  80. var (
  81. ief net.Interface
  82. addrs []net.Addr
  83. )
  84. for _, ief = range localnets {
  85. if ief.Flags&net.FlagBroadcast != 0 && ief.Flags&net.FlagUp != 0 {
  86. addrs, err = ief.Addrs()
  87. if err == nil {
  88. return addrs, nil
  89. }
  90. }
  91. }
  92. return nil, errors.New("couldn't obtain the broadcast addr")
  93. }