flow_rx.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. package nebula
  2. import (
  3. "encoding/binary"
  4. "net/netip"
  5. "github.com/rcrowley/go-metrics"
  6. "github.com/slackhq/nebula/header"
  7. "github.com/slackhq/nebula/udp"
  8. )
  9. // handoffConn is a udp conn that can hand each received batch over. The callback returns replacement buffers with
  10. // the same count and at least the same lengths.
  11. type handoffConn interface {
  12. ListenOutHandoff(udp.EncReader, func([][]byte) [][]byte) error
  13. }
  14. const rxChunkMin = 16
  15. // rxItem is one received packet. A data packet for an established tunnel has ci set; out and err are written by
  16. // whoever decrypts it.
  17. type rxItem struct {
  18. packet []byte
  19. hostinfo *HostInfo
  20. ci *ConnectionState
  21. counter uint64
  22. via netip.AddrPort
  23. out []byte
  24. err error
  25. }
  26. // rxChunk is a contiguous run of a batch's items for one worker to decrypt.
  27. type rxChunk struct {
  28. items []rxItem
  29. done chan struct{}
  30. }
  31. func (c *rxChunk) run(nb []byte) {
  32. decryptRxItems(c.items, nb)
  33. c.done <- struct{}{}
  34. }
  35. // decryptRxItems decrypts the data packets among items in place. The replay window is left to the ordered stage, as
  36. // are packets without a tunnel and the known replays precheck marked.
  37. func decryptRxItems(items []rxItem, nb []byte) {
  38. for i := range items {
  39. it := &items[i]
  40. if it.ci == nil || it.err != nil {
  41. continue
  42. }
  43. it.out, it.err = it.ci.decryptPacket(it.counter, it.packet, nb)
  44. }
  45. }
  46. // rxBatch is one recvmmsg batch moving through the staged receive pipeline.
  47. type rxBatch struct {
  48. // items is every packet of the batch in arrival order. Data packets are decrypted by a worker; anything else is
  49. // handled whole by the writer, in its place.
  50. items []rxItem
  51. data int
  52. // bufs is the set of recvmmsg buffers the items point into, owned by the batch from handoff until it is reused.
  53. bufs [][]byte
  54. // chunks are the decrypt jobs, nChunks of them in use. With none the writer decrypts the batch itself.
  55. chunks []rxChunk
  56. nChunks int
  57. }
  58. func (b *rxBatch) reset() {
  59. clear(b.items)
  60. b.items = b.items[:0]
  61. b.data = 0
  62. for i := range b.nChunks {
  63. b.chunks[i].items = nil
  64. }
  65. b.nChunks = 0
  66. }
  67. // stagedRx is the staged receive pipeline of one udp listener. deliver and handoff run on the listener goroutine.
  68. type stagedRx struct {
  69. f *Interface
  70. q int
  71. pool *flowPool
  72. // h and hostmapCache are the listener's own. wrxc is the commit context: the writer's, or the listener's while
  73. // nothing is in flight.
  74. h *header.H
  75. hostmapCache map[uint32]*HostInfo
  76. wrxc *rxContext
  77. cur *rxBatch
  78. free []*rxBatch
  79. ordered chan *rxBatch
  80. returned chan *rxBatch
  81. inFlight int
  82. writerDone chan struct{}
  83. metricBatches metrics.Counter
  84. metricInline metrics.Counter
  85. }
  86. func newStagedRx(f *Interface, q int, wrxc *rxContext) *stagedRx {
  87. p := &stagedRx{
  88. f: f,
  89. q: q,
  90. h: &header.H{},
  91. hostmapCache: map[uint32]*HostInfo{},
  92. wrxc: wrxc,
  93. ordered: make(chan *rxBatch, f.staged.rxSlots),
  94. returned: make(chan *rxBatch, f.staged.rxSlots),
  95. writerDone: make(chan struct{}),
  96. metricBatches: metrics.GetOrRegisterCounter("flow.rx.batches", nil),
  97. metricInline: metrics.GetOrRegisterCounter("flow.rx.inline", nil),
  98. }
  99. workers := f.staged.workers
  100. p.pool = newFlowPool(workers, f.staged.rxSlots*2*workers)
  101. for range f.staged.rxSlots {
  102. // Two chunks per worker, so the writer can start committing while the workers are still on the rest
  103. b := &rxBatch{items: make([]rxItem, 0, 256), chunks: make([]rxChunk, 2*workers)}
  104. for i := range b.chunks {
  105. b.chunks[i].done = make(chan struct{}, 1)
  106. }
  107. p.free = append(p.free, b)
  108. }
  109. p.cur = p.free[len(p.free)-1]
  110. p.free = p.free[:len(p.free)-1]
  111. go p.writer()
  112. return p
  113. }
  114. // listen runs the conn's receive loop through the pipeline until it fails, then drains the pipeline. The conn hands
  115. // its buffers over, so a batch moves between stages without a copy.
  116. func (p *stagedRx) listen(li handoffConn) error {
  117. defer p.close()
  118. return li.ListenOutHandoff(p.deliver, p.handoff)
  119. }
  120. // deliver is the listener's per-packet work: classify the packet and add it to the current batch. Nothing here
  121. // decrypts or touches the tun.
  122. func (p *stagedRx) deliver(via netip.AddrPort, packet []byte) {
  123. b := p.cur
  124. it := rxItem{packet: packet, via: via}
  125. p.classify(&it)
  126. if it.ci != nil {
  127. b.data++
  128. }
  129. b.items = append(b.items, it)
  130. }
  131. // classify fills in the tunnel for a plain data packet of an established, non-relayed tunnel, leaving anything else
  132. // for the writer to handle whole. The replay pre-check waits for the end of the batch, see precheck.
  133. func (p *stagedRx) classify(it *rxItem) {
  134. f := p.f
  135. h := p.h
  136. packet := it.packet
  137. if h.Parse(packet) != nil || h.Version != header.Version || h.Type != header.Message || h.Subtype != header.MessageNone {
  138. return
  139. }
  140. if f.myVpnNetworksTable.Contains(it.via.Addr()) {
  141. return
  142. }
  143. hostinfo := f.hostMap.QueryIndexCached(h.RemoteIndex, p.hostmapCache)
  144. if hostinfo == nil || hostinfo.ConnectionState == nil {
  145. return
  146. }
  147. ci := hostinfo.ConnectionState
  148. if len(packet) < header.Len+ci.dKey.Overhead() {
  149. return
  150. }
  151. it.hostinfo, it.ci, it.counter = hostinfo, ci, h.MessageCounter
  152. }
  153. // precheck marks obvious replays before anything decrypts them, like ConnectionState.Decrypt does, taking each
  154. // tunnel's lock once per run of its packets rather than once per packet: the writer takes the same lock for its
  155. // window updates, from another core. The writer checks again when it commits. The window only moves forward in
  156. // between, so a stale check here can only let a replay through to that second check. Marked packets keep their
  157. // place: an earlier RecvError may delete their tunnel, and inline receive then replies with a RecvError rather than
  158. // dropping a replay.
  159. func (p *stagedRx) precheck(b *rxBatch) {
  160. f := p.f
  161. items := b.items
  162. for i := 0; i < len(items); {
  163. ci := items[i].ci
  164. if ci == nil {
  165. i++
  166. continue
  167. }
  168. ci.decryptLock.Lock()
  169. for ; i < len(items) && items[i].ci == ci; i++ {
  170. if ci.window.Check(f.l, items[i].counter) {
  171. continue
  172. }
  173. b.data--
  174. items[i].err = ErrAlreadySeen
  175. }
  176. ci.decryptLock.Unlock()
  177. }
  178. }
  179. // handoff ends a batch: the batch takes bufs, and the conn reads the next batch into the buffers of the next free
  180. // batch.
  181. func (p *stagedRx) handoff(bufs [][]byte) [][]byte {
  182. p.cur.bufs = bufs
  183. p.endBatch()
  184. b := p.cur
  185. if len(b.bufs) != len(bufs) || len(b.bufs[0]) < len(bufs[0]) {
  186. b.bufs = make([][]byte, len(bufs))
  187. for i := range b.bufs {
  188. b.bufs[i] = make([]byte, len(bufs[0]))
  189. }
  190. }
  191. return b.bufs
  192. }
  193. // endBatch hands the batch to the workers and the ordered writer, then takes a free batch.
  194. func (p *stagedRx) endBatch() {
  195. clear(p.hostmapCache)
  196. p.reap()
  197. b := p.cur
  198. p.precheck(b)
  199. n := len(b.items)
  200. if n == 0 {
  201. b.reset()
  202. return
  203. }
  204. if p.inFlight == 0 && n < p.f.staged.inlineBelow {
  205. // The writer is idle with nothing in flight, so the listener may commit with its context and flush the tun
  206. p.metricInline.Inc(1)
  207. p.process(b, p.wrxc)
  208. b.reset()
  209. return
  210. }
  211. parts := min(len(b.chunks), b.data/rxChunkMin)
  212. p.metricBatches.Inc(1)
  213. if parts > 0 {
  214. size := (n + parts - 1) / parts
  215. for off := 0; off < n; off += size {
  216. c := &b.chunks[b.nChunks]
  217. c.items = b.items[off:min(off+size, n)]
  218. b.nChunks++
  219. }
  220. }
  221. // The jobs go out before the batch does: once the writer has it, it may finish and reset it at any moment
  222. for i := range b.nChunks {
  223. p.pool.jobs <- &b.chunks[i]
  224. }
  225. p.inFlight++
  226. p.ordered <- b
  227. if len(p.free) == 0 {
  228. // Every batch is in flight, wait for the writer: the socket buffer absorbs the backlog meanwhile.
  229. p.release(<-p.returned)
  230. }
  231. p.cur = p.free[len(p.free)-1]
  232. p.free = p.free[:len(p.free)-1]
  233. }
  234. // reap takes back every batch the writer has finished with, without waiting.
  235. func (p *stagedRx) reap() {
  236. for {
  237. select {
  238. case b := <-p.returned:
  239. p.release(b)
  240. default:
  241. return
  242. }
  243. }
  244. }
  245. func (p *stagedRx) release(b *rxBatch) {
  246. p.inFlight--
  247. p.free = append(p.free, b)
  248. }
  249. // process is the ordered stage for one batch: decrypt whatever no worker is decrypting, commit every item in arrival
  250. // order, and flush the tun batcher.
  251. func (p *stagedRx) process(b *rxBatch, rxc *rxContext) {
  252. if b.nChunks == 0 {
  253. decryptRxItems(b.items, rxc.nb)
  254. p.commit(b.items, rxc)
  255. } else {
  256. // Commit chunk by chunk, so the commit overlaps the workers still on later chunks
  257. for i := range b.nChunks {
  258. c := &b.chunks[i]
  259. <-c.done
  260. p.commit(c.items, rxc)
  261. }
  262. }
  263. p.f.flushOutside(rxc)
  264. }
  265. // commit runs the ordered stage over items in arrival order. A non-data packet goes through readOutsidePackets in
  266. // its place, a run of data packets on one tunnel through commitRun.
  267. func (p *stagedRx) commit(items []rxItem, rxc *rxContext) {
  268. for i := 0; i < len(items); {
  269. ci := items[i].ci
  270. if ci == nil {
  271. p.f.readOutsidePackets(ViaSender{UdpAddr: items[i].via}, items[i].packet, rxc)
  272. i++
  273. continue
  274. }
  275. j := i + 1
  276. for j < len(items) && items[j].ci == ci {
  277. j++
  278. }
  279. p.commitRun(items[i:j], rxc)
  280. i = j
  281. }
  282. }
  283. // commitRun commits a run of decrypted data packets on one tunnel. The window updates go first, under one lock, then
  284. // the rest; handling a data packet never touches the window, so that is the same as one packet at a time.
  285. func (p *stagedRx) commitRun(run []rxItem, rxc *rxContext) {
  286. f := p.f
  287. ci := run[0].ci
  288. // Classification is speculative: earlier control packets may have removed this tunnel. Resolve it through the
  289. // writer's batch-local cache, exactly where inline processing would, before touching replay state.
  290. index := binary.BigEndian.Uint32(run[0].packet[4:8])
  291. hostinfo := f.hostMap.QueryIndexCached(index, rxc.hostmapCache)
  292. if hostinfo != run[0].hostinfo || hostinfo.ConnectionState != ci {
  293. if hostinfo == nil {
  294. for i := range run {
  295. f.maybeSendRecvError(run[i].via, index)
  296. }
  297. }
  298. return
  299. }
  300. ci.decryptLock.Lock()
  301. for i := range run {
  302. // A packet that failed to decrypt does not touch the window, like ConnectionState.Decrypt
  303. if run[i].err == nil && !ci.window.Update(f.l, run[i].counter) {
  304. run[i].err = ErrAlreadySeen
  305. }
  306. }
  307. ci.decryptLock.Unlock()
  308. for i := range run {
  309. it := &run[i]
  310. if f.finishOutsideDecrypt(it.hostinfo, ViaSender{UdpAddr: it.via}, it.counter, it.err) {
  311. f.handleOutsideMessagePacket(it.hostinfo, it.counter, it.out, rxc)
  312. }
  313. }
  314. }
  315. // writer is the ordered receive stage: window, firewall, coalescer and tun write, one batch at a time in arrival
  316. // order.
  317. func (p *stagedRx) writer() {
  318. defer close(p.writerDone)
  319. for b := range p.ordered {
  320. if p.f.closed.Load() {
  321. // The tun is going away, a write would only log errors. Still wait out the workers on the batch.
  322. for i := range b.nChunks {
  323. <-b.chunks[i].done
  324. }
  325. } else {
  326. p.process(b, p.wrxc)
  327. }
  328. b.reset()
  329. p.returned <- b
  330. }
  331. }
  332. // close commits anything still in flight, in order, and stops the writer and the workers.
  333. func (p *stagedRx) close() {
  334. if len(p.cur.items) > 0 {
  335. p.endBatch()
  336. }
  337. close(p.ordered)
  338. <-p.writerDone
  339. p.pool.close()
  340. }