receiving.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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. if timeToSleep > 5*time.Second {
  100. timeToSleep = 5 * time.Second
  101. }
  102. }
  103. }
  104. return totalBytes, nil
  105. }
  106. func (this *ReceivingQueue) Put(payload *alloc.Buffer) bool {
  107. if this.closed {
  108. payload.Release()
  109. return false
  110. }
  111. select {
  112. case this.queue <- payload:
  113. return true
  114. default:
  115. return false
  116. }
  117. }
  118. func (this *ReceivingQueue) SetReadDeadline(t time.Time) error {
  119. this.timeout = t
  120. return nil
  121. }
  122. func (this *ReceivingQueue) Close() {
  123. this.Lock()
  124. defer this.Unlock()
  125. if this.closed {
  126. return
  127. }
  128. this.closed = true
  129. close(this.queue)
  130. }
  131. type AckList struct {
  132. sync.Mutex
  133. writer SegmentWriter
  134. timestamps []uint32
  135. numbers []uint32
  136. nextFlush []uint32
  137. }
  138. func NewAckList(writer SegmentWriter) *AckList {
  139. return &AckList{
  140. writer: writer,
  141. timestamps: make([]uint32, 0, 32),
  142. numbers: make([]uint32, 0, 32),
  143. nextFlush: make([]uint32, 0, 32),
  144. }
  145. }
  146. func (this *AckList) Add(number uint32, timestamp uint32) {
  147. this.Lock()
  148. defer this.Unlock()
  149. this.timestamps = append(this.timestamps, timestamp)
  150. this.numbers = append(this.numbers, number)
  151. this.nextFlush = append(this.nextFlush, 0)
  152. }
  153. func (this *AckList) Clear(una uint32) {
  154. this.Lock()
  155. defer this.Unlock()
  156. count := 0
  157. for i := 0; i < len(this.numbers); i++ {
  158. if this.numbers[i] >= una {
  159. if i != count {
  160. this.numbers[count] = this.numbers[i]
  161. this.timestamps[count] = this.timestamps[i]
  162. this.nextFlush[count] = this.nextFlush[i]
  163. }
  164. count++
  165. }
  166. }
  167. if count < len(this.numbers) {
  168. this.numbers = this.numbers[:count]
  169. this.timestamps = this.timestamps[:count]
  170. this.nextFlush = this.nextFlush[:count]
  171. }
  172. }
  173. func (this *AckList) Flush(current uint32, rto uint32) {
  174. seg := NewAckSegment()
  175. this.Lock()
  176. for i := 0; i < len(this.numbers) && !seg.IsFull(); i++ {
  177. if this.nextFlush[i] <= current {
  178. seg.PutNumber(this.numbers[i], this.timestamps[i])
  179. this.nextFlush[i] = current + rto/2
  180. }
  181. }
  182. this.Unlock()
  183. if seg.Count > 0 {
  184. this.writer.Write(seg)
  185. seg.Release()
  186. }
  187. }
  188. type ReceivingWorker struct {
  189. conn *Connection
  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 *Connection) *ReceivingWorker {
  199. windowSize := effectiveConfig.GetReceivingWindowSize()
  200. worker := &ReceivingWorker{
  201. conn: kcp,
  202. queue: NewReceivingQueue(effectiveConfig.GetReceivingQueueSize()),
  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. idx := number - this.nextNumber
  215. if idx >= this.windowSize {
  216. return
  217. }
  218. this.ProcessSendingNext(seg.SendingNext)
  219. this.acklist.Add(number, seg.Timestamp)
  220. this.windowMutex.Lock()
  221. defer this.windowMutex.Unlock()
  222. if !this.window.Set(idx, seg) {
  223. seg.Release()
  224. }
  225. for {
  226. seg := this.window.RemoveFirst()
  227. if seg == nil {
  228. break
  229. }
  230. if !this.queue.Put(seg.Data) {
  231. this.window.Set(0, seg)
  232. break
  233. }
  234. seg.Data = nil
  235. seg.Release()
  236. this.window.Advance()
  237. this.nextNumber++
  238. this.updated = true
  239. }
  240. }
  241. func (this *ReceivingWorker) Read(b []byte) (int, error) {
  242. return this.queue.Read(b)
  243. }
  244. func (this *ReceivingWorker) SetReadDeadline(t time.Time) {
  245. this.queue.SetReadDeadline(t)
  246. }
  247. func (this *ReceivingWorker) Flush(current uint32) {
  248. this.acklist.Flush(current, this.conn.rx_rto)
  249. }
  250. func (this *ReceivingWorker) Write(seg Segment) {
  251. ackSeg := seg.(*AckSegment)
  252. ackSeg.Conv = this.conn.conv
  253. ackSeg.ReceivingNext = this.nextNumber
  254. ackSeg.ReceivingWindow = this.nextNumber + this.windowSize
  255. if this.conn.state == StateReadyToClose {
  256. ackSeg.Opt = SegmentOptionClose
  257. }
  258. this.conn.output.Write(ackSeg)
  259. this.updated = false
  260. }
  261. func (this *ReceivingWorker) CloseRead() {
  262. this.queue.Close()
  263. }
  264. func (this *ReceivingWorker) PingNecessary() bool {
  265. return this.updated
  266. }