udp_linux.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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) error {
  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. return err
  109. }
  110. for i := 0; i < n; i++ {
  111. // Its ok to skip the ok check here, the slicing is the only error that can occur and it will panic
  112. if u.isV4 {
  113. ip, _ = netip.AddrFromSlice(names[i][4:8])
  114. } else {
  115. ip, _ = netip.AddrFromSlice(names[i][8:24])
  116. }
  117. r(netip.AddrPortFrom(ip.Unmap(), binary.BigEndian.Uint16(names[i][2:4])), buffers[i][:msgs[i].Len])
  118. }
  119. }
  120. }
  121. func (u *StdConn) ReadSingle(msgs []rawMessage) (int, error) {
  122. for {
  123. n, _, err := unix.Syscall6(
  124. unix.SYS_RECVMSG,
  125. uintptr(u.sysFd),
  126. uintptr(unsafe.Pointer(&(msgs[0].Hdr))),
  127. 0,
  128. 0,
  129. 0,
  130. 0,
  131. )
  132. if err != 0 {
  133. if err == unix.EAGAIN || err == unix.EINTR {
  134. continue
  135. }
  136. return 0, &net.OpError{Op: "recvmsg", Err: err}
  137. }
  138. msgs[0].Len = uint32(n)
  139. return 1, nil
  140. }
  141. }
  142. func (u *StdConn) ReadMulti(msgs []rawMessage) (int, error) {
  143. for {
  144. n, _, err := unix.Syscall6(
  145. unix.SYS_RECVMMSG,
  146. uintptr(u.sysFd),
  147. uintptr(unsafe.Pointer(&msgs[0])),
  148. uintptr(len(msgs)),
  149. unix.MSG_WAITFORONE,
  150. 0,
  151. 0,
  152. )
  153. if err != 0 {
  154. if err == unix.EAGAIN || err == unix.EINTR {
  155. continue
  156. }
  157. return 0, &net.OpError{Op: "recvmmsg", Err: err}
  158. }
  159. return int(n), nil
  160. }
  161. }
  162. func (u *StdConn) WriteTo(b []byte, ip netip.AddrPort) error {
  163. if u.isV4 {
  164. return u.writeTo4(b, ip)
  165. }
  166. return u.writeTo6(b, ip)
  167. }
  168. func (u *StdConn) writeTo6(b []byte, ip netip.AddrPort) error {
  169. var rsa unix.RawSockaddrInet6
  170. rsa.Family = unix.AF_INET6
  171. rsa.Addr = ip.Addr().As16()
  172. binary.BigEndian.PutUint16((*[2]byte)(unsafe.Pointer(&rsa.Port))[:], ip.Port())
  173. for {
  174. _, _, err := unix.Syscall6(
  175. unix.SYS_SENDTO,
  176. uintptr(u.sysFd),
  177. uintptr(unsafe.Pointer(&b[0])),
  178. uintptr(len(b)),
  179. uintptr(0),
  180. uintptr(unsafe.Pointer(&rsa)),
  181. uintptr(unix.SizeofSockaddrInet6),
  182. )
  183. if err != 0 {
  184. return &net.OpError{Op: "sendto", Err: err}
  185. }
  186. return nil
  187. }
  188. }
  189. func (u *StdConn) writeTo4(b []byte, ip netip.AddrPort) error {
  190. if !ip.Addr().Is4() {
  191. return fmt.Errorf("Listener is IPv4, but writing to IPv6 remote")
  192. }
  193. var rsa unix.RawSockaddrInet4
  194. rsa.Family = unix.AF_INET
  195. rsa.Addr = ip.Addr().As4()
  196. binary.BigEndian.PutUint16((*[2]byte)(unsafe.Pointer(&rsa.Port))[:], ip.Port())
  197. for {
  198. _, _, err := unix.Syscall6(
  199. unix.SYS_SENDTO,
  200. uintptr(u.sysFd),
  201. uintptr(unsafe.Pointer(&b[0])),
  202. uintptr(len(b)),
  203. uintptr(0),
  204. uintptr(unsafe.Pointer(&rsa)),
  205. uintptr(unix.SizeofSockaddrInet4),
  206. )
  207. if err != 0 {
  208. return &net.OpError{Op: "sendto", Err: err}
  209. }
  210. return nil
  211. }
  212. }
  213. func (u *StdConn) ReloadConfig(c *config.C) {
  214. b := c.GetInt("listen.read_buffer", 0)
  215. if b > 0 {
  216. err := u.SetRecvBuffer(b)
  217. if err == nil {
  218. s, err := u.GetRecvBuffer()
  219. if err == nil {
  220. u.l.WithField("size", s).Info("listen.read_buffer was set")
  221. } else {
  222. u.l.WithError(err).Warn("Failed to get listen.read_buffer")
  223. }
  224. } else {
  225. u.l.WithError(err).Error("Failed to set listen.read_buffer")
  226. }
  227. }
  228. b = c.GetInt("listen.write_buffer", 0)
  229. if b > 0 {
  230. err := u.SetSendBuffer(b)
  231. if err == nil {
  232. s, err := u.GetSendBuffer()
  233. if err == nil {
  234. u.l.WithField("size", s).Info("listen.write_buffer was set")
  235. } else {
  236. u.l.WithError(err).Warn("Failed to get listen.write_buffer")
  237. }
  238. } else {
  239. u.l.WithError(err).Error("Failed to set listen.write_buffer")
  240. }
  241. }
  242. b = c.GetInt("listen.so_mark", 0)
  243. s, err := u.GetSoMark()
  244. if b > 0 || (err == nil && s != 0) {
  245. err := u.SetSoMark(b)
  246. if err == nil {
  247. s, err := u.GetSoMark()
  248. if err == nil {
  249. u.l.WithField("mark", s).Info("listen.so_mark was set")
  250. } else {
  251. u.l.WithError(err).Warn("Failed to get listen.so_mark")
  252. }
  253. } else {
  254. u.l.WithError(err).Error("Failed to set listen.so_mark")
  255. }
  256. }
  257. }
  258. func (u *StdConn) getMemInfo(meminfo *[unix.SK_MEMINFO_VARS]uint32) error {
  259. var vallen uint32 = 4 * unix.SK_MEMINFO_VARS
  260. _, _, 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)
  261. if err != 0 {
  262. return err
  263. }
  264. return nil
  265. }
  266. func (u *StdConn) Close() error {
  267. return syscall.Close(u.sysFd)
  268. }
  269. func NewUDPStatsEmitter(udpConns []Conn) func() {
  270. // Check if our kernel supports SO_MEMINFO before registering the gauges
  271. var udpGauges [][unix.SK_MEMINFO_VARS]metrics.Gauge
  272. var meminfo [unix.SK_MEMINFO_VARS]uint32
  273. if err := udpConns[0].(*StdConn).getMemInfo(&meminfo); err == nil {
  274. udpGauges = make([][unix.SK_MEMINFO_VARS]metrics.Gauge, len(udpConns))
  275. for i := range udpConns {
  276. udpGauges[i] = [unix.SK_MEMINFO_VARS]metrics.Gauge{
  277. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.rmem_alloc", i), nil),
  278. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.rcvbuf", i), nil),
  279. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.wmem_alloc", i), nil),
  280. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.sndbuf", i), nil),
  281. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.fwd_alloc", i), nil),
  282. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.wmem_queued", i), nil),
  283. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.optmem", i), nil),
  284. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.backlog", i), nil),
  285. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.drops", i), nil),
  286. }
  287. }
  288. }
  289. return func() {
  290. for i, gauges := range udpGauges {
  291. if err := udpConns[i].(*StdConn).getMemInfo(&meminfo); err == nil {
  292. for j := 0; j < unix.SK_MEMINFO_VARS; j++ {
  293. gauges[j].Update(int64(meminfo[j]))
  294. }
  295. }
  296. }
  297. }
  298. }