1
0

udp_linux.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. //go:build !android && !e2e_testing
  2. // +build !android,!e2e_testing
  3. package udp
  4. import (
  5. "encoding/binary"
  6. "errors"
  7. "fmt"
  8. "net"
  9. "net/netip"
  10. "syscall"
  11. "unsafe"
  12. "github.com/rcrowley/go-metrics"
  13. "github.com/sirupsen/logrus"
  14. "github.com/slackhq/nebula/config"
  15. "golang.org/x/sys/unix"
  16. )
  17. type StdConn struct {
  18. sysFd int
  19. isV4 bool
  20. l *logrus.Logger
  21. batch int
  22. gsoSupported bool
  23. }
  24. func maybeIPV4(ip net.IP) (net.IP, bool) {
  25. ip4 := ip.To4()
  26. if ip4 != nil {
  27. return ip4, true
  28. }
  29. return ip, false
  30. }
  31. // supportsUDPOffload checks if the kernel supports UDP GSO (Generic Segmentation Offload)
  32. // by attempting to get the UDP_SEGMENT socket option.
  33. func supportsUDPOffload(fd int) bool {
  34. _, err := unix.GetsockoptInt(fd, unix.IPPROTO_UDP, unix.UDP_SEGMENT)
  35. return err == nil
  36. }
  37. const (
  38. // Maximum number of datagrams that can be coalesced with GSO
  39. udpSegmentMaxDatagrams = 64
  40. )
  41. // setGSOSize writes a UDP_SEGMENT control message to the provided buffer
  42. // with the given segment size. Returns the actual control message length.
  43. func setGSOSize(control []byte, gsoSize uint16) int {
  44. // Build the cmsghdr structure
  45. cmsgLen := unix.CmsgLen(2) // 2 bytes for uint16 segment size
  46. cmsg := (*unix.Cmsghdr)(unsafe.Pointer(&control[0]))
  47. cmsg.Level = unix.IPPROTO_UDP
  48. cmsg.Type = unix.UDP_SEGMENT
  49. cmsg.SetLen(cmsgLen)
  50. // Write the segment size after the header (after cmsghdr)
  51. binary.NativeEndian.PutUint16(control[unix.SizeofCmsghdr:], gsoSize)
  52. return unix.CmsgSpace(2) // aligned size
  53. }
  54. func NewListener(l *logrus.Logger, ip netip.Addr, port int, multi bool, batch int) (Conn, error) {
  55. af := unix.AF_INET6
  56. if ip.Is4() {
  57. af = unix.AF_INET
  58. }
  59. syscall.ForkLock.RLock()
  60. fd, err := unix.Socket(af, unix.SOCK_DGRAM, unix.IPPROTO_UDP)
  61. if err == nil {
  62. unix.CloseOnExec(fd)
  63. }
  64. syscall.ForkLock.RUnlock()
  65. if err != nil {
  66. unix.Close(fd)
  67. return nil, fmt.Errorf("unable to open socket: %s", err)
  68. }
  69. if multi {
  70. if err = unix.SetsockoptInt(fd, unix.SOL_SOCKET, unix.SO_REUSEPORT, 1); err != nil {
  71. return nil, fmt.Errorf("unable to set SO_REUSEPORT: %s", err)
  72. }
  73. }
  74. var sa unix.Sockaddr
  75. if ip.Is4() {
  76. sa4 := &unix.SockaddrInet4{Port: port}
  77. sa4.Addr = ip.As4()
  78. sa = sa4
  79. } else {
  80. sa6 := &unix.SockaddrInet6{Port: port}
  81. sa6.Addr = ip.As16()
  82. sa = sa6
  83. }
  84. if err = unix.Bind(fd, sa); err != nil {
  85. return nil, fmt.Errorf("unable to bind to socket: %s", err)
  86. }
  87. gsoSupported := supportsUDPOffload(fd)
  88. if gsoSupported {
  89. l.Info("UDP GSO offload is supported")
  90. }
  91. return &StdConn{sysFd: fd, isV4: ip.Is4(), l: l, batch: batch, gsoSupported: gsoSupported}, err
  92. }
  93. func (u *StdConn) SupportsMultipleReaders() bool {
  94. return true
  95. }
  96. func (u *StdConn) SupportsGSO() bool {
  97. return u.gsoSupported
  98. }
  99. func (u *StdConn) Rebind() error {
  100. return nil
  101. }
  102. func (u *StdConn) SetRecvBuffer(n int) error {
  103. return unix.SetsockoptInt(u.sysFd, unix.SOL_SOCKET, unix.SO_RCVBUFFORCE, n)
  104. }
  105. func (u *StdConn) SetSendBuffer(n int) error {
  106. return unix.SetsockoptInt(u.sysFd, unix.SOL_SOCKET, unix.SO_SNDBUFFORCE, n)
  107. }
  108. func (u *StdConn) SetSoMark(mark int) error {
  109. return unix.SetsockoptInt(u.sysFd, unix.SOL_SOCKET, unix.SO_MARK, mark)
  110. }
  111. func (u *StdConn) GetRecvBuffer() (int, error) {
  112. return unix.GetsockoptInt(int(u.sysFd), unix.SOL_SOCKET, unix.SO_RCVBUF)
  113. }
  114. func (u *StdConn) GetSendBuffer() (int, error) {
  115. return unix.GetsockoptInt(int(u.sysFd), unix.SOL_SOCKET, unix.SO_SNDBUF)
  116. }
  117. func (u *StdConn) GetSoMark() (int, error) {
  118. return unix.GetsockoptInt(int(u.sysFd), unix.SOL_SOCKET, unix.SO_MARK)
  119. }
  120. func (u *StdConn) LocalAddr() (netip.AddrPort, error) {
  121. sa, err := unix.Getsockname(u.sysFd)
  122. if err != nil {
  123. return netip.AddrPort{}, err
  124. }
  125. switch sa := sa.(type) {
  126. case *unix.SockaddrInet4:
  127. return netip.AddrPortFrom(netip.AddrFrom4(sa.Addr), uint16(sa.Port)), nil
  128. case *unix.SockaddrInet6:
  129. return netip.AddrPortFrom(netip.AddrFrom16(sa.Addr), uint16(sa.Port)), nil
  130. default:
  131. return netip.AddrPort{}, fmt.Errorf("unsupported sock type: %T", sa)
  132. }
  133. }
  134. func (u *StdConn) ListenOut(r EncReader) {
  135. var ip netip.Addr
  136. msgs, buffers, names := u.PrepareRawMessages(u.batch)
  137. read := u.ReadMulti
  138. if u.batch == 1 {
  139. read = u.ReadSingle
  140. }
  141. for {
  142. n, err := read(msgs)
  143. if err != nil {
  144. u.l.WithError(err).Debug("udp socket is closed, exiting read loop")
  145. return
  146. }
  147. for i := 0; i < n; i++ {
  148. // Its ok to skip the ok check here, the slicing is the only error that can occur and it will panic
  149. if u.isV4 {
  150. ip, _ = netip.AddrFromSlice(names[i][4:8])
  151. } else {
  152. ip, _ = netip.AddrFromSlice(names[i][8:24])
  153. }
  154. r(netip.AddrPortFrom(ip.Unmap(), binary.BigEndian.Uint16(names[i][2:4])), buffers[i][:msgs[i].Len])
  155. }
  156. }
  157. }
  158. func (u *StdConn) ReadSingle(msgs []rawMessage) (int, error) {
  159. for {
  160. n, _, err := unix.Syscall6(
  161. unix.SYS_RECVMSG,
  162. uintptr(u.sysFd),
  163. uintptr(unsafe.Pointer(&(msgs[0].Hdr))),
  164. 0,
  165. 0,
  166. 0,
  167. 0,
  168. )
  169. if err != 0 {
  170. return 0, &net.OpError{Op: "recvmsg", Err: err}
  171. }
  172. msgs[0].Len = uint32(n)
  173. return 1, nil
  174. }
  175. }
  176. func (u *StdConn) ReadMulti(msgs []rawMessage) (int, error) {
  177. for {
  178. n, _, err := unix.Syscall6(
  179. unix.SYS_RECVMMSG,
  180. uintptr(u.sysFd),
  181. uintptr(unsafe.Pointer(&msgs[0])),
  182. uintptr(len(msgs)),
  183. unix.MSG_WAITFORONE,
  184. 0,
  185. 0,
  186. )
  187. if err != 0 {
  188. return 0, &net.OpError{Op: "recvmmsg", Err: err}
  189. }
  190. return int(n), nil
  191. }
  192. }
  193. func (u *StdConn) WriteTo(b []byte, ip netip.AddrPort) error {
  194. if u.isV4 {
  195. return u.writeTo4(b, ip)
  196. }
  197. return u.writeTo6(b, ip)
  198. }
  199. func (u *StdConn) writeTo6(b []byte, ip netip.AddrPort) error {
  200. var rsa unix.RawSockaddrInet6
  201. rsa.Family = unix.AF_INET6
  202. rsa.Addr = ip.Addr().As16()
  203. binary.BigEndian.PutUint16((*[2]byte)(unsafe.Pointer(&rsa.Port))[:], ip.Port())
  204. for {
  205. _, _, err := unix.Syscall6(
  206. unix.SYS_SENDTO,
  207. uintptr(u.sysFd),
  208. uintptr(unsafe.Pointer(&b[0])),
  209. uintptr(len(b)),
  210. uintptr(0),
  211. uintptr(unsafe.Pointer(&rsa)),
  212. uintptr(unix.SizeofSockaddrInet6),
  213. )
  214. if err != 0 {
  215. return &net.OpError{Op: "sendto", Err: err}
  216. }
  217. return nil
  218. }
  219. }
  220. func (u *StdConn) writeTo4(b []byte, ip netip.AddrPort) error {
  221. if !ip.Addr().Is4() {
  222. return ErrInvalidIPv6RemoteForSocket
  223. }
  224. var rsa unix.RawSockaddrInet4
  225. rsa.Family = unix.AF_INET
  226. rsa.Addr = ip.Addr().As4()
  227. binary.BigEndian.PutUint16((*[2]byte)(unsafe.Pointer(&rsa.Port))[:], ip.Port())
  228. for {
  229. _, _, err := unix.Syscall6(
  230. unix.SYS_SENDTO,
  231. uintptr(u.sysFd),
  232. uintptr(unsafe.Pointer(&b[0])),
  233. uintptr(len(b)),
  234. uintptr(0),
  235. uintptr(unsafe.Pointer(&rsa)),
  236. uintptr(unix.SizeofSockaddrInet4),
  237. )
  238. if err != 0 {
  239. return &net.OpError{Op: "sendto", Err: err}
  240. }
  241. return nil
  242. }
  243. }
  244. func (u *StdConn) ReloadConfig(c *config.C) {
  245. b := c.GetInt("listen.read_buffer", 0)
  246. if b > 0 {
  247. err := u.SetRecvBuffer(b)
  248. if err == nil {
  249. s, err := u.GetRecvBuffer()
  250. if err == nil {
  251. u.l.WithField("size", s).Info("listen.read_buffer was set")
  252. } else {
  253. u.l.WithError(err).Warn("Failed to get listen.read_buffer")
  254. }
  255. } else {
  256. u.l.WithError(err).Error("Failed to set listen.read_buffer")
  257. }
  258. }
  259. b = c.GetInt("listen.write_buffer", 0)
  260. if b > 0 {
  261. err := u.SetSendBuffer(b)
  262. if err == nil {
  263. s, err := u.GetSendBuffer()
  264. if err == nil {
  265. u.l.WithField("size", s).Info("listen.write_buffer was set")
  266. } else {
  267. u.l.WithError(err).Warn("Failed to get listen.write_buffer")
  268. }
  269. } else {
  270. u.l.WithError(err).Error("Failed to set listen.write_buffer")
  271. }
  272. }
  273. b = c.GetInt("listen.so_mark", 0)
  274. s, err := u.GetSoMark()
  275. if b > 0 || (err == nil && s != 0) {
  276. err := u.SetSoMark(b)
  277. if err == nil {
  278. s, err := u.GetSoMark()
  279. if err == nil {
  280. u.l.WithField("mark", s).Info("listen.so_mark was set")
  281. } else {
  282. u.l.WithError(err).Warn("Failed to get listen.so_mark")
  283. }
  284. } else {
  285. u.l.WithError(err).Error("Failed to set listen.so_mark")
  286. }
  287. }
  288. }
  289. func (u *StdConn) getMemInfo(meminfo *[unix.SK_MEMINFO_VARS]uint32) error {
  290. var vallen uint32 = 4 * unix.SK_MEMINFO_VARS
  291. _, _, 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)
  292. if err != 0 {
  293. return err
  294. }
  295. return nil
  296. }
  297. func (u *StdConn) Close() error {
  298. return syscall.Close(u.sysFd)
  299. }
  300. func (u *StdConn) WriteBatch(pkts []BatchPacket) (int, error) {
  301. if len(pkts) == 0 {
  302. return 0, nil
  303. }
  304. // If GSO is supported, try to coalesce packets to the same destination
  305. if u.gsoSupported {
  306. return u.writeBatchGSO(pkts)
  307. }
  308. return u.writeBatchSendmmsg(pkts)
  309. }
  310. // writeBatchSendmmsg sends packets using sendmmsg without GSO coalescing
  311. func (u *StdConn) writeBatchSendmmsg(pkts []BatchPacket) (int, error) {
  312. msgs := make([]rawMessage, len(pkts))
  313. iovecs := make([]iovec, len(pkts))
  314. var names4 []unix.RawSockaddrInet4
  315. var names6 []unix.RawSockaddrInet6
  316. if u.isV4 {
  317. names4 = make([]unix.RawSockaddrInet4, len(pkts))
  318. } else {
  319. names6 = make([]unix.RawSockaddrInet6, len(pkts))
  320. }
  321. for i := range pkts {
  322. setIovecBase(&iovecs[i], &pkts[i].Payload[0])
  323. setIovecLen(&iovecs[i], len(pkts[i].Payload))
  324. msgs[i].Hdr.Iov = &iovecs[i]
  325. setMsghdrIovlen(&msgs[i].Hdr, 1)
  326. if u.isV4 {
  327. names4[i].Family = unix.AF_INET
  328. names4[i].Addr = pkts[i].Addr.Addr().As4()
  329. binary.BigEndian.PutUint16((*[2]byte)(unsafe.Pointer(&names4[i].Port))[:], pkts[i].Addr.Port())
  330. msgs[i].Hdr.Name = (*byte)(unsafe.Pointer(&names4[i]))
  331. msgs[i].Hdr.Namelen = unix.SizeofSockaddrInet4
  332. } else {
  333. names6[i].Family = unix.AF_INET6
  334. names6[i].Addr = pkts[i].Addr.Addr().As16()
  335. binary.BigEndian.PutUint16((*[2]byte)(unsafe.Pointer(&names6[i].Port))[:], pkts[i].Addr.Port())
  336. msgs[i].Hdr.Name = (*byte)(unsafe.Pointer(&names6[i]))
  337. msgs[i].Hdr.Namelen = unix.SizeofSockaddrInet6
  338. }
  339. }
  340. var sent int
  341. for sent < len(msgs) {
  342. n, _, errno := unix.Syscall6(
  343. unix.SYS_SENDMMSG,
  344. uintptr(u.sysFd),
  345. uintptr(unsafe.Pointer(&msgs[sent])),
  346. uintptr(len(msgs)-sent),
  347. 0,
  348. 0,
  349. 0,
  350. )
  351. if errno == unix.EINTR {
  352. continue
  353. }
  354. if errno != 0 {
  355. return sent, &net.OpError{Op: "sendmmsg", Err: errno}
  356. }
  357. sent += int(n)
  358. }
  359. return sent, nil
  360. }
  361. // writeBatchGSO sends packets using GSO coalescing when possible.
  362. // Packets to the same destination with the same size are coalesced into a single
  363. // GSO message. Mixed destinations or sizes fall back to individual sendmmsg calls.
  364. func (u *StdConn) writeBatchGSO(pkts []BatchPacket) (int, error) {
  365. // Group packets by destination and try to coalesce
  366. totalSent := 0
  367. i := 0
  368. for i < len(pkts) {
  369. // Find a run of packets to the same destination with compatible sizes
  370. startIdx := i
  371. dst := pkts[i].Addr
  372. segmentSize := len(pkts[i].Payload)
  373. // Count how many packets we can coalesce (same destination, same size except possibly last)
  374. coalescedCount := 1
  375. totalSize := segmentSize
  376. for i+coalescedCount < len(pkts) && coalescedCount < udpSegmentMaxDatagrams {
  377. next := pkts[i+coalescedCount]
  378. if next.Addr != dst {
  379. break
  380. }
  381. nextSize := len(next.Payload)
  382. // For GSO, all packets except the last must have the same size
  383. // The last packet can be smaller (but not larger)
  384. if nextSize != segmentSize {
  385. // Check if this could be the last packet (smaller is ok)
  386. if nextSize < segmentSize && i+coalescedCount == len(pkts)-1 {
  387. coalescedCount++
  388. totalSize += nextSize
  389. }
  390. break
  391. }
  392. coalescedCount++
  393. totalSize += nextSize
  394. }
  395. // If we have multiple packets to coalesce, use GSO
  396. if coalescedCount > 1 {
  397. err := u.sendGSO(pkts[startIdx:startIdx+coalescedCount], dst, segmentSize, totalSize)
  398. if err != nil {
  399. // If GSO fails (e.g., EIO due to NIC not supporting checksum offload),
  400. // disable GSO and fall back to sendmmsg for the rest
  401. if isGSOError(err) {
  402. u.l.WithError(err).Warn("GSO send failed, disabling GSO for this connection")
  403. u.gsoSupported = false
  404. // Send remaining packets with sendmmsg
  405. remaining, rerr := u.writeBatchSendmmsg(pkts[startIdx:])
  406. return totalSent + remaining, rerr
  407. }
  408. return totalSent, err
  409. }
  410. totalSent += coalescedCount
  411. i += coalescedCount
  412. } else {
  413. // Single packet, send without GSO overhead
  414. err := u.WriteTo(pkts[i].Payload, pkts[i].Addr)
  415. if err != nil {
  416. return totalSent, err
  417. }
  418. totalSent++
  419. i++
  420. }
  421. }
  422. return totalSent, nil
  423. }
  424. // sendGSO sends coalesced packets using UDP GSO
  425. func (u *StdConn) sendGSO(pkts []BatchPacket, dst netip.AddrPort, segmentSize, totalSize int) error {
  426. // Allocate a buffer large enough for all packet payloads
  427. coalescedBuf := make([]byte, totalSize)
  428. offset := 0
  429. for _, pkt := range pkts {
  430. copy(coalescedBuf[offset:], pkt.Payload)
  431. offset += len(pkt.Payload)
  432. }
  433. // Prepare control message with GSO segment size
  434. control := make([]byte, unix.CmsgSpace(2))
  435. controlLen := setGSOSize(control, uint16(segmentSize))
  436. // Prepare the iovec
  437. iov := iovec{}
  438. setIovecBase(&iov, &coalescedBuf[0])
  439. setIovecLen(&iov, totalSize)
  440. // Prepare the msghdr
  441. var hdr msghdr
  442. hdr.Iov = &iov
  443. setMsghdrIovlen(&hdr, 1)
  444. hdr.Control = &control[0]
  445. setMsghdrControllen(&hdr, controlLen)
  446. // Set destination address
  447. if u.isV4 {
  448. var rsa unix.RawSockaddrInet4
  449. rsa.Family = unix.AF_INET
  450. rsa.Addr = dst.Addr().As4()
  451. binary.BigEndian.PutUint16((*[2]byte)(unsafe.Pointer(&rsa.Port))[:], dst.Port())
  452. hdr.Name = (*byte)(unsafe.Pointer(&rsa))
  453. hdr.Namelen = unix.SizeofSockaddrInet4
  454. } else {
  455. var rsa unix.RawSockaddrInet6
  456. rsa.Family = unix.AF_INET6
  457. rsa.Addr = dst.Addr().As16()
  458. binary.BigEndian.PutUint16((*[2]byte)(unsafe.Pointer(&rsa.Port))[:], dst.Port())
  459. hdr.Name = (*byte)(unsafe.Pointer(&rsa))
  460. hdr.Namelen = unix.SizeofSockaddrInet6
  461. }
  462. for {
  463. _, _, errno := unix.Syscall6(
  464. unix.SYS_SENDMSG,
  465. uintptr(u.sysFd),
  466. uintptr(unsafe.Pointer(&hdr)),
  467. 0,
  468. 0,
  469. 0,
  470. 0,
  471. )
  472. if errno == unix.EINTR {
  473. continue
  474. }
  475. if errno != 0 {
  476. return &net.OpError{Op: "sendmsg", Err: errno}
  477. }
  478. return nil
  479. }
  480. }
  481. // isGSOError returns true if the error indicates GSO is not supported by the NIC
  482. func isGSOError(err error) bool {
  483. var opErr *net.OpError
  484. if !errors.As(err, &opErr) {
  485. return false
  486. }
  487. // EIO typically means the NIC doesn't support checksum offload required for GSO
  488. return errors.Is(opErr.Err, unix.EIO)
  489. }
  490. func NewUDPStatsEmitter(udpConns []Conn) func() {
  491. // Check if our kernel supports SO_MEMINFO before registering the gauges
  492. var udpGauges [][unix.SK_MEMINFO_VARS]metrics.Gauge
  493. var meminfo [unix.SK_MEMINFO_VARS]uint32
  494. if err := udpConns[0].(*StdConn).getMemInfo(&meminfo); err == nil {
  495. udpGauges = make([][unix.SK_MEMINFO_VARS]metrics.Gauge, len(udpConns))
  496. for i := range udpConns {
  497. udpGauges[i] = [unix.SK_MEMINFO_VARS]metrics.Gauge{
  498. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.rmem_alloc", i), nil),
  499. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.rcvbuf", i), nil),
  500. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.wmem_alloc", i), nil),
  501. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.sndbuf", i), nil),
  502. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.fwd_alloc", i), nil),
  503. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.wmem_queued", i), nil),
  504. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.optmem", i), nil),
  505. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.backlog", i), nil),
  506. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.drops", i), nil),
  507. }
  508. }
  509. }
  510. return func() {
  511. for i, gauges := range udpGauges {
  512. if err := udpConns[i].(*StdConn).getMemInfo(&meminfo); err == nil {
  513. for j := 0; j < unix.SK_MEMINFO_VARS; j++ {
  514. gauges[j].Update(int64(meminfo[j]))
  515. }
  516. }
  517. }
  518. }
  519. }