2
0

udp_raw_linux.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. //go:build !android && !e2e_testing
  2. // +build !android,!e2e_testing
  3. package udp
  4. import (
  5. "encoding/binary"
  6. "fmt"
  7. "net"
  8. "net/netip"
  9. "syscall"
  10. "unsafe"
  11. "github.com/rcrowley/go-metrics"
  12. "github.com/sirupsen/logrus"
  13. "github.com/slackhq/nebula/config"
  14. "golang.org/x/net/ipv4"
  15. "golang.org/x/sys/unix"
  16. )
  17. // RawOverhead is the number of bytes that need to be reserved at the start of
  18. // the raw bytes passed to (*RawConn).WriteTo. This is used by WriteTo to prefix
  19. // the IP and UDP headers.
  20. const RawOverhead = 28
  21. type RawConn struct {
  22. sysFd int
  23. basePort uint16
  24. l *logrus.Logger
  25. }
  26. func NewRawConn(l *logrus.Logger, ip string, port int, basePort uint16) (*RawConn, error) {
  27. syscall.ForkLock.RLock()
  28. // With IPPROTO_UDP, the linux kernel tries to deliver every UDP packet
  29. // received in the system to our socket. This constantly overflows our
  30. // buffer and marks our socket as having dropped packets. This makes the
  31. // stats on the socket useless.
  32. //
  33. // In contrast, IPPROTO_RAW is not delivered any packets and thus our read
  34. // buffer will not fill up and mark as having dropped packets. The only
  35. // difference is that we have to assemble the IP header as well, but this
  36. // is fairly easy since Linux does the checksum for us.
  37. //
  38. // TODO: How to get this working with Inet6 correctly? I was having issues
  39. // with the source address when testing before, probably need to `bind(2)`?
  40. fd, err := unix.Socket(unix.AF_INET, unix.SOCK_RAW, unix.IPPROTO_RAW)
  41. if err == nil {
  42. unix.CloseOnExec(fd)
  43. }
  44. syscall.ForkLock.RUnlock()
  45. if err != nil {
  46. return nil, err
  47. }
  48. // We only want to send, not recv. This will hopefully help the kernel avoid
  49. // wasting time on us
  50. if err = unix.SetsockoptInt(fd, unix.SOL_SOCKET, unix.SO_RCVBUF, 0); err != nil {
  51. return nil, fmt.Errorf("unable to set SO_RCVBUF: %s", err)
  52. }
  53. var lip [16]byte
  54. copy(lip[:], net.ParseIP(ip))
  55. // TODO do we need to `bind(2)` so that we send from the correct address/interface?
  56. if err = unix.Bind(fd, &unix.SockaddrInet6{Addr: lip, Port: port}); err != nil {
  57. return nil, fmt.Errorf("unable to bind to socket: %s", err)
  58. }
  59. return &RawConn{
  60. sysFd: fd,
  61. basePort: basePort,
  62. l: l,
  63. }, nil
  64. }
  65. // WriteTo must be called with raw leaving the first `udp.RawOverhead` bytes empty,
  66. // for the IP/UDP headers.
  67. func (u *RawConn) WriteTo(raw []byte, fromPort uint16, ip netip.AddrPort) error {
  68. var rsa unix.RawSockaddrInet4
  69. rsa.Family = unix.AF_INET
  70. rsa.Addr = ip.Addr().As4()
  71. totalLen := len(raw)
  72. udpLen := totalLen - ipv4.HeaderLen
  73. // IP header
  74. raw[0] = byte(ipv4.Version<<4 | (ipv4.HeaderLen >> 2 & 0x0f))
  75. raw[1] = 0 // tos
  76. binary.BigEndian.PutUint16(raw[2:4], uint16(totalLen))
  77. binary.BigEndian.PutUint16(raw[4:6], 0) // id (linux does it for us)
  78. binary.BigEndian.PutUint16(raw[6:8], 0) // frag options
  79. raw[8] = byte(64) // ttl
  80. raw[9] = byte(17) // protocol
  81. binary.BigEndian.PutUint16(raw[10:12], 0) // checksum (linux does it for us)
  82. binary.BigEndian.PutUint32(raw[12:16], 0) // src (linux does it for us)
  83. copy(raw[16:20], rsa.Addr[:]) // dst
  84. // UDP header
  85. fromPort = u.basePort + fromPort
  86. binary.BigEndian.PutUint16(raw[20:22], uint16(fromPort)) // src port
  87. binary.BigEndian.PutUint16(raw[22:24], uint16(ip.Port())) // dst port
  88. binary.BigEndian.PutUint16(raw[24:26], uint16(udpLen)) // UDP length
  89. binary.BigEndian.PutUint16(raw[26:28], 0) // checksum (optional)
  90. for {
  91. _, _, err := unix.Syscall6(
  92. unix.SYS_SENDTO,
  93. uintptr(u.sysFd),
  94. uintptr(unsafe.Pointer(&raw[0])),
  95. uintptr(len(raw)),
  96. uintptr(0),
  97. uintptr(unsafe.Pointer(&rsa)),
  98. uintptr(unix.SizeofSockaddrInet4),
  99. )
  100. if err != 0 {
  101. return &net.OpError{Op: "sendto", Err: err}
  102. }
  103. //TODO: handle incomplete writes
  104. return nil
  105. }
  106. }
  107. func (u *RawConn) ReloadConfig(c *config.C) {
  108. b := c.GetInt("listen.write_buffer", 0)
  109. if b <= 0 {
  110. return
  111. }
  112. if err := u.SetSendBuffer(b); err != nil {
  113. u.l.WithError(err).Error("Failed to set listen.write_buffer")
  114. return
  115. }
  116. s, err := u.GetSendBuffer()
  117. if err != nil {
  118. u.l.WithError(err).Warn("Failed to get listen.write_buffer")
  119. return
  120. }
  121. u.l.WithField("size", s).Info("listen.write_buffer was set")
  122. }
  123. func (u *RawConn) SetSendBuffer(n int) error {
  124. return unix.SetsockoptInt(u.sysFd, unix.SOL_SOCKET, unix.SO_SNDBUFFORCE, n)
  125. }
  126. func (u *RawConn) GetSendBuffer() (int, error) {
  127. return unix.GetsockoptInt(u.sysFd, unix.SOL_SOCKET, unix.SO_SNDBUF)
  128. }
  129. func (u *RawConn) getMemInfo(meminfo *[unix.SK_MEMINFO_VARS]uint32) error {
  130. var vallen uint32 = 4 * unix.SK_MEMINFO_VARS
  131. _, _, err := unix.Syscall6(unix.SYS_GETSOCKOPT, uintptr(u.sysFd), uintptr(unix.SOL_SOCKET), uintptr(unix.SO_MEMINFO), uintptr(unsafe.Pointer(meminfo)), uintptr(unsafe.Pointer(&vallen)), 0)
  132. if err != 0 {
  133. return err
  134. }
  135. return nil
  136. }
  137. func NewRawStatsEmitter(rawConn *RawConn) func() {
  138. // Check if our kernel supports SO_MEMINFO before registering the gauges
  139. var gauges [unix.SK_MEMINFO_VARS]metrics.Gauge
  140. var meminfo [unix.SK_MEMINFO_VARS]uint32
  141. if err := rawConn.getMemInfo(&meminfo); err == nil {
  142. gauges = [unix.SK_MEMINFO_VARS]metrics.Gauge{
  143. metrics.GetOrRegisterGauge("raw.rmem_alloc", nil),
  144. metrics.GetOrRegisterGauge("raw.rcvbuf", nil),
  145. metrics.GetOrRegisterGauge("raw.wmem_alloc", nil),
  146. metrics.GetOrRegisterGauge("raw.sndbuf", nil),
  147. metrics.GetOrRegisterGauge("raw.fwd_alloc", nil),
  148. metrics.GetOrRegisterGauge("raw.wmem_queued", nil),
  149. metrics.GetOrRegisterGauge("raw.optmem", nil),
  150. metrics.GetOrRegisterGauge("raw.backlog", nil),
  151. metrics.GetOrRegisterGauge("raw.drops", nil),
  152. }
  153. } else {
  154. // return no-op because we don't support SO_MEMINFO
  155. return func() {}
  156. }
  157. return func() {
  158. if err := rawConn.getMemInfo(&meminfo); err == nil {
  159. for j := 0; j < unix.SK_MEMINFO_VARS; j++ {
  160. gauges[j].Update(int64(meminfo[j]))
  161. }
  162. }
  163. }
  164. }