udp_linux.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775
  1. //go:build !android && !e2e_testing
  2. // +build !android,!e2e_testing
  3. package udp
  4. import (
  5. "context"
  6. "encoding/binary"
  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. udpConn *net.UDPConn
  19. rawConn syscall.RawConn
  20. isV4 bool
  21. l *logrus.Logger
  22. batch int
  23. // sendmmsg scratch. Each queue has its own StdConn, so no locking is
  24. // needed. Sized to MaxWriteBatch at construction; WriteBatch chunks
  25. // larger inputs.
  26. writeMsgs []rawMessage
  27. writeIovs []iovec
  28. writeNames [][]byte
  29. // Per-entry UDP_SEGMENT cmsg scratch. writeCmsg is one contiguous slab
  30. // of MaxWriteBatch * writeCmsgSpace bytes; each entry's cmsg header is
  31. // pre-filled once in prepareWriteMessages. WriteBatch only rewrites the
  32. // 2-byte gso_size payload (and toggles Hdr.Control on/off) per call.
  33. writeCmsg []byte
  34. writeCmsgSpace int
  35. // writeEntryEnd[e] is the bufs index *after* the last packet packed
  36. // into mmsghdr entry e. Used to rewind `i` on partial sendmmsg success.
  37. writeEntryEnd []int
  38. // Preallocated closure + in/out slots for sendmmsg, so the hot path
  39. // does not heap-allocate a fresh closure per call.
  40. writeChunk int
  41. writeSent int
  42. writeErrno syscall.Errno
  43. writeFunc func(fd uintptr) bool
  44. // UDP GSO (sendmsg with UDP_SEGMENT cmsg) support. gsoSupported is
  45. // probed once at socket creation. When true, WriteSegmented takes a
  46. // single-syscall GSO path; otherwise it falls back to a WriteTo loop.
  47. gsoSupported bool
  48. gsoMsg msghdr
  49. gsoIovs []iovec
  50. gsoName []byte // SizeofSockaddrInet6
  51. gsoCmsg []byte // CmsgSpace(2)
  52. gsoSent int
  53. gsoErrno syscall.Errno
  54. gsoFunc func(fd uintptr) bool
  55. }
  56. func setReusePort(network, address string, c syscall.RawConn) error {
  57. var opErr error
  58. err := c.Control(func(fd uintptr) {
  59. opErr = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEPORT, 1)
  60. //CloseOnExec already set by the runtime
  61. })
  62. if err != nil {
  63. return err
  64. }
  65. return opErr
  66. }
  67. func NewListener(l *logrus.Logger, ip netip.Addr, port int, multi bool, batch int) (Conn, error) {
  68. listen := netip.AddrPortFrom(ip, uint16(port))
  69. lc := net.ListenConfig{}
  70. if multi {
  71. lc.Control = setReusePort
  72. }
  73. //this context is only used during the bind operation, you can't cancel it to kill the socket
  74. pc, err := lc.ListenPacket(context.Background(), "udp", listen.String())
  75. if err != nil {
  76. return nil, fmt.Errorf("unable to open socket: %s", err)
  77. }
  78. udpConn := pc.(*net.UDPConn)
  79. rawConn, err := udpConn.SyscallConn()
  80. if err != nil {
  81. _ = udpConn.Close()
  82. return nil, err
  83. }
  84. //gotta find out if we got an AF_INET6 socket or not:
  85. out := &StdConn{
  86. udpConn: udpConn,
  87. rawConn: rawConn,
  88. l: l,
  89. batch: batch,
  90. }
  91. af, err := out.getSockOptInt(unix.SO_DOMAIN)
  92. if err != nil {
  93. _ = out.Close()
  94. return nil, err
  95. }
  96. out.isV4 = af == unix.AF_INET
  97. out.prepareWriteMessages(MaxWriteBatch)
  98. out.writeFunc = out.sendmmsgRawWrite
  99. out.prepareGSO()
  100. return out, nil
  101. }
  102. // prepareWriteMessages allocates one mmsghdr/iovec/sockaddr/cmsg scratch
  103. // slot per sendmmsg entry. The iovec slab is sized to the same n so a
  104. // single entry can fan out to up to n iovecs (needed for UDP_SEGMENT runs
  105. // that coalesce consecutive bufs into one entry). Hdr.Iov / Hdr.Iovlen /
  106. // Hdr.Control / Hdr.Controllen are wired per call since each entry can
  107. // span a variable number of iovecs and may or may not carry a cmsg.
  108. func (u *StdConn) prepareWriteMessages(n int) {
  109. u.writeMsgs = make([]rawMessage, n)
  110. u.writeIovs = make([]iovec, n)
  111. u.writeNames = make([][]byte, n)
  112. u.writeEntryEnd = make([]int, n)
  113. u.writeCmsgSpace = unix.CmsgSpace(2)
  114. u.writeCmsg = make([]byte, n*u.writeCmsgSpace)
  115. for k := 0; k < n; k++ {
  116. off := k * u.writeCmsgSpace
  117. h := (*unix.Cmsghdr)(unsafe.Pointer(&u.writeCmsg[off]))
  118. h.Level = unix.SOL_UDP
  119. h.Type = unix.UDP_SEGMENT
  120. setCmsgLen(h, unix.CmsgLen(2))
  121. }
  122. for i := range u.writeMsgs {
  123. u.writeNames[i] = make([]byte, unix.SizeofSockaddrInet6)
  124. u.writeMsgs[i].Hdr.Name = &u.writeNames[i][0]
  125. }
  126. }
  127. // maxGSOSegments caps the per-sendmsg GSO fan-out. Linux kernels have
  128. // historically capped UDP_MAX_SEGMENTS at 64; newer kernels raise it to 128
  129. // but we stay conservative so the same code works everywhere.
  130. const maxGSOSegments = 64
  131. // maxGSOBytes bounds the total payload per sendmsg() when UDP_SEGMENT is
  132. // set. The kernel stitches all iovecs into a single skb whose length the
  133. // UDP length field can represent, and also enforces sk_gso_max_size (which
  134. // on most devices is 65536). We use 65535 so ciphertext + headers always
  135. // fits, avoiding EMSGSIZE on large TSO superpackets.
  136. const maxGSOBytes = 65535
  137. // prepareGSO probes UDP_SEGMENT support and, on success, sets up the
  138. // reusable sendmsg scratch (iovecs, sockaddr, cmsg) plus the preallocated
  139. // raw-write closure used to avoid heap allocations on the hot path.
  140. func (u *StdConn) prepareGSO() {
  141. var probeErr error
  142. if err := u.rawConn.Control(func(fd uintptr) {
  143. probeErr = unix.SetsockoptInt(int(fd), unix.IPPROTO_UDP, unix.UDP_SEGMENT, 0)
  144. }); err != nil {
  145. return
  146. }
  147. if probeErr != nil {
  148. return
  149. }
  150. u.gsoSupported = true
  151. u.gsoIovs = make([]iovec, maxGSOSegments)
  152. u.gsoName = make([]byte, unix.SizeofSockaddrInet6)
  153. u.gsoCmsg = make([]byte, unix.CmsgSpace(2))
  154. // Wire up the static pieces of gsoMsg. Iovlen / Controllen / Namelen /
  155. // cmsg contents get refreshed per call; Iov, Name, Control pointers are
  156. // fixed because the scratch slices never move.
  157. u.gsoMsg.Iov = &u.gsoIovs[0]
  158. u.gsoMsg.Name = &u.gsoName[0]
  159. u.gsoMsg.Control = &u.gsoCmsg[0]
  160. // Prepopulate the cmsg header. Len/Level/Type are constant for our use;
  161. // only the 2-byte gso_size payload changes per call.
  162. cmsghdr := (*unix.Cmsghdr)(unsafe.Pointer(&u.gsoCmsg[0]))
  163. cmsghdr.Level = unix.SOL_UDP
  164. cmsghdr.Type = unix.UDP_SEGMENT
  165. setCmsgLen(cmsghdr, unix.CmsgLen(2))
  166. u.gsoFunc = u.sendmsgRawWriteGSO
  167. }
  168. func (u *StdConn) SupportsMultipleReaders() bool {
  169. return true
  170. }
  171. func (u *StdConn) Rebind() error {
  172. return nil
  173. }
  174. func (u *StdConn) getSockOptInt(opt int) (int, error) {
  175. if u.rawConn == nil {
  176. return 0, fmt.Errorf("no UDP connection")
  177. }
  178. var out int
  179. var opErr error
  180. err := u.rawConn.Control(func(fd uintptr) {
  181. out, opErr = unix.GetsockoptInt(int(fd), unix.SOL_SOCKET, opt)
  182. })
  183. if err != nil {
  184. return 0, err
  185. }
  186. return out, opErr
  187. }
  188. func (u *StdConn) setSockOptInt(opt int, n int) error {
  189. if u.rawConn == nil {
  190. return fmt.Errorf("no UDP connection")
  191. }
  192. var opErr error
  193. err := u.rawConn.Control(func(fd uintptr) {
  194. opErr = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, opt, n)
  195. })
  196. if err != nil {
  197. return err
  198. }
  199. return opErr
  200. }
  201. func (u *StdConn) SetRecvBuffer(n int) error {
  202. return u.setSockOptInt(unix.SO_RCVBUFFORCE, n)
  203. }
  204. func (u *StdConn) SetSendBuffer(n int) error {
  205. return u.setSockOptInt(unix.SO_SNDBUFFORCE, n)
  206. }
  207. func (u *StdConn) SetSoMark(mark int) error {
  208. return u.setSockOptInt(unix.SO_MARK, mark)
  209. }
  210. func (u *StdConn) GetRecvBuffer() (int, error) {
  211. return u.getSockOptInt(unix.SO_RCVBUF)
  212. }
  213. func (u *StdConn) GetSendBuffer() (int, error) {
  214. return u.getSockOptInt(unix.SO_SNDBUF)
  215. }
  216. func (u *StdConn) GetSoMark() (int, error) {
  217. return u.getSockOptInt(unix.SO_MARK)
  218. }
  219. func (u *StdConn) LocalAddr() (netip.AddrPort, error) {
  220. a := u.udpConn.LocalAddr()
  221. switch v := a.(type) {
  222. case *net.UDPAddr:
  223. addr, ok := netip.AddrFromSlice(v.IP)
  224. if !ok {
  225. return netip.AddrPort{}, fmt.Errorf("LocalAddr returned invalid IP address: %s", v.IP)
  226. }
  227. return netip.AddrPortFrom(addr, uint16(v.Port)), nil
  228. default:
  229. return netip.AddrPort{}, fmt.Errorf("LocalAddr returned: %#v", a)
  230. }
  231. }
  232. func recvmmsg(fd uintptr, msgs []rawMessage) (int, bool, error) {
  233. var errno syscall.Errno
  234. n, _, errno := unix.Syscall6(
  235. unix.SYS_RECVMMSG,
  236. fd,
  237. uintptr(unsafe.Pointer(&msgs[0])),
  238. uintptr(len(msgs)),
  239. unix.MSG_WAITFORONE,
  240. 0,
  241. 0,
  242. )
  243. if errno == syscall.EAGAIN || errno == syscall.EWOULDBLOCK {
  244. // No data available, block for I/O and try again.
  245. return int(n), false, nil
  246. }
  247. if errno != 0 {
  248. return int(n), true, &net.OpError{Op: "recvmmsg", Err: errno}
  249. }
  250. return int(n), true, nil
  251. }
  252. func (u *StdConn) listenOutSingle(r EncReader, flush func()) error {
  253. var err error
  254. var n int
  255. var from netip.AddrPort
  256. buffer := make([]byte, MTU)
  257. for {
  258. n, from, err = u.udpConn.ReadFromUDPAddrPort(buffer)
  259. if err != nil {
  260. return err
  261. }
  262. from = netip.AddrPortFrom(from.Addr().Unmap(), from.Port())
  263. r(from, buffer[:n])
  264. flush()
  265. }
  266. }
  267. func (u *StdConn) listenOutBatch(r EncReader, flush func()) error {
  268. var ip netip.Addr
  269. var n int
  270. var operr error
  271. msgs, buffers, names := u.PrepareRawMessages(u.batch)
  272. //reader needs to capture variables from this function, since it's used as a lambda with rawConn.Read
  273. //defining it outside the loop so it gets re-used
  274. reader := func(fd uintptr) (done bool) {
  275. n, done, operr = recvmmsg(fd, msgs)
  276. return done
  277. }
  278. for {
  279. err := u.rawConn.Read(reader)
  280. if err != nil {
  281. return err
  282. }
  283. if operr != nil {
  284. return operr
  285. }
  286. for i := 0; i < n; i++ {
  287. // Its ok to skip the ok check here, the slicing is the only error that can occur and it will panic
  288. if u.isV4 {
  289. ip, _ = netip.AddrFromSlice(names[i][4:8])
  290. } else {
  291. ip, _ = netip.AddrFromSlice(names[i][8:24])
  292. }
  293. r(netip.AddrPortFrom(ip.Unmap(), binary.BigEndian.Uint16(names[i][2:4])), buffers[i][:msgs[i].Len])
  294. }
  295. // End-of-batch: let callers (e.g. TUN write coalescer) flush any
  296. // state they accumulated across this batch.
  297. flush()
  298. }
  299. }
  300. func (u *StdConn) ListenOut(r EncReader, flush func()) error {
  301. if u.batch == 1 {
  302. return u.listenOutSingle(r, flush)
  303. } else {
  304. return u.listenOutBatch(r, flush)
  305. }
  306. }
  307. func (u *StdConn) WriteTo(b []byte, ip netip.AddrPort) error {
  308. _, err := u.udpConn.WriteToUDPAddrPort(b, ip)
  309. return err
  310. }
  311. // WriteBatch sends bufs via sendmmsg(2) using the preallocated scratch on
  312. // StdConn. Consecutive packets to the same destination with matching segment
  313. // sizes (all but possibly the last) are coalesced into a single mmsghdr entry
  314. // carrying a UDP_SEGMENT cmsg, so one syscall can mix runs of GSO superpackets
  315. // with plain one-off datagrams. Without GSO support every packet is its own
  316. // entry, matching the prior behaviour.
  317. //
  318. // Chunks larger than the scratch are processed across multiple syscalls. If
  319. // sendmmsg returns a fatal error before any entry is sent we fall back to
  320. // per-packet WriteTo for that chunk so the caller still gets best-effort
  321. // delivery.
  322. func (u *StdConn) WriteBatch(bufs [][]byte, addrs []netip.AddrPort) error {
  323. if len(bufs) != len(addrs) {
  324. return fmt.Errorf("WriteBatch: len(bufs)=%d != len(addrs)=%d", len(bufs), len(addrs))
  325. }
  326. i := 0
  327. for i < len(bufs) {
  328. baseI := i
  329. entry := 0
  330. iovIdx := 0
  331. for entry < len(u.writeMsgs) && i < len(bufs) {
  332. iovBudget := len(u.writeIovs) - iovIdx
  333. if iovBudget < 1 {
  334. break
  335. }
  336. runLen, segSize := u.planRun(bufs, addrs, i, iovBudget)
  337. if runLen == 0 {
  338. break
  339. }
  340. for k := 0; k < runLen; k++ {
  341. b := bufs[i+k]
  342. if len(b) == 0 {
  343. u.writeIovs[iovIdx+k].Base = nil
  344. setIovLen(&u.writeIovs[iovIdx+k], 0)
  345. } else {
  346. u.writeIovs[iovIdx+k].Base = &b[0]
  347. setIovLen(&u.writeIovs[iovIdx+k], len(b))
  348. }
  349. }
  350. nlen, err := writeSockaddr(u.writeNames[entry], addrs[i], u.isV4)
  351. if err != nil {
  352. return err
  353. }
  354. hdr := &u.writeMsgs[entry].Hdr
  355. hdr.Iov = &u.writeIovs[iovIdx]
  356. setMsgIovlen(hdr, runLen)
  357. hdr.Namelen = uint32(nlen)
  358. if runLen >= 2 {
  359. off := entry * u.writeCmsgSpace
  360. dataOff := off + unix.CmsgLen(0)
  361. binary.NativeEndian.PutUint16(u.writeCmsg[dataOff:dataOff+2], uint16(segSize))
  362. hdr.Control = &u.writeCmsg[off]
  363. setMsgControllen(hdr, u.writeCmsgSpace)
  364. } else {
  365. hdr.Control = nil
  366. setMsgControllen(hdr, 0)
  367. }
  368. i += runLen
  369. iovIdx += runLen
  370. u.writeEntryEnd[entry] = i
  371. entry++
  372. }
  373. if entry == 0 {
  374. return fmt.Errorf("sendmmsg: no progress")
  375. }
  376. sent, serr := u.sendmmsg(entry)
  377. if serr != nil && sent <= 0 {
  378. // Nothing went out for this chunk; fall back to WriteTo for each
  379. // packet that was queued this iteration.
  380. for k := baseI; k < i; k++ {
  381. if werr := u.WriteTo(bufs[k], addrs[k]); werr != nil {
  382. return werr
  383. }
  384. }
  385. continue
  386. }
  387. if sent == 0 {
  388. return fmt.Errorf("sendmmsg made no progress")
  389. }
  390. // Rewind i to the end of the last successfully sent entry. For a
  391. // full-success send this leaves i unchanged; for a partial send it
  392. // replays the remainder on the next outer-loop iteration.
  393. i = u.writeEntryEnd[sent-1]
  394. }
  395. return nil
  396. }
  397. // planRun groups consecutive packets starting at `start` that can be sent as
  398. // a single UDP GSO superpacket (one sendmmsg entry with UDP_SEGMENT cmsg).
  399. // A run of length 1 means the entry carries no cmsg and the kernel treats
  400. // it as a plain datagram. Returns the run length and the per-segment size
  401. // (which equals len(bufs[start])). Without GSO support every call returns
  402. // runLen=1.
  403. func (u *StdConn) planRun(bufs [][]byte, addrs []netip.AddrPort, start, iovBudget int) (int, int) {
  404. if start >= len(bufs) || iovBudget < 1 {
  405. return 0, 0
  406. }
  407. segSize := len(bufs[start])
  408. if !u.gsoSupported || segSize == 0 || segSize > maxGSOBytes {
  409. return 1, segSize
  410. }
  411. dst := addrs[start]
  412. maxLen := maxGSOSegments
  413. if iovBudget < maxLen {
  414. maxLen = iovBudget
  415. }
  416. runLen := 1
  417. total := segSize
  418. for runLen < maxLen && start+runLen < len(bufs) {
  419. nextLen := len(bufs[start+runLen])
  420. if nextLen == 0 || nextLen > segSize {
  421. break
  422. }
  423. if addrs[start+runLen] != dst {
  424. break
  425. }
  426. if total+nextLen > maxGSOBytes {
  427. break
  428. }
  429. total += nextLen
  430. runLen++
  431. if nextLen < segSize {
  432. // A short packet must be the last in the run.
  433. break
  434. }
  435. }
  436. return runLen, segSize
  437. }
  438. // sendmmsgRawWrite is the preallocated callback passed to rawConn.Write. It
  439. // reads its input (u.writeChunk) and writes its outputs (u.writeSent,
  440. // u.writeErrno) through StdConn fields so the closure itself does not
  441. // capture per-call locals and therefore does not heap-allocate.
  442. func (u *StdConn) sendmmsgRawWrite(fd uintptr) bool {
  443. r1, _, errno := unix.Syscall6(
  444. unix.SYS_SENDMMSG,
  445. fd,
  446. uintptr(unsafe.Pointer(&u.writeMsgs[0])),
  447. uintptr(u.writeChunk),
  448. 0,
  449. 0,
  450. 0,
  451. )
  452. if errno == syscall.EAGAIN || errno == syscall.EWOULDBLOCK {
  453. return false
  454. }
  455. u.writeSent = int(r1)
  456. u.writeErrno = errno
  457. return true
  458. }
  459. func (u *StdConn) SupportsGSO() bool {
  460. return u.gsoSupported
  461. }
  462. // WriteSegmented sends bufs to addr as a UDP GSO superpacket. The kernel
  463. // emits one datagram per iovec on the wire; all iovecs except the last must
  464. // be exactly segSize bytes. Non-GSO kernels hit the WriteTo fallback.
  465. // Called with len(bufs) >= 1. len(bufs) > maxGSOSegments is chunked.
  466. func (u *StdConn) WriteSegmented(bufs [][]byte, addr netip.AddrPort, segSize int) error {
  467. if len(bufs) == 0 {
  468. return nil
  469. }
  470. if !u.gsoSupported {
  471. for _, b := range bufs {
  472. if err := u.WriteTo(b, addr); err != nil {
  473. return err
  474. }
  475. }
  476. return nil
  477. }
  478. nlen, err := writeSockaddr(u.gsoName, addr, u.isV4)
  479. if err != nil {
  480. return err
  481. }
  482. u.gsoMsg.Namelen = uint32(nlen)
  483. setMsgControllen(&u.gsoMsg, unix.CmsgSpace(2))
  484. // Cap the per-syscall fan-out by both segment count and total bytes.
  485. // Kernel rejects sendmsg with EMSGSIZE when segCount*segSize would
  486. // exceed sk_gso_max_size (typically 65536). For segSize > maxGSOBytes
  487. // we can't use GSO at all and must fall back per-packet.
  488. segsByBytes := maxGSOBytes / segSize
  489. if segsByBytes == 0 {
  490. for _, b := range bufs {
  491. if werr := u.WriteTo(b, addr); werr != nil {
  492. return werr
  493. }
  494. }
  495. return nil
  496. }
  497. maxChunk := maxGSOSegments
  498. if segsByBytes < maxChunk {
  499. maxChunk = segsByBytes
  500. }
  501. i := 0
  502. for i < len(bufs) {
  503. chunk := len(bufs) - i
  504. if chunk > maxChunk {
  505. chunk = maxChunk
  506. }
  507. for k := 0; k < chunk; k++ {
  508. b := bufs[i+k]
  509. if len(b) == 0 {
  510. u.gsoIovs[k].Base = nil
  511. setIovLen(&u.gsoIovs[k], 0)
  512. } else {
  513. u.gsoIovs[k].Base = &b[0]
  514. setIovLen(&u.gsoIovs[k], len(b))
  515. }
  516. }
  517. setMsgIovlen(&u.gsoMsg, chunk)
  518. binary.NativeEndian.PutUint16(u.gsoCmsg[unix.CmsgLen(0):unix.CmsgLen(0)+2], uint16(segSize))
  519. if serr := u.sendmsgGSO(); serr != nil {
  520. // Fall back to a per-packet loop for the remainder of the
  521. // batch. Dropping the GSO call entirely is safer than
  522. // returning mid-superpacket and losing bytes.
  523. for k := 0; k < chunk; k++ {
  524. if werr := u.WriteTo(bufs[i+k], addr); werr != nil {
  525. return werr
  526. }
  527. }
  528. }
  529. i += chunk
  530. }
  531. return nil
  532. }
  533. // sendmsgRawWriteGSO is the preallocated rawConn.Write callback for the GSO
  534. // path. Reads the prebuilt u.gsoMsg and writes u.gsoSent / u.gsoErrno.
  535. func (u *StdConn) sendmsgRawWriteGSO(fd uintptr) bool {
  536. r1, _, errno := unix.Syscall(
  537. unix.SYS_SENDMSG,
  538. fd,
  539. uintptr(unsafe.Pointer(&u.gsoMsg)),
  540. 0,
  541. )
  542. if errno == syscall.EAGAIN || errno == syscall.EWOULDBLOCK {
  543. return false
  544. }
  545. u.gsoSent = int(r1)
  546. u.gsoErrno = errno
  547. return true
  548. }
  549. func (u *StdConn) sendmsgGSO() error {
  550. u.gsoSent = 0
  551. u.gsoErrno = 0
  552. if err := u.rawConn.Write(u.gsoFunc); err != nil {
  553. return err
  554. }
  555. if u.gsoErrno != 0 {
  556. return &net.OpError{Op: "sendmsg", Err: u.gsoErrno}
  557. }
  558. return nil
  559. }
  560. func (u *StdConn) sendmmsg(n int) (int, error) {
  561. u.writeChunk = n
  562. u.writeSent = 0
  563. u.writeErrno = 0
  564. if err := u.rawConn.Write(u.writeFunc); err != nil {
  565. return u.writeSent, err
  566. }
  567. if u.writeErrno != 0 {
  568. return u.writeSent, &net.OpError{Op: "sendmmsg", Err: u.writeErrno}
  569. }
  570. return u.writeSent, nil
  571. }
  572. // writeSockaddr encodes addr into buf (which must be at least
  573. // SizeofSockaddrInet6 bytes). Returns the number of bytes used. If isV4 is
  574. // true and addr is not a v4 (or v4-in-v6) address, returns an error.
  575. func writeSockaddr(buf []byte, addr netip.AddrPort, isV4 bool) (int, error) {
  576. ap := addr.Addr().Unmap()
  577. if isV4 {
  578. if !ap.Is4() {
  579. return 0, ErrInvalidIPv6RemoteForSocket
  580. }
  581. // struct sockaddr_in: { sa_family_t(2), in_port_t(2, BE), in_addr(4), zero(8) }
  582. // sa_family is host endian.
  583. binary.NativeEndian.PutUint16(buf[0:2], unix.AF_INET)
  584. binary.BigEndian.PutUint16(buf[2:4], addr.Port())
  585. ip4 := ap.As4()
  586. copy(buf[4:8], ip4[:])
  587. for j := 8; j < 16; j++ {
  588. buf[j] = 0
  589. }
  590. return unix.SizeofSockaddrInet4, nil
  591. }
  592. // struct sockaddr_in6: { sa_family_t(2), in_port_t(2, BE), flowinfo(4), in6_addr(16), scope_id(4) }
  593. binary.NativeEndian.PutUint16(buf[0:2], unix.AF_INET6)
  594. binary.BigEndian.PutUint16(buf[2:4], addr.Port())
  595. binary.NativeEndian.PutUint32(buf[4:8], 0)
  596. ip6 := addr.Addr().As16()
  597. copy(buf[8:24], ip6[:])
  598. binary.NativeEndian.PutUint32(buf[24:28], 0)
  599. return unix.SizeofSockaddrInet6, nil
  600. }
  601. func (u *StdConn) ReloadConfig(c *config.C) {
  602. b := c.GetInt("listen.read_buffer", 0)
  603. if b > 0 {
  604. err := u.SetRecvBuffer(b)
  605. if err == nil {
  606. s, err := u.GetRecvBuffer()
  607. if err == nil {
  608. u.l.WithField("size", s).Info("listen.read_buffer was set")
  609. } else {
  610. u.l.WithError(err).Warn("Failed to get listen.read_buffer")
  611. }
  612. } else {
  613. u.l.WithError(err).Error("Failed to set listen.read_buffer")
  614. }
  615. }
  616. b = c.GetInt("listen.write_buffer", 0)
  617. if b > 0 {
  618. err := u.SetSendBuffer(b)
  619. if err == nil {
  620. s, err := u.GetSendBuffer()
  621. if err == nil {
  622. u.l.WithField("size", s).Info("listen.write_buffer was set")
  623. } else {
  624. u.l.WithError(err).Warn("Failed to get listen.write_buffer")
  625. }
  626. } else {
  627. u.l.WithError(err).Error("Failed to set listen.write_buffer")
  628. }
  629. }
  630. b = c.GetInt("listen.so_mark", 0)
  631. s, err := u.GetSoMark()
  632. if b > 0 || (err == nil && s != 0) {
  633. err := u.SetSoMark(b)
  634. if err == nil {
  635. s, err := u.GetSoMark()
  636. if err == nil {
  637. u.l.WithField("mark", s).Info("listen.so_mark was set")
  638. } else {
  639. u.l.WithError(err).Warn("Failed to get listen.so_mark")
  640. }
  641. } else {
  642. u.l.WithError(err).Error("Failed to set listen.so_mark")
  643. }
  644. }
  645. }
  646. func (u *StdConn) getMemInfo(meminfo *[unix.SK_MEMINFO_VARS]uint32) error {
  647. var vallen uint32 = 4 * unix.SK_MEMINFO_VARS
  648. if u.rawConn == nil {
  649. return fmt.Errorf("no UDP connection")
  650. }
  651. var opErr error
  652. err := u.rawConn.Control(func(fd uintptr) {
  653. _, _, syserr := unix.Syscall6(unix.SYS_GETSOCKOPT, fd, uintptr(unix.SOL_SOCKET), uintptr(unix.SO_MEMINFO), uintptr(unsafe.Pointer(meminfo)), uintptr(unsafe.Pointer(&vallen)), 0)
  654. if syserr != 0 {
  655. opErr = syserr
  656. }
  657. })
  658. if err != nil {
  659. return err
  660. }
  661. return opErr
  662. }
  663. func (u *StdConn) Close() error {
  664. if u.udpConn != nil {
  665. return u.udpConn.Close()
  666. }
  667. return nil
  668. }
  669. func NewUDPStatsEmitter(udpConns []Conn) func() {
  670. // Check if our kernel supports SO_MEMINFO before registering the gauges
  671. var udpGauges [][unix.SK_MEMINFO_VARS]metrics.Gauge
  672. var meminfo [unix.SK_MEMINFO_VARS]uint32
  673. if err := udpConns[0].(*StdConn).getMemInfo(&meminfo); err == nil {
  674. udpGauges = make([][unix.SK_MEMINFO_VARS]metrics.Gauge, len(udpConns))
  675. for i := range udpConns {
  676. udpGauges[i] = [unix.SK_MEMINFO_VARS]metrics.Gauge{
  677. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.rmem_alloc", i), nil),
  678. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.rcvbuf", i), nil),
  679. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.wmem_alloc", i), nil),
  680. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.sndbuf", i), nil),
  681. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.fwd_alloc", i), nil),
  682. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.wmem_queued", i), nil),
  683. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.optmem", i), nil),
  684. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.backlog", i), nil),
  685. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.drops", i), nil),
  686. }
  687. }
  688. }
  689. return func() {
  690. for i, gauges := range udpGauges {
  691. if err := udpConns[i].(*StdConn).getMemInfo(&meminfo); err == nil {
  692. for j := 0; j < unix.SK_MEMINFO_VARS; j++ {
  693. gauges[j].Update(int64(meminfo[j]))
  694. }
  695. }
  696. }
  697. }
  698. }