session.go 18 KB

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