session.go 16 KB

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