tun.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package overlay
  2. import (
  3. "net"
  4. "net/netip"
  5. "github.com/sirupsen/logrus"
  6. "github.com/slackhq/nebula/config"
  7. "github.com/slackhq/nebula/util"
  8. )
  9. const DefaultMTU = 1300
  10. // TODO: We may be able to remove routines
  11. type DeviceFactory func(c *config.C, l *logrus.Logger, vpnNetworks []netip.Prefix, routines int) (Device, error)
  12. func NewDeviceFromConfig(c *config.C, l *logrus.Logger, vpnNetworks []netip.Prefix, routines int) (Device, error) {
  13. switch {
  14. case c.GetBool("tun.disabled", false):
  15. tun := newDisabledTun(vpnNetworks, c.GetInt("tun.tx_queue", 500), c.GetBool("stats.message_metrics", false), l)
  16. return tun, nil
  17. default:
  18. return newTun(c, l, vpnNetworks, routines > 1)
  19. }
  20. }
  21. func NewFdDeviceFromConfig(fd *int) DeviceFactory {
  22. return func(c *config.C, l *logrus.Logger, vpnNetworks []netip.Prefix, routines int) (Device, error) {
  23. return newTunFromFd(c, l, *fd, vpnNetworks)
  24. }
  25. }
  26. func getAllRoutesFromConfig(c *config.C, vpnNetworks []netip.Prefix, initial bool) (bool, []Route, error) {
  27. if !initial && !c.HasChanged("tun.routes") && !c.HasChanged("tun.unsafe_routes") {
  28. return false, nil, nil
  29. }
  30. routes, err := parseRoutes(c, vpnNetworks)
  31. if err != nil {
  32. return true, nil, util.NewContextualError("Could not parse tun.routes", nil, err)
  33. }
  34. unsafeRoutes, err := parseUnsafeRoutes(c, vpnNetworks)
  35. if err != nil {
  36. return true, nil, util.NewContextualError("Could not parse tun.unsafe_routes", nil, err)
  37. }
  38. routes = append(routes, unsafeRoutes...)
  39. return true, routes, nil
  40. }
  41. // findRemovedRoutes will return all routes that are not present in the newRoutes list and would affect the system route table.
  42. // Via is not used to evaluate since it does not affect the system route table.
  43. func findRemovedRoutes(newRoutes, oldRoutes []Route) []Route {
  44. var removed []Route
  45. has := func(entry Route) bool {
  46. for _, check := range newRoutes {
  47. if check.Equal(entry) {
  48. return true
  49. }
  50. }
  51. return false
  52. }
  53. for _, oldEntry := range oldRoutes {
  54. if !has(oldEntry) {
  55. removed = append(removed, oldEntry)
  56. }
  57. }
  58. return removed
  59. }
  60. func prefixToMask(prefix netip.Prefix) netip.Addr {
  61. pLen := 128
  62. if prefix.Addr().Is4() {
  63. pLen = 32
  64. }
  65. addr, _ := netip.AddrFromSlice(net.CIDRMask(prefix.Bits(), pLen))
  66. return addr
  67. }