session.go 10 KB

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