receive_stream.go 8.4 KB

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