session.go 18 KB

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