receiving.go 6.2 KB

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