udp_generic.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. //go:build (!linux || android) && !e2e_testing
  2. // +build !linux android
  3. // +build !e2e_testing
  4. // udp_generic implements the nebula UDP interface in pure Go stdlib. This
  5. // means it can be used on platforms like Darwin and Windows.
  6. package nebula
  7. import (
  8. "context"
  9. "fmt"
  10. "net"
  11. "github.com/sirupsen/logrus"
  12. )
  13. type udpConn struct {
  14. *net.UDPConn
  15. l *logrus.Logger
  16. }
  17. func NewListener(l *logrus.Logger, ip string, port int, multi bool) (*udpConn, error) {
  18. lc := NewListenConfig(multi)
  19. pc, err := lc.ListenPacket(context.TODO(), "udp", fmt.Sprintf("%s:%d", ip, port))
  20. if err != nil {
  21. return nil, err
  22. }
  23. if uc, ok := pc.(*net.UDPConn); ok {
  24. return &udpConn{UDPConn: uc, l: l}, nil
  25. }
  26. return nil, fmt.Errorf("Unexpected PacketConn: %T %#v", pc, pc)
  27. }
  28. func (uc *udpConn) WriteTo(b []byte, addr *udpAddr) error {
  29. _, err := uc.UDPConn.WriteToUDP(b, &net.UDPAddr{IP: addr.IP, Port: int(addr.Port)})
  30. return err
  31. }
  32. func (uc *udpConn) LocalAddr() (*udpAddr, error) {
  33. a := uc.UDPConn.LocalAddr()
  34. switch v := a.(type) {
  35. case *net.UDPAddr:
  36. addr := &udpAddr{IP: make([]byte, len(v.IP))}
  37. copy(addr.IP, v.IP)
  38. addr.Port = uint16(v.Port)
  39. return addr, nil
  40. default:
  41. return nil, fmt.Errorf("LocalAddr returned: %#v", a)
  42. }
  43. }
  44. func (u *udpConn) reloadConfig(c *Config) {
  45. // TODO
  46. }
  47. func NewUDPStatsEmitter(udpConns []*udpConn) func() {
  48. // No UDP stats for non-linux
  49. return func() {}
  50. }
  51. type rawMessage struct {
  52. Len uint32
  53. }
  54. func (u *udpConn) ListenOut(f *Interface, q int) {
  55. plaintext := make([]byte, mtu)
  56. buffer := make([]byte, mtu)
  57. header := &Header{}
  58. fwPacket := &FirewallPacket{}
  59. udpAddr := &udpAddr{IP: make([]byte, 16)}
  60. nb := make([]byte, 12, 12)
  61. lhh := f.lightHouse.NewRequestHandler()
  62. conntrackCache := NewConntrackCacheTicker(f.conntrackCacheTimeout)
  63. for {
  64. // Just read one packet at a time
  65. n, rua, err := u.ReadFromUDP(buffer)
  66. if err != nil {
  67. f.l.WithError(err).Error("Failed to read packets")
  68. continue
  69. }
  70. udpAddr.IP = rua.IP
  71. udpAddr.Port = uint16(rua.Port)
  72. f.readOutsidePackets(udpAddr, plaintext[:0], buffer[:n], header, fwPacket, lhh, nb, q, conntrackCache.Get(f.l))
  73. }
  74. }
  75. func hostDidRoam(addr *udpAddr, newaddr *udpAddr) bool {
  76. return !addr.Equals(newaddr)
  77. }