udp_generic.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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 udp
  7. import (
  8. "context"
  9. "fmt"
  10. "net"
  11. "net/netip"
  12. "github.com/sirupsen/logrus"
  13. "github.com/slackhq/nebula/config"
  14. "github.com/slackhq/nebula/firewall"
  15. "github.com/slackhq/nebula/header"
  16. )
  17. type GenericConn struct {
  18. *net.UDPConn
  19. l *logrus.Logger
  20. }
  21. var _ Conn = &GenericConn{}
  22. func NewGenericListener(l *logrus.Logger, ip netip.Addr, port int, multi bool, batch int) (Conn, error) {
  23. lc := NewListenConfig(multi)
  24. pc, err := lc.ListenPacket(context.TODO(), "udp", net.JoinHostPort(ip.String(), fmt.Sprintf("%v", port)))
  25. if err != nil {
  26. return nil, err
  27. }
  28. if uc, ok := pc.(*net.UDPConn); ok {
  29. return &GenericConn{UDPConn: uc, l: l}, nil
  30. }
  31. return nil, fmt.Errorf("Unexpected PacketConn: %T %#v", pc, pc)
  32. }
  33. func (u *GenericConn) WriteTo(b []byte, addr netip.AddrPort) error {
  34. _, err := u.UDPConn.WriteToUDPAddrPort(b, addr)
  35. return err
  36. }
  37. func (u *GenericConn) LocalAddr() (netip.AddrPort, error) {
  38. a := u.UDPConn.LocalAddr()
  39. switch v := a.(type) {
  40. case *net.UDPAddr:
  41. addr, ok := netip.AddrFromSlice(v.IP)
  42. if !ok {
  43. return netip.AddrPort{}, fmt.Errorf("LocalAddr returned invalid IP address: %s", v.IP)
  44. }
  45. return netip.AddrPortFrom(addr, uint16(v.Port)), nil
  46. default:
  47. return netip.AddrPort{}, fmt.Errorf("LocalAddr returned: %#v", a)
  48. }
  49. }
  50. func (u *GenericConn) ReloadConfig(c *config.C) {
  51. // TODO
  52. }
  53. func NewUDPStatsEmitter(udpConns []Conn) func() {
  54. // No UDP stats for non-linux
  55. return func() {}
  56. }
  57. type rawMessage struct {
  58. Len uint32
  59. }
  60. func (u *GenericConn) ListenOut(r EncReader, lhf LightHouseHandlerFunc, cache *firewall.ConntrackCacheTicker, q int) {
  61. plaintext := make([]byte, MTU)
  62. buffer := make([]byte, MTU)
  63. h := &header.H{}
  64. fwPacket := &firewall.Packet{}
  65. nb := make([]byte, 12, 12)
  66. for {
  67. // Just read one packet at a time
  68. n, rua, err := u.ReadFromUDPAddrPort(buffer)
  69. if err != nil {
  70. u.l.WithError(err).Debug("udp socket is closed, exiting read loop")
  71. return
  72. }
  73. r(
  74. netip.AddrPortFrom(rua.Addr().Unmap(), rua.Port()),
  75. plaintext[:0],
  76. buffer[:n],
  77. h,
  78. fwPacket,
  79. lhf,
  80. nb,
  81. q,
  82. cache.Get(u.l),
  83. )
  84. }
  85. }