stream.go 12 KB

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