send_stream.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. package quic
  2. import (
  3. "context"
  4. "fmt"
  5. "sync"
  6. "time"
  7. "github.com/Psiphon-Labs/quic-go/internal/ackhandler"
  8. "github.com/Psiphon-Labs/quic-go/internal/flowcontrol"
  9. "github.com/Psiphon-Labs/quic-go/internal/protocol"
  10. "github.com/Psiphon-Labs/quic-go/internal/qerr"
  11. "github.com/Psiphon-Labs/quic-go/internal/utils"
  12. "github.com/Psiphon-Labs/quic-go/internal/wire"
  13. )
  14. type sendStreamI interface {
  15. SendStream
  16. handleStopSendingFrame(*wire.StopSendingFrame)
  17. hasData() bool
  18. popStreamFrame(protocol.ByteCount, protocol.Version) (_ ackhandler.StreamFrame, _ *wire.StreamDataBlockedFrame, hasMore bool)
  19. closeForShutdown(error)
  20. updateSendWindow(protocol.ByteCount)
  21. }
  22. type sendStream struct {
  23. mutex sync.Mutex
  24. numOutstandingFrames int64 // outstanding STREAM and RESET_STREAM frames
  25. retransmissionQueue []*wire.StreamFrame
  26. ctx context.Context
  27. ctxCancel context.CancelCauseFunc
  28. streamID protocol.StreamID
  29. sender streamSender
  30. writeOffset protocol.ByteCount
  31. // finalError is the error that is returned by Write.
  32. // It can either be a cancellation error or the shutdown error.
  33. finalError error
  34. queuedResetStreamFrame *wire.ResetStreamFrame
  35. finishedWriting bool // set once Close() is called
  36. finSent bool // set when a STREAM_FRAME with FIN bit has been sent
  37. // Set when the application knows about the cancellation.
  38. // This can happen because the application called CancelWrite,
  39. // or because Write returned the error (for remote cancellations).
  40. cancellationFlagged bool
  41. cancelled bool // both local and remote cancellations
  42. closedForShutdown bool // set by closeForShutdown
  43. completed bool // set when this stream has been reported to the streamSender as completed
  44. dataForWriting []byte // during a Write() call, this slice is the part of p that still needs to be sent out
  45. nextFrame *wire.StreamFrame
  46. writeChan chan struct{}
  47. writeOnce chan struct{}
  48. deadline time.Time
  49. flowController flowcontrol.StreamFlowController
  50. }
  51. var (
  52. _ SendStream = &sendStream{}
  53. _ sendStreamI = &sendStream{}
  54. _ streamControlFrameGetter = &sendStream{}
  55. )
  56. func newSendStream(
  57. ctx context.Context,
  58. streamID protocol.StreamID,
  59. sender streamSender,
  60. flowController flowcontrol.StreamFlowController,
  61. ) *sendStream {
  62. s := &sendStream{
  63. streamID: streamID,
  64. sender: sender,
  65. flowController: flowController,
  66. writeChan: make(chan struct{}, 1),
  67. writeOnce: make(chan struct{}, 1), // cap: 1, to protect against concurrent use of Write
  68. }
  69. s.ctx, s.ctxCancel = context.WithCancelCause(ctx)
  70. return s
  71. }
  72. func (s *sendStream) StreamID() protocol.StreamID {
  73. return s.streamID // same for receiveStream and sendStream
  74. }
  75. func (s *sendStream) Write(p []byte) (int, error) {
  76. // Concurrent use of Write is not permitted (and doesn't make any sense),
  77. // but sometimes people do it anyway.
  78. // Make sure that we only execute one call at any given time to avoid hard to debug failures.
  79. s.writeOnce <- struct{}{}
  80. defer func() { <-s.writeOnce }()
  81. isNewlyCompleted, n, err := s.write(p)
  82. if isNewlyCompleted {
  83. s.sender.onStreamCompleted(s.streamID)
  84. }
  85. return n, err
  86. }
  87. func (s *sendStream) write(p []byte) (bool /* is newly completed */, int, error) {
  88. s.mutex.Lock()
  89. defer s.mutex.Unlock()
  90. if s.finalError != nil {
  91. if s.cancelled {
  92. s.cancellationFlagged = true
  93. }
  94. return s.isNewlyCompleted(), 0, s.finalError
  95. }
  96. if s.finishedWriting {
  97. return false, 0, fmt.Errorf("write on closed stream %d", s.streamID)
  98. }
  99. if !s.deadline.IsZero() && !time.Now().Before(s.deadline) {
  100. return false, 0, errDeadline
  101. }
  102. if len(p) == 0 {
  103. return false, 0, nil
  104. }
  105. s.dataForWriting = p
  106. var (
  107. deadlineTimer *utils.Timer
  108. bytesWritten int
  109. notifiedSender bool
  110. )
  111. for {
  112. var copied bool
  113. var deadline time.Time
  114. // As soon as dataForWriting becomes smaller than a certain size x, we copy all the data to a STREAM frame (s.nextFrame),
  115. // which can then be popped the next time we assemble a packet.
  116. // This allows us to return Write() when all data but x bytes have been sent out.
  117. // When the user now calls Close(), this is much more likely to happen before we popped that last STREAM frame,
  118. // allowing us to set the FIN bit on that frame (instead of sending an empty STREAM frame with FIN).
  119. if s.canBufferStreamFrame() && len(s.dataForWriting) > 0 {
  120. if s.nextFrame == nil {
  121. f := wire.GetStreamFrame()
  122. f.Offset = s.writeOffset
  123. f.StreamID = s.streamID
  124. f.DataLenPresent = true
  125. f.Data = f.Data[:len(s.dataForWriting)]
  126. copy(f.Data, s.dataForWriting)
  127. s.nextFrame = f
  128. } else {
  129. l := len(s.nextFrame.Data)
  130. s.nextFrame.Data = s.nextFrame.Data[:l+len(s.dataForWriting)]
  131. copy(s.nextFrame.Data[l:], s.dataForWriting)
  132. }
  133. s.dataForWriting = nil
  134. bytesWritten = len(p)
  135. copied = true
  136. } else {
  137. bytesWritten = len(p) - len(s.dataForWriting)
  138. deadline = s.deadline
  139. if !deadline.IsZero() {
  140. if !time.Now().Before(deadline) {
  141. s.dataForWriting = nil
  142. return false, bytesWritten, errDeadline
  143. }
  144. if deadlineTimer == nil {
  145. deadlineTimer = utils.NewTimer()
  146. defer deadlineTimer.Stop()
  147. }
  148. deadlineTimer.Reset(deadline)
  149. }
  150. if s.dataForWriting == nil || s.finalError != nil {
  151. break
  152. }
  153. }
  154. s.mutex.Unlock()
  155. if !notifiedSender {
  156. s.sender.onHasStreamData(s.streamID, s) // must be called without holding the mutex
  157. notifiedSender = true
  158. }
  159. if copied {
  160. s.mutex.Lock()
  161. break
  162. }
  163. if deadline.IsZero() {
  164. <-s.writeChan
  165. } else {
  166. select {
  167. case <-s.writeChan:
  168. case <-deadlineTimer.Chan():
  169. deadlineTimer.SetRead()
  170. }
  171. }
  172. s.mutex.Lock()
  173. }
  174. if bytesWritten == len(p) {
  175. return false, bytesWritten, nil
  176. }
  177. if s.finalError != nil {
  178. if s.cancelled {
  179. s.cancellationFlagged = true
  180. }
  181. return s.isNewlyCompleted(), bytesWritten, s.finalError
  182. }
  183. return false, bytesWritten, nil
  184. }
  185. func (s *sendStream) canBufferStreamFrame() bool {
  186. var l protocol.ByteCount
  187. if s.nextFrame != nil {
  188. l = s.nextFrame.DataLen()
  189. }
  190. return l+protocol.ByteCount(len(s.dataForWriting)) <= protocol.MaxPacketBufferSize
  191. }
  192. // popStreamFrame returns the next STREAM frame that is supposed to be sent on this stream
  193. // maxBytes is the maximum length this frame (including frame header) will have.
  194. func (s *sendStream) popStreamFrame(maxBytes protocol.ByteCount, v protocol.Version) (_ ackhandler.StreamFrame, _ *wire.StreamDataBlockedFrame, hasMore bool) {
  195. s.mutex.Lock()
  196. f, blocked, hasMoreData := s.popNewOrRetransmittedStreamFrame(maxBytes, v)
  197. if f != nil {
  198. s.numOutstandingFrames++
  199. }
  200. s.mutex.Unlock()
  201. if f == nil {
  202. return ackhandler.StreamFrame{}, blocked, hasMoreData
  203. }
  204. return ackhandler.StreamFrame{
  205. Frame: f,
  206. Handler: (*sendStreamAckHandler)(s),
  207. }, blocked, hasMoreData
  208. }
  209. func (s *sendStream) popNewOrRetransmittedStreamFrame(maxBytes protocol.ByteCount, v protocol.Version) (_ *wire.StreamFrame, _ *wire.StreamDataBlockedFrame, hasMoreData bool) {
  210. if s.finalError != nil {
  211. return nil, nil, false
  212. }
  213. if len(s.retransmissionQueue) > 0 {
  214. f, hasMoreRetransmissions := s.maybeGetRetransmission(maxBytes, v)
  215. if f != nil || hasMoreRetransmissions {
  216. if f == nil {
  217. return nil, nil, true
  218. }
  219. // We always claim that we have more data to send.
  220. // This might be incorrect, in which case there'll be a spurious call to popStreamFrame in the future.
  221. return f, nil, true
  222. }
  223. }
  224. if len(s.dataForWriting) == 0 && s.nextFrame == nil {
  225. if s.finishedWriting && !s.finSent {
  226. s.finSent = true
  227. return &wire.StreamFrame{
  228. StreamID: s.streamID,
  229. Offset: s.writeOffset,
  230. DataLenPresent: true,
  231. Fin: true,
  232. }, nil, false
  233. }
  234. return nil, nil, false
  235. }
  236. sendWindow := s.flowController.SendWindowSize()
  237. if sendWindow == 0 {
  238. return nil, nil, true
  239. }
  240. f, hasMoreData := s.popNewStreamFrame(maxBytes, sendWindow, v)
  241. if f == nil {
  242. return nil, nil, hasMoreData
  243. }
  244. if f.DataLen() > 0 {
  245. s.writeOffset += f.DataLen()
  246. s.flowController.AddBytesSent(f.DataLen())
  247. }
  248. var blocked *wire.StreamDataBlockedFrame
  249. // If the entire send window is used, the stream might have become blocked on stream-level flow control.
  250. // This is not guaranteed though, because the stream might also have been blocked on connection-level flow control.
  251. if f.DataLen() == sendWindow && s.flowController.IsNewlyBlocked() {
  252. blocked = &wire.StreamDataBlockedFrame{StreamID: s.streamID, MaximumStreamData: s.writeOffset}
  253. }
  254. f.Fin = s.finishedWriting && s.dataForWriting == nil && s.nextFrame == nil && !s.finSent
  255. if f.Fin {
  256. s.finSent = true
  257. }
  258. return f, blocked, hasMoreData
  259. }
  260. func (s *sendStream) popNewStreamFrame(maxBytes, sendWindow protocol.ByteCount, v protocol.Version) (*wire.StreamFrame, bool) {
  261. if s.nextFrame != nil {
  262. maxDataLen := min(sendWindow, s.nextFrame.MaxDataLen(maxBytes, v))
  263. if maxDataLen == 0 {
  264. return nil, true
  265. }
  266. nextFrame := s.nextFrame
  267. s.nextFrame = nil
  268. if nextFrame.DataLen() > maxDataLen {
  269. s.nextFrame = wire.GetStreamFrame()
  270. s.nextFrame.StreamID = s.streamID
  271. s.nextFrame.Offset = s.writeOffset + maxDataLen
  272. s.nextFrame.Data = s.nextFrame.Data[:nextFrame.DataLen()-maxDataLen]
  273. s.nextFrame.DataLenPresent = true
  274. copy(s.nextFrame.Data, nextFrame.Data[maxDataLen:])
  275. nextFrame.Data = nextFrame.Data[:maxDataLen]
  276. } else {
  277. s.signalWrite()
  278. }
  279. return nextFrame, s.nextFrame != nil || s.dataForWriting != nil
  280. }
  281. f := wire.GetStreamFrame()
  282. f.Fin = false
  283. f.StreamID = s.streamID
  284. f.Offset = s.writeOffset
  285. f.DataLenPresent = true
  286. f.Data = f.Data[:0]
  287. hasMoreData := s.popNewStreamFrameWithoutBuffer(f, maxBytes, sendWindow, v)
  288. if len(f.Data) == 0 && !f.Fin {
  289. f.PutBack()
  290. return nil, hasMoreData
  291. }
  292. return f, hasMoreData
  293. }
  294. func (s *sendStream) popNewStreamFrameWithoutBuffer(f *wire.StreamFrame, maxBytes, sendWindow protocol.ByteCount, v protocol.Version) bool {
  295. maxDataLen := f.MaxDataLen(maxBytes, v)
  296. if maxDataLen == 0 { // a STREAM frame must have at least one byte of data
  297. return s.dataForWriting != nil || s.nextFrame != nil || s.finishedWriting
  298. }
  299. s.getDataForWriting(f, min(maxDataLen, sendWindow))
  300. return s.dataForWriting != nil || s.nextFrame != nil || s.finishedWriting
  301. }
  302. func (s *sendStream) maybeGetRetransmission(maxBytes protocol.ByteCount, v protocol.Version) (*wire.StreamFrame, bool /* has more retransmissions */) {
  303. f := s.retransmissionQueue[0]
  304. newFrame, needsSplit := f.MaybeSplitOffFrame(maxBytes, v)
  305. if needsSplit {
  306. return newFrame, true
  307. }
  308. s.retransmissionQueue = s.retransmissionQueue[1:]
  309. return f, len(s.retransmissionQueue) > 0
  310. }
  311. func (s *sendStream) hasData() bool {
  312. s.mutex.Lock()
  313. hasData := len(s.dataForWriting) > 0
  314. s.mutex.Unlock()
  315. return hasData
  316. }
  317. func (s *sendStream) getDataForWriting(f *wire.StreamFrame, maxBytes protocol.ByteCount) {
  318. if protocol.ByteCount(len(s.dataForWriting)) <= maxBytes {
  319. f.Data = f.Data[:len(s.dataForWriting)]
  320. copy(f.Data, s.dataForWriting)
  321. s.dataForWriting = nil
  322. s.signalWrite()
  323. return
  324. }
  325. f.Data = f.Data[:maxBytes]
  326. copy(f.Data, s.dataForWriting)
  327. s.dataForWriting = s.dataForWriting[maxBytes:]
  328. if s.canBufferStreamFrame() {
  329. s.signalWrite()
  330. }
  331. }
  332. func (s *sendStream) isNewlyCompleted() bool {
  333. if s.completed {
  334. return false
  335. }
  336. // We need to keep the stream around until all frames have been sent and acknowledged.
  337. if s.numOutstandingFrames > 0 || len(s.retransmissionQueue) > 0 || s.queuedResetStreamFrame != nil {
  338. return false
  339. }
  340. // The stream is completed if we sent the FIN.
  341. if s.finSent {
  342. s.completed = true
  343. return true
  344. }
  345. // The stream is also completed if:
  346. // 1. the application called CancelWrite, or
  347. // 2. we received a STOP_SENDING, and
  348. // * the application consumed the error via Write, or
  349. // * the application called Close
  350. if s.cancelled && (s.cancellationFlagged || s.finishedWriting) {
  351. s.completed = true
  352. return true
  353. }
  354. return false
  355. }
  356. func (s *sendStream) Close() error {
  357. s.mutex.Lock()
  358. if s.closedForShutdown || s.finishedWriting {
  359. s.mutex.Unlock()
  360. return nil
  361. }
  362. s.finishedWriting = true
  363. cancelled := s.cancelled
  364. if cancelled {
  365. s.cancellationFlagged = true
  366. }
  367. completed := s.isNewlyCompleted()
  368. s.mutex.Unlock()
  369. if completed {
  370. s.sender.onStreamCompleted(s.streamID)
  371. }
  372. if cancelled {
  373. return fmt.Errorf("close called for canceled stream %d", s.streamID)
  374. }
  375. s.sender.onHasStreamData(s.streamID, s) // need to send the FIN, must be called without holding the mutex
  376. s.ctxCancel(nil)
  377. return nil
  378. }
  379. func (s *sendStream) CancelWrite(errorCode StreamErrorCode) {
  380. s.cancelWrite(errorCode, false)
  381. }
  382. // cancelWrite cancels the stream
  383. // It is possible to cancel a stream after it has been closed, both locally and remotely.
  384. // This is useful to prevent the retransmission of outstanding stream data.
  385. func (s *sendStream) cancelWrite(errorCode qerr.StreamErrorCode, remote bool) {
  386. s.mutex.Lock()
  387. if s.closedForShutdown {
  388. s.mutex.Unlock()
  389. return
  390. }
  391. if !remote {
  392. s.cancellationFlagged = true
  393. if s.cancelled {
  394. completed := s.isNewlyCompleted()
  395. s.mutex.Unlock()
  396. // The user has called CancelWrite. If the previous cancellation was
  397. // because of a STOP_SENDING, we don't need to flag the error to the
  398. // user anymore.
  399. if completed {
  400. s.sender.onStreamCompleted(s.streamID)
  401. }
  402. return
  403. }
  404. }
  405. if s.cancelled {
  406. s.mutex.Unlock()
  407. return
  408. }
  409. s.cancelled = true
  410. s.finalError = &StreamError{StreamID: s.streamID, ErrorCode: errorCode, Remote: remote}
  411. s.ctxCancel(s.finalError)
  412. s.numOutstandingFrames = 0
  413. s.retransmissionQueue = nil
  414. s.queuedResetStreamFrame = &wire.ResetStreamFrame{
  415. StreamID: s.streamID,
  416. FinalSize: s.writeOffset,
  417. ErrorCode: errorCode,
  418. }
  419. s.mutex.Unlock()
  420. s.signalWrite()
  421. s.sender.onHasStreamControlFrame(s.streamID, s)
  422. }
  423. func (s *sendStream) updateSendWindow(limit protocol.ByteCount) {
  424. updated := s.flowController.UpdateSendWindow(limit)
  425. if !updated { // duplicate or reordered MAX_STREAM_DATA frame
  426. return
  427. }
  428. s.mutex.Lock()
  429. hasStreamData := s.dataForWriting != nil || s.nextFrame != nil
  430. s.mutex.Unlock()
  431. if hasStreamData {
  432. s.sender.onHasStreamData(s.streamID, s)
  433. }
  434. }
  435. func (s *sendStream) handleStopSendingFrame(frame *wire.StopSendingFrame) {
  436. s.cancelWrite(frame.ErrorCode, true)
  437. }
  438. func (s *sendStream) getControlFrame(time.Time) (_ ackhandler.Frame, ok, hasMore bool) {
  439. s.mutex.Lock()
  440. defer s.mutex.Unlock()
  441. if s.queuedResetStreamFrame == nil {
  442. return ackhandler.Frame{}, false, false
  443. }
  444. s.numOutstandingFrames++
  445. f := ackhandler.Frame{
  446. Frame: s.queuedResetStreamFrame,
  447. Handler: (*sendStreamResetStreamHandler)(s),
  448. }
  449. s.queuedResetStreamFrame = nil
  450. return f, true, false
  451. }
  452. func (s *sendStream) Context() context.Context {
  453. return s.ctx
  454. }
  455. func (s *sendStream) SetWriteDeadline(t time.Time) error {
  456. s.mutex.Lock()
  457. s.deadline = t
  458. s.mutex.Unlock()
  459. s.signalWrite()
  460. return nil
  461. }
  462. // CloseForShutdown closes a stream abruptly.
  463. // It makes Write unblock (and return the error) immediately.
  464. // The peer will NOT be informed about this: the stream is closed without sending a FIN or RST.
  465. func (s *sendStream) closeForShutdown(err error) {
  466. s.mutex.Lock()
  467. s.closedForShutdown = true
  468. if s.finalError == nil && !s.finishedWriting {
  469. s.finalError = err
  470. }
  471. s.mutex.Unlock()
  472. s.signalWrite()
  473. }
  474. // signalWrite performs a non-blocking send on the writeChan
  475. func (s *sendStream) signalWrite() {
  476. select {
  477. case s.writeChan <- struct{}{}:
  478. default:
  479. }
  480. }
  481. type sendStreamAckHandler sendStream
  482. var _ ackhandler.FrameHandler = &sendStreamAckHandler{}
  483. func (s *sendStreamAckHandler) OnAcked(f wire.Frame) {
  484. sf := f.(*wire.StreamFrame)
  485. sf.PutBack()
  486. s.mutex.Lock()
  487. if s.cancelled {
  488. s.mutex.Unlock()
  489. return
  490. }
  491. s.numOutstandingFrames--
  492. if s.numOutstandingFrames < 0 {
  493. panic("numOutStandingFrames negative")
  494. }
  495. completed := (*sendStream)(s).isNewlyCompleted()
  496. s.mutex.Unlock()
  497. if completed {
  498. s.sender.onStreamCompleted(s.streamID)
  499. }
  500. }
  501. func (s *sendStreamAckHandler) OnLost(f wire.Frame) {
  502. sf := f.(*wire.StreamFrame)
  503. s.mutex.Lock()
  504. if s.cancelled {
  505. s.mutex.Unlock()
  506. return
  507. }
  508. sf.DataLenPresent = true
  509. s.retransmissionQueue = append(s.retransmissionQueue, sf)
  510. s.numOutstandingFrames--
  511. if s.numOutstandingFrames < 0 {
  512. panic("numOutStandingFrames negative")
  513. }
  514. s.mutex.Unlock()
  515. s.sender.onHasStreamData(s.streamID, (*sendStream)(s))
  516. }
  517. type sendStreamResetStreamHandler sendStream
  518. var _ ackhandler.FrameHandler = &sendStreamResetStreamHandler{}
  519. func (s *sendStreamResetStreamHandler) OnAcked(wire.Frame) {
  520. s.mutex.Lock()
  521. s.numOutstandingFrames--
  522. if s.numOutstandingFrames < 0 {
  523. panic("numOutStandingFrames negative")
  524. }
  525. completed := (*sendStream)(s).isNewlyCompleted()
  526. s.mutex.Unlock()
  527. if completed {
  528. s.sender.onStreamCompleted(s.streamID)
  529. }
  530. }
  531. func (s *sendStreamResetStreamHandler) OnLost(f wire.Frame) {
  532. s.mutex.Lock()
  533. s.queuedResetStreamFrame = f.(*wire.ResetStreamFrame)
  534. s.numOutstandingFrames--
  535. s.mutex.Unlock()
  536. s.sender.onHasStreamControlFrame(s.streamID, (*sendStream)(s))
  537. }