session.go 16 KB

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