session.go 11 KB

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