routes.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package local
  2. import (
  3. "net"
  4. "github.com/gravitl/netmaker/netclient/ncutils"
  5. "golang.zx2c4.com/wireguard/wgctrl/wgtypes"
  6. )
  7. // SetPeerRoutes - sets/removes ip routes for each peer on a network
  8. func SetPeerRoutes(iface, currentNodeAddr string, oldPeers map[string][]net.IPNet, newPeers []wgtypes.PeerConfig) {
  9. // traverse through all recieved peers
  10. for _, peer := range newPeers {
  11. // if pubkey found in existing peers, check against existing peer
  12. currPeerAllowedIPs := oldPeers[peer.PublicKey.String()]
  13. if currPeerAllowedIPs != nil {
  14. // traverse IPs, check to see if old peer contains each IP
  15. for _, allowedIP := range peer.AllowedIPs { // compare new ones (if any) to old ones
  16. if !ncutils.IPNetSliceContains(currPeerAllowedIPs, allowedIP) {
  17. if err := setRoute(iface, &allowedIP, allowedIP.IP.String()); err != nil {
  18. ncutils.PrintLog(err.Error(), 1)
  19. }
  20. }
  21. }
  22. for _, allowedIP := range currPeerAllowedIPs { // compare old ones (if any) to new ones
  23. if !ncutils.IPNetSliceContains(peer.AllowedIPs, allowedIP) {
  24. if err := deleteRoute(iface, &allowedIP, allowedIP.IP.String()); err != nil {
  25. ncutils.PrintLog(err.Error(), 1)
  26. }
  27. }
  28. }
  29. delete(oldPeers, peer.PublicKey.String()) // remove peer as it was found and processed
  30. } else {
  31. for _, allowedIP := range peer.AllowedIPs { // add all routes as peer doesn't exist
  32. if err := setRoute(iface, &allowedIP, allowedIP.String()); err != nil {
  33. ncutils.PrintLog(err.Error(), 1)
  34. }
  35. }
  36. }
  37. }
  38. // traverse through all remaining existing peers
  39. for _, allowedIPs := range oldPeers {
  40. for _, allowedIP := range allowedIPs {
  41. deleteRoute(iface, &allowedIP, allowedIP.IP.String())
  42. }
  43. }
  44. }
  45. // SetCurrentPeerRoutes - sets all the current peers
  46. func SetCurrentPeerRoutes(iface, currentAddr string, peers []wgtypes.Peer) {
  47. for _, peer := range peers {
  48. for _, allowedIP := range peer.AllowedIPs {
  49. setRoute(iface, &allowedIP, currentAddr)
  50. }
  51. }
  52. }