3
0

udp_linux.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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. "github.com/slackhq/nebula/firewall"
  15. "github.com/slackhq/nebula/header"
  16. "golang.org/x/sys/unix"
  17. )
  18. //TODO: make it support reload as best you can!
  19. type StdConn struct {
  20. sysFd int
  21. isV4 bool
  22. l *logrus.Logger
  23. batch int
  24. }
  25. func maybeIPV4(ip net.IP) (net.IP, bool) {
  26. ip4 := ip.To4()
  27. if ip4 != nil {
  28. return ip4, true
  29. }
  30. return ip, false
  31. }
  32. func NewListener(l *logrus.Logger, ip netip.Addr, port int, multi bool, batch int) (Conn, error) {
  33. af := unix.AF_INET6
  34. if ip.Is4() {
  35. af = unix.AF_INET
  36. }
  37. syscall.ForkLock.RLock()
  38. fd, err := unix.Socket(af, unix.SOCK_DGRAM, unix.IPPROTO_UDP)
  39. if err == nil {
  40. unix.CloseOnExec(fd)
  41. }
  42. syscall.ForkLock.RUnlock()
  43. if err != nil {
  44. unix.Close(fd)
  45. return nil, fmt.Errorf("unable to open socket: %s", err)
  46. }
  47. if multi {
  48. if err = unix.SetsockoptInt(fd, unix.SOL_SOCKET, unix.SO_REUSEPORT, 1); err != nil {
  49. return nil, fmt.Errorf("unable to set SO_REUSEPORT: %s", err)
  50. }
  51. }
  52. //TODO: support multiple listening IPs (for limiting ipv6)
  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. //TODO: this may be useful for forcing threads into specific cores
  67. //unix.SetsockoptInt(fd, unix.SOL_SOCKET, unix.SO_INCOMING_CPU, x)
  68. //v, err := unix.GetsockoptInt(fd, unix.SOL_SOCKET, unix.SO_INCOMING_CPU)
  69. //l.Println(v, err)
  70. return &StdConn{sysFd: fd, isV4: ip.Is4(), l: l, batch: batch}, err
  71. }
  72. func (u *StdConn) Rebind() error {
  73. return nil
  74. }
  75. func (u *StdConn) SetRecvBuffer(n int) error {
  76. return unix.SetsockoptInt(u.sysFd, unix.SOL_SOCKET, unix.SO_RCVBUFFORCE, n)
  77. }
  78. func (u *StdConn) SetSendBuffer(n int) error {
  79. return unix.SetsockoptInt(u.sysFd, unix.SOL_SOCKET, unix.SO_SNDBUFFORCE, n)
  80. }
  81. func (u *StdConn) GetRecvBuffer() (int, error) {
  82. return unix.GetsockoptInt(int(u.sysFd), unix.SOL_SOCKET, unix.SO_RCVBUF)
  83. }
  84. func (u *StdConn) GetSendBuffer() (int, error) {
  85. return unix.GetsockoptInt(int(u.sysFd), unix.SOL_SOCKET, unix.SO_SNDBUF)
  86. }
  87. func (u *StdConn) LocalAddr() (netip.AddrPort, error) {
  88. sa, err := unix.Getsockname(u.sysFd)
  89. if err != nil {
  90. return netip.AddrPort{}, err
  91. }
  92. switch sa := sa.(type) {
  93. case *unix.SockaddrInet4:
  94. return netip.AddrPortFrom(netip.AddrFrom4(sa.Addr), uint16(sa.Port)), nil
  95. case *unix.SockaddrInet6:
  96. return netip.AddrPortFrom(netip.AddrFrom16(sa.Addr), uint16(sa.Port)), nil
  97. default:
  98. return netip.AddrPort{}, fmt.Errorf("unsupported sock type: %T", sa)
  99. }
  100. }
  101. func (u *StdConn) ListenOut(r EncReader, lhf LightHouseHandlerFunc, cache *firewall.ConntrackCacheTicker, q int) {
  102. plaintext := make([]byte, MTU)
  103. h := &header.H{}
  104. fwPacket := &firewall.Packet{}
  105. var ip netip.Addr
  106. nb := make([]byte, 12, 12)
  107. //TODO: should we track this?
  108. //metric := metrics.GetOrRegisterHistogram("test.batch_read", nil, metrics.NewExpDecaySample(1028, 0.015))
  109. msgs, buffers, names := u.PrepareRawMessages(u.batch)
  110. read := u.ReadMulti
  111. if u.batch == 1 {
  112. read = u.ReadSingle
  113. }
  114. for {
  115. n, err := read(msgs)
  116. if err != nil {
  117. u.l.WithError(err).Debug("udp socket is closed, exiting read loop")
  118. return
  119. }
  120. //metric.Update(int64(n))
  121. for i := 0; i < n; i++ {
  122. if u.isV4 {
  123. ip, _ = netip.AddrFromSlice(names[i][4:8])
  124. //TODO: IPV6-WORK what is not ok?
  125. } else {
  126. ip, _ = netip.AddrFromSlice(names[i][8:24])
  127. //TODO: IPV6-WORK what is not ok?
  128. }
  129. r(
  130. netip.AddrPortFrom(ip.Unmap(), binary.BigEndian.Uint16(names[i][2:4])),
  131. plaintext[:0],
  132. buffers[i][:msgs[i].Len],
  133. h,
  134. fwPacket,
  135. lhf,
  136. nb,
  137. q,
  138. cache.Get(u.l),
  139. )
  140. }
  141. }
  142. }
  143. func (u *StdConn) ReadSingle(msgs []rawMessage) (int, error) {
  144. for {
  145. n, _, err := unix.Syscall6(
  146. unix.SYS_RECVMSG,
  147. uintptr(u.sysFd),
  148. uintptr(unsafe.Pointer(&(msgs[0].Hdr))),
  149. 0,
  150. 0,
  151. 0,
  152. 0,
  153. )
  154. if err != 0 {
  155. return 0, &net.OpError{Op: "recvmsg", Err: err}
  156. }
  157. msgs[0].Len = uint32(n)
  158. return 1, nil
  159. }
  160. }
  161. func (u *StdConn) ReadMulti(msgs []rawMessage) (int, error) {
  162. for {
  163. n, _, err := unix.Syscall6(
  164. unix.SYS_RECVMMSG,
  165. uintptr(u.sysFd),
  166. uintptr(unsafe.Pointer(&msgs[0])),
  167. uintptr(len(msgs)),
  168. unix.MSG_WAITFORONE,
  169. 0,
  170. 0,
  171. )
  172. if err != 0 {
  173. return 0, &net.OpError{Op: "recvmmsg", Err: err}
  174. }
  175. return int(n), nil
  176. }
  177. }
  178. func (u *StdConn) WriteTo(b []byte, ip netip.AddrPort) error {
  179. if u.isV4 {
  180. return u.writeTo4(b, ip)
  181. }
  182. return u.writeTo6(b, ip)
  183. }
  184. func (u *StdConn) writeTo6(b []byte, ip netip.AddrPort) error {
  185. var rsa unix.RawSockaddrInet6
  186. rsa.Family = unix.AF_INET6
  187. rsa.Addr = ip.Addr().As16()
  188. binary.BigEndian.PutUint16((*[2]byte)(unsafe.Pointer(&rsa.Port))[:], ip.Port())
  189. for {
  190. _, _, err := unix.Syscall6(
  191. unix.SYS_SENDTO,
  192. uintptr(u.sysFd),
  193. uintptr(unsafe.Pointer(&b[0])),
  194. uintptr(len(b)),
  195. uintptr(0),
  196. uintptr(unsafe.Pointer(&rsa)),
  197. uintptr(unix.SizeofSockaddrInet6),
  198. )
  199. if err != 0 {
  200. return &net.OpError{Op: "sendto", Err: err}
  201. }
  202. //TODO: handle incomplete writes
  203. return nil
  204. }
  205. }
  206. func (u *StdConn) writeTo4(b []byte, ip netip.AddrPort) error {
  207. if !ip.Addr().Is4() {
  208. return ErrInvalidIPv6RemoteForSocket
  209. }
  210. var rsa unix.RawSockaddrInet4
  211. rsa.Family = unix.AF_INET
  212. rsa.Addr = ip.Addr().As4()
  213. binary.BigEndian.PutUint16((*[2]byte)(unsafe.Pointer(&rsa.Port))[:], ip.Port())
  214. for {
  215. _, _, err := unix.Syscall6(
  216. unix.SYS_SENDTO,
  217. uintptr(u.sysFd),
  218. uintptr(unsafe.Pointer(&b[0])),
  219. uintptr(len(b)),
  220. uintptr(0),
  221. uintptr(unsafe.Pointer(&rsa)),
  222. uintptr(unix.SizeofSockaddrInet4),
  223. )
  224. if err != 0 {
  225. return &net.OpError{Op: "sendto", Err: err}
  226. }
  227. //TODO: handle incomplete writes
  228. return nil
  229. }
  230. }
  231. func (u *StdConn) ReloadConfig(c *config.C) {
  232. b := c.GetInt("listen.read_buffer", 0)
  233. if b > 0 {
  234. err := u.SetRecvBuffer(b)
  235. if err == nil {
  236. s, err := u.GetRecvBuffer()
  237. if err == nil {
  238. u.l.WithField("size", s).Info("listen.read_buffer was set")
  239. } else {
  240. u.l.WithError(err).Warn("Failed to get listen.read_buffer")
  241. }
  242. } else {
  243. u.l.WithError(err).Error("Failed to set listen.read_buffer")
  244. }
  245. }
  246. b = c.GetInt("listen.write_buffer", 0)
  247. if b > 0 {
  248. err := u.SetSendBuffer(b)
  249. if err == nil {
  250. s, err := u.GetSendBuffer()
  251. if err == nil {
  252. u.l.WithField("size", s).Info("listen.write_buffer was set")
  253. } else {
  254. u.l.WithError(err).Warn("Failed to get listen.write_buffer")
  255. }
  256. } else {
  257. u.l.WithError(err).Error("Failed to set listen.write_buffer")
  258. }
  259. }
  260. }
  261. func (u *StdConn) getMemInfo(meminfo *[unix.SK_MEMINFO_VARS]uint32) error {
  262. var vallen uint32 = 4 * unix.SK_MEMINFO_VARS
  263. _, _, 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)
  264. if err != 0 {
  265. return err
  266. }
  267. return nil
  268. }
  269. func (u *StdConn) Close() error {
  270. //TODO: this will not interrupt the read loop
  271. return syscall.Close(u.sysFd)
  272. }
  273. func NewUDPStatsEmitter(udpConns []Conn) func() {
  274. // Check if our kernel supports SO_MEMINFO before registering the gauges
  275. var udpGauges [][unix.SK_MEMINFO_VARS]metrics.Gauge
  276. var meminfo [unix.SK_MEMINFO_VARS]uint32
  277. if err := udpConns[0].(*StdConn).getMemInfo(&meminfo); err == nil {
  278. udpGauges = make([][unix.SK_MEMINFO_VARS]metrics.Gauge, len(udpConns))
  279. for i := range udpConns {
  280. udpGauges[i] = [unix.SK_MEMINFO_VARS]metrics.Gauge{
  281. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.rmem_alloc", i), nil),
  282. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.rcvbuf", i), nil),
  283. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.wmem_alloc", i), nil),
  284. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.sndbuf", i), nil),
  285. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.fwd_alloc", i), nil),
  286. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.wmem_queued", i), nil),
  287. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.optmem", i), nil),
  288. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.backlog", i), nil),
  289. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.drops", i), nil),
  290. }
  291. }
  292. }
  293. return func() {
  294. for i, gauges := range udpGauges {
  295. if err := udpConns[i].(*StdConn).getMemInfo(&meminfo); err == nil {
  296. for j := 0; j < unix.SK_MEMINFO_VARS; j++ {
  297. gauges[j].Update(int64(meminfo[j]))
  298. }
  299. }
  300. }
  301. }
  302. }