session.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646
  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. s.logger.Printf("[ERR] yamux: keepalive failed: %v", err)
  273. s.exitErr(ErrKeepAliveTimeout)
  274. return
  275. }
  276. case <-s.shutdownCh:
  277. return
  278. }
  279. }
  280. }
  281. // waitForSendErr waits to send a header, checking for a potential shutdown
  282. func (s *Session) waitForSend(hdr header, body io.Reader) error {
  283. errCh := make(chan error, 1)
  284. return s.waitForSendErr(hdr, body, errCh)
  285. }
  286. // waitForSendErr waits to send a header with optional data, checking for a
  287. // potential shutdown. Since there's the expectation that sends can happen
  288. // in a timely manner, we enforce the connection write timeout here.
  289. func (s *Session) waitForSendErr(hdr header, body io.Reader, errCh chan error) error {
  290. t := timerPool.Get()
  291. timer := t.(*time.Timer)
  292. timer.Reset(s.config.ConnectionWriteTimeout)
  293. defer func() {
  294. timer.Stop()
  295. select {
  296. case <-timer.C:
  297. default:
  298. }
  299. timerPool.Put(t)
  300. }()
  301. ready := sendReady{Hdr: hdr, Body: body, Err: errCh}
  302. select {
  303. case s.sendCh <- ready:
  304. case <-s.shutdownCh:
  305. return ErrSessionShutdown
  306. case <-timer.C:
  307. return ErrConnectionWriteTimeout
  308. }
  309. select {
  310. case err := <-errCh:
  311. return err
  312. case <-s.shutdownCh:
  313. return ErrSessionShutdown
  314. case <-timer.C:
  315. return ErrConnectionWriteTimeout
  316. }
  317. }
  318. // sendNoWait does a send without waiting. Since there's the expectation that
  319. // the send happens right here, we enforce the connection write timeout if we
  320. // can't queue the header to be sent.
  321. func (s *Session) sendNoWait(hdr header) error {
  322. t := timerPool.Get()
  323. timer := t.(*time.Timer)
  324. timer.Reset(s.config.ConnectionWriteTimeout)
  325. defer func() {
  326. timer.Stop()
  327. select {
  328. case <-timer.C:
  329. default:
  330. }
  331. timerPool.Put(t)
  332. }()
  333. select {
  334. case s.sendCh <- sendReady{Hdr: hdr}:
  335. return nil
  336. case <-s.shutdownCh:
  337. return ErrSessionShutdown
  338. case <-timer.C:
  339. return ErrConnectionWriteTimeout
  340. }
  341. }
  342. // send is a long running goroutine that sends data
  343. func (s *Session) send() {
  344. for {
  345. select {
  346. case ready := <-s.sendCh:
  347. // Send a header if ready
  348. if ready.Hdr != nil {
  349. sent := 0
  350. for sent < len(ready.Hdr) {
  351. n, err := s.conn.Write(ready.Hdr[sent:])
  352. if err != nil {
  353. s.logger.Printf("[ERR] yamux: Failed to write header: %v", err)
  354. asyncSendErr(ready.Err, err)
  355. s.exitErr(err)
  356. return
  357. }
  358. sent += n
  359. }
  360. }
  361. // Send data from a body if given
  362. if ready.Body != nil {
  363. _, err := io.Copy(s.conn, ready.Body)
  364. if err != nil {
  365. s.logger.Printf("[ERR] yamux: Failed to write body: %v", err)
  366. asyncSendErr(ready.Err, err)
  367. s.exitErr(err)
  368. return
  369. }
  370. }
  371. // No error, successful send
  372. asyncSendErr(ready.Err, nil)
  373. case <-s.shutdownCh:
  374. return
  375. }
  376. }
  377. }
  378. // recv is a long running goroutine that accepts new data
  379. func (s *Session) recv() {
  380. if err := s.recvLoop(); err != nil {
  381. s.exitErr(err)
  382. }
  383. }
  384. // Ensure that the index of the handler (typeData/typeWindowUpdate/etc) matches the message type
  385. var (
  386. handlers = []func(*Session, header) error{
  387. typeData: (*Session).handleStreamMessage,
  388. typeWindowUpdate: (*Session).handleStreamMessage,
  389. typePing: (*Session).handlePing,
  390. typeGoAway: (*Session).handleGoAway,
  391. }
  392. )
  393. // recvLoop continues to receive data until a fatal error is encountered
  394. func (s *Session) recvLoop() error {
  395. defer close(s.recvDoneCh)
  396. hdr := header(make([]byte, headerSize))
  397. for {
  398. // Read the header
  399. if _, err := io.ReadFull(s.bufRead, hdr); err != nil {
  400. if err != io.EOF && !strings.Contains(err.Error(), "closed") && !strings.Contains(err.Error(), "reset by peer") {
  401. s.logger.Printf("[ERR] yamux: Failed to read header: %v", err)
  402. }
  403. return err
  404. }
  405. // Verify the version
  406. if hdr.Version() != protoVersion {
  407. s.logger.Printf("[ERR] yamux: Invalid protocol version: %d", hdr.Version())
  408. return ErrInvalidVersion
  409. }
  410. mt := hdr.MsgType()
  411. if mt < typeData || mt > typeGoAway {
  412. return ErrInvalidMsgType
  413. }
  414. if err := handlers[mt](s, hdr); err != nil {
  415. return err
  416. }
  417. }
  418. }
  419. // handleStreamMessage handles either a data or window update frame
  420. func (s *Session) handleStreamMessage(hdr header) error {
  421. // Check for a new stream creation
  422. id := hdr.StreamID()
  423. flags := hdr.Flags()
  424. if flags&flagSYN == flagSYN {
  425. if err := s.incomingStream(id); err != nil {
  426. return err
  427. }
  428. }
  429. // Get the stream
  430. s.streamLock.Lock()
  431. stream := s.streams[id]
  432. s.streamLock.Unlock()
  433. // If we do not have a stream, likely we sent a RST
  434. if stream == nil {
  435. // Drain any data on the wire
  436. if hdr.MsgType() == typeData && hdr.Length() > 0 {
  437. s.logger.Printf("[WARN] yamux: Discarding data for stream: %d", id)
  438. if _, err := io.CopyN(ioutil.Discard, s.bufRead, int64(hdr.Length())); err != nil {
  439. s.logger.Printf("[ERR] yamux: Failed to discard data: %v", err)
  440. return nil
  441. }
  442. } else {
  443. s.logger.Printf("[WARN] yamux: frame for missing stream: %v", hdr)
  444. }
  445. return nil
  446. }
  447. // Check if this is a window update
  448. if hdr.MsgType() == typeWindowUpdate {
  449. if err := stream.incrSendWindow(hdr, flags); err != nil {
  450. if sendErr := s.sendNoWait(s.goAway(goAwayProtoErr)); sendErr != nil {
  451. s.logger.Printf("[WARN] yamux: failed to send go away: %v", sendErr)
  452. }
  453. return err
  454. }
  455. return nil
  456. }
  457. // Read the new data
  458. if err := stream.readData(hdr, flags, s.bufRead); err != nil {
  459. if sendErr := s.sendNoWait(s.goAway(goAwayProtoErr)); sendErr != nil {
  460. s.logger.Printf("[WARN] yamux: failed to send go away: %v", sendErr)
  461. }
  462. return err
  463. }
  464. return nil
  465. }
  466. // handlePing is invokde for a typePing frame
  467. func (s *Session) handlePing(hdr header) error {
  468. flags := hdr.Flags()
  469. pingID := hdr.Length()
  470. // Check if this is a query, respond back in a separate context so we
  471. // don't interfere with the receiving thread blocking for the write.
  472. if flags&flagSYN == flagSYN {
  473. go func() {
  474. hdr := header(make([]byte, headerSize))
  475. hdr.encode(typePing, flagACK, 0, pingID)
  476. if err := s.sendNoWait(hdr); err != nil {
  477. s.logger.Printf("[WARN] yamux: failed to send ping reply: %v", err)
  478. }
  479. }()
  480. return nil
  481. }
  482. // Handle a response
  483. s.pingLock.Lock()
  484. ch := s.pings[pingID]
  485. if ch != nil {
  486. delete(s.pings, pingID)
  487. close(ch)
  488. }
  489. s.pingLock.Unlock()
  490. return nil
  491. }
  492. // handleGoAway is invokde for a typeGoAway frame
  493. func (s *Session) handleGoAway(hdr header) error {
  494. code := hdr.Length()
  495. switch code {
  496. case goAwayNormal:
  497. atomic.SwapInt32(&s.remoteGoAway, 1)
  498. case goAwayProtoErr:
  499. s.logger.Printf("[ERR] yamux: received protocol error go away")
  500. return fmt.Errorf("yamux protocol error")
  501. case goAwayInternalErr:
  502. s.logger.Printf("[ERR] yamux: received internal error go away")
  503. return fmt.Errorf("remote yamux internal error")
  504. default:
  505. s.logger.Printf("[ERR] yamux: received unexpected go away")
  506. return fmt.Errorf("unexpected go away received")
  507. }
  508. return nil
  509. }
  510. // incomingStream is used to create a new incoming stream
  511. func (s *Session) incomingStream(id uint32) error {
  512. // Reject immediately if we are doing a go away
  513. if atomic.LoadInt32(&s.localGoAway) == 1 {
  514. hdr := header(make([]byte, headerSize))
  515. hdr.encode(typeWindowUpdate, flagRST, id, 0)
  516. return s.sendNoWait(hdr)
  517. }
  518. // Allocate a new stream
  519. stream := newStream(s, id, streamSYNReceived)
  520. s.streamLock.Lock()
  521. defer s.streamLock.Unlock()
  522. // Check if stream already exists
  523. if _, ok := s.streams[id]; ok {
  524. s.logger.Printf("[ERR] yamux: duplicate stream declared")
  525. if sendErr := s.sendNoWait(s.goAway(goAwayProtoErr)); sendErr != nil {
  526. s.logger.Printf("[WARN] yamux: failed to send go away: %v", sendErr)
  527. }
  528. return ErrDuplicateStream
  529. }
  530. // Register the stream
  531. s.streams[id] = stream
  532. // Check if we've exceeded the backlog
  533. select {
  534. case s.acceptCh <- stream:
  535. return nil
  536. default:
  537. // Backlog exceeded! RST the stream
  538. s.logger.Printf("[WARN] yamux: backlog exceeded, forcing connection reset")
  539. delete(s.streams, id)
  540. stream.sendHdr.encode(typeWindowUpdate, flagRST, id, 0)
  541. return s.sendNoWait(stream.sendHdr)
  542. }
  543. }
  544. // closeStream is used to close a stream once both sides have
  545. // issued a close. If there was an in-flight SYN and the stream
  546. // was not yet established, then this will give the credit back.
  547. func (s *Session) closeStream(id uint32) {
  548. s.streamLock.Lock()
  549. if _, ok := s.inflight[id]; ok {
  550. select {
  551. case <-s.synCh:
  552. default:
  553. s.logger.Printf("[ERR] yamux: SYN tracking out of sync")
  554. }
  555. }
  556. delete(s.streams, id)
  557. s.streamLock.Unlock()
  558. }
  559. // establishStream is used to mark a stream that was in the
  560. // SYN Sent state as established.
  561. func (s *Session) establishStream(id uint32) {
  562. s.streamLock.Lock()
  563. if _, ok := s.inflight[id]; ok {
  564. delete(s.inflight, id)
  565. } else {
  566. s.logger.Printf("[ERR] yamux: established stream without inflight SYN (no tracking entry)")
  567. }
  568. select {
  569. case <-s.synCh:
  570. default:
  571. s.logger.Printf("[ERR] yamux: established stream without inflight SYN (didn't have semaphore)")
  572. }
  573. s.streamLock.Unlock()
  574. }