stream.go 7.7 KB

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