udp_generic.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. )
  16. type GenericConn struct {
  17. *net.UDPConn
  18. l *logrus.Logger
  19. }
  20. var _ Conn = &GenericConn{}
  21. func NewGenericListener(l *logrus.Logger, ip netip.Addr, port int, multi bool, batch int) (Conn, error) {
  22. lc := NewListenConfig(multi)
  23. pc, err := lc.ListenPacket(context.TODO(), "udp", net.JoinHostPort(ip.String(), fmt.Sprintf("%v", port)))
  24. if err != nil {
  25. return nil, err
  26. }
  27. if uc, ok := pc.(*net.UDPConn); ok {
  28. return &GenericConn{UDPConn: uc, l: l}, nil
  29. }
  30. return nil, fmt.Errorf("Unexpected PacketConn: %T %#v", pc, pc)
  31. }
  32. func (u *GenericConn) WriteTo(b []byte, addr netip.AddrPort) error {
  33. _, err := u.UDPConn.WriteToUDPAddrPort(b, addr)
  34. return err
  35. }
  36. func (u *GenericConn) WriteBatch(pkts []BatchPacket) (int, error) {
  37. sent := 0
  38. for _, pkt := range pkts {
  39. if err := u.WriteTo(pkt.Payload, pkt.Addr); err != nil {
  40. return sent, err
  41. }
  42. sent++
  43. }
  44. return sent, nil
  45. }
  46. func (u *GenericConn) LocalAddr() (netip.AddrPort, error) {
  47. a := u.UDPConn.LocalAddr()
  48. switch v := a.(type) {
  49. case *net.UDPAddr:
  50. addr, ok := netip.AddrFromSlice(v.IP)
  51. if !ok {
  52. return netip.AddrPort{}, fmt.Errorf("LocalAddr returned invalid IP address: %s", v.IP)
  53. }
  54. return netip.AddrPortFrom(addr, uint16(v.Port)), nil
  55. default:
  56. return netip.AddrPort{}, fmt.Errorf("LocalAddr returned: %#v", a)
  57. }
  58. }
  59. func (u *GenericConn) ReloadConfig(c *config.C) {
  60. }
  61. func NewUDPStatsEmitter(udpConns []Conn) func() {
  62. // No UDP stats for non-linux
  63. return func() {}
  64. }
  65. type rawMessage struct {
  66. Len uint32
  67. }
  68. func (u *GenericConn) ListenOut(r EncReader) error {
  69. buffer := make([]byte, MTU)
  70. for {
  71. // Just read one packet at a time
  72. n, rua, err := u.ReadFromUDPAddrPort(buffer)
  73. if err != nil {
  74. return err
  75. }
  76. r(netip.AddrPortFrom(rua.Addr().Unmap(), rua.Port()), buffer[:n])
  77. }
  78. }