peerhelper.go 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package ncutils
  2. import (
  3. "net"
  4. "strconv"
  5. "strings"
  6. "time"
  7. "github.com/gravitl/netmaker/logger"
  8. "golang.zx2c4.com/wireguard/wgctrl/wgtypes"
  9. )
  10. func GetPeers(iface string) ([]wgtypes.Peer, error) {
  11. var peers []wgtypes.Peer
  12. output, err := RunCmd("wg show "+iface+" dump", true)
  13. if err != nil {
  14. return peers, err
  15. }
  16. for i, line := range strings.Split(strings.TrimSuffix(output, "\n"), "\n") {
  17. if i == 0 {
  18. continue
  19. }
  20. var allowedIPs []net.IPNet
  21. fields := strings.Fields(line)
  22. if len(fields) < 4 {
  23. logger.Log(0, "error parsing peer: "+line)
  24. continue
  25. }
  26. pubkeystring := fields[0]
  27. endpointstring := fields[2]
  28. allowedipstring := fields[3]
  29. var pkeepalivestring string
  30. if len(fields) > 7 {
  31. pkeepalivestring = fields[7]
  32. }
  33. // AllowedIPs = private IP + defined networks
  34. pubkey, err := wgtypes.ParseKey(pubkeystring)
  35. if err != nil {
  36. logger.Log(0, "error parsing peer key "+pubkeystring)
  37. continue
  38. }
  39. ipstrings := strings.Split(allowedipstring, ",")
  40. for _, ipstring := range ipstrings {
  41. var netip net.IP
  42. if netip = net.ParseIP(strings.Split(ipstring, "/")[0]); netip != nil {
  43. allowedIPs = append(
  44. allowedIPs,
  45. net.IPNet{
  46. IP: netip,
  47. Mask: netip.DefaultMask(),
  48. },
  49. )
  50. }
  51. }
  52. if len(allowedIPs) == 0 {
  53. logger.Log(0, "error parsing peer "+pubkeystring+", no allowedips found")
  54. continue
  55. }
  56. var endpointarr []string
  57. var endpointip net.IP
  58. if endpointarr = strings.Split(endpointstring, ":"); len(endpointarr) != 2 {
  59. logger.Log(0, "error parsing peer "+pubkeystring+", could not parse endpoint: "+endpointstring)
  60. continue
  61. }
  62. if endpointip = net.ParseIP(endpointarr[0]); endpointip == nil {
  63. logger.Log(0, "error parsing peer "+pubkeystring+", could not parse endpoint: "+endpointarr[0])
  64. continue
  65. }
  66. var port int
  67. if port, err = strconv.Atoi(endpointarr[1]); err != nil {
  68. logger.Log(0, "error parsing peer "+pubkeystring+", could not parse port: "+err.Error())
  69. continue
  70. }
  71. var endpoint = net.UDPAddr{
  72. IP: endpointip,
  73. Port: port,
  74. }
  75. var dur time.Duration
  76. if pkeepalivestring != "" {
  77. if dur, err = time.ParseDuration(pkeepalivestring + "s"); err != nil {
  78. logger.Log(0, "error parsing peer "+pubkeystring+", could not parse keepalive: "+err.Error())
  79. }
  80. }
  81. peers = append(peers, wgtypes.Peer{
  82. PublicKey: pubkey,
  83. Endpoint: &endpoint,
  84. AllowedIPs: allowedIPs,
  85. PersistentKeepaliveInterval: dur,
  86. })
  87. }
  88. return peers, err
  89. }