session.go 16 KB

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