session.go 13 KB

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