session.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  1. package yamux
  2. import (
  3. "bufio"
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "log"
  8. "math"
  9. "net"
  10. "strings"
  11. "sync"
  12. "sync/atomic"
  13. "time"
  14. )
  15. // Session is used to wrap a reliable ordered connection and to
  16. // multiplex it into multiple streams.
  17. type Session struct {
  18. // remoteGoAway indicates the remote side does
  19. // not want futher connections. Must be first for alignment.
  20. remoteGoAway int32
  21. // localGoAway indicates that we should stop
  22. // accepting futher connections. Must be first for alignment.
  23. localGoAway int32
  24. // nextStreamID is the next stream we should
  25. // send. This depends if we are a client/server.
  26. nextStreamID uint32
  27. // config holds our configuration
  28. config *Config
  29. // logger is used for our logs
  30. logger *log.Logger
  31. // conn is the underlying connection
  32. conn io.ReadWriteCloser
  33. // bufRead is a buffered reader
  34. bufRead *bufio.Reader
  35. // pings is used to track inflight pings
  36. pings map[uint32]chan struct{}
  37. pingID uint32
  38. pingLock sync.Mutex
  39. // streams maps a stream id to a stream, and inflight has an entry
  40. // for any outgoing stream that has not yet been established. Both are
  41. // protected by streamLock.
  42. streams map[uint32]*Stream
  43. inflight map[uint32]struct{}
  44. streamLock sync.Mutex
  45. // synCh acts like a semaphore. It is sized to the AcceptBacklog which
  46. // is assumed to be symmetric between the client and server. This allows
  47. // the client to avoid exceeding the backlog and instead blocks the open.
  48. synCh chan struct{}
  49. // acceptCh is used to pass ready streams to the client
  50. acceptCh chan *Stream
  51. // sendCh is used to mark a stream as ready to send,
  52. // or to send a header out directly.
  53. sendCh chan sendReady
  54. // recvDoneCh is closed when recv() exits to avoid a race
  55. // between stream registration and stream shutdown
  56. recvDoneCh chan struct{}
  57. // shutdown is used to safely close a session
  58. shutdown bool
  59. shutdownErr error
  60. shutdownCh chan struct{}
  61. shutdownLock sync.Mutex
  62. }
  63. // sendReady is used to either mark a stream as ready
  64. // or to directly send a header
  65. type sendReady struct {
  66. Hdr []byte
  67. Body io.Reader
  68. Err chan error
  69. }
  70. // Optional interface that the underlying connection can implement to return
  71. // an existing *bufio.Reader if there is one. This prevents yamux from creating
  72. // a layered bufio.Reader in the case that the conn already has one.
  73. type BufioReaderer interface {
  74. BufioReader() *bufio.Reader
  75. }
  76. // newSession is used to construct a new session
  77. func newSession(config *Config, conn io.ReadWriteCloser, client bool) *Session {
  78. logger := config.Logger
  79. if logger == nil {
  80. logger = log.New(config.LogOutput, "", log.LstdFlags)
  81. }
  82. var bufRead *bufio.Reader
  83. if br, ok := conn.(BufioReaderer); ok {
  84. bufRead = br.BufioReader()
  85. } else {
  86. bufRead = bufio.NewReader(conn)
  87. }
  88. s := &Session{
  89. config: config,
  90. logger: logger,
  91. conn: conn,
  92. bufRead: bufRead,
  93. pings: make(map[uint32]chan struct{}),
  94. streams: make(map[uint32]*Stream),
  95. inflight: make(map[uint32]struct{}),
  96. synCh: make(chan struct{}, config.AcceptBacklog),
  97. acceptCh: make(chan *Stream, config.AcceptBacklog),
  98. sendCh: make(chan sendReady, 64),
  99. recvDoneCh: make(chan struct{}),
  100. shutdownCh: make(chan struct{}),
  101. }
  102. if client {
  103. s.nextStreamID = 1
  104. } else {
  105. s.nextStreamID = 2
  106. }
  107. go s.recv()
  108. go s.send()
  109. if config.EnableKeepAlive {
  110. go s.keepalive()
  111. }
  112. return s
  113. }
  114. // IsClosed does a safe check to see if we have shutdown
  115. func (s *Session) IsClosed() bool {
  116. select {
  117. case <-s.shutdownCh:
  118. return true
  119. default:
  120. return false
  121. }
  122. }
  123. // CloseChan returns a read-only channel which is closed as
  124. // soon as the session is closed.
  125. func (s *Session) CloseChan() <-chan struct{} {
  126. return s.shutdownCh
  127. }
  128. // NumStreams returns the number of currently open streams
  129. func (s *Session) NumStreams() int {
  130. s.streamLock.Lock()
  131. num := len(s.streams)
  132. s.streamLock.Unlock()
  133. return num
  134. }
  135. // Open is used to create a new stream as a net.Conn
  136. func (s *Session) Open() (net.Conn, error) {
  137. conn, err := s.OpenStream()
  138. if err != nil {
  139. return nil, err
  140. }
  141. return conn, nil
  142. }
  143. // OpenStream is used to create a new stream
  144. func (s *Session) OpenStream() (*Stream, error) {
  145. if s.IsClosed() {
  146. return nil, ErrSessionShutdown
  147. }
  148. if atomic.LoadInt32(&s.remoteGoAway) == 1 {
  149. return nil, ErrRemoteGoAway
  150. }
  151. // Block if we have too many inflight SYNs
  152. select {
  153. case s.synCh <- struct{}{}:
  154. case <-s.shutdownCh:
  155. return nil, ErrSessionShutdown
  156. }
  157. GET_ID:
  158. // Get an ID, and check for stream exhaustion
  159. id := atomic.LoadUint32(&s.nextStreamID)
  160. if id >= math.MaxUint32-1 {
  161. return nil, ErrStreamsExhausted
  162. }
  163. if !atomic.CompareAndSwapUint32(&s.nextStreamID, id, id+2) {
  164. goto GET_ID
  165. }
  166. // Register the stream
  167. stream := newStream(s, id, streamInit)
  168. s.streamLock.Lock()
  169. s.streams[id] = stream
  170. s.inflight[id] = struct{}{}
  171. s.streamLock.Unlock()
  172. // Send the window update to create
  173. if err := stream.sendWindowUpdate(); err != nil {
  174. select {
  175. case <-s.synCh:
  176. default:
  177. s.logger.Printf("[ERR] yamux: aborted stream open without inflight syn semaphore")
  178. }
  179. return nil, err
  180. }
  181. return stream, nil
  182. }
  183. // Accept is used to block until the next available stream
  184. // is ready to be accepted.
  185. func (s *Session) Accept() (net.Conn, error) {
  186. conn, err := s.AcceptStream()
  187. if err != nil {
  188. return nil, err
  189. }
  190. return conn, err
  191. }
  192. // AcceptStream is used to block until the next available stream
  193. // is ready to be accepted.
  194. func (s *Session) AcceptStream() (*Stream, error) {
  195. select {
  196. case stream := <-s.acceptCh:
  197. if err := stream.sendWindowUpdate(); err != nil {
  198. return nil, err
  199. }
  200. return stream, nil
  201. case <-s.shutdownCh:
  202. return nil, s.shutdownErr
  203. }
  204. }
  205. // Close is used to close the session and all streams.
  206. // Attempts to send a GoAway before closing the connection.
  207. func (s *Session) Close() error {
  208. s.shutdownLock.Lock()
  209. defer s.shutdownLock.Unlock()
  210. if s.shutdown {
  211. return nil
  212. }
  213. s.shutdown = true
  214. if s.shutdownErr == nil {
  215. s.shutdownErr = ErrSessionShutdown
  216. }
  217. close(s.shutdownCh)
  218. s.conn.Close()
  219. <-s.recvDoneCh
  220. s.streamLock.Lock()
  221. defer s.streamLock.Unlock()
  222. for _, stream := range s.streams {
  223. stream.forceClose()
  224. }
  225. return nil
  226. }
  227. // exitErr is used to handle an error that is causing the
  228. // session to terminate.
  229. func (s *Session) exitErr(err error) {
  230. s.shutdownLock.Lock()
  231. if s.shutdownErr == nil {
  232. s.shutdownErr = err
  233. }
  234. s.shutdownLock.Unlock()
  235. s.Close()
  236. }
  237. // GoAway can be used to prevent accepting further
  238. // connections. It does not close the underlying conn.
  239. func (s *Session) GoAway() error {
  240. return s.waitForSend(s.goAway(goAwayNormal), nil)
  241. }
  242. // goAway is used to send a goAway message
  243. func (s *Session) goAway(reason uint32) header {
  244. atomic.SwapInt32(&s.localGoAway, 1)
  245. hdr := header(make([]byte, headerSize))
  246. hdr.encode(typeGoAway, 0, 0, reason)
  247. return hdr
  248. }
  249. // Ping is used to measure the RTT response time
  250. func (s *Session) Ping() (time.Duration, error) {
  251. // Get a channel for the ping
  252. ch := make(chan struct{})
  253. // Get a new ping id, mark as pending
  254. s.pingLock.Lock()
  255. id := s.pingID
  256. s.pingID++
  257. s.pings[id] = ch
  258. s.pingLock.Unlock()
  259. // Send the ping request
  260. hdr := header(make([]byte, headerSize))
  261. hdr.encode(typePing, flagSYN, 0, id)
  262. if err := s.waitForSend(hdr, nil); err != nil {
  263. return 0, err
  264. }
  265. // Wait for a response
  266. start := time.Now()
  267. select {
  268. case <-ch:
  269. case <-time.After(s.config.ConnectionWriteTimeout):
  270. s.pingLock.Lock()
  271. delete(s.pings, id) // Ignore it if a response comes later.
  272. s.pingLock.Unlock()
  273. return 0, ErrTimeout
  274. case <-s.shutdownCh:
  275. return 0, ErrSessionShutdown
  276. }
  277. // Compute the RTT
  278. return time.Now().Sub(start), nil
  279. }
  280. // keepalive is a long running goroutine that periodically does
  281. // a ping to keep the connection alive.
  282. func (s *Session) keepalive() {
  283. for {
  284. select {
  285. case <-time.After(s.config.KeepAliveInterval):
  286. _, err := s.Ping()
  287. if err != nil {
  288. if err != ErrSessionShutdown {
  289. s.logger.Printf("[ERR] yamux: keepalive failed: %v", err)
  290. s.exitErr(ErrKeepAliveTimeout)
  291. }
  292. return
  293. }
  294. case <-s.shutdownCh:
  295. return
  296. }
  297. }
  298. }
  299. // waitForSendErr waits to send a header, checking for a potential shutdown
  300. func (s *Session) waitForSend(hdr header, body io.Reader) error {
  301. errCh := make(chan error, 1)
  302. return s.waitForSendErr(hdr, body, errCh)
  303. }
  304. // waitForSendErr waits to send a header with optional data, checking for a
  305. // potential shutdown. Since there's the expectation that sends can happen
  306. // in a timely manner, we enforce the connection write timeout here.
  307. func (s *Session) waitForSendErr(hdr header, body io.Reader, errCh chan error) error {
  308. t := timerPool.Get()
  309. timer := t.(*time.Timer)
  310. timer.Reset(s.config.ConnectionWriteTimeout)
  311. defer func() {
  312. timer.Stop()
  313. select {
  314. case <-timer.C:
  315. default:
  316. }
  317. timerPool.Put(t)
  318. }()
  319. ready := sendReady{Hdr: hdr, Body: body, Err: errCh}
  320. select {
  321. case s.sendCh <- ready:
  322. case <-s.shutdownCh:
  323. return ErrSessionShutdown
  324. case <-timer.C:
  325. return ErrConnectionWriteTimeout
  326. }
  327. select {
  328. case err := <-errCh:
  329. return err
  330. case <-s.shutdownCh:
  331. return ErrSessionShutdown
  332. case <-timer.C:
  333. return ErrConnectionWriteTimeout
  334. }
  335. }
  336. // sendNoWait does a send without waiting. Since there's the expectation that
  337. // the send happens right here, we enforce the connection write timeout if we
  338. // can't queue the header to be sent.
  339. func (s *Session) sendNoWait(hdr header) error {
  340. t := timerPool.Get()
  341. timer := t.(*time.Timer)
  342. timer.Reset(s.config.ConnectionWriteTimeout)
  343. defer func() {
  344. timer.Stop()
  345. select {
  346. case <-timer.C:
  347. default:
  348. }
  349. timerPool.Put(t)
  350. }()
  351. select {
  352. case s.sendCh <- sendReady{Hdr: hdr}:
  353. return nil
  354. case <-s.shutdownCh:
  355. return ErrSessionShutdown
  356. case <-timer.C:
  357. return ErrConnectionWriteTimeout
  358. }
  359. }
  360. // send is a long running goroutine that sends data
  361. func (s *Session) send() {
  362. for {
  363. select {
  364. case ready := <-s.sendCh:
  365. // Send a header if ready
  366. if ready.Hdr != nil {
  367. sent := 0
  368. for sent < len(ready.Hdr) {
  369. n, err := s.conn.Write(ready.Hdr[sent:])
  370. if err != nil {
  371. s.logger.Printf("[ERR] yamux: Failed to write header: %v", err)
  372. asyncSendErr(ready.Err, err)
  373. s.exitErr(err)
  374. return
  375. }
  376. sent += n
  377. }
  378. }
  379. // Send data from a body if given
  380. if ready.Body != nil {
  381. _, err := io.Copy(s.conn, ready.Body)
  382. if err != nil {
  383. s.logger.Printf("[ERR] yamux: Failed to write body: %v", err)
  384. asyncSendErr(ready.Err, err)
  385. s.exitErr(err)
  386. return
  387. }
  388. }
  389. // No error, successful send
  390. asyncSendErr(ready.Err, nil)
  391. case <-s.shutdownCh:
  392. return
  393. }
  394. }
  395. }
  396. // recv is a long running goroutine that accepts new data
  397. func (s *Session) recv() {
  398. if err := s.recvLoop(); err != nil {
  399. s.exitErr(err)
  400. }
  401. }
  402. // Ensure that the index of the handler (typeData/typeWindowUpdate/etc) matches the message type
  403. var (
  404. handlers = []func(*Session, header) error{
  405. typeData: (*Session).handleStreamMessage,
  406. typeWindowUpdate: (*Session).handleStreamMessage,
  407. typePing: (*Session).handlePing,
  408. typeGoAway: (*Session).handleGoAway,
  409. }
  410. )
  411. // recvLoop continues to receive data until a fatal error is encountered
  412. func (s *Session) recvLoop() error {
  413. defer close(s.recvDoneCh)
  414. hdr := header(make([]byte, headerSize))
  415. for {
  416. // Read the header
  417. if _, err := io.ReadFull(s.bufRead, hdr); err != nil {
  418. if err != io.EOF && !strings.Contains(err.Error(), "closed") && !strings.Contains(err.Error(), "reset by peer") {
  419. s.logger.Printf("[ERR] yamux: Failed to read header: %v", err)
  420. }
  421. return err
  422. }
  423. // Verify the version
  424. if hdr.Version() != protoVersion {
  425. s.logger.Printf("[ERR] yamux: Invalid protocol version: %d", hdr.Version())
  426. return ErrInvalidVersion
  427. }
  428. mt := hdr.MsgType()
  429. if mt < typeData || mt > typeGoAway {
  430. return ErrInvalidMsgType
  431. }
  432. if err := handlers[mt](s, hdr); err != nil {
  433. return err
  434. }
  435. }
  436. }
  437. // handleStreamMessage handles either a data or window update frame
  438. func (s *Session) handleStreamMessage(hdr header) error {
  439. // Check for a new stream creation
  440. id := hdr.StreamID()
  441. flags := hdr.Flags()
  442. if flags&flagSYN == flagSYN {
  443. if err := s.incomingStream(id); err != nil {
  444. return err
  445. }
  446. }
  447. // Get the stream
  448. s.streamLock.Lock()
  449. stream := s.streams[id]
  450. s.streamLock.Unlock()
  451. // If we do not have a stream, likely we sent a RST
  452. if stream == nil {
  453. // Drain any data on the wire
  454. if hdr.MsgType() == typeData && hdr.Length() > 0 {
  455. s.logger.Printf("[WARN] yamux: Discarding data for stream: %d", id)
  456. if _, err := io.CopyN(ioutil.Discard, s.bufRead, int64(hdr.Length())); err != nil {
  457. s.logger.Printf("[ERR] yamux: Failed to discard data: %v", err)
  458. return nil
  459. }
  460. } else {
  461. s.logger.Printf("[WARN] yamux: frame for missing stream: %v", hdr)
  462. }
  463. return nil
  464. }
  465. // Check if this is a window update
  466. if hdr.MsgType() == typeWindowUpdate {
  467. if err := stream.incrSendWindow(hdr, flags); err != nil {
  468. if sendErr := s.sendNoWait(s.goAway(goAwayProtoErr)); sendErr != nil {
  469. s.logger.Printf("[WARN] yamux: failed to send go away: %v", sendErr)
  470. }
  471. return err
  472. }
  473. return nil
  474. }
  475. // Read the new data
  476. if err := stream.readData(hdr, flags, s.bufRead); err != nil {
  477. if sendErr := s.sendNoWait(s.goAway(goAwayProtoErr)); sendErr != nil {
  478. s.logger.Printf("[WARN] yamux: failed to send go away: %v", sendErr)
  479. }
  480. return err
  481. }
  482. return nil
  483. }
  484. // handlePing is invokde for a typePing frame
  485. func (s *Session) handlePing(hdr header) error {
  486. flags := hdr.Flags()
  487. pingID := hdr.Length()
  488. // Check if this is a query, respond back in a separate context so we
  489. // don't interfere with the receiving thread blocking for the write.
  490. if flags&flagSYN == flagSYN {
  491. go func() {
  492. hdr := header(make([]byte, headerSize))
  493. hdr.encode(typePing, flagACK, 0, pingID)
  494. if err := s.sendNoWait(hdr); err != nil {
  495. s.logger.Printf("[WARN] yamux: failed to send ping reply: %v", err)
  496. }
  497. }()
  498. return nil
  499. }
  500. // Handle a response
  501. s.pingLock.Lock()
  502. ch := s.pings[pingID]
  503. if ch != nil {
  504. delete(s.pings, pingID)
  505. close(ch)
  506. }
  507. s.pingLock.Unlock()
  508. return nil
  509. }
  510. // handleGoAway is invokde for a typeGoAway frame
  511. func (s *Session) handleGoAway(hdr header) error {
  512. code := hdr.Length()
  513. switch code {
  514. case goAwayNormal:
  515. atomic.SwapInt32(&s.remoteGoAway, 1)
  516. case goAwayProtoErr:
  517. s.logger.Printf("[ERR] yamux: received protocol error go away")
  518. return fmt.Errorf("yamux protocol error")
  519. case goAwayInternalErr:
  520. s.logger.Printf("[ERR] yamux: received internal error go away")
  521. return fmt.Errorf("remote yamux internal error")
  522. default:
  523. s.logger.Printf("[ERR] yamux: received unexpected go away")
  524. return fmt.Errorf("unexpected go away received")
  525. }
  526. return nil
  527. }
  528. // incomingStream is used to create a new incoming stream
  529. func (s *Session) incomingStream(id uint32) error {
  530. // Reject immediately if we are doing a go away
  531. if atomic.LoadInt32(&s.localGoAway) == 1 {
  532. hdr := header(make([]byte, headerSize))
  533. hdr.encode(typeWindowUpdate, flagRST, id, 0)
  534. return s.sendNoWait(hdr)
  535. }
  536. // Allocate a new stream
  537. stream := newStream(s, id, streamSYNReceived)
  538. s.streamLock.Lock()
  539. defer s.streamLock.Unlock()
  540. // Check if stream already exists
  541. if _, ok := s.streams[id]; ok {
  542. s.logger.Printf("[ERR] yamux: duplicate stream declared")
  543. if sendErr := s.sendNoWait(s.goAway(goAwayProtoErr)); sendErr != nil {
  544. s.logger.Printf("[WARN] yamux: failed to send go away: %v", sendErr)
  545. }
  546. return ErrDuplicateStream
  547. }
  548. // Register the stream
  549. s.streams[id] = stream
  550. // Check if we've exceeded the backlog
  551. select {
  552. case s.acceptCh <- stream:
  553. return nil
  554. default:
  555. // Backlog exceeded! RST the stream
  556. s.logger.Printf("[WARN] yamux: backlog exceeded, forcing connection reset")
  557. delete(s.streams, id)
  558. stream.sendHdr.encode(typeWindowUpdate, flagRST, id, 0)
  559. return s.sendNoWait(stream.sendHdr)
  560. }
  561. }
  562. // closeStream is used to close a stream once both sides have
  563. // issued a close. If there was an in-flight SYN and the stream
  564. // was not yet established, then this will give the credit back.
  565. func (s *Session) closeStream(id uint32) {
  566. s.streamLock.Lock()
  567. if _, ok := s.inflight[id]; ok {
  568. select {
  569. case <-s.synCh:
  570. default:
  571. s.logger.Printf("[ERR] yamux: SYN tracking out of sync")
  572. }
  573. }
  574. delete(s.streams, id)
  575. s.streamLock.Unlock()
  576. }
  577. // establishStream is used to mark a stream that was in the
  578. // SYN Sent state as established.
  579. func (s *Session) establishStream(id uint32) {
  580. s.streamLock.Lock()
  581. if _, ok := s.inflight[id]; ok {
  582. delete(s.inflight, id)
  583. } else {
  584. s.logger.Printf("[ERR] yamux: established stream without inflight SYN (no tracking entry)")
  585. }
  586. select {
  587. case <-s.synCh:
  588. default:
  589. s.logger.Printf("[ERR] yamux: established stream without inflight SYN (didn't have semaphore)")
  590. }
  591. s.streamLock.Unlock()
  592. }