send_stream.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. package quic
  2. import (
  3. "context"
  4. "fmt"
  5. "sync"
  6. "time"
  7. "v2ray.com/core/external/github.com/lucas-clemente/quic-go/internal/flowcontrol"
  8. "v2ray.com/core/external/github.com/lucas-clemente/quic-go/internal/protocol"
  9. "v2ray.com/core/external/github.com/lucas-clemente/quic-go/internal/utils"
  10. "v2ray.com/core/external/github.com/lucas-clemente/quic-go/internal/wire"
  11. )
  12. type sendStreamI interface {
  13. SendStream
  14. handleStopSendingFrame(*wire.StopSendingFrame)
  15. hasData() bool
  16. popStreamFrame(maxBytes protocol.ByteCount) (*wire.StreamFrame, bool)
  17. closeForShutdown(error)
  18. handleMaxStreamDataFrame(*wire.MaxStreamDataFrame)
  19. }
  20. type sendStream struct {
  21. mutex sync.Mutex
  22. ctx context.Context
  23. ctxCancel context.CancelFunc
  24. streamID protocol.StreamID
  25. sender streamSender
  26. writeOffset protocol.ByteCount
  27. cancelWriteErr error
  28. closeForShutdownErr error
  29. closedForShutdown bool // set when CloseForShutdown() is called
  30. finishedWriting bool // set once Close() is called
  31. canceledWrite bool // set when CancelWrite() is called, or a STOP_SENDING frame is received
  32. finSent bool // set when a STREAM_FRAME with FIN bit has b
  33. dataForWriting []byte
  34. writeChan chan struct{}
  35. deadline time.Time
  36. flowController flowcontrol.StreamFlowController
  37. version protocol.VersionNumber
  38. }
  39. var _ SendStream = &sendStream{}
  40. var _ sendStreamI = &sendStream{}
  41. func newSendStream(
  42. streamID protocol.StreamID,
  43. sender streamSender,
  44. flowController flowcontrol.StreamFlowController,
  45. version protocol.VersionNumber,
  46. ) *sendStream {
  47. s := &sendStream{
  48. streamID: streamID,
  49. sender: sender,
  50. flowController: flowController,
  51. writeChan: make(chan struct{}, 1),
  52. version: version,
  53. }
  54. s.ctx, s.ctxCancel = context.WithCancel(context.Background())
  55. return s
  56. }
  57. func (s *sendStream) StreamID() protocol.StreamID {
  58. return s.streamID // same for receiveStream and sendStream
  59. }
  60. func (s *sendStream) Write(p []byte) (int, error) {
  61. s.mutex.Lock()
  62. defer s.mutex.Unlock()
  63. if s.finishedWriting {
  64. return 0, fmt.Errorf("write on closed stream %d", s.streamID)
  65. }
  66. if s.canceledWrite {
  67. return 0, s.cancelWriteErr
  68. }
  69. if s.closeForShutdownErr != nil {
  70. return 0, s.closeForShutdownErr
  71. }
  72. if !s.deadline.IsZero() && !time.Now().Before(s.deadline) {
  73. return 0, errDeadline
  74. }
  75. if len(p) == 0 {
  76. return 0, nil
  77. }
  78. s.dataForWriting = p
  79. var (
  80. deadlineTimer *utils.Timer
  81. bytesWritten int
  82. notifiedSender bool
  83. )
  84. for {
  85. bytesWritten = len(p) - len(s.dataForWriting)
  86. deadline := s.deadline
  87. if !deadline.IsZero() {
  88. if !time.Now().Before(deadline) {
  89. s.dataForWriting = nil
  90. return bytesWritten, errDeadline
  91. }
  92. if deadlineTimer == nil {
  93. deadlineTimer = utils.NewTimer()
  94. }
  95. deadlineTimer.Reset(deadline)
  96. }
  97. if s.dataForWriting == nil || s.canceledWrite || s.closedForShutdown {
  98. break
  99. }
  100. s.mutex.Unlock()
  101. if !notifiedSender {
  102. s.sender.onHasStreamData(s.streamID) // must be called without holding the mutex
  103. notifiedSender = true
  104. }
  105. if deadline.IsZero() {
  106. <-s.writeChan
  107. } else {
  108. select {
  109. case <-s.writeChan:
  110. case <-deadlineTimer.Chan():
  111. deadlineTimer.SetRead()
  112. }
  113. }
  114. s.mutex.Lock()
  115. }
  116. if s.closeForShutdownErr != nil {
  117. return bytesWritten, s.closeForShutdownErr
  118. } else if s.cancelWriteErr != nil {
  119. return bytesWritten, s.cancelWriteErr
  120. }
  121. return bytesWritten, nil
  122. }
  123. // popStreamFrame returns the next STREAM frame that is supposed to be sent on this stream
  124. // maxBytes is the maximum length this frame (including frame header) will have.
  125. func (s *sendStream) popStreamFrame(maxBytes protocol.ByteCount) (*wire.StreamFrame, bool /* has more data to send */) {
  126. completed, frame, hasMoreData := s.popStreamFrameImpl(maxBytes)
  127. if completed {
  128. s.sender.onStreamCompleted(s.streamID)
  129. }
  130. return frame, hasMoreData
  131. }
  132. func (s *sendStream) popStreamFrameImpl(maxBytes protocol.ByteCount) (bool /* completed */, *wire.StreamFrame, bool /* has more data to send */) {
  133. s.mutex.Lock()
  134. defer s.mutex.Unlock()
  135. if s.closeForShutdownErr != nil {
  136. return false, nil, false
  137. }
  138. frame := &wire.StreamFrame{
  139. StreamID: s.streamID,
  140. Offset: s.writeOffset,
  141. DataLenPresent: true,
  142. }
  143. maxDataLen := frame.MaxDataLen(maxBytes, s.version)
  144. if maxDataLen == 0 { // a STREAM frame must have at least one byte of data
  145. return false, nil, s.dataForWriting != nil
  146. }
  147. frame.Data, frame.FinBit = s.getDataForWriting(maxDataLen)
  148. if len(frame.Data) == 0 && !frame.FinBit {
  149. // this can happen if:
  150. // - popStreamFrame is called but there's no data for writing
  151. // - there's data for writing, but the stream is stream-level flow control blocked
  152. // - there's data for writing, but the stream is connection-level flow control blocked
  153. if s.dataForWriting == nil {
  154. return false, nil, false
  155. }
  156. if isBlocked, offset := s.flowController.IsNewlyBlocked(); isBlocked {
  157. s.sender.queueControlFrame(&wire.StreamDataBlockedFrame{
  158. StreamID: s.streamID,
  159. DataLimit: offset,
  160. })
  161. return false, nil, false
  162. }
  163. return false, nil, true
  164. }
  165. if frame.FinBit {
  166. s.finSent = true
  167. }
  168. return frame.FinBit, frame, s.dataForWriting != nil
  169. }
  170. func (s *sendStream) hasData() bool {
  171. s.mutex.Lock()
  172. hasData := len(s.dataForWriting) > 0
  173. s.mutex.Unlock()
  174. return hasData
  175. }
  176. func (s *sendStream) getDataForWriting(maxBytes protocol.ByteCount) ([]byte, bool /* should send FIN */) {
  177. if s.dataForWriting == nil {
  178. return nil, s.finishedWriting && !s.finSent
  179. }
  180. maxBytes = utils.MinByteCount(maxBytes, s.flowController.SendWindowSize())
  181. if maxBytes == 0 {
  182. return nil, false
  183. }
  184. var ret []byte
  185. if protocol.ByteCount(len(s.dataForWriting)) > maxBytes {
  186. ret = make([]byte, int(maxBytes))
  187. copy(ret, s.dataForWriting[:maxBytes])
  188. s.dataForWriting = s.dataForWriting[maxBytes:]
  189. } else {
  190. ret = make([]byte, len(s.dataForWriting))
  191. copy(ret, s.dataForWriting)
  192. s.dataForWriting = nil
  193. s.signalWrite()
  194. }
  195. s.writeOffset += protocol.ByteCount(len(ret))
  196. s.flowController.AddBytesSent(protocol.ByteCount(len(ret)))
  197. return ret, s.finishedWriting && s.dataForWriting == nil && !s.finSent
  198. }
  199. func (s *sendStream) Close() error {
  200. s.mutex.Lock()
  201. if s.canceledWrite {
  202. s.mutex.Unlock()
  203. return fmt.Errorf("Close called for canceled stream %d", s.streamID)
  204. }
  205. s.finishedWriting = true
  206. s.mutex.Unlock()
  207. s.sender.onHasStreamData(s.streamID) // need to send the FIN, must be called without holding the mutex
  208. s.ctxCancel()
  209. return nil
  210. }
  211. func (s *sendStream) CancelWrite(errorCode protocol.ApplicationErrorCode) error {
  212. s.mutex.Lock()
  213. completed, err := s.cancelWriteImpl(errorCode, fmt.Errorf("Write on stream %d canceled with error code %d", s.streamID, errorCode))
  214. s.mutex.Unlock()
  215. if completed {
  216. s.sender.onStreamCompleted(s.streamID) // must be called without holding the mutex
  217. }
  218. return err
  219. }
  220. // must be called after locking the mutex
  221. func (s *sendStream) cancelWriteImpl(errorCode protocol.ApplicationErrorCode, writeErr error) (bool /*completed */, error) {
  222. if s.canceledWrite {
  223. return false, nil
  224. }
  225. if s.finishedWriting {
  226. return false, fmt.Errorf("CancelWrite for closed stream %d", s.streamID)
  227. }
  228. s.canceledWrite = true
  229. s.cancelWriteErr = writeErr
  230. s.signalWrite()
  231. s.sender.queueControlFrame(&wire.ResetStreamFrame{
  232. StreamID: s.streamID,
  233. ByteOffset: s.writeOffset,
  234. ErrorCode: errorCode,
  235. })
  236. // TODO(#991): cancel retransmissions for this stream
  237. s.ctxCancel()
  238. return true, nil
  239. }
  240. func (s *sendStream) handleStopSendingFrame(frame *wire.StopSendingFrame) {
  241. if completed := s.handleStopSendingFrameImpl(frame); completed {
  242. s.sender.onStreamCompleted(s.streamID)
  243. }
  244. }
  245. func (s *sendStream) handleMaxStreamDataFrame(frame *wire.MaxStreamDataFrame) {
  246. s.mutex.Lock()
  247. hasStreamData := s.dataForWriting != nil
  248. s.mutex.Unlock()
  249. s.flowController.UpdateSendWindow(frame.ByteOffset)
  250. if hasStreamData {
  251. s.sender.onHasStreamData(s.streamID)
  252. }
  253. }
  254. // must be called after locking the mutex
  255. func (s *sendStream) handleStopSendingFrameImpl(frame *wire.StopSendingFrame) bool /*completed*/ {
  256. s.mutex.Lock()
  257. defer s.mutex.Unlock()
  258. writeErr := streamCanceledError{
  259. errorCode: frame.ErrorCode,
  260. error: fmt.Errorf("Stream %d was reset with error code %d", s.streamID, frame.ErrorCode),
  261. }
  262. errorCode := errorCodeStopping
  263. completed, _ := s.cancelWriteImpl(errorCode, writeErr)
  264. return completed
  265. }
  266. func (s *sendStream) Context() context.Context {
  267. return s.ctx
  268. }
  269. func (s *sendStream) SetWriteDeadline(t time.Time) error {
  270. s.mutex.Lock()
  271. s.deadline = t
  272. s.mutex.Unlock()
  273. s.signalWrite()
  274. return nil
  275. }
  276. // CloseForShutdown closes a stream abruptly.
  277. // It makes Write unblock (and return the error) immediately.
  278. // The peer will NOT be informed about this: the stream is closed without sending a FIN or RST.
  279. func (s *sendStream) closeForShutdown(err error) {
  280. s.mutex.Lock()
  281. s.closedForShutdown = true
  282. s.closeForShutdownErr = err
  283. s.mutex.Unlock()
  284. s.signalWrite()
  285. s.ctxCancel()
  286. }
  287. func (s *sendStream) getWriteOffset() protocol.ByteCount {
  288. return s.writeOffset
  289. }
  290. // signalWrite performs a non-blocking send on the writeChan
  291. func (s *sendStream) signalWrite() {
  292. select {
  293. case s.writeChan <- struct{}{}:
  294. default:
  295. }
  296. }