session.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. package yamux
  2. import (
  3. "bufio"
  4. "fmt"
  5. "io"
  6. "math"
  7. "net"
  8. "sync"
  9. "sync/atomic"
  10. "time"
  11. )
  12. // Session is used to wrap a reliable ordered connection and to
  13. // multiplex it into multiple streams.
  14. type Session struct {
  15. // remoteGoAway indicates the remote side does
  16. // not want futher connections. Must be first for alignment.
  17. remoteGoAway int32
  18. // localGoAway indicates that we should stop
  19. // accepting futher connections. Must be first for alignment.
  20. localGoAway int32
  21. // nextStreamID is the next stream we should
  22. // send. This depends if we are a client/server.
  23. nextStreamID uint32
  24. // config holds our configuration
  25. config *Config
  26. // conn is the underlying connection
  27. conn io.ReadWriteCloser
  28. // bufRead is a buffered reader
  29. bufRead *bufio.Reader
  30. // pings is used to track inflight pings
  31. pings map[uint32]chan struct{}
  32. pingID uint32
  33. pingLock sync.Mutex
  34. // streams maps a stream id to a stream
  35. streams map[uint32]*Stream
  36. streamLock sync.Mutex
  37. // acceptCh is used to pass ready streams to the client
  38. acceptCh chan *Stream
  39. // sendCh is used to mark a stream as ready to send,
  40. // or to send a header out directly.
  41. sendCh chan sendReady
  42. // shutdown is used to safely close a session
  43. shutdown bool
  44. shutdownErr error
  45. shutdownCh chan struct{}
  46. shutdownLock sync.Mutex
  47. }
  48. // sendReady is used to either mark a stream as ready
  49. // or to directly send a header
  50. type sendReady struct {
  51. Hdr []byte
  52. Body io.Reader
  53. Err chan error
  54. }
  55. // newSession is used to construct a new session
  56. func newSession(config *Config, conn io.ReadWriteCloser, client bool) *Session {
  57. s := &Session{
  58. config: config,
  59. conn: conn,
  60. bufRead: bufio.NewReader(conn),
  61. pings: make(map[uint32]chan struct{}),
  62. streams: make(map[uint32]*Stream),
  63. acceptCh: make(chan *Stream, config.AcceptBacklog),
  64. sendCh: make(chan sendReady, 64),
  65. shutdownCh: make(chan struct{}),
  66. }
  67. if client {
  68. s.nextStreamID = 1
  69. } else {
  70. s.nextStreamID = 2
  71. }
  72. go s.recv()
  73. go s.send()
  74. if config.EnableKeepAlive {
  75. go s.keepalive()
  76. }
  77. return s
  78. }
  79. // IsClosed does a safe check to see if we have shutdown
  80. func (s *Session) IsClosed() bool {
  81. select {
  82. case <-s.shutdownCh:
  83. return true
  84. default:
  85. return false
  86. }
  87. }
  88. // Open is used to create a new stream
  89. func (s *Session) Open() (*Stream, error) {
  90. if s.IsClosed() {
  91. return nil, ErrSessionShutdown
  92. }
  93. if atomic.LoadInt32(&s.remoteGoAway) == 1 {
  94. return nil, ErrRemoteGoAway
  95. }
  96. GET_ID:
  97. // Get and ID, and check for stream exhaustion
  98. id := atomic.LoadUint32(&s.nextStreamID)
  99. if id >= math.MaxUint32-1 {
  100. return nil, ErrStreamsExhausted
  101. }
  102. if !atomic.CompareAndSwapUint32(&s.nextStreamID, id, id+2) {
  103. goto GET_ID
  104. }
  105. // Register the stream
  106. stream := newStream(s, id, streamInit)
  107. s.streamLock.Lock()
  108. s.streams[id] = stream
  109. s.streamLock.Unlock()
  110. // Send the window update to create
  111. return stream, stream.sendWindowUpdate()
  112. }
  113. // Accept is used to block until the next available stream
  114. // is ready to be accepted.
  115. func (s *Session) Accept() (net.Conn, error) {
  116. return s.AcceptStream()
  117. }
  118. // AcceptStream is used to block until the next available stream
  119. // is ready to be accepted.
  120. func (s *Session) AcceptStream() (*Stream, error) {
  121. select {
  122. case stream := <-s.acceptCh:
  123. return stream, nil
  124. case <-s.shutdownCh:
  125. return nil, s.shutdownErr
  126. }
  127. }
  128. // Close is used to close the session and all streams.
  129. // Attempts to send a GoAway before closing the connection.
  130. func (s *Session) Close() error {
  131. s.shutdownLock.Lock()
  132. defer s.shutdownLock.Unlock()
  133. if s.shutdown {
  134. return nil
  135. }
  136. s.shutdown = true
  137. if s.shutdownErr == nil {
  138. s.shutdownErr = ErrSessionShutdown
  139. }
  140. close(s.shutdownCh)
  141. s.conn.Close()
  142. s.streamLock.Lock()
  143. defer s.streamLock.Unlock()
  144. for _, stream := range s.streams {
  145. stream.forceClose()
  146. }
  147. return nil
  148. }
  149. // exitErr is used to handle an error that is causing the
  150. // session to terminate.
  151. func (s *Session) exitErr(err error) {
  152. s.shutdownErr = err
  153. s.Close()
  154. }
  155. // GoAway can be used to prevent accepting further
  156. // connections. It does not close the underlying conn.
  157. func (s *Session) GoAway() error {
  158. return s.waitForSend(s.goAway(goAwayNormal), nil)
  159. }
  160. // goAway is used to send a goAway message
  161. func (s *Session) goAway(reason uint32) header {
  162. atomic.SwapInt32(&s.localGoAway, 1)
  163. hdr := header(make([]byte, headerSize))
  164. hdr.encode(typeGoAway, 0, 0, reason)
  165. return hdr
  166. }
  167. // Ping is used to measure the RTT response time
  168. func (s *Session) Ping() (time.Duration, error) {
  169. // Get a channel for the ping
  170. ch := make(chan struct{})
  171. // Get a new ping id, mark as pending
  172. s.pingLock.Lock()
  173. id := s.pingID
  174. s.pingID++
  175. s.pings[id] = ch
  176. s.pingLock.Unlock()
  177. // Send the ping request
  178. hdr := header(make([]byte, headerSize))
  179. hdr.encode(typePing, flagSYN, 0, id)
  180. if err := s.waitForSend(hdr, nil); err != nil {
  181. return 0, err
  182. }
  183. // Wait for a response
  184. start := time.Now()
  185. select {
  186. case <-ch:
  187. case <-s.shutdownCh:
  188. return 0, ErrSessionShutdown
  189. }
  190. // Compute the RTT
  191. return time.Now().Sub(start), nil
  192. }
  193. // keepalive is a long running goroutine that periodically does
  194. // a ping to keep the connection alive.
  195. func (s *Session) keepalive() {
  196. for {
  197. select {
  198. case <-time.After(s.config.KeepAliveInterval):
  199. s.Ping()
  200. case <-s.shutdownCh:
  201. return
  202. }
  203. }
  204. }
  205. // waitForSendErr waits to send a header, checking for a potential shutdown
  206. func (s *Session) waitForSend(hdr header, body io.Reader) error {
  207. errCh := make(chan error, 1)
  208. return s.waitForSendErr(hdr, body, errCh)
  209. }
  210. // waitForSendErr waits to send a header, checking for a potential shutdown
  211. func (s *Session) waitForSendErr(hdr header, body io.Reader, errCh chan error) error {
  212. ready := sendReady{Hdr: hdr, Body: body, Err: errCh}
  213. select {
  214. case s.sendCh <- ready:
  215. case <-s.shutdownCh:
  216. return ErrSessionShutdown
  217. }
  218. select {
  219. case err := <-errCh:
  220. return err
  221. case <-s.shutdownCh:
  222. return ErrSessionShutdown
  223. }
  224. }
  225. // sendNoWait does a send without waiting
  226. func (s *Session) sendNoWait(hdr header) error {
  227. select {
  228. case s.sendCh <- sendReady{Hdr: hdr}:
  229. return nil
  230. case <-s.shutdownCh:
  231. return ErrSessionShutdown
  232. }
  233. }
  234. // send is a long running goroutine that sends data
  235. func (s *Session) send() {
  236. for {
  237. select {
  238. case ready := <-s.sendCh:
  239. // Send a header if ready
  240. if ready.Hdr != nil {
  241. sent := 0
  242. for sent < len(ready.Hdr) {
  243. n, err := s.conn.Write(ready.Hdr[sent:])
  244. if err != nil {
  245. asyncSendErr(ready.Err, err)
  246. s.exitErr(err)
  247. return
  248. }
  249. sent += n
  250. }
  251. }
  252. // Send data from a body if given
  253. if ready.Body != nil {
  254. _, err := io.Copy(s.conn, ready.Body)
  255. if err != nil {
  256. asyncSendErr(ready.Err, err)
  257. s.exitErr(err)
  258. return
  259. }
  260. }
  261. // No error, successful send
  262. asyncSendErr(ready.Err, nil)
  263. case <-s.shutdownCh:
  264. return
  265. }
  266. }
  267. }
  268. // recv is a long running goroutine that accepts new data
  269. func (s *Session) recv() {
  270. hdr := header(make([]byte, headerSize))
  271. var handler func(header) error
  272. for {
  273. // Read the header
  274. if _, err := io.ReadFull(s.bufRead, hdr); err != nil {
  275. s.exitErr(err)
  276. return
  277. }
  278. // Verify the version
  279. if hdr.Version() != protoVersion {
  280. s.exitErr(ErrInvalidVersion)
  281. return
  282. }
  283. // Switch on the type
  284. switch hdr.MsgType() {
  285. case typeData:
  286. handler = s.handleStreamMessage
  287. case typeWindowUpdate:
  288. handler = s.handleStreamMessage
  289. case typeGoAway:
  290. handler = s.handleGoAway
  291. case typePing:
  292. handler = s.handlePing
  293. default:
  294. s.exitErr(ErrInvalidMsgType)
  295. return
  296. }
  297. // Invoke the handler
  298. if err := handler(hdr); err != nil {
  299. s.exitErr(err)
  300. return
  301. }
  302. }
  303. }
  304. // handleStreamMessage handles either a data or window update frame
  305. func (s *Session) handleStreamMessage(hdr header) error {
  306. // Check for a new stream creation
  307. id := hdr.StreamID()
  308. flags := hdr.Flags()
  309. if flags&flagSYN == flagSYN {
  310. if err := s.incomingStream(id); err != nil {
  311. return err
  312. }
  313. }
  314. // Get the stream
  315. s.streamLock.Lock()
  316. stream := s.streams[id]
  317. s.streamLock.Unlock()
  318. // If we do not have a stream, likely we sent a RST
  319. if stream == nil {
  320. return nil
  321. }
  322. // Check if this is a window update
  323. if hdr.MsgType() == typeWindowUpdate {
  324. if err := stream.incrSendWindow(hdr, flags); err != nil {
  325. s.sendNoWait(s.goAway(goAwayProtoErr))
  326. return err
  327. }
  328. return nil
  329. }
  330. // Read the new data
  331. if err := stream.readData(hdr, flags, s.bufRead); err != nil {
  332. s.sendNoWait(s.goAway(goAwayProtoErr))
  333. return err
  334. }
  335. return nil
  336. }
  337. // handlePing is invokde for a typePing frame
  338. func (s *Session) handlePing(hdr header) error {
  339. flags := hdr.Flags()
  340. pingID := hdr.Length()
  341. // Check if this is a query, respond back
  342. if flags&flagSYN == flagSYN {
  343. hdr := header(make([]byte, headerSize))
  344. hdr.encode(typePing, flagACK, 0, pingID)
  345. s.sendNoWait(hdr)
  346. return nil
  347. }
  348. // Handle a response
  349. s.pingLock.Lock()
  350. ch := s.pings[pingID]
  351. if ch != nil {
  352. delete(s.pings, pingID)
  353. close(ch)
  354. }
  355. s.pingLock.Unlock()
  356. return nil
  357. }
  358. // handleGoAway is invokde for a typeGoAway frame
  359. func (s *Session) handleGoAway(hdr header) error {
  360. code := hdr.Length()
  361. switch code {
  362. case goAwayNormal:
  363. atomic.SwapInt32(&s.remoteGoAway, 1)
  364. case goAwayProtoErr:
  365. return fmt.Errorf("yamux protocol error")
  366. case goAwayInternalErr:
  367. return fmt.Errorf("remote yamux internal error")
  368. default:
  369. return fmt.Errorf("unexpected go away received")
  370. }
  371. return nil
  372. }
  373. // incomingStream is used to create a new incoming stream
  374. func (s *Session) incomingStream(id uint32) error {
  375. // Reject immediately if we are doing a go away
  376. if atomic.LoadInt32(&s.localGoAway) == 1 {
  377. hdr := header(make([]byte, headerSize))
  378. hdr.encode(typeWindowUpdate, flagRST, id, 0)
  379. return s.sendNoWait(hdr)
  380. }
  381. // Allocate a new stream
  382. stream := newStream(s, id, streamSYNReceived)
  383. s.streamLock.Lock()
  384. defer s.streamLock.Unlock()
  385. // Check if stream already exists
  386. if _, ok := s.streams[id]; ok {
  387. s.sendNoWait(s.goAway(goAwayProtoErr))
  388. return ErrDuplicateStream
  389. }
  390. // Register the stream
  391. s.streams[id] = stream
  392. // Check if we've exceeded the backlog
  393. select {
  394. case s.acceptCh <- stream:
  395. return nil
  396. default:
  397. // Backlog exceeded! RST the stream
  398. delete(s.streams, id)
  399. stream.sendHdr.encode(typeWindowUpdate, flagRST, id, 0)
  400. return s.sendNoWait(stream.sendHdr)
  401. }
  402. }
  403. // closeStream is used to close a stream once both sides have
  404. // issued a close.
  405. func (s *Session) closeStream(id uint32, withLock bool) {
  406. if !withLock {
  407. s.streamLock.Lock()
  408. defer s.streamLock.Unlock()
  409. }
  410. delete(s.streams, id)
  411. }