session.go 18 KB

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