stream.go 13 KB

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