session.go 19 KB

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