3
0

udp_generic.go 2.3 KB

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