udp_linux.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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. port := ip.Port()
  189. // Little Endian -> Network Endian
  190. rsa.Port = (port >> 8) | ((port & 0xff) << 8)
  191. for {
  192. _, _, err := unix.Syscall6(
  193. unix.SYS_SENDTO,
  194. uintptr(u.sysFd),
  195. uintptr(unsafe.Pointer(&b[0])),
  196. uintptr(len(b)),
  197. uintptr(0),
  198. uintptr(unsafe.Pointer(&rsa)),
  199. uintptr(unix.SizeofSockaddrInet6),
  200. )
  201. if err != 0 {
  202. return &net.OpError{Op: "sendto", Err: err}
  203. }
  204. //TODO: handle incomplete writes
  205. return nil
  206. }
  207. }
  208. func (u *StdConn) writeTo4(b []byte, ip netip.AddrPort) error {
  209. if !ip.Addr().Is4() {
  210. return fmt.Errorf("Listener is IPv4, but writing to IPv6 remote")
  211. }
  212. var rsa unix.RawSockaddrInet4
  213. rsa.Family = unix.AF_INET
  214. rsa.Addr = ip.Addr().As4()
  215. port := ip.Port()
  216. // Little Endian -> Network Endian
  217. rsa.Port = (port >> 8) | ((port & 0xff) << 8)
  218. for {
  219. _, _, err := unix.Syscall6(
  220. unix.SYS_SENDTO,
  221. uintptr(u.sysFd),
  222. uintptr(unsafe.Pointer(&b[0])),
  223. uintptr(len(b)),
  224. uintptr(0),
  225. uintptr(unsafe.Pointer(&rsa)),
  226. uintptr(unix.SizeofSockaddrInet4),
  227. )
  228. if err != 0 {
  229. return &net.OpError{Op: "sendto", Err: err}
  230. }
  231. //TODO: handle incomplete writes
  232. return nil
  233. }
  234. }
  235. func (u *StdConn) ReloadConfig(c *config.C) {
  236. b := c.GetInt("listen.read_buffer", 0)
  237. if b > 0 {
  238. err := u.SetRecvBuffer(b)
  239. if err == nil {
  240. s, err := u.GetRecvBuffer()
  241. if err == nil {
  242. u.l.WithField("size", s).Info("listen.read_buffer was set")
  243. } else {
  244. u.l.WithError(err).Warn("Failed to get listen.read_buffer")
  245. }
  246. } else {
  247. u.l.WithError(err).Error("Failed to set listen.read_buffer")
  248. }
  249. }
  250. b = c.GetInt("listen.write_buffer", 0)
  251. if b > 0 {
  252. err := u.SetSendBuffer(b)
  253. if err == nil {
  254. s, err := u.GetSendBuffer()
  255. if err == nil {
  256. u.l.WithField("size", s).Info("listen.write_buffer was set")
  257. } else {
  258. u.l.WithError(err).Warn("Failed to get listen.write_buffer")
  259. }
  260. } else {
  261. u.l.WithError(err).Error("Failed to set listen.write_buffer")
  262. }
  263. }
  264. }
  265. func (u *StdConn) getMemInfo(meminfo *[unix.SK_MEMINFO_VARS]uint32) error {
  266. var vallen uint32 = 4 * unix.SK_MEMINFO_VARS
  267. _, _, 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)
  268. if err != 0 {
  269. return err
  270. }
  271. return nil
  272. }
  273. func (u *StdConn) Close() error {
  274. //TODO: this will not interrupt the read loop
  275. return syscall.Close(u.sysFd)
  276. }
  277. func NewUDPStatsEmitter(udpConns []Conn) func() {
  278. // Check if our kernel supports SO_MEMINFO before registering the gauges
  279. var udpGauges [][unix.SK_MEMINFO_VARS]metrics.Gauge
  280. var meminfo [unix.SK_MEMINFO_VARS]uint32
  281. if err := udpConns[0].(*StdConn).getMemInfo(&meminfo); err == nil {
  282. udpGauges = make([][unix.SK_MEMINFO_VARS]metrics.Gauge, len(udpConns))
  283. for i := range udpConns {
  284. udpGauges[i] = [unix.SK_MEMINFO_VARS]metrics.Gauge{
  285. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.rmem_alloc", i), nil),
  286. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.rcvbuf", i), nil),
  287. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.wmem_alloc", i), nil),
  288. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.sndbuf", i), nil),
  289. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.fwd_alloc", i), nil),
  290. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.wmem_queued", i), nil),
  291. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.optmem", i), nil),
  292. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.backlog", i), nil),
  293. metrics.GetOrRegisterGauge(fmt.Sprintf("udp.%d.drops", i), nil),
  294. }
  295. }
  296. }
  297. return func() {
  298. for i, gauges := range udpGauges {
  299. if err := udpConns[i].(*StdConn).getMemInfo(&meminfo); err == nil {
  300. for j := 0; j < unix.SK_MEMINFO_VARS; j++ {
  301. gauges[j].Update(int64(meminfo[j]))
  302. }
  303. }
  304. }
  305. }
  306. }