session.go 15 KB

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