session.go 10 KB

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