udp_generic.go 2.1 KB

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