receiving.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. package kcp
  2. import (
  3. "io"
  4. "sync"
  5. "time"
  6. "github.com/v2ray/v2ray-core/common/alloc"
  7. )
  8. type ReceivingWindow struct {
  9. start uint32
  10. size uint32
  11. list []*DataSegment
  12. }
  13. func NewReceivingWindow(size uint32) *ReceivingWindow {
  14. return &ReceivingWindow{
  15. start: 0,
  16. size: size,
  17. list: make([]*DataSegment, size),
  18. }
  19. }
  20. func (this *ReceivingWindow) Size() uint32 {
  21. return this.size
  22. }
  23. func (this *ReceivingWindow) Position(idx uint32) uint32 {
  24. return (idx + this.start) % this.size
  25. }
  26. func (this *ReceivingWindow) Set(idx uint32, value *DataSegment) bool {
  27. pos := this.Position(idx)
  28. if this.list[pos] != nil {
  29. return false
  30. }
  31. this.list[pos] = value
  32. return true
  33. }
  34. func (this *ReceivingWindow) Remove(idx uint32) *DataSegment {
  35. pos := this.Position(idx)
  36. e := this.list[pos]
  37. this.list[pos] = nil
  38. return e
  39. }
  40. func (this *ReceivingWindow) RemoveFirst() *DataSegment {
  41. return this.Remove(0)
  42. }
  43. func (this *ReceivingWindow) Advance() {
  44. this.start++
  45. if this.start == this.size {
  46. this.start = 0
  47. }
  48. }
  49. type ReceivingQueue struct {
  50. sync.Mutex
  51. closed bool
  52. cache *alloc.Buffer
  53. queue chan *alloc.Buffer
  54. timeout time.Time
  55. }
  56. func NewReceivingQueue(size uint32) *ReceivingQueue {
  57. return &ReceivingQueue{
  58. queue: make(chan *alloc.Buffer, size),
  59. }
  60. }
  61. func (this *ReceivingQueue) Read(buf []byte) (int, error) {
  62. if this.closed {
  63. return 0, io.EOF
  64. }
  65. if this.cache.Len() > 0 {
  66. nBytes, err := this.cache.Read(buf)
  67. if this.cache.IsEmpty() {
  68. this.cache.Release()
  69. this.cache = nil
  70. }
  71. return nBytes, err
  72. }
  73. var totalBytes int
  74. L:
  75. for totalBytes < len(buf) {
  76. timeToSleep := time.Millisecond
  77. select {
  78. case payload, open := <-this.queue:
  79. if !open {
  80. return totalBytes, io.EOF
  81. }
  82. nBytes, err := payload.Read(buf)
  83. totalBytes += nBytes
  84. if err != nil {
  85. return totalBytes, err
  86. }
  87. if !payload.IsEmpty() {
  88. this.cache = payload
  89. }
  90. buf = buf[nBytes:]
  91. case <-time.After(timeToSleep):
  92. if totalBytes > 0 {
  93. break L
  94. }
  95. if !this.timeout.IsZero() && this.timeout.Before(time.Now()) {
  96. return totalBytes, errTimeout
  97. }
  98. timeToSleep += 500 * time.Millisecond
  99. }
  100. }
  101. return totalBytes, nil
  102. }
  103. func (this *ReceivingQueue) Put(payload *alloc.Buffer) bool {
  104. this.Lock()
  105. defer this.Unlock()
  106. if this.closed {
  107. payload.Release()
  108. return false
  109. }
  110. select {
  111. case this.queue <- payload:
  112. return true
  113. default:
  114. return false
  115. }
  116. }
  117. func (this *ReceivingQueue) SetReadDeadline(t time.Time) error {
  118. this.timeout = t
  119. return nil
  120. }
  121. func (this *ReceivingQueue) Close() {
  122. this.Lock()
  123. defer this.Unlock()
  124. if this.closed {
  125. return
  126. }
  127. this.closed = true
  128. close(this.queue)
  129. }
  130. type AckList struct {
  131. sync.Mutex
  132. writer SegmentWriter
  133. timestamps []uint32
  134. numbers []uint32
  135. nextFlush []uint32
  136. }
  137. func NewAckList(writer SegmentWriter) *AckList {
  138. return &AckList{
  139. writer: writer,
  140. timestamps: make([]uint32, 0, 32),
  141. numbers: make([]uint32, 0, 32),
  142. nextFlush: make([]uint32, 0, 32),
  143. }
  144. }
  145. func (this *AckList) Add(number uint32, timestamp uint32) {
  146. this.Lock()
  147. defer this.Unlock()
  148. this.timestamps = append(this.timestamps, timestamp)
  149. this.numbers = append(this.numbers, number)
  150. this.nextFlush = append(this.nextFlush, 0)
  151. }
  152. func (this *AckList) Clear(una uint32) {
  153. this.Lock()
  154. defer this.Unlock()
  155. count := 0
  156. for i := 0; i < len(this.numbers); i++ {
  157. if this.numbers[i] >= una {
  158. if i != count {
  159. this.numbers[count] = this.numbers[i]
  160. this.timestamps[count] = this.timestamps[i]
  161. this.nextFlush[count] = this.nextFlush[i]
  162. }
  163. count++
  164. }
  165. }
  166. if count < len(this.numbers) {
  167. this.numbers = this.numbers[:count]
  168. this.timestamps = this.timestamps[:count]
  169. this.nextFlush = this.nextFlush[:count]
  170. }
  171. }
  172. func (this *AckList) Flush(current uint32, rto uint32) {
  173. seg := new(AckSegment)
  174. this.Lock()
  175. for i := 0; i < len(this.numbers); i++ {
  176. if this.nextFlush[i] <= current {
  177. seg.Count++
  178. seg.NumberList = append(seg.NumberList, this.numbers[i])
  179. seg.TimestampList = append(seg.TimestampList, this.timestamps[i])
  180. this.nextFlush[i] = current + rto/2
  181. if seg.Count == 128 {
  182. break
  183. }
  184. }
  185. }
  186. this.Unlock()
  187. if seg.Count > 0 {
  188. this.writer.Write(seg)
  189. }
  190. }
  191. type ReceivingWorker struct {
  192. kcp *KCP
  193. queue *ReceivingQueue
  194. window *ReceivingWindow
  195. windowMutex sync.Mutex
  196. acklist *AckList
  197. updated bool
  198. nextNumber uint32
  199. windowSize uint32
  200. }
  201. func NewReceivingWorker(kcp *KCP) *ReceivingWorker {
  202. windowSize := effectiveConfig.GetReceivingWindowSize()
  203. worker := &ReceivingWorker{
  204. kcp: kcp,
  205. queue: NewReceivingQueue(effectiveConfig.GetReceivingQueueSize()),
  206. window: NewReceivingWindow(windowSize),
  207. windowSize: windowSize,
  208. }
  209. worker.acklist = NewAckList(worker)
  210. return worker
  211. }
  212. func (this *ReceivingWorker) ProcessSendingNext(number uint32) {
  213. this.acklist.Clear(number)
  214. }
  215. func (this *ReceivingWorker) ProcessSegment(seg *DataSegment) {
  216. number := seg.Number
  217. idx := number - this.nextNumber
  218. if idx >= this.windowSize {
  219. return
  220. }
  221. this.ProcessSendingNext(seg.SendingNext)
  222. this.acklist.Add(number, seg.Timestamp)
  223. this.windowMutex.Lock()
  224. defer this.windowMutex.Unlock()
  225. if !this.window.Set(idx, seg) {
  226. seg.Release()
  227. }
  228. for {
  229. seg := this.window.RemoveFirst()
  230. if seg == nil {
  231. break
  232. }
  233. if !this.queue.Put(seg.Data) {
  234. this.window.Set(0, seg)
  235. break
  236. }
  237. seg.Data = nil
  238. this.window.Advance()
  239. this.nextNumber++
  240. this.updated = true
  241. }
  242. }
  243. func (this *ReceivingWorker) Read(b []byte) (int, error) {
  244. return this.queue.Read(b)
  245. }
  246. func (this *ReceivingWorker) SetReadDeadline(t time.Time) {
  247. this.queue.SetReadDeadline(t)
  248. }
  249. func (this *ReceivingWorker) Flush() {
  250. this.acklist.Flush(this.kcp.current, this.kcp.rx_rto)
  251. }
  252. func (this *ReceivingWorker) Write(seg Segment) {
  253. ackSeg := seg.(*AckSegment)
  254. ackSeg.Conv = this.kcp.conv
  255. ackSeg.ReceivingNext = this.nextNumber
  256. ackSeg.ReceivingWindow = this.nextNumber + this.windowSize
  257. if this.kcp.state == StateReadyToClose {
  258. ackSeg.Opt = SegmentOptionClose
  259. }
  260. this.kcp.output.Write(ackSeg)
  261. this.updated = false
  262. }
  263. func (this *ReceivingWorker) CloseRead() {
  264. this.queue.Close()
  265. }
  266. func (this *ReceivingWorker) PingNecessary() bool {
  267. return this.updated
  268. }