stream.go 10 KB

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