udp_linux.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  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/sys/unix"
  15. )
  16. type StdConn struct {
  17. sysFd int
  18. isV4 bool
  19. l *logrus.Logger
  20. batch int
  21. // Pre-allocated buffers for batch writes (sized for IPv6, works for both)
  22. writeMsgs []rawMessage
  23. writeIovecs []iovec
  24. writeNames [][]byte
  25. }
  26. func maybeIPV4(ip net.IP) (net.IP, bool) {
  27. ip4 := ip.To4()
  28. if ip4 != nil {
  29. return ip4, true
  30. }
  31. return ip, false
  32. }
  33. func NewListener(l *logrus.Logger, ip netip.Addr, port int, multi bool, batch int) (Conn, error) {
  34. af := unix.AF_INET6
  35. if ip.Is4() {
  36. af = unix.AF_INET
  37. }
  38. syscall.ForkLock.RLock()
  39. fd, err := unix.Socket(af, unix.SOCK_DGRAM, unix.IPPROTO_UDP)
  40. if err == nil {
  41. unix.CloseOnExec(fd)
  42. }
  43. syscall.ForkLock.RUnlock()
  44. if err != nil {
  45. unix.Close(fd)
  46. return nil, fmt.Errorf("unable to open socket: %s", err)
  47. }
  48. if multi {
  49. if err = unix.SetsockoptInt(fd, unix.SOL_SOCKET, unix.SO_REUSEPORT, 1); err != nil {
  50. return nil, fmt.Errorf("unable to set SO_REUSEPORT: %s", err)
  51. }
  52. }
  53. var sa unix.Sockaddr
  54. if ip.Is4() {
  55. sa4 := &unix.SockaddrInet4{Port: port}
  56. sa4.Addr = ip.As4()
  57. sa = sa4
  58. } else {
  59. sa6 := &unix.SockaddrInet6{Port: port}
  60. sa6.Addr = ip.As16()
  61. sa = sa6
  62. }
  63. if err = unix.Bind(fd, sa); err != nil {
  64. return nil, fmt.Errorf("unable to bind to socket: %s", err)
  65. }
  66. c := &StdConn{sysFd: fd, isV4: ip.Is4(), l: l, batch: batch}
  67. // Pre-allocate write message structures for batching (sized for IPv6, works for both)
  68. c.writeMsgs = make([]rawMessage, batch)
  69. c.writeIovecs = make([]iovec, batch)
  70. c.writeNames = make([][]byte, batch)
  71. for i := range c.writeMsgs {
  72. // Allocate for IPv6 size (larger than IPv4, works for both)
  73. c.writeNames[i] = make([]byte, unix.SizeofSockaddrInet6)
  74. // Point to the iovec in the slice
  75. c.writeMsgs[i].Hdr.Iov = &c.writeIovecs[i]
  76. c.writeMsgs[i].Hdr.Iovlen = 1
  77. c.writeMsgs[i].Hdr.Name = &c.writeNames[i][0]
  78. // Namelen will be set appropriately in writeMulti4/writeMulti6
  79. }
  80. return c, err
  81. }
  82. func (u *StdConn) Rebind() error {
  83. return nil
  84. }
  85. func (u *StdConn) SetRecvBuffer(n int) error {
  86. return unix.SetsockoptInt(u.sysFd, unix.SOL_SOCKET, unix.SO_RCVBUFFORCE, n)
  87. }
  88. func (u *StdConn) SetSendBuffer(n int) error {
  89. return unix.SetsockoptInt(u.sysFd, unix.SOL_SOCKET, unix.SO_SNDBUFFORCE, n)
  90. }
  91. func (u *StdConn) SetSoMark(mark int) error {
  92. return unix.SetsockoptInt(u.sysFd, unix.SOL_SOCKET, unix.SO_MARK, mark)
  93. }
  94. func (u *StdConn) GetRecvBuffer() (int, error) {
  95. return unix.GetsockoptInt(int(u.sysFd), unix.SOL_SOCKET, unix.SO_RCVBUF)
  96. }
  97. func (u *StdConn) GetSendBuffer() (int, error) {
  98. return unix.GetsockoptInt(int(u.sysFd), unix.SOL_SOCKET, unix.SO_SNDBUF)
  99. }
  100. func (u *StdConn) GetSoMark() (int, error) {
  101. return unix.GetsockoptInt(int(u.sysFd), unix.SOL_SOCKET, unix.SO_MARK)
  102. }
  103. func (u *StdConn) LocalAddr() (netip.AddrPort, error) {
  104. sa, err := unix.Getsockname(u.sysFd)
  105. if err != nil {
  106. return netip.AddrPort{}, err
  107. }
  108. switch sa := sa.(type) {
  109. case *unix.SockaddrInet4:
  110. return netip.AddrPortFrom(netip.AddrFrom4(sa.Addr), uint16(sa.Port)), nil
  111. case *unix.SockaddrInet6:
  112. return netip.AddrPortFrom(netip.AddrFrom16(sa.Addr), uint16(sa.Port)), nil
  113. default:
  114. return netip.AddrPort{}, fmt.Errorf("unsupported sock type: %T", sa)
  115. }
  116. }
  117. func (u *StdConn) ListenOut(r EncReader) {
  118. var ip netip.Addr
  119. msgs, buffers, names := u.PrepareRawMessages(u.batch)
  120. read := u.ReadMulti
  121. if u.batch == 1 {
  122. read = u.ReadSingle
  123. }
  124. udpBatchHist := metrics.GetOrRegisterHistogram("batch.udp_read_size", nil, metrics.NewUniformSample(1024))
  125. for {
  126. n, err := read(msgs)
  127. if err != nil {
  128. u.l.WithError(err).Debug("udp socket is closed, exiting read loop")
  129. return
  130. }
  131. udpBatchHist.Update(int64(n))
  132. for i := 0; i < n; i++ {
  133. // Its ok to skip the ok check here, the slicing is the only error that can occur and it will panic
  134. if u.isV4 {
  135. ip, _ = netip.AddrFromSlice(names[i][4:8])
  136. } else {
  137. ip, _ = netip.AddrFromSlice(names[i][8:24])
  138. }
  139. r(netip.AddrPortFrom(ip.Unmap(), binary.BigEndian.Uint16(names[i][2:4])), buffers[i][:msgs[i].Len])
  140. }
  141. }
  142. }
  143. func (u *StdConn) ListenOutBatch(r EncBatchReader) {
  144. var ip netip.Addr
  145. msgs, buffers, names := u.PrepareRawMessages(u.batch)
  146. read := u.ReadMulti
  147. if u.batch == 1 {
  148. read = u.ReadSingle
  149. }
  150. udpBatchHist := metrics.GetOrRegisterHistogram("batch.udp_read_size", nil, metrics.NewUniformSample(1024))
  151. // Pre-allocate slices for batch callback
  152. addrs := make([]netip.AddrPort, u.batch)
  153. payloads := make([][]byte, u.batch)
  154. for {
  155. n, err := read(msgs)
  156. if err != nil {
  157. u.l.WithError(err).Debug("udp socket is closed, exiting read loop")
  158. return
  159. }
  160. udpBatchHist.Update(int64(n))
  161. // Prepare batch data
  162. for i := 0; i < n; i++ {
  163. if u.isV4 {
  164. ip, _ = netip.AddrFromSlice(names[i][4:8])
  165. } else {
  166. ip, _ = netip.AddrFromSlice(names[i][8:24])
  167. }
  168. addrs[i] = netip.AddrPortFrom(ip.Unmap(), binary.BigEndian.Uint16(names[i][2:4]))
  169. payloads[i] = buffers[i][:msgs[i].Len]
  170. }
  171. // Call batch callback with all packets
  172. r(addrs, payloads, n)
  173. }
  174. }
  175. func (u *StdConn) ReadSingle(msgs []rawMessage) (int, error) {
  176. for {
  177. n, _, err := unix.Syscall6(
  178. unix.SYS_RECVMSG,
  179. uintptr(u.sysFd),
  180. uintptr(unsafe.Pointer(&(msgs[0].Hdr))),
  181. 0,
  182. 0,
  183. 0,
  184. 0,
  185. )
  186. if err != 0 {
  187. return 0, &net.OpError{Op: "recvmsg", Err: err}
  188. }
  189. msgs[0].Len = uint32(n)
  190. return 1, nil
  191. }
  192. }
  193. func (u *StdConn) ReadMulti(msgs []rawMessage) (int, error) {
  194. for {
  195. n, _, err := unix.Syscall6(
  196. unix.SYS_RECVMMSG,
  197. uintptr(u.sysFd),
  198. uintptr(unsafe.Pointer(&msgs[0])),
  199. uintptr(len(msgs)),
  200. unix.MSG_WAITFORONE,
  201. 0,
  202. 0,
  203. )
  204. if err != 0 {
  205. return 0, &net.OpError{Op: "recvmmsg", Err: err}
  206. }
  207. return int(n), nil
  208. }
  209. }
  210. func (u *StdConn) WriteTo(b []byte, ip netip.AddrPort) error {
  211. if u.isV4 {
  212. return u.writeTo4(b, ip)
  213. }
  214. return u.writeTo6(b, ip)
  215. }
  216. func (u *StdConn) WriteMulti(packets [][]byte, addrs []netip.AddrPort) (int, error) {
  217. if len(packets) != len(addrs) {
  218. return 0, fmt.Errorf("packets and addrs length mismatch")
  219. }
  220. if len(packets) == 0 {
  221. return 0, nil
  222. }
  223. if u.isV4 {
  224. return u.writeMulti4(packets, addrs)
  225. }
  226. return u.writeMulti6(packets, addrs)
  227. }
  228. func (u *StdConn) writeTo6(b []byte, ip netip.AddrPort) error {
  229. var rsa unix.RawSockaddrInet6
  230. rsa.Family = unix.AF_INET6
  231. rsa.Addr = ip.Addr().As16()
  232. binary.BigEndian.PutUint16((*[2]byte)(unsafe.Pointer(&rsa.Port))[:], ip.Port())
  233. for {
  234. _, _, err := unix.Syscall6(
  235. unix.SYS_SENDTO,
  236. uintptr(u.sysFd),
  237. uintptr(unsafe.Pointer(&b[0])),
  238. uintptr(len(b)),
  239. uintptr(0),
  240. uintptr(unsafe.Pointer(&rsa)),
  241. uintptr(unix.SizeofSockaddrInet6),
  242. )
  243. if err != 0 {
  244. return &net.OpError{Op: "sendto", Err: err}
  245. }
  246. return nil
  247. }
  248. }
  249. func (u *StdConn) writeTo4(b []byte, ip netip.AddrPort) error {
  250. if !ip.Addr().Is4() {
  251. return ErrInvalidIPv6RemoteForSocket
  252. }
  253. var rsa unix.RawSockaddrInet4
  254. rsa.Family = unix.AF_INET
  255. rsa.Addr = ip.Addr().As4()
  256. binary.BigEndian.PutUint16((*[2]byte)(unsafe.Pointer(&rsa.Port))[:], ip.Port())
  257. for {
  258. _, _, err := unix.Syscall6(
  259. unix.SYS_SENDTO,
  260. uintptr(u.sysFd),
  261. uintptr(unsafe.Pointer(&b[0])),
  262. uintptr(len(b)),
  263. uintptr(0),
  264. uintptr(unsafe.Pointer(&rsa)),
  265. uintptr(unix.SizeofSockaddrInet4),
  266. )
  267. if err != 0 {
  268. return &net.OpError{Op: "sendto", Err: err}
  269. }
  270. return nil
  271. }
  272. }
  273. func (u *StdConn) writeMulti4(packets [][]byte, addrs []netip.AddrPort) (int, error) {
  274. sent := 0
  275. for sent < len(packets) {
  276. // Determine batch size based on remaining packets and buffer capacity
  277. batchSize := len(packets) - sent
  278. if batchSize > len(u.writeMsgs) {
  279. batchSize = len(u.writeMsgs)
  280. }
  281. // Use pre-allocated buffers
  282. msgs := u.writeMsgs[:batchSize]
  283. iovecs := u.writeIovecs[:batchSize]
  284. names := u.writeNames[:batchSize]
  285. // Setup message structures for this batch
  286. for i := 0; i < batchSize; i++ {
  287. pktIdx := sent + i
  288. if !addrs[pktIdx].Addr().Is4() {
  289. return sent + i, ErrInvalidIPv6RemoteForSocket
  290. }
  291. // Setup the packet buffer
  292. iovecs[i].Base = &packets[pktIdx][0]
  293. iovecs[i].Len = uint(len(packets[pktIdx]))
  294. // Setup the destination address
  295. rsa := (*unix.RawSockaddrInet4)(unsafe.Pointer(&names[i][0]))
  296. rsa.Family = unix.AF_INET
  297. rsa.Addr = addrs[pktIdx].Addr().As4()
  298. binary.BigEndian.PutUint16((*[2]byte)(unsafe.Pointer(&rsa.Port))[:], addrs[pktIdx].Port())
  299. // Set the appropriate address length for IPv4
  300. msgs[i].Hdr.Namelen = unix.SizeofSockaddrInet4
  301. }
  302. // Send this batch
  303. nsent, _, err := unix.Syscall6(
  304. unix.SYS_SENDMMSG,
  305. uintptr(u.sysFd),
  306. uintptr(unsafe.Pointer(&msgs[0])),
  307. uintptr(batchSize),
  308. 0,
  309. 0,
  310. 0,
  311. )
  312. if err != 0 {
  313. return sent + int(nsent), &net.OpError{Op: "sendmmsg", Err: err}
  314. }
  315. sent += int(nsent)
  316. if int(nsent) < batchSize {
  317. // Couldn't send all packets in batch, return what we sent
  318. return sent, nil
  319. }
  320. }
  321. return sent, nil
  322. }
  323. func (u *StdConn) writeMulti6(packets [][]byte, addrs []netip.AddrPort) (int, error) {
  324. sent := 0
  325. for sent < len(packets) {
  326. // Determine batch size based on remaining packets and buffer capacity
  327. batchSize := len(packets) - sent
  328. if batchSize > len(u.writeMsgs) {
  329. batchSize = len(u.writeMsgs)
  330. }
  331. // Use pre-allocated buffers
  332. msgs := u.writeMsgs[:batchSize]
  333. iovecs := u.writeIovecs[:batchSize]
  334. names := u.writeNames[:batchSize]
  335. // Setup message structures for this batch
  336. for i := 0; i < batchSize; i++ {
  337. pktIdx := sent + i
  338. // Setup the packet buffer
  339. iovecs[i].Base = &packets[pktIdx][0]
  340. iovecs[i].Len = uint(len(packets[pktIdx]))
  341. // Setup the destination address
  342. rsa := (*unix.RawSockaddrInet6)(unsafe.Pointer(&names[i][0]))
  343. rsa.Family = unix.AF_INET6
  344. rsa.Addr = addrs[pktIdx].Addr().As16()
  345. binary.BigEndian.PutUint16((*[2]byte)(unsafe.Pointer(&rsa.Port))[:], addrs[pktIdx].Port())
  346. // Set the appropriate address length for IPv6
  347. msgs[i].Hdr.Namelen = unix.SizeofSockaddrInet6
  348. }
  349. // Send this batch
  350. nsent, _, err := unix.Syscall6(
  351. unix.SYS_SENDMMSG,
  352. uintptr(u.sysFd),
  353. uintptr(unsafe.Pointer(&msgs[0])),
  354. uintptr(batchSize),
  355. 0,
  356. 0,
  357. 0,
  358. )
  359. if err != 0 {
  360. return sent + int(nsent), &net.OpError{Op: "sendmmsg", Err: err}
  361. }
  362. sent += int(nsent)
  363. if int(nsent) < batchSize {
  364. // Couldn't send all packets in batch, return what we sent
  365. return sent, nil
  366. }
  367. }
  368. return sent, nil
  369. }
  370. func (u *StdConn) ReloadConfig(c *config.C) {
  371. b := c.GetInt("listen.read_buffer", 0)
  372. if b > 0 {
  373. err := u.SetRecvBuffer(b)
  374. if err == nil {
  375. s, err := u.GetRecvBuffer()
  376. if err == nil {
  377. u.l.WithField("size", s).Info("listen.read_buffer was set")
  378. } else {
  379. u.l.WithError(err).Warn("Failed to get listen.read_buffer")
  380. }
  381. } else {
  382. u.l.WithError(err).Error("Failed to set listen.read_buffer")
  383. }
  384. }
  385. b = c.GetInt("listen.write_buffer", 0)
  386. if b > 0 {
  387. err := u.SetSendBuffer(b)
  388. if err == nil {
  389. s, err := u.GetSendBuffer()
  390. if err == nil {
  391. u.l.WithField("size", s).Info("listen.write_buffer was set")
  392. } else {
  393. u.l.WithError(err).Warn("Failed to get listen.write_buffer")
  394. }
  395. } else {
  396. u.l.WithError(err).Error("Failed to set listen.write_buffer")
  397. }
  398. }
  399. b = c.GetInt("listen.so_mark", 0)
  400. s, err := u.GetSoMark()
  401. if b > 0 || (err == nil && s != 0) {
  402. err := u.SetSoMark(b)
  403. if err == nil {
  404. s, err := u.GetSoMark()
  405. if err == nil {
  406. u.l.WithField("mark", s).Info("listen.so_mark was set")
  407. } else {
  408. u.l.WithError(err).Warn("Failed to get listen.so_mark")
  409. }
  410. } else {
  411. u.l.WithError(err).Error("Failed to set listen.so_mark")
  412. }
  413. }
  414. }
  415. func (u *StdConn) getMemInfo(meminfo *[unix.SK_MEMINFO_VARS]uint32) error {
  416. var vallen uint32 = 4 * unix.SK_MEMINFO_VARS
  417. _, _, 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)
  418. if err != 0 {
  419. return err
  420. }
  421. return nil
  422. }
  423. func (u *StdConn) BatchSize() int {
  424. return u.batch
  425. }
  426. func (u *StdConn) Close() error {
  427. return syscall.Close(u.sysFd)
  428. }
  429. func NewUDPStatsEmitter(udpConns []Conn) func() {
  430. // Check if our kernel supports SO_MEMINFO before registering the gauges
  431. var udpGauges [][unix.SK_MEMINFO_VARS]metrics.Gauge
  432. var meminfo [unix.SK_MEMINFO_VARS]uint32
  433. if err := udpConns[0].(*StdConn).getMemInfo(&meminfo); err == nil {
  434. udpGauges = make([][unix.SK_MEMINFO_VARS]metrics.Gauge, len(udpConns))
  435. for i := range udpConns {
  436. udpGauges[i] = [unix.SK_MEMINFO_VARS]metrics.Gauge{
  437. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.rmem_alloc", i), nil),
  438. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.rcvbuf", i), nil),
  439. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.wmem_alloc", i), nil),
  440. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.sndbuf", i), nil),
  441. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.fwd_alloc", i), nil),
  442. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.wmem_queued", i), nil),
  443. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.optmem", i), nil),
  444. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.backlog", i), nil),
  445. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.drops", i), nil),
  446. }
  447. }
  448. }
  449. return func() {
  450. for i, gauges := range udpGauges {
  451. if err := udpConns[i].(*StdConn).getMemInfo(&meminfo); err == nil {
  452. for j := 0; j < unix.SK_MEMINFO_VARS; j++ {
  453. gauges[j].Update(int64(meminfo[j]))
  454. }
  455. }
  456. }
  457. }
  458. }