session.go 16 KB

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