receive_stream.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. package quic
  2. import (
  3. "fmt"
  4. "io"
  5. "sync"
  6. "time"
  7. "github.com/Psiphon-Labs/quic-go/internal/flowcontrol"
  8. "github.com/Psiphon-Labs/quic-go/internal/protocol"
  9. "github.com/Psiphon-Labs/quic-go/internal/qerr"
  10. "github.com/Psiphon-Labs/quic-go/internal/utils"
  11. "github.com/Psiphon-Labs/quic-go/internal/wire"
  12. )
  13. type receiveStreamI interface {
  14. ReceiveStream
  15. handleStreamFrame(*wire.StreamFrame) error
  16. handleResetStreamFrame(*wire.ResetStreamFrame) error
  17. closeForShutdown(error)
  18. getWindowUpdate() protocol.ByteCount
  19. }
  20. type receiveStream struct {
  21. mutex sync.Mutex
  22. streamID protocol.StreamID
  23. sender streamSender
  24. frameQueue *frameSorter
  25. finalOffset protocol.ByteCount
  26. currentFrame []byte
  27. currentFrameDone func()
  28. currentFrameIsLast bool // is the currentFrame the last frame on this stream
  29. readPosInFrame int
  30. closeForShutdownErr error
  31. cancelReadErr error
  32. resetRemotelyErr *StreamError
  33. closedForShutdown bool // set when CloseForShutdown() is called
  34. finRead bool // set once we read a frame with a Fin
  35. canceledRead bool // set when CancelRead() is called
  36. resetRemotely bool // set when handleResetStreamFrame() is called
  37. readChan chan struct{}
  38. readOnce chan struct{} // cap: 1, to protect against concurrent use of Read
  39. deadline time.Time
  40. flowController flowcontrol.StreamFlowController
  41. }
  42. var (
  43. _ ReceiveStream = &receiveStream{}
  44. _ receiveStreamI = &receiveStream{}
  45. )
  46. func newReceiveStream(
  47. streamID protocol.StreamID,
  48. sender streamSender,
  49. flowController flowcontrol.StreamFlowController,
  50. ) *receiveStream {
  51. return &receiveStream{
  52. streamID: streamID,
  53. sender: sender,
  54. flowController: flowController,
  55. frameQueue: newFrameSorter(),
  56. readChan: make(chan struct{}, 1),
  57. readOnce: make(chan struct{}, 1),
  58. finalOffset: protocol.MaxByteCount,
  59. }
  60. }
  61. func (s *receiveStream) StreamID() protocol.StreamID {
  62. return s.streamID
  63. }
  64. // Read implements io.Reader. It is not thread safe!
  65. func (s *receiveStream) Read(p []byte) (int, error) {
  66. // Concurrent use of Read is not permitted (and doesn't make any sense),
  67. // but sometimes people do it anyway.
  68. // Make sure that we only execute one call at any given time to avoid hard to debug failures.
  69. s.readOnce <- struct{}{}
  70. defer func() { <-s.readOnce }()
  71. s.mutex.Lock()
  72. completed, n, err := s.readImpl(p)
  73. s.mutex.Unlock()
  74. if completed {
  75. s.sender.onStreamCompleted(s.streamID)
  76. }
  77. return n, err
  78. }
  79. func (s *receiveStream) readImpl(p []byte) (bool /*stream completed */, int, error) {
  80. if s.finRead {
  81. return false, 0, io.EOF
  82. }
  83. if s.canceledRead {
  84. return false, 0, s.cancelReadErr
  85. }
  86. if s.resetRemotely {
  87. return false, 0, s.resetRemotelyErr
  88. }
  89. if s.closedForShutdown {
  90. return false, 0, s.closeForShutdownErr
  91. }
  92. var bytesRead int
  93. var deadlineTimer *utils.Timer
  94. for bytesRead < len(p) {
  95. if s.currentFrame == nil || s.readPosInFrame >= len(s.currentFrame) {
  96. s.dequeueNextFrame()
  97. }
  98. if s.currentFrame == nil && bytesRead > 0 {
  99. return false, bytesRead, s.closeForShutdownErr
  100. }
  101. for {
  102. // Stop waiting on errors
  103. if s.closedForShutdown {
  104. return false, bytesRead, s.closeForShutdownErr
  105. }
  106. if s.canceledRead {
  107. return false, bytesRead, s.cancelReadErr
  108. }
  109. if s.resetRemotely {
  110. return false, bytesRead, s.resetRemotelyErr
  111. }
  112. deadline := s.deadline
  113. if !deadline.IsZero() {
  114. if !time.Now().Before(deadline) {
  115. return false, bytesRead, errDeadline
  116. }
  117. if deadlineTimer == nil {
  118. deadlineTimer = utils.NewTimer()
  119. defer deadlineTimer.Stop()
  120. }
  121. deadlineTimer.Reset(deadline)
  122. }
  123. if s.currentFrame != nil || s.currentFrameIsLast {
  124. break
  125. }
  126. s.mutex.Unlock()
  127. if deadline.IsZero() {
  128. <-s.readChan
  129. } else {
  130. select {
  131. case <-s.readChan:
  132. case <-deadlineTimer.Chan():
  133. deadlineTimer.SetRead()
  134. }
  135. }
  136. s.mutex.Lock()
  137. if s.currentFrame == nil {
  138. s.dequeueNextFrame()
  139. }
  140. }
  141. if bytesRead > len(p) {
  142. return false, bytesRead, fmt.Errorf("BUG: bytesRead (%d) > len(p) (%d) in stream.Read", bytesRead, len(p))
  143. }
  144. if s.readPosInFrame > len(s.currentFrame) {
  145. return false, bytesRead, fmt.Errorf("BUG: readPosInFrame (%d) > frame.DataLen (%d) in stream.Read", s.readPosInFrame, len(s.currentFrame))
  146. }
  147. m := copy(p[bytesRead:], s.currentFrame[s.readPosInFrame:])
  148. s.readPosInFrame += m
  149. bytesRead += m
  150. // when a RESET_STREAM was received, the was already informed about the final byteOffset for this stream
  151. if !s.resetRemotely {
  152. s.flowController.AddBytesRead(protocol.ByteCount(m))
  153. }
  154. if s.readPosInFrame >= len(s.currentFrame) && s.currentFrameIsLast {
  155. s.finRead = true
  156. return true, bytesRead, io.EOF
  157. }
  158. }
  159. return false, bytesRead, nil
  160. }
  161. func (s *receiveStream) dequeueNextFrame() {
  162. var offset protocol.ByteCount
  163. // We're done with the last frame. Release the buffer.
  164. if s.currentFrameDone != nil {
  165. s.currentFrameDone()
  166. }
  167. offset, s.currentFrame, s.currentFrameDone = s.frameQueue.Pop()
  168. s.currentFrameIsLast = offset+protocol.ByteCount(len(s.currentFrame)) >= s.finalOffset
  169. s.readPosInFrame = 0
  170. }
  171. func (s *receiveStream) CancelRead(errorCode StreamErrorCode) {
  172. s.mutex.Lock()
  173. completed := s.cancelReadImpl(errorCode)
  174. s.mutex.Unlock()
  175. if completed {
  176. s.flowController.Abandon()
  177. s.sender.onStreamCompleted(s.streamID)
  178. }
  179. }
  180. func (s *receiveStream) cancelReadImpl(errorCode qerr.StreamErrorCode) bool /* completed */ {
  181. if s.finRead || s.canceledRead || s.resetRemotely {
  182. return false
  183. }
  184. s.canceledRead = true
  185. s.cancelReadErr = &StreamError{StreamID: s.streamID, ErrorCode: errorCode, Remote: false}
  186. s.signalRead()
  187. s.sender.queueControlFrame(&wire.StopSendingFrame{
  188. StreamID: s.streamID,
  189. ErrorCode: errorCode,
  190. })
  191. // We're done with this stream if the final offset was already received.
  192. return s.finalOffset != protocol.MaxByteCount
  193. }
  194. func (s *receiveStream) handleStreamFrame(frame *wire.StreamFrame) error {
  195. s.mutex.Lock()
  196. completed, err := s.handleStreamFrameImpl(frame)
  197. s.mutex.Unlock()
  198. if completed {
  199. s.flowController.Abandon()
  200. s.sender.onStreamCompleted(s.streamID)
  201. }
  202. return err
  203. }
  204. func (s *receiveStream) handleStreamFrameImpl(frame *wire.StreamFrame) (bool /* completed */, error) {
  205. maxOffset := frame.Offset + frame.DataLen()
  206. if err := s.flowController.UpdateHighestReceived(maxOffset, frame.Fin); err != nil {
  207. return false, err
  208. }
  209. var newlyRcvdFinalOffset bool
  210. if frame.Fin {
  211. newlyRcvdFinalOffset = s.finalOffset == protocol.MaxByteCount
  212. s.finalOffset = maxOffset
  213. }
  214. if s.canceledRead {
  215. return newlyRcvdFinalOffset, nil
  216. }
  217. if err := s.frameQueue.Push(frame.Data, frame.Offset, frame.PutBack); err != nil {
  218. return false, err
  219. }
  220. s.signalRead()
  221. return false, nil
  222. }
  223. func (s *receiveStream) handleResetStreamFrame(frame *wire.ResetStreamFrame) error {
  224. s.mutex.Lock()
  225. completed, err := s.handleResetStreamFrameImpl(frame)
  226. s.mutex.Unlock()
  227. if completed {
  228. s.flowController.Abandon()
  229. s.sender.onStreamCompleted(s.streamID)
  230. }
  231. return err
  232. }
  233. func (s *receiveStream) handleResetStreamFrameImpl(frame *wire.ResetStreamFrame) (bool /*completed */, error) {
  234. if s.closedForShutdown {
  235. return false, nil
  236. }
  237. if err := s.flowController.UpdateHighestReceived(frame.FinalSize, true); err != nil {
  238. return false, err
  239. }
  240. newlyRcvdFinalOffset := s.finalOffset == protocol.MaxByteCount
  241. s.finalOffset = frame.FinalSize
  242. // ignore duplicate RESET_STREAM frames for this stream (after checking their final offset)
  243. if s.resetRemotely {
  244. return false, nil
  245. }
  246. s.resetRemotely = true
  247. s.resetRemotelyErr = &StreamError{
  248. StreamID: s.streamID,
  249. ErrorCode: frame.ErrorCode,
  250. Remote: true,
  251. }
  252. s.signalRead()
  253. return newlyRcvdFinalOffset, nil
  254. }
  255. func (s *receiveStream) CloseRemote(offset protocol.ByteCount) {
  256. s.handleStreamFrame(&wire.StreamFrame{Fin: true, Offset: offset})
  257. }
  258. func (s *receiveStream) SetReadDeadline(t time.Time) error {
  259. s.mutex.Lock()
  260. s.deadline = t
  261. s.mutex.Unlock()
  262. s.signalRead()
  263. return nil
  264. }
  265. // CloseForShutdown closes a stream abruptly.
  266. // It makes Read unblock (and return the error) immediately.
  267. // The peer will NOT be informed about this: the stream is closed without sending a FIN or RESET.
  268. func (s *receiveStream) closeForShutdown(err error) {
  269. s.mutex.Lock()
  270. s.closedForShutdown = true
  271. s.closeForShutdownErr = err
  272. s.mutex.Unlock()
  273. s.signalRead()
  274. }
  275. func (s *receiveStream) getWindowUpdate() protocol.ByteCount {
  276. return s.flowController.GetWindowUpdate()
  277. }
  278. // signalRead performs a non-blocking send on the readChan
  279. func (s *receiveStream) signalRead() {
  280. select {
  281. case s.readChan <- struct{}{}:
  282. default:
  283. }
  284. }