stream.go 9.2 KB

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