send_stream.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  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(maxBytes protocol.ByteCount, v protocol.VersionNumber) (*ackhandler.Frame, bool)
  19. closeForShutdown(error)
  20. updateSendWindow(protocol.ByteCount)
  21. }
  22. type sendStream struct {
  23. mutex sync.Mutex
  24. numOutstandingFrames int64
  25. retransmissionQueue []*wire.StreamFrame
  26. ctx context.Context
  27. ctxCancel context.CancelFunc
  28. streamID protocol.StreamID
  29. sender streamSender
  30. writeOffset protocol.ByteCount
  31. cancelWriteErr error
  32. closeForShutdownErr error
  33. finishedWriting bool // set once Close() is called
  34. finSent bool // set when a STREAM_FRAME with FIN bit has been sent
  35. completed bool // set when this stream has been reported to the streamSender as completed
  36. dataForWriting []byte // during a Write() call, this slice is the part of p that still needs to be sent out
  37. nextFrame *wire.StreamFrame
  38. writeChan chan struct{}
  39. writeOnce chan struct{}
  40. deadline time.Time
  41. flowController flowcontrol.StreamFlowController
  42. }
  43. var (
  44. _ SendStream = &sendStream{}
  45. _ sendStreamI = &sendStream{}
  46. )
  47. func newSendStream(
  48. streamID protocol.StreamID,
  49. sender streamSender,
  50. flowController flowcontrol.StreamFlowController,
  51. ) *sendStream {
  52. s := &sendStream{
  53. streamID: streamID,
  54. sender: sender,
  55. flowController: flowController,
  56. writeChan: make(chan struct{}, 1),
  57. writeOnce: make(chan struct{}, 1), // cap: 1, to protect against concurrent use of Write
  58. }
  59. s.ctx, s.ctxCancel = context.WithCancel(context.Background())
  60. return s
  61. }
  62. func (s *sendStream) StreamID() protocol.StreamID {
  63. return s.streamID // same for receiveStream and sendStream
  64. }
  65. func (s *sendStream) Write(p []byte) (int, error) {
  66. // Concurrent use of Write 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.writeOnce <- struct{}{}
  70. defer func() { <-s.writeOnce }()
  71. s.mutex.Lock()
  72. defer s.mutex.Unlock()
  73. if s.finishedWriting {
  74. return 0, fmt.Errorf("write on closed stream %d", s.streamID)
  75. }
  76. if s.cancelWriteErr != nil {
  77. return 0, s.cancelWriteErr
  78. }
  79. if s.closeForShutdownErr != nil {
  80. return 0, s.closeForShutdownErr
  81. }
  82. if !s.deadline.IsZero() && !time.Now().Before(s.deadline) {
  83. return 0, errDeadline
  84. }
  85. if len(p) == 0 {
  86. return 0, nil
  87. }
  88. s.dataForWriting = p
  89. var (
  90. deadlineTimer *utils.Timer
  91. bytesWritten int
  92. notifiedSender bool
  93. )
  94. for {
  95. var copied bool
  96. var deadline time.Time
  97. // As soon as dataForWriting becomes smaller than a certain size x, we copy all the data to a STREAM frame (s.nextFrame),
  98. // which can then be popped the next time we assemble a packet.
  99. // This allows us to return Write() when all data but x bytes have been sent out.
  100. // When the user now calls Close(), this is much more likely to happen before we popped that last STREAM frame,
  101. // allowing us to set the FIN bit on that frame (instead of sending an empty STREAM frame with FIN).
  102. if s.canBufferStreamFrame() && len(s.dataForWriting) > 0 {
  103. if s.nextFrame == nil {
  104. f := wire.GetStreamFrame()
  105. f.Offset = s.writeOffset
  106. f.StreamID = s.streamID
  107. f.DataLenPresent = true
  108. f.Data = f.Data[:len(s.dataForWriting)]
  109. copy(f.Data, s.dataForWriting)
  110. s.nextFrame = f
  111. } else {
  112. l := len(s.nextFrame.Data)
  113. s.nextFrame.Data = s.nextFrame.Data[:l+len(s.dataForWriting)]
  114. copy(s.nextFrame.Data[l:], s.dataForWriting)
  115. }
  116. s.dataForWriting = nil
  117. bytesWritten = len(p)
  118. copied = true
  119. } else {
  120. bytesWritten = len(p) - len(s.dataForWriting)
  121. deadline = s.deadline
  122. if !deadline.IsZero() {
  123. if !time.Now().Before(deadline) {
  124. s.dataForWriting = nil
  125. return bytesWritten, errDeadline
  126. }
  127. if deadlineTimer == nil {
  128. deadlineTimer = utils.NewTimer()
  129. defer deadlineTimer.Stop()
  130. }
  131. deadlineTimer.Reset(deadline)
  132. }
  133. if s.dataForWriting == nil || s.cancelWriteErr != nil || s.closeForShutdownErr != nil {
  134. break
  135. }
  136. }
  137. s.mutex.Unlock()
  138. if !notifiedSender {
  139. s.sender.onHasStreamData(s.streamID) // must be called without holding the mutex
  140. notifiedSender = true
  141. }
  142. if copied {
  143. s.mutex.Lock()
  144. break
  145. }
  146. if deadline.IsZero() {
  147. <-s.writeChan
  148. } else {
  149. select {
  150. case <-s.writeChan:
  151. case <-deadlineTimer.Chan():
  152. deadlineTimer.SetRead()
  153. }
  154. }
  155. s.mutex.Lock()
  156. }
  157. if bytesWritten == len(p) {
  158. return bytesWritten, nil
  159. }
  160. if s.closeForShutdownErr != nil {
  161. return bytesWritten, s.closeForShutdownErr
  162. } else if s.cancelWriteErr != nil {
  163. return bytesWritten, s.cancelWriteErr
  164. }
  165. return bytesWritten, nil
  166. }
  167. func (s *sendStream) canBufferStreamFrame() bool {
  168. var l protocol.ByteCount
  169. if s.nextFrame != nil {
  170. l = s.nextFrame.DataLen()
  171. }
  172. return l+protocol.ByteCount(len(s.dataForWriting)) <= protocol.MaxPacketBufferSize
  173. }
  174. // popStreamFrame returns the next STREAM frame that is supposed to be sent on this stream
  175. // maxBytes is the maximum length this frame (including frame header) will have.
  176. func (s *sendStream) popStreamFrame(maxBytes protocol.ByteCount, v protocol.VersionNumber) (*ackhandler.Frame, bool /* has more data to send */) {
  177. s.mutex.Lock()
  178. f, hasMoreData := s.popNewOrRetransmittedStreamFrame(maxBytes, v)
  179. if f != nil {
  180. s.numOutstandingFrames++
  181. }
  182. s.mutex.Unlock()
  183. if f == nil {
  184. return nil, hasMoreData
  185. }
  186. af := ackhandler.GetFrame()
  187. af.Frame = f
  188. af.OnLost = s.queueRetransmission
  189. af.OnAcked = s.frameAcked
  190. return af, hasMoreData
  191. }
  192. func (s *sendStream) popNewOrRetransmittedStreamFrame(maxBytes protocol.ByteCount, v protocol.VersionNumber) (*wire.StreamFrame, bool /* has more data to send */) {
  193. if s.cancelWriteErr != nil || s.closeForShutdownErr != nil {
  194. return nil, false
  195. }
  196. if len(s.retransmissionQueue) > 0 {
  197. f, hasMoreRetransmissions := s.maybeGetRetransmission(maxBytes, v)
  198. if f != nil || hasMoreRetransmissions {
  199. if f == nil {
  200. return nil, true
  201. }
  202. // We always claim that we have more data to send.
  203. // This might be incorrect, in which case there'll be a spurious call to popStreamFrame in the future.
  204. return f, true
  205. }
  206. }
  207. if len(s.dataForWriting) == 0 && s.nextFrame == nil {
  208. if s.finishedWriting && !s.finSent {
  209. s.finSent = true
  210. return &wire.StreamFrame{
  211. StreamID: s.streamID,
  212. Offset: s.writeOffset,
  213. DataLenPresent: true,
  214. Fin: true,
  215. }, false
  216. }
  217. return nil, false
  218. }
  219. sendWindow := s.flowController.SendWindowSize()
  220. if sendWindow == 0 {
  221. if isBlocked, offset := s.flowController.IsNewlyBlocked(); isBlocked {
  222. s.sender.queueControlFrame(&wire.StreamDataBlockedFrame{
  223. StreamID: s.streamID,
  224. MaximumStreamData: offset,
  225. })
  226. return nil, false
  227. }
  228. return nil, true
  229. }
  230. f, hasMoreData := s.popNewStreamFrame(maxBytes, sendWindow, v)
  231. if dataLen := f.DataLen(); dataLen > 0 {
  232. s.writeOffset += f.DataLen()
  233. s.flowController.AddBytesSent(f.DataLen())
  234. }
  235. f.Fin = s.finishedWriting && s.dataForWriting == nil && s.nextFrame == nil && !s.finSent
  236. if f.Fin {
  237. s.finSent = true
  238. }
  239. return f, hasMoreData
  240. }
  241. func (s *sendStream) popNewStreamFrame(maxBytes, sendWindow protocol.ByteCount, v protocol.VersionNumber) (*wire.StreamFrame, bool) {
  242. if s.nextFrame != nil {
  243. nextFrame := s.nextFrame
  244. s.nextFrame = nil
  245. maxDataLen := utils.Min(sendWindow, nextFrame.MaxDataLen(maxBytes, v))
  246. if nextFrame.DataLen() > maxDataLen {
  247. s.nextFrame = wire.GetStreamFrame()
  248. s.nextFrame.StreamID = s.streamID
  249. s.nextFrame.Offset = s.writeOffset + maxDataLen
  250. s.nextFrame.Data = s.nextFrame.Data[:nextFrame.DataLen()-maxDataLen]
  251. s.nextFrame.DataLenPresent = true
  252. copy(s.nextFrame.Data, nextFrame.Data[maxDataLen:])
  253. nextFrame.Data = nextFrame.Data[:maxDataLen]
  254. } else {
  255. s.signalWrite()
  256. }
  257. return nextFrame, s.nextFrame != nil || s.dataForWriting != nil
  258. }
  259. f := wire.GetStreamFrame()
  260. f.Fin = false
  261. f.StreamID = s.streamID
  262. f.Offset = s.writeOffset
  263. f.DataLenPresent = true
  264. f.Data = f.Data[:0]
  265. hasMoreData := s.popNewStreamFrameWithoutBuffer(f, maxBytes, sendWindow, v)
  266. if len(f.Data) == 0 && !f.Fin {
  267. f.PutBack()
  268. return nil, hasMoreData
  269. }
  270. return f, hasMoreData
  271. }
  272. func (s *sendStream) popNewStreamFrameWithoutBuffer(f *wire.StreamFrame, maxBytes, sendWindow protocol.ByteCount, v protocol.VersionNumber) bool {
  273. maxDataLen := f.MaxDataLen(maxBytes, v)
  274. if maxDataLen == 0 { // a STREAM frame must have at least one byte of data
  275. return s.dataForWriting != nil || s.nextFrame != nil || s.finishedWriting
  276. }
  277. s.getDataForWriting(f, utils.Min(maxDataLen, sendWindow))
  278. return s.dataForWriting != nil || s.nextFrame != nil || s.finishedWriting
  279. }
  280. func (s *sendStream) maybeGetRetransmission(maxBytes protocol.ByteCount, v protocol.VersionNumber) (*wire.StreamFrame, bool /* has more retransmissions */) {
  281. f := s.retransmissionQueue[0]
  282. newFrame, needsSplit := f.MaybeSplitOffFrame(maxBytes, v)
  283. if needsSplit {
  284. return newFrame, true
  285. }
  286. s.retransmissionQueue = s.retransmissionQueue[1:]
  287. return f, len(s.retransmissionQueue) > 0
  288. }
  289. func (s *sendStream) hasData() bool {
  290. s.mutex.Lock()
  291. hasData := len(s.dataForWriting) > 0
  292. s.mutex.Unlock()
  293. return hasData
  294. }
  295. func (s *sendStream) getDataForWriting(f *wire.StreamFrame, maxBytes protocol.ByteCount) {
  296. if protocol.ByteCount(len(s.dataForWriting)) <= maxBytes {
  297. f.Data = f.Data[:len(s.dataForWriting)]
  298. copy(f.Data, s.dataForWriting)
  299. s.dataForWriting = nil
  300. s.signalWrite()
  301. return
  302. }
  303. f.Data = f.Data[:maxBytes]
  304. copy(f.Data, s.dataForWriting)
  305. s.dataForWriting = s.dataForWriting[maxBytes:]
  306. if s.canBufferStreamFrame() {
  307. s.signalWrite()
  308. }
  309. }
  310. func (s *sendStream) frameAcked(f wire.Frame) {
  311. f.(*wire.StreamFrame).PutBack()
  312. s.mutex.Lock()
  313. if s.cancelWriteErr != nil {
  314. s.mutex.Unlock()
  315. return
  316. }
  317. s.numOutstandingFrames--
  318. if s.numOutstandingFrames < 0 {
  319. panic("numOutStandingFrames negative")
  320. }
  321. newlyCompleted := s.isNewlyCompleted()
  322. s.mutex.Unlock()
  323. if newlyCompleted {
  324. s.sender.onStreamCompleted(s.streamID)
  325. }
  326. }
  327. func (s *sendStream) isNewlyCompleted() bool {
  328. completed := (s.finSent || s.cancelWriteErr != nil) && s.numOutstandingFrames == 0 && len(s.retransmissionQueue) == 0
  329. if completed && !s.completed {
  330. s.completed = true
  331. return true
  332. }
  333. return false
  334. }
  335. func (s *sendStream) queueRetransmission(f wire.Frame) {
  336. sf := f.(*wire.StreamFrame)
  337. sf.DataLenPresent = true
  338. s.mutex.Lock()
  339. if s.cancelWriteErr != nil {
  340. s.mutex.Unlock()
  341. return
  342. }
  343. s.retransmissionQueue = append(s.retransmissionQueue, sf)
  344. s.numOutstandingFrames--
  345. if s.numOutstandingFrames < 0 {
  346. panic("numOutStandingFrames negative")
  347. }
  348. s.mutex.Unlock()
  349. s.sender.onHasStreamData(s.streamID)
  350. }
  351. func (s *sendStream) Close() error {
  352. s.mutex.Lock()
  353. if s.closeForShutdownErr != nil {
  354. s.mutex.Unlock()
  355. return nil
  356. }
  357. if s.cancelWriteErr != nil {
  358. s.mutex.Unlock()
  359. return fmt.Errorf("close called for canceled stream %d", s.streamID)
  360. }
  361. s.ctxCancel()
  362. s.finishedWriting = true
  363. s.mutex.Unlock()
  364. s.sender.onHasStreamData(s.streamID) // need to send the FIN, must be called without holding the mutex
  365. return nil
  366. }
  367. func (s *sendStream) CancelWrite(errorCode StreamErrorCode) {
  368. s.cancelWriteImpl(errorCode, false)
  369. }
  370. // must be called after locking the mutex
  371. func (s *sendStream) cancelWriteImpl(errorCode qerr.StreamErrorCode, remote bool) {
  372. s.mutex.Lock()
  373. if s.cancelWriteErr != nil {
  374. s.mutex.Unlock()
  375. return
  376. }
  377. s.ctxCancel()
  378. s.cancelWriteErr = &StreamError{StreamID: s.streamID, ErrorCode: errorCode, Remote: remote}
  379. s.numOutstandingFrames = 0
  380. s.retransmissionQueue = nil
  381. newlyCompleted := s.isNewlyCompleted()
  382. s.mutex.Unlock()
  383. s.signalWrite()
  384. s.sender.queueControlFrame(&wire.ResetStreamFrame{
  385. StreamID: s.streamID,
  386. FinalSize: s.writeOffset,
  387. ErrorCode: errorCode,
  388. })
  389. if newlyCompleted {
  390. s.sender.onStreamCompleted(s.streamID)
  391. }
  392. }
  393. func (s *sendStream) updateSendWindow(limit protocol.ByteCount) {
  394. s.mutex.Lock()
  395. hasStreamData := s.dataForWriting != nil || s.nextFrame != nil
  396. s.mutex.Unlock()
  397. s.flowController.UpdateSendWindow(limit)
  398. if hasStreamData {
  399. s.sender.onHasStreamData(s.streamID)
  400. }
  401. }
  402. func (s *sendStream) handleStopSendingFrame(frame *wire.StopSendingFrame) {
  403. s.cancelWriteImpl(frame.ErrorCode, true)
  404. }
  405. func (s *sendStream) Context() context.Context {
  406. return s.ctx
  407. }
  408. func (s *sendStream) SetWriteDeadline(t time.Time) error {
  409. s.mutex.Lock()
  410. s.deadline = t
  411. s.mutex.Unlock()
  412. s.signalWrite()
  413. return nil
  414. }
  415. // CloseForShutdown closes a stream abruptly.
  416. // It makes Write unblock (and return the error) immediately.
  417. // The peer will NOT be informed about this: the stream is closed without sending a FIN or RST.
  418. func (s *sendStream) closeForShutdown(err error) {
  419. s.mutex.Lock()
  420. s.ctxCancel()
  421. s.closeForShutdownErr = err
  422. s.mutex.Unlock()
  423. s.signalWrite()
  424. }
  425. // signalWrite performs a non-blocking send on the writeChan
  426. func (s *sendStream) signalWrite() {
  427. select {
  428. case s.writeChan <- struct{}{}:
  429. default:
  430. }
  431. }