session.go 12 KB

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