udp_linux.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. //go:build !android && !e2e_testing
  2. // +build !android,!e2e_testing
  3. package udp
  4. import (
  5. "encoding/binary"
  6. "fmt"
  7. "net"
  8. "syscall"
  9. "unsafe"
  10. "github.com/rcrowley/go-metrics"
  11. "github.com/sirupsen/logrus"
  12. "github.com/slackhq/nebula/config"
  13. "github.com/slackhq/nebula/firewall"
  14. "github.com/slackhq/nebula/header"
  15. "golang.org/x/sys/unix"
  16. )
  17. //TODO: make it support reload as best you can!
  18. type StdConn struct {
  19. sysFd int
  20. l *logrus.Logger
  21. batch int
  22. }
  23. var x int
  24. // From linux/sock_diag.h
  25. const (
  26. _SK_MEMINFO_RMEM_ALLOC = iota
  27. _SK_MEMINFO_RCVBUF
  28. _SK_MEMINFO_WMEM_ALLOC
  29. _SK_MEMINFO_SNDBUF
  30. _SK_MEMINFO_FWD_ALLOC
  31. _SK_MEMINFO_WMEM_QUEUED
  32. _SK_MEMINFO_OPTMEM
  33. _SK_MEMINFO_BACKLOG
  34. _SK_MEMINFO_DROPS
  35. _SK_MEMINFO_VARS
  36. )
  37. type _SK_MEMINFO [_SK_MEMINFO_VARS]uint32
  38. func NewListener(l *logrus.Logger, ip net.IP, port int, multi bool, batch int) (Conn, error) {
  39. syscall.ForkLock.RLock()
  40. fd, err := unix.Socket(unix.AF_INET6, unix.SOCK_DGRAM, unix.IPPROTO_UDP)
  41. if err == nil {
  42. unix.CloseOnExec(fd)
  43. }
  44. syscall.ForkLock.RUnlock()
  45. if err != nil {
  46. unix.Close(fd)
  47. return nil, fmt.Errorf("unable to open socket: %s", err)
  48. }
  49. var lip [16]byte
  50. copy(lip[:], ip.To16())
  51. if multi {
  52. if err = unix.SetsockoptInt(fd, unix.SOL_SOCKET, unix.SO_REUSEPORT, 1); err != nil {
  53. return nil, fmt.Errorf("unable to set SO_REUSEPORT: %s", err)
  54. }
  55. }
  56. //TODO: support multiple listening IPs (for limiting ipv6)
  57. if err = unix.Bind(fd, &unix.SockaddrInet6{Addr: lip, Port: port}); err != nil {
  58. return nil, fmt.Errorf("unable to bind to socket: %s", err)
  59. }
  60. //TODO: this may be useful for forcing threads into specific cores
  61. //unix.SetsockoptInt(fd, unix.SOL_SOCKET, unix.SO_INCOMING_CPU, x)
  62. //v, err := unix.GetsockoptInt(fd, unix.SOL_SOCKET, unix.SO_INCOMING_CPU)
  63. //l.Println(v, err)
  64. return &StdConn{sysFd: fd, l: l, batch: batch}, err
  65. }
  66. func (u *StdConn) Rebind() error {
  67. return nil
  68. }
  69. func (u *StdConn) SetRecvBuffer(n int) error {
  70. return unix.SetsockoptInt(u.sysFd, unix.SOL_SOCKET, unix.SO_RCVBUFFORCE, n)
  71. }
  72. func (u *StdConn) SetSendBuffer(n int) error {
  73. return unix.SetsockoptInt(u.sysFd, unix.SOL_SOCKET, unix.SO_SNDBUFFORCE, n)
  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) LocalAddr() (*Addr, error) {
  82. sa, err := unix.Getsockname(u.sysFd)
  83. if err != nil {
  84. return nil, err
  85. }
  86. addr := &Addr{}
  87. switch sa := sa.(type) {
  88. case *unix.SockaddrInet4:
  89. addr.IP = net.IP{sa.Addr[0], sa.Addr[1], sa.Addr[2], sa.Addr[3]}.To16()
  90. addr.Port = uint16(sa.Port)
  91. case *unix.SockaddrInet6:
  92. addr.IP = sa.Addr[0:]
  93. addr.Port = uint16(sa.Port)
  94. }
  95. return addr, nil
  96. }
  97. func (u *StdConn) ListenOut(r EncReader, lhf LightHouseHandlerFunc, cache *firewall.ConntrackCacheTicker, q int) {
  98. plaintext := make([]byte, MTU)
  99. h := &header.H{}
  100. fwPacket := &firewall.Packet{}
  101. udpAddr := &Addr{}
  102. nb := make([]byte, 12, 12)
  103. //TODO: should we track this?
  104. //metric := metrics.GetOrRegisterHistogram("test.batch_read", nil, metrics.NewExpDecaySample(1028, 0.015))
  105. msgs, buffers, names := u.PrepareRawMessages(u.batch)
  106. read := u.ReadMulti
  107. if u.batch == 1 {
  108. read = u.ReadSingle
  109. }
  110. for {
  111. n, err := read(msgs)
  112. if err != nil {
  113. u.l.WithError(err).Debug("udp socket is closed, exiting read loop")
  114. return
  115. }
  116. //metric.Update(int64(n))
  117. for i := 0; i < n; i++ {
  118. udpAddr.IP = names[i][8:24]
  119. udpAddr.Port = binary.BigEndian.Uint16(names[i][2:4])
  120. r(udpAddr, plaintext[:0], buffers[i][:msgs[i].Len], h, fwPacket, lhf, nb, q, cache.Get(u.l))
  121. }
  122. }
  123. }
  124. func (u *StdConn) ReadSingle(msgs []rawMessage) (int, error) {
  125. for {
  126. n, _, err := unix.Syscall6(
  127. unix.SYS_RECVMSG,
  128. uintptr(u.sysFd),
  129. uintptr(unsafe.Pointer(&(msgs[0].Hdr))),
  130. 0,
  131. 0,
  132. 0,
  133. 0,
  134. )
  135. if err != 0 {
  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. return 0, &net.OpError{Op: "recvmmsg", Err: err}
  155. }
  156. return int(n), nil
  157. }
  158. }
  159. func (u *StdConn) WriteTo(b []byte, addr *Addr) error {
  160. var rsa unix.RawSockaddrInet6
  161. rsa.Family = unix.AF_INET6
  162. p := (*[2]byte)(unsafe.Pointer(&rsa.Port))
  163. p[0] = byte(addr.Port >> 8)
  164. p[1] = byte(addr.Port)
  165. copy(rsa.Addr[:], addr.IP)
  166. for {
  167. _, _, err := unix.Syscall6(
  168. unix.SYS_SENDTO,
  169. uintptr(u.sysFd),
  170. uintptr(unsafe.Pointer(&b[0])),
  171. uintptr(len(b)),
  172. uintptr(0),
  173. uintptr(unsafe.Pointer(&rsa)),
  174. uintptr(unix.SizeofSockaddrInet6),
  175. )
  176. if err != 0 {
  177. return &net.OpError{Op: "sendto", Err: err}
  178. }
  179. //TODO: handle incomplete writes
  180. return nil
  181. }
  182. }
  183. func (u *StdConn) ReloadConfig(c *config.C) {
  184. b := c.GetInt("listen.read_buffer", 0)
  185. if b > 0 {
  186. err := u.SetRecvBuffer(b)
  187. if err == nil {
  188. s, err := u.GetRecvBuffer()
  189. if err == nil {
  190. u.l.WithField("size", s).Info("listen.read_buffer was set")
  191. } else {
  192. u.l.WithError(err).Warn("Failed to get listen.read_buffer")
  193. }
  194. } else {
  195. u.l.WithError(err).Error("Failed to set listen.read_buffer")
  196. }
  197. }
  198. b = c.GetInt("listen.write_buffer", 0)
  199. if b > 0 {
  200. err := u.SetSendBuffer(b)
  201. if err == nil {
  202. s, err := u.GetSendBuffer()
  203. if err == nil {
  204. u.l.WithField("size", s).Info("listen.write_buffer was set")
  205. } else {
  206. u.l.WithError(err).Warn("Failed to get listen.write_buffer")
  207. }
  208. } else {
  209. u.l.WithError(err).Error("Failed to set listen.write_buffer")
  210. }
  211. }
  212. }
  213. func (u *StdConn) getMemInfo(meminfo *_SK_MEMINFO) error {
  214. var vallen uint32 = 4 * _SK_MEMINFO_VARS
  215. _, _, 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)
  216. if err != 0 {
  217. return err
  218. }
  219. return nil
  220. }
  221. func (u *StdConn) Close() error {
  222. //TODO: this will not interrupt the read loop
  223. return syscall.Close(u.sysFd)
  224. }
  225. func NewUDPStatsEmitter(udpConns []Conn) func() {
  226. // Check if our kernel supports SO_MEMINFO before registering the gauges
  227. var udpGauges [][_SK_MEMINFO_VARS]metrics.Gauge
  228. var meminfo _SK_MEMINFO
  229. if err := udpConns[0].(*StdConn).getMemInfo(&meminfo); err == nil {
  230. udpGauges = make([][_SK_MEMINFO_VARS]metrics.Gauge, len(udpConns))
  231. for i := range udpConns {
  232. udpGauges[i] = [_SK_MEMINFO_VARS]metrics.Gauge{
  233. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.rmem_alloc", i), nil),
  234. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.rcvbuf", i), nil),
  235. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.wmem_alloc", i), nil),
  236. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.sndbuf", i), nil),
  237. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.fwd_alloc", i), nil),
  238. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.wmem_queued", i), nil),
  239. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.optmem", i), nil),
  240. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.backlog", i), nil),
  241. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.drops", i), nil),
  242. }
  243. }
  244. }
  245. return func() {
  246. for i, gauges := range udpGauges {
  247. if err := udpConns[i].(*StdConn).getMemInfo(&meminfo); err == nil {
  248. for j := 0; j < _SK_MEMINFO_VARS; j++ {
  249. gauges[j].Update(int64(meminfo[j]))
  250. }
  251. }
  252. }
  253. }
  254. }