receiving.go 6.1 KB

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