udp_linux.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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. "time"
  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. var readTimeout = unix.NsecToTimeval(int64(time.Millisecond * 500))
  18. type StdConn struct {
  19. sysFd int
  20. isV4 bool
  21. l *logrus.Logger
  22. batch int
  23. }
  24. func NewListener(l *logrus.Logger, ip netip.Addr, port int, multi bool, batch int) (Conn, error) {
  25. af := unix.AF_INET6
  26. if ip.Is4() {
  27. af = unix.AF_INET
  28. }
  29. syscall.ForkLock.RLock()
  30. fd, err := unix.Socket(af, unix.SOCK_DGRAM, unix.IPPROTO_UDP)
  31. if err == nil {
  32. unix.CloseOnExec(fd)
  33. }
  34. syscall.ForkLock.RUnlock()
  35. if err != nil {
  36. unix.Close(fd)
  37. return nil, fmt.Errorf("unable to open socket: %s", err)
  38. }
  39. if multi {
  40. if err = unix.SetsockoptInt(fd, unix.SOL_SOCKET, unix.SO_REUSEPORT, 1); err != nil {
  41. return nil, fmt.Errorf("unable to set SO_REUSEPORT: %s", err)
  42. }
  43. }
  44. // Set a read timeout
  45. if err = unix.SetsockoptTimeval(fd, unix.SOL_SOCKET, unix.SO_RCVTIMEO, &readTimeout); err != nil {
  46. return nil, fmt.Errorf("unable to set SO_RCVTIMEO: %s", err)
  47. }
  48. var sa unix.Sockaddr
  49. if ip.Is4() {
  50. sa4 := &unix.SockaddrInet4{Port: port}
  51. sa4.Addr = ip.As4()
  52. sa = sa4
  53. } else {
  54. sa6 := &unix.SockaddrInet6{Port: port}
  55. sa6.Addr = ip.As16()
  56. sa = sa6
  57. }
  58. if err = unix.Bind(fd, sa); err != nil {
  59. return nil, fmt.Errorf("unable to bind to socket: %s", err)
  60. }
  61. return &StdConn{sysFd: fd, isV4: ip.Is4(), l: l, batch: batch}, err
  62. }
  63. func (u *StdConn) Rebind() error {
  64. return nil
  65. }
  66. func (u *StdConn) SetRecvBuffer(n int) error {
  67. return unix.SetsockoptInt(u.sysFd, unix.SOL_SOCKET, unix.SO_RCVBUFFORCE, n)
  68. }
  69. func (u *StdConn) SetSendBuffer(n int) error {
  70. return unix.SetsockoptInt(u.sysFd, unix.SOL_SOCKET, unix.SO_SNDBUFFORCE, n)
  71. }
  72. func (u *StdConn) SetSoMark(mark int) error {
  73. return unix.SetsockoptInt(u.sysFd, unix.SOL_SOCKET, unix.SO_MARK, mark)
  74. }
  75. func (u *StdConn) GetRecvBuffer() (int, error) {
  76. return unix.GetsockoptInt(int(u.sysFd), unix.SOL_SOCKET, unix.SO_RCVBUF)
  77. }
  78. func (u *StdConn) GetSendBuffer() (int, error) {
  79. return unix.GetsockoptInt(int(u.sysFd), unix.SOL_SOCKET, unix.SO_SNDBUF)
  80. }
  81. func (u *StdConn) GetSoMark() (int, error) {
  82. return unix.GetsockoptInt(int(u.sysFd), unix.SOL_SOCKET, unix.SO_MARK)
  83. }
  84. func (u *StdConn) LocalAddr() (netip.AddrPort, error) {
  85. sa, err := unix.Getsockname(u.sysFd)
  86. if err != nil {
  87. return netip.AddrPort{}, err
  88. }
  89. switch sa := sa.(type) {
  90. case *unix.SockaddrInet4:
  91. return netip.AddrPortFrom(netip.AddrFrom4(sa.Addr), uint16(sa.Port)), nil
  92. case *unix.SockaddrInet6:
  93. return netip.AddrPortFrom(netip.AddrFrom16(sa.Addr), uint16(sa.Port)), nil
  94. default:
  95. return netip.AddrPort{}, fmt.Errorf("unsupported sock type: %T", sa)
  96. }
  97. }
  98. func (u *StdConn) ListenOut(r EncReader) {
  99. var ip netip.Addr
  100. msgs, buffers, names := u.PrepareRawMessages(u.batch)
  101. read := u.ReadMulti
  102. if u.batch == 1 {
  103. read = u.ReadSingle
  104. }
  105. for {
  106. n, err := read(msgs)
  107. if err != nil {
  108. u.l.WithError(err).Debug("udp socket is closed, exiting read loop")
  109. return
  110. }
  111. for i := 0; i < n; i++ {
  112. // Its ok to skip the ok check here, the slicing is the only error that can occur and it will panic
  113. if u.isV4 {
  114. ip, _ = netip.AddrFromSlice(names[i][4:8])
  115. } else {
  116. ip, _ = netip.AddrFromSlice(names[i][8:24])
  117. }
  118. r(netip.AddrPortFrom(ip.Unmap(), binary.BigEndian.Uint16(names[i][2:4])), buffers[i][:msgs[i].Len])
  119. }
  120. }
  121. }
  122. func (u *StdConn) ReadSingle(msgs []rawMessage) (int, error) {
  123. for {
  124. n, _, err := unix.Syscall6(
  125. unix.SYS_RECVMSG,
  126. uintptr(u.sysFd),
  127. uintptr(unsafe.Pointer(&(msgs[0].Hdr))),
  128. 0,
  129. 0,
  130. 0,
  131. 0,
  132. )
  133. if err != 0 {
  134. if err == unix.EAGAIN || err == unix.EINTR {
  135. continue
  136. }
  137. return 0, &net.OpError{Op: "recvmsg", Err: err}
  138. }
  139. msgs[0].Len = uint32(n)
  140. return 1, nil
  141. }
  142. }
  143. func (u *StdConn) ReadMulti(msgs []rawMessage) (int, error) {
  144. for {
  145. n, _, err := unix.Syscall6(
  146. unix.SYS_RECVMMSG,
  147. uintptr(u.sysFd),
  148. uintptr(unsafe.Pointer(&msgs[0])),
  149. uintptr(len(msgs)),
  150. unix.MSG_WAITFORONE,
  151. 0,
  152. 0,
  153. )
  154. if err != 0 {
  155. if err == unix.EAGAIN || err == unix.EINTR {
  156. continue
  157. }
  158. return 0, &net.OpError{Op: "recvmmsg", Err: err}
  159. }
  160. return int(n), nil
  161. }
  162. }
  163. func (u *StdConn) WriteTo(b []byte, ip netip.AddrPort) error {
  164. if u.isV4 {
  165. return u.writeTo4(b, ip)
  166. }
  167. return u.writeTo6(b, ip)
  168. }
  169. func (u *StdConn) writeTo6(b []byte, ip netip.AddrPort) error {
  170. var rsa unix.RawSockaddrInet6
  171. rsa.Family = unix.AF_INET6
  172. rsa.Addr = ip.Addr().As16()
  173. binary.BigEndian.PutUint16((*[2]byte)(unsafe.Pointer(&rsa.Port))[:], ip.Port())
  174. for {
  175. _, _, err := unix.Syscall6(
  176. unix.SYS_SENDTO,
  177. uintptr(u.sysFd),
  178. uintptr(unsafe.Pointer(&b[0])),
  179. uintptr(len(b)),
  180. uintptr(0),
  181. uintptr(unsafe.Pointer(&rsa)),
  182. uintptr(unix.SizeofSockaddrInet6),
  183. )
  184. if err != 0 {
  185. return &net.OpError{Op: "sendto", Err: err}
  186. }
  187. return nil
  188. }
  189. }
  190. func (u *StdConn) writeTo4(b []byte, ip netip.AddrPort) error {
  191. if !ip.Addr().Is4() {
  192. return fmt.Errorf("Listener is IPv4, but writing to IPv6 remote")
  193. }
  194. var rsa unix.RawSockaddrInet4
  195. rsa.Family = unix.AF_INET
  196. rsa.Addr = ip.Addr().As4()
  197. binary.BigEndian.PutUint16((*[2]byte)(unsafe.Pointer(&rsa.Port))[:], ip.Port())
  198. for {
  199. _, _, err := unix.Syscall6(
  200. unix.SYS_SENDTO,
  201. uintptr(u.sysFd),
  202. uintptr(unsafe.Pointer(&b[0])),
  203. uintptr(len(b)),
  204. uintptr(0),
  205. uintptr(unsafe.Pointer(&rsa)),
  206. uintptr(unix.SizeofSockaddrInet4),
  207. )
  208. if err != 0 {
  209. return &net.OpError{Op: "sendto", Err: err}
  210. }
  211. return nil
  212. }
  213. }
  214. func (u *StdConn) ReloadConfig(c *config.C) {
  215. b := c.GetInt("listen.read_buffer", 0)
  216. if b > 0 {
  217. err := u.SetRecvBuffer(b)
  218. if err == nil {
  219. s, err := u.GetRecvBuffer()
  220. if err == nil {
  221. u.l.WithField("size", s).Info("listen.read_buffer was set")
  222. } else {
  223. u.l.WithError(err).Warn("Failed to get listen.read_buffer")
  224. }
  225. } else {
  226. u.l.WithError(err).Error("Failed to set listen.read_buffer")
  227. }
  228. }
  229. b = c.GetInt("listen.write_buffer", 0)
  230. if b > 0 {
  231. err := u.SetSendBuffer(b)
  232. if err == nil {
  233. s, err := u.GetSendBuffer()
  234. if err == nil {
  235. u.l.WithField("size", s).Info("listen.write_buffer was set")
  236. } else {
  237. u.l.WithError(err).Warn("Failed to get listen.write_buffer")
  238. }
  239. } else {
  240. u.l.WithError(err).Error("Failed to set listen.write_buffer")
  241. }
  242. }
  243. b = c.GetInt("listen.so_mark", 0)
  244. s, err := u.GetSoMark()
  245. if b > 0 || (err == nil && s != 0) {
  246. err := u.SetSoMark(b)
  247. if err == nil {
  248. s, err := u.GetSoMark()
  249. if err == nil {
  250. u.l.WithField("mark", s).Info("listen.so_mark was set")
  251. } else {
  252. u.l.WithError(err).Warn("Failed to get listen.so_mark")
  253. }
  254. } else {
  255. u.l.WithError(err).Error("Failed to set listen.so_mark")
  256. }
  257. }
  258. }
  259. func (u *StdConn) getMemInfo(meminfo *[unix.SK_MEMINFO_VARS]uint32) error {
  260. var vallen uint32 = 4 * unix.SK_MEMINFO_VARS
  261. _, _, 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)
  262. if err != 0 {
  263. return err
  264. }
  265. return nil
  266. }
  267. func (u *StdConn) Close() error {
  268. return syscall.Close(u.sysFd)
  269. }
  270. func NewUDPStatsEmitter(udpConns []Conn) func() {
  271. // Check if our kernel supports SO_MEMINFO before registering the gauges
  272. var udpGauges [][unix.SK_MEMINFO_VARS]metrics.Gauge
  273. var meminfo [unix.SK_MEMINFO_VARS]uint32
  274. if err := udpConns[0].(*StdConn).getMemInfo(&meminfo); err == nil {
  275. udpGauges = make([][unix.SK_MEMINFO_VARS]metrics.Gauge, len(udpConns))
  276. for i := range udpConns {
  277. udpGauges[i] = [unix.SK_MEMINFO_VARS]metrics.Gauge{
  278. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.rmem_alloc", i), nil),
  279. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.rcvbuf", i), nil),
  280. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.wmem_alloc", i), nil),
  281. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.sndbuf", i), nil),
  282. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.fwd_alloc", i), nil),
  283. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.wmem_queued", i), nil),
  284. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.optmem", i), nil),
  285. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.backlog", i), nil),
  286. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.drops", i), nil),
  287. }
  288. }
  289. }
  290. return func() {
  291. for i, gauges := range udpGauges {
  292. if err := udpConns[i].(*StdConn).getMemInfo(&meminfo); err == nil {
  293. for j := 0; j < unix.SK_MEMINFO_VARS; j++ {
  294. gauges[j].Update(int64(meminfo[j]))
  295. }
  296. }
  297. }
  298. }
  299. }