stream.go 9.8 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. 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 time.Time
  40. writeDeadline time.Time
  41. }
  42. // newStream is used to construct a new stream within
  43. // a given session for an ID
  44. func newStream(session *Session, id uint32, state streamState) *Stream {
  45. s := &Stream{
  46. id: id,
  47. session: session,
  48. state: state,
  49. controlHdr: header(make([]byte, headerSize)),
  50. controlErr: make(chan error, 1),
  51. sendHdr: header(make([]byte, headerSize)),
  52. sendErr: make(chan error, 1),
  53. recvWindow: initialStreamWindow,
  54. sendWindow: initialStreamWindow,
  55. recvNotifyCh: make(chan struct{}, 1),
  56. sendNotifyCh: make(chan struct{}, 1),
  57. }
  58. return s
  59. }
  60. // Session returns the associated stream session
  61. func (s *Stream) Session() *Session {
  62. return s.session
  63. }
  64. // StreamID returns the ID of this stream
  65. func (s *Stream) StreamID() uint32 {
  66. return s.id
  67. }
  68. // Read is used to read from the stream
  69. func (s *Stream) Read(b []byte) (n int, err error) {
  70. defer asyncNotify(s.recvNotifyCh)
  71. START:
  72. s.stateLock.Lock()
  73. switch s.state {
  74. case streamLocalClose:
  75. fallthrough
  76. case streamRemoteClose:
  77. fallthrough
  78. case streamClosed:
  79. s.recvLock.Lock()
  80. if s.recvBuf == nil || s.recvBuf.Len() == 0 {
  81. s.recvLock.Unlock()
  82. s.stateLock.Unlock()
  83. return 0, io.EOF
  84. }
  85. s.recvLock.Unlock()
  86. case streamReset:
  87. s.stateLock.Unlock()
  88. return 0, ErrConnectionReset
  89. }
  90. s.stateLock.Unlock()
  91. // If there is no data available, block
  92. s.recvLock.Lock()
  93. if s.recvBuf == nil || s.recvBuf.Len() == 0 {
  94. s.recvLock.Unlock()
  95. goto WAIT
  96. }
  97. // Read any bytes
  98. n, _ = s.recvBuf.Read(b)
  99. s.recvLock.Unlock()
  100. // Send a window update potentially
  101. err = s.sendWindowUpdate()
  102. return n, err
  103. WAIT:
  104. var timeout <-chan time.Time
  105. var timer *time.Timer
  106. if !s.readDeadline.IsZero() {
  107. delay := s.readDeadline.Sub(time.Now())
  108. timer = time.NewTimer(delay)
  109. timeout = timer.C
  110. }
  111. select {
  112. case <-s.recvNotifyCh:
  113. if timer != nil {
  114. timer.Stop()
  115. }
  116. goto START
  117. case <-timeout:
  118. return 0, ErrTimeout
  119. }
  120. }
  121. // Write is used to write to the stream
  122. func (s *Stream) Write(b []byte) (n int, err error) {
  123. s.sendLock.Lock()
  124. defer s.sendLock.Unlock()
  125. total := 0
  126. for total < len(b) {
  127. n, err := s.write(b[total:])
  128. total += n
  129. if err != nil {
  130. return total, err
  131. }
  132. }
  133. return total, nil
  134. }
  135. // write is used to write to the stream, may return on
  136. // a short write.
  137. func (s *Stream) write(b []byte) (n int, err error) {
  138. var flags uint16
  139. var max uint32
  140. var body io.Reader
  141. START:
  142. s.stateLock.Lock()
  143. switch s.state {
  144. case streamLocalClose:
  145. fallthrough
  146. case streamClosed:
  147. s.stateLock.Unlock()
  148. return 0, ErrStreamClosed
  149. case streamReset:
  150. s.stateLock.Unlock()
  151. return 0, ErrConnectionReset
  152. }
  153. s.stateLock.Unlock()
  154. // If there is no data available, block
  155. window := atomic.LoadUint32(&s.sendWindow)
  156. if window == 0 {
  157. goto WAIT
  158. }
  159. // Determine the flags if any
  160. flags = s.sendFlags()
  161. // Send up to our send window
  162. max = min(window, uint32(len(b)))
  163. body = bytes.NewReader(b[:max])
  164. // Send the header
  165. s.sendHdr.encode(typeData, flags, s.id, max)
  166. if err := s.session.waitForSendErr(s.sendHdr, body, s.sendErr); err != nil {
  167. return 0, err
  168. }
  169. // Reduce our send window
  170. atomic.AddUint32(&s.sendWindow, ^uint32(max-1))
  171. // Unlock
  172. return int(max), err
  173. WAIT:
  174. var timeout <-chan time.Time
  175. if !s.writeDeadline.IsZero() {
  176. delay := s.writeDeadline.Sub(time.Now())
  177. timeout = time.After(delay)
  178. }
  179. select {
  180. case <-s.sendNotifyCh:
  181. goto START
  182. case <-timeout:
  183. return 0, ErrTimeout
  184. }
  185. return 0, nil
  186. }
  187. // sendFlags determines any flags that are appropriate
  188. // based on the current stream state
  189. func (s *Stream) sendFlags() uint16 {
  190. s.stateLock.Lock()
  191. defer s.stateLock.Unlock()
  192. var flags uint16
  193. switch s.state {
  194. case streamInit:
  195. flags |= flagSYN
  196. s.state = streamSYNSent
  197. case streamSYNReceived:
  198. flags |= flagACK
  199. s.state = streamEstablished
  200. }
  201. return flags
  202. }
  203. // sendWindowUpdate potentially sends a window update enabling
  204. // further writes to take place. Must be invoked with the lock.
  205. func (s *Stream) sendWindowUpdate() error {
  206. s.controlHdrLock.Lock()
  207. defer s.controlHdrLock.Unlock()
  208. // Determine the delta update
  209. max := s.session.config.MaxStreamWindowSize
  210. delta := max - atomic.LoadUint32(&s.recvWindow)
  211. // Determine the flags if any
  212. flags := s.sendFlags()
  213. // Check if we can omit the update
  214. if delta < (max/2) && flags == 0 {
  215. return nil
  216. }
  217. // Update our window
  218. atomic.AddUint32(&s.recvWindow, delta)
  219. // Send the header
  220. s.controlHdr.encode(typeWindowUpdate, flags, s.id, delta)
  221. if err := s.session.waitForSendErr(s.controlHdr, nil, s.controlErr); err != nil {
  222. return err
  223. }
  224. return nil
  225. }
  226. // sendClose is used to send a FIN
  227. func (s *Stream) sendClose() error {
  228. s.controlHdrLock.Lock()
  229. defer s.controlHdrLock.Unlock()
  230. flags := s.sendFlags()
  231. flags |= flagFIN
  232. s.controlHdr.encode(typeWindowUpdate, flags, s.id, 0)
  233. if err := s.session.waitForSendErr(s.controlHdr, nil, s.controlErr); err != nil {
  234. return err
  235. }
  236. return nil
  237. }
  238. // Close is used to close the stream
  239. func (s *Stream) Close() error {
  240. closeStream := false
  241. s.stateLock.Lock()
  242. switch s.state {
  243. // Opened means we need to signal a close
  244. case streamSYNSent:
  245. fallthrough
  246. case streamSYNReceived:
  247. fallthrough
  248. case streamEstablished:
  249. s.state = streamLocalClose
  250. goto SEND_CLOSE
  251. case streamLocalClose:
  252. case streamRemoteClose:
  253. s.state = streamClosed
  254. closeStream = true
  255. goto SEND_CLOSE
  256. case streamClosed:
  257. case streamReset:
  258. default:
  259. panic("unhandled state")
  260. }
  261. s.stateLock.Unlock()
  262. return nil
  263. SEND_CLOSE:
  264. s.stateLock.Unlock()
  265. s.sendClose()
  266. s.notifyWaiting()
  267. if closeStream {
  268. s.session.closeStream(s.id)
  269. }
  270. return nil
  271. }
  272. // forceClose is used for when the session is exiting
  273. func (s *Stream) forceClose() {
  274. s.stateLock.Lock()
  275. s.state = streamClosed
  276. s.stateLock.Unlock()
  277. s.notifyWaiting()
  278. }
  279. // processFlags is used to update the state of the stream
  280. // based on set flags, if any. Lock must be held
  281. func (s *Stream) processFlags(flags uint16) error {
  282. // Close the stream without holding the state lock
  283. closeStream := false
  284. defer func() {
  285. if closeStream {
  286. s.session.closeStream(s.id)
  287. }
  288. }()
  289. s.stateLock.Lock()
  290. defer s.stateLock.Unlock()
  291. if flags&flagACK == flagACK {
  292. if s.state == streamSYNSent {
  293. s.state = streamEstablished
  294. }
  295. s.session.establishStream(s.id)
  296. }
  297. if flags&flagFIN == flagFIN {
  298. switch s.state {
  299. case streamSYNSent:
  300. fallthrough
  301. case streamSYNReceived:
  302. fallthrough
  303. case streamEstablished:
  304. s.state = streamRemoteClose
  305. s.notifyWaiting()
  306. case streamLocalClose:
  307. s.state = streamClosed
  308. closeStream = true
  309. s.notifyWaiting()
  310. default:
  311. s.session.logger.Printf("[ERR] yamux: unexpected FIN flag in state %d", s.state)
  312. return ErrUnexpectedFlag
  313. }
  314. }
  315. if flags&flagRST == flagRST {
  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. }