receiving.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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 := NewAckSegment()
  174. this.Lock()
  175. for i := 0; i < len(this.numbers) && !seg.IsFull(); i++ {
  176. if this.nextFlush[i] <= current {
  177. seg.PutNumber(this.numbers[i], this.timestamps[i])
  178. this.nextFlush[i] = current + rto/2
  179. }
  180. }
  181. this.Unlock()
  182. if seg.Count > 0 {
  183. this.writer.Write(seg)
  184. }
  185. }
  186. type ReceivingWorker struct {
  187. kcp *KCP
  188. queue *ReceivingQueue
  189. window *ReceivingWindow
  190. windowMutex sync.Mutex
  191. acklist *AckList
  192. updated bool
  193. nextNumber uint32
  194. windowSize uint32
  195. }
  196. func NewReceivingWorker(kcp *KCP) *ReceivingWorker {
  197. windowSize := effectiveConfig.GetReceivingWindowSize()
  198. worker := &ReceivingWorker{
  199. kcp: kcp,
  200. queue: NewReceivingQueue(effectiveConfig.GetReceivingQueueSize()),
  201. window: NewReceivingWindow(windowSize),
  202. windowSize: windowSize,
  203. }
  204. worker.acklist = NewAckList(worker)
  205. return worker
  206. }
  207. func (this *ReceivingWorker) ProcessSendingNext(number uint32) {
  208. this.acklist.Clear(number)
  209. }
  210. func (this *ReceivingWorker) ProcessSegment(seg *DataSegment) {
  211. number := seg.Number
  212. idx := number - this.nextNumber
  213. if idx >= this.windowSize {
  214. return
  215. }
  216. this.ProcessSendingNext(seg.SendingNext)
  217. this.acklist.Add(number, seg.Timestamp)
  218. this.windowMutex.Lock()
  219. defer this.windowMutex.Unlock()
  220. if !this.window.Set(idx, seg) {
  221. seg.Release()
  222. }
  223. for {
  224. seg := this.window.RemoveFirst()
  225. if seg == nil {
  226. break
  227. }
  228. if !this.queue.Put(seg.Data) {
  229. this.window.Set(0, seg)
  230. break
  231. }
  232. seg.Data = nil
  233. this.window.Advance()
  234. this.nextNumber++
  235. this.updated = true
  236. }
  237. }
  238. func (this *ReceivingWorker) Read(b []byte) (int, error) {
  239. return this.queue.Read(b)
  240. }
  241. func (this *ReceivingWorker) SetReadDeadline(t time.Time) {
  242. this.queue.SetReadDeadline(t)
  243. }
  244. func (this *ReceivingWorker) Flush() {
  245. this.acklist.Flush(this.kcp.current, this.kcp.rx_rto)
  246. }
  247. func (this *ReceivingWorker) Write(seg Segment) {
  248. ackSeg := seg.(*AckSegment)
  249. ackSeg.Conv = this.kcp.conv
  250. ackSeg.ReceivingNext = this.nextNumber
  251. ackSeg.ReceivingWindow = this.nextNumber + this.windowSize
  252. if this.kcp.state == StateReadyToClose {
  253. ackSeg.Opt = SegmentOptionClose
  254. }
  255. this.kcp.output.Write(ackSeg)
  256. this.updated = false
  257. }
  258. func (this *ReceivingWorker) CloseRead() {
  259. this.queue.Close()
  260. }
  261. func (this *ReceivingWorker) PingNecessary() bool {
  262. return this.updated
  263. }