stream.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. package yamux
  2. import (
  3. "bytes"
  4. "errors"
  5. "io"
  6. "sync"
  7. "sync/atomic"
  8. "time"
  9. )
  10. type streamState int
  11. const (
  12. streamInit streamState = iota
  13. streamSYNSent
  14. streamSYNReceived
  15. streamEstablished
  16. streamLocalClose
  17. streamRemoteClose
  18. streamClosed
  19. streamReset
  20. )
  21. // Stream is used to represent a logical stream
  22. // within a session.
  23. type Stream struct {
  24. recvWindow uint32
  25. sendWindow uint32
  26. id uint32
  27. session *Session
  28. state streamState
  29. stateLock sync.Mutex
  30. recvBuf *bytes.Buffer
  31. recvLock sync.Mutex
  32. controlHdr header
  33. controlErr chan error
  34. controlHdrLock sync.Mutex
  35. sendHdr header
  36. sendErr chan error
  37. sendLock sync.Mutex
  38. recvNotifyCh chan struct{}
  39. sendNotifyCh chan struct{}
  40. readDeadline atomic.Value // time.Time
  41. writeDeadline atomic.Value // time.Time
  42. // establishCh is notified if the stream is established or being closed.
  43. establishCh chan struct{}
  44. // closeTimer is set with stateLock held to honor the StreamCloseTimeout
  45. // setting on Session.
  46. closeTimer *time.Timer
  47. }
  48. // newStream is used to construct a new stream within
  49. // a given session for an ID
  50. func newStream(session *Session, id uint32, state streamState) *Stream {
  51. s := &Stream{
  52. id: id,
  53. session: session,
  54. state: state,
  55. controlHdr: header(make([]byte, headerSize)),
  56. controlErr: make(chan error, 1),
  57. sendHdr: header(make([]byte, headerSize)),
  58. sendErr: make(chan error, 1),
  59. recvWindow: initialStreamWindow,
  60. sendWindow: initialStreamWindow,
  61. recvNotifyCh: make(chan struct{}, 1),
  62. sendNotifyCh: make(chan struct{}, 1),
  63. establishCh: make(chan struct{}, 1),
  64. }
  65. s.readDeadline.Store(time.Time{})
  66. s.writeDeadline.Store(time.Time{})
  67. return s
  68. }
  69. // Session returns the associated stream session
  70. func (s *Stream) Session() *Session {
  71. return s.session
  72. }
  73. // StreamID returns the ID of this stream
  74. func (s *Stream) StreamID() uint32 {
  75. return s.id
  76. }
  77. // Read is used to read from the stream
  78. func (s *Stream) Read(b []byte) (n int, err error) {
  79. defer asyncNotify(s.recvNotifyCh)
  80. START:
  81. s.stateLock.Lock()
  82. switch s.state {
  83. case streamLocalClose:
  84. fallthrough
  85. case streamRemoteClose:
  86. fallthrough
  87. case streamClosed:
  88. s.recvLock.Lock()
  89. if s.recvBuf == nil || s.recvBuf.Len() == 0 {
  90. s.recvLock.Unlock()
  91. s.stateLock.Unlock()
  92. return 0, io.EOF
  93. }
  94. s.recvLock.Unlock()
  95. case streamReset:
  96. s.stateLock.Unlock()
  97. return 0, ErrConnectionReset
  98. }
  99. s.stateLock.Unlock()
  100. // If there is no data available, block
  101. s.recvLock.Lock()
  102. if s.recvBuf == nil || s.recvBuf.Len() == 0 {
  103. s.recvLock.Unlock()
  104. goto WAIT
  105. }
  106. // Read any bytes
  107. n, _ = s.recvBuf.Read(b)
  108. s.recvLock.Unlock()
  109. // Send a window update potentially
  110. err = s.sendWindowUpdate()
  111. return n, err
  112. WAIT:
  113. var timeout <-chan time.Time
  114. var timer *time.Timer
  115. readDeadline := s.readDeadline.Load().(time.Time)
  116. if !readDeadline.IsZero() {
  117. delay := readDeadline.Sub(time.Now())
  118. timer = time.NewTimer(delay)
  119. timeout = timer.C
  120. }
  121. select {
  122. case <-s.recvNotifyCh:
  123. if timer != nil {
  124. timer.Stop()
  125. }
  126. goto START
  127. case <-timeout:
  128. return 0, ErrTimeout
  129. }
  130. }
  131. // Write is used to write to the stream
  132. func (s *Stream) Write(b []byte) (n int, err error) {
  133. s.sendLock.Lock()
  134. defer s.sendLock.Unlock()
  135. total := 0
  136. for total < len(b) {
  137. n, err := s.write(b[total:])
  138. total += n
  139. if err != nil {
  140. return total, err
  141. }
  142. }
  143. return total, nil
  144. }
  145. // write is used to write to the stream, may return on
  146. // a short write.
  147. func (s *Stream) write(b []byte) (n int, err error) {
  148. var flags uint16
  149. var max uint32
  150. var body []byte
  151. START:
  152. s.stateLock.Lock()
  153. switch s.state {
  154. case streamLocalClose:
  155. fallthrough
  156. case streamClosed:
  157. s.stateLock.Unlock()
  158. return 0, ErrStreamClosed
  159. case streamReset:
  160. s.stateLock.Unlock()
  161. return 0, ErrConnectionReset
  162. }
  163. s.stateLock.Unlock()
  164. // If there is no data available, block
  165. window := atomic.LoadUint32(&s.sendWindow)
  166. if window == 0 {
  167. goto WAIT
  168. }
  169. // Determine the flags if any
  170. flags = s.sendFlags()
  171. // Send up to our send window
  172. max = min(window, uint32(len(b)))
  173. body = b[:max]
  174. // Send the header
  175. s.sendHdr.encode(typeData, flags, s.id, max)
  176. if err = s.session.waitForSendErr(s.sendHdr, body, s.sendErr); err != nil {
  177. if errors.Is(err, ErrSessionShutdown) || errors.Is(err, ErrConnectionWriteTimeout) {
  178. // Message left in ready queue, header re-use is unsafe.
  179. s.sendHdr = header(make([]byte, headerSize))
  180. }
  181. return 0, err
  182. }
  183. // Reduce our send window
  184. atomic.AddUint32(&s.sendWindow, ^uint32(max-1))
  185. // Unlock
  186. return int(max), err
  187. WAIT:
  188. var timeout <-chan time.Time
  189. writeDeadline := s.writeDeadline.Load().(time.Time)
  190. if !writeDeadline.IsZero() {
  191. delay := writeDeadline.Sub(time.Now())
  192. timeout = time.After(delay)
  193. }
  194. select {
  195. case <-s.sendNotifyCh:
  196. goto START
  197. case <-timeout:
  198. return 0, ErrTimeout
  199. }
  200. return 0, nil
  201. }
  202. // sendFlags determines any flags that are appropriate
  203. // based on the current stream state
  204. func (s *Stream) sendFlags() uint16 {
  205. s.stateLock.Lock()
  206. defer s.stateLock.Unlock()
  207. var flags uint16
  208. switch s.state {
  209. case streamInit:
  210. flags |= flagSYN
  211. s.state = streamSYNSent
  212. case streamSYNReceived:
  213. flags |= flagACK
  214. s.state = streamEstablished
  215. }
  216. return flags
  217. }
  218. // sendWindowUpdate potentially sends a window update enabling
  219. // further writes to take place. Must be invoked with the lock.
  220. func (s *Stream) sendWindowUpdate() error {
  221. s.controlHdrLock.Lock()
  222. defer s.controlHdrLock.Unlock()
  223. // Determine the delta update
  224. max := s.session.config.MaxStreamWindowSize
  225. var bufLen uint32
  226. s.recvLock.Lock()
  227. if s.recvBuf != nil {
  228. bufLen = uint32(s.recvBuf.Len())
  229. }
  230. delta := (max - bufLen) - s.recvWindow
  231. // Determine the flags if any
  232. flags := s.sendFlags()
  233. // Check if we can omit the update
  234. if delta < (max/2) && flags == 0 {
  235. s.recvLock.Unlock()
  236. return nil
  237. }
  238. // Update our window
  239. s.recvWindow += delta
  240. s.recvLock.Unlock()
  241. // Send the header
  242. s.controlHdr.encode(typeWindowUpdate, flags, s.id, delta)
  243. if err := s.session.waitForSendErr(s.controlHdr, nil, s.controlErr); err != nil {
  244. if errors.Is(err, ErrSessionShutdown) || errors.Is(err, ErrConnectionWriteTimeout) {
  245. // Message left in ready queue, header re-use is unsafe.
  246. s.controlHdr = header(make([]byte, headerSize))
  247. }
  248. return err
  249. }
  250. return nil
  251. }
  252. // sendClose is used to send a FIN
  253. func (s *Stream) sendClose() error {
  254. s.controlHdrLock.Lock()
  255. defer s.controlHdrLock.Unlock()
  256. flags := s.sendFlags()
  257. flags |= flagFIN
  258. s.controlHdr.encode(typeWindowUpdate, flags, s.id, 0)
  259. if err := s.session.waitForSendErr(s.controlHdr, nil, s.controlErr); err != nil {
  260. if errors.Is(err, ErrSessionShutdown) || errors.Is(err, ErrConnectionWriteTimeout) {
  261. // Message left in ready queue, header re-use is unsafe.
  262. s.controlHdr = header(make([]byte, headerSize))
  263. }
  264. return err
  265. }
  266. return nil
  267. }
  268. // Close is used to close the stream
  269. func (s *Stream) Close() error {
  270. closeStream := false
  271. s.stateLock.Lock()
  272. switch s.state {
  273. // Opened means we need to signal a close
  274. case streamSYNSent:
  275. fallthrough
  276. case streamSYNReceived:
  277. fallthrough
  278. case streamEstablished:
  279. s.state = streamLocalClose
  280. goto SEND_CLOSE
  281. case streamLocalClose:
  282. case streamRemoteClose:
  283. s.state = streamClosed
  284. closeStream = true
  285. goto SEND_CLOSE
  286. case streamClosed:
  287. case streamReset:
  288. default:
  289. panic("unhandled state")
  290. }
  291. s.stateLock.Unlock()
  292. return nil
  293. SEND_CLOSE:
  294. // This shouldn't happen (the more realistic scenario to cancel the
  295. // timer is via processFlags) but just in case this ever happens, we
  296. // cancel the timer to prevent dangling timers.
  297. if s.closeTimer != nil {
  298. s.closeTimer.Stop()
  299. s.closeTimer = nil
  300. }
  301. // If we have a StreamCloseTimeout set we start the timeout timer.
  302. // We do this only if we're not already closing the stream since that
  303. // means this was a graceful close.
  304. //
  305. // This prevents memory leaks if one side (this side) closes and the
  306. // remote side poorly behaves and never responds with a FIN to complete
  307. // the close. After the specified timeout, we clean our resources up no
  308. // matter what.
  309. if !closeStream && s.session.config.StreamCloseTimeout > 0 {
  310. s.closeTimer = time.AfterFunc(
  311. s.session.config.StreamCloseTimeout, s.closeTimeout)
  312. }
  313. s.stateLock.Unlock()
  314. s.sendClose()
  315. s.notifyWaiting()
  316. if closeStream {
  317. s.session.closeStream(s.id)
  318. }
  319. return nil
  320. }
  321. // closeTimeout is called after StreamCloseTimeout during a close to
  322. // close this stream.
  323. func (s *Stream) closeTimeout() {
  324. // Close our side forcibly
  325. s.forceClose()
  326. // Free the stream from the session map
  327. s.session.closeStream(s.id)
  328. // Send a RST so the remote side closes too.
  329. s.sendLock.Lock()
  330. defer s.sendLock.Unlock()
  331. hdr := header(make([]byte, headerSize))
  332. hdr.encode(typeWindowUpdate, flagRST, s.id, 0)
  333. s.session.sendNoWait(hdr)
  334. }
  335. // forceClose is used for when the session is exiting
  336. func (s *Stream) forceClose() {
  337. s.stateLock.Lock()
  338. s.state = streamClosed
  339. s.stateLock.Unlock()
  340. s.notifyWaiting()
  341. }
  342. // processFlags is used to update the state of the stream
  343. // based on set flags, if any. Lock must be held
  344. func (s *Stream) processFlags(flags uint16) error {
  345. s.stateLock.Lock()
  346. defer s.stateLock.Unlock()
  347. // Close the stream without holding the state lock
  348. closeStream := false
  349. defer func() {
  350. if closeStream {
  351. if s.closeTimer != nil {
  352. // Stop our close timeout timer since we gracefully closed
  353. s.closeTimer.Stop()
  354. }
  355. s.session.closeStream(s.id)
  356. }
  357. }()
  358. if flags&flagACK == flagACK {
  359. if s.state == streamSYNSent {
  360. s.state = streamEstablished
  361. }
  362. asyncNotify(s.establishCh)
  363. s.session.establishStream(s.id)
  364. }
  365. if flags&flagFIN == flagFIN {
  366. switch s.state {
  367. case streamSYNSent:
  368. fallthrough
  369. case streamSYNReceived:
  370. fallthrough
  371. case streamEstablished:
  372. s.state = streamRemoteClose
  373. s.notifyWaiting()
  374. case streamLocalClose:
  375. s.state = streamClosed
  376. closeStream = true
  377. s.notifyWaiting()
  378. default:
  379. s.session.logger.Printf("[ERR] yamux: unexpected FIN flag in state %d", s.state)
  380. return ErrUnexpectedFlag
  381. }
  382. }
  383. if flags&flagRST == flagRST {
  384. s.state = streamReset
  385. closeStream = true
  386. s.notifyWaiting()
  387. }
  388. return nil
  389. }
  390. // notifyWaiting notifies all the waiting channels
  391. func (s *Stream) notifyWaiting() {
  392. asyncNotify(s.recvNotifyCh)
  393. asyncNotify(s.sendNotifyCh)
  394. asyncNotify(s.establishCh)
  395. }
  396. // incrSendWindow updates the size of our send window
  397. func (s *Stream) incrSendWindow(hdr header, flags uint16) error {
  398. if err := s.processFlags(flags); err != nil {
  399. return err
  400. }
  401. // Increase window, unblock a sender
  402. atomic.AddUint32(&s.sendWindow, hdr.Length())
  403. asyncNotify(s.sendNotifyCh)
  404. return nil
  405. }
  406. // readData is used to handle a data frame
  407. func (s *Stream) readData(hdr header, flags uint16, conn io.Reader) error {
  408. if err := s.processFlags(flags); err != nil {
  409. return err
  410. }
  411. // Check that our recv window is not exceeded
  412. length := hdr.Length()
  413. if length == 0 {
  414. return nil
  415. }
  416. // Wrap in a limited reader
  417. conn = &io.LimitedReader{R: conn, N: int64(length)}
  418. // Copy into buffer
  419. s.recvLock.Lock()
  420. if length > s.recvWindow {
  421. s.session.logger.Printf("[ERR] yamux: receive window exceeded (stream: %d, remain: %d, recv: %d)", s.id, s.recvWindow, length)
  422. s.recvLock.Unlock()
  423. return ErrRecvWindowExceeded
  424. }
  425. if s.recvBuf == nil {
  426. // Allocate the receive buffer just-in-time to fit the full data frame.
  427. // This way we can read in the whole packet without further allocations.
  428. s.recvBuf = bytes.NewBuffer(make([]byte, 0, length))
  429. }
  430. if _, err := io.Copy(s.recvBuf, conn); err != nil {
  431. s.session.logger.Printf("[ERR] yamux: Failed to read stream data: %v", err)
  432. s.recvLock.Unlock()
  433. return err
  434. }
  435. // Decrement the receive window
  436. s.recvWindow -= length
  437. s.recvLock.Unlock()
  438. // Unblock any readers
  439. asyncNotify(s.recvNotifyCh)
  440. return nil
  441. }
  442. // SetDeadline sets the read and write deadlines
  443. func (s *Stream) SetDeadline(t time.Time) error {
  444. if err := s.SetReadDeadline(t); err != nil {
  445. return err
  446. }
  447. if err := s.SetWriteDeadline(t); err != nil {
  448. return err
  449. }
  450. return nil
  451. }
  452. // SetReadDeadline sets the deadline for blocked and future Read calls.
  453. func (s *Stream) SetReadDeadline(t time.Time) error {
  454. s.readDeadline.Store(t)
  455. asyncNotify(s.recvNotifyCh)
  456. return nil
  457. }
  458. // SetWriteDeadline sets the deadline for blocked and future Write calls
  459. func (s *Stream) SetWriteDeadline(t time.Time) error {
  460. s.writeDeadline.Store(t)
  461. asyncNotify(s.sendNotifyCh)
  462. return nil
  463. }
  464. // Shrink is used to compact the amount of buffers utilized
  465. // This is useful when using Yamux in a connection pool to reduce
  466. // the idle memory utilization.
  467. func (s *Stream) Shrink() {
  468. s.recvLock.Lock()
  469. if s.recvBuf != nil && s.recvBuf.Len() == 0 {
  470. s.recvBuf = nil
  471. }
  472. s.recvLock.Unlock()
  473. }