session.go 10.0 KB

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