session.go 12 KB

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