stream.go 12 KB

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