stream.go 9.9 KB

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