session.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. package mux
  2. import (
  3. "io"
  4. "sync"
  5. "v2ray.com/core/common/buf"
  6. "v2ray.com/core/common/protocol"
  7. "v2ray.com/core/transport/ray"
  8. )
  9. type SessionManager struct {
  10. sync.RWMutex
  11. sessions map[uint16]*Session
  12. count uint16
  13. closed bool
  14. }
  15. func NewSessionManager() *SessionManager {
  16. return &SessionManager{
  17. count: 0,
  18. sessions: make(map[uint16]*Session, 16),
  19. }
  20. }
  21. func (m *SessionManager) Size() int {
  22. m.RLock()
  23. defer m.RUnlock()
  24. return len(m.sessions)
  25. }
  26. func (m *SessionManager) Count() int {
  27. m.RLock()
  28. defer m.RUnlock()
  29. return int(m.count)
  30. }
  31. func (m *SessionManager) Allocate() *Session {
  32. m.Lock()
  33. defer m.Unlock()
  34. if m.closed {
  35. return nil
  36. }
  37. m.count++
  38. s := &Session{
  39. ID: m.count,
  40. parent: m,
  41. }
  42. m.sessions[s.ID] = s
  43. return s
  44. }
  45. func (m *SessionManager) Add(s *Session) {
  46. m.Lock()
  47. defer m.Unlock()
  48. if m.closed {
  49. return
  50. }
  51. m.sessions[s.ID] = s
  52. }
  53. func (m *SessionManager) Remove(id uint16) {
  54. m.Lock()
  55. defer m.Unlock()
  56. if m.closed {
  57. return
  58. }
  59. delete(m.sessions, id)
  60. }
  61. func (m *SessionManager) Get(id uint16) (*Session, bool) {
  62. m.RLock()
  63. defer m.RUnlock()
  64. if m.closed {
  65. return nil, false
  66. }
  67. s, found := m.sessions[id]
  68. return s, found
  69. }
  70. func (m *SessionManager) CloseIfNoSession() bool {
  71. m.Lock()
  72. defer m.Unlock()
  73. if m.closed {
  74. return true
  75. }
  76. if len(m.sessions) != 0 {
  77. return false
  78. }
  79. m.closed = true
  80. return true
  81. }
  82. func (m *SessionManager) Close() {
  83. m.Lock()
  84. defer m.Unlock()
  85. if m.closed {
  86. return
  87. }
  88. m.closed = true
  89. for _, s := range m.sessions {
  90. s.input.Close()
  91. s.output.Close()
  92. }
  93. m.sessions = nil
  94. }
  95. type Session struct {
  96. input ray.InputStream
  97. output ray.OutputStream
  98. parent *SessionManager
  99. ID uint16
  100. transferType protocol.TransferType
  101. }
  102. // Close closes all resources associated with this session.
  103. func (s *Session) Close() {
  104. s.output.Close()
  105. s.input.Close()
  106. s.parent.Remove(s.ID)
  107. }
  108. func (s *Session) NewReader(reader io.Reader) buf.Reader {
  109. if s.transferType == protocol.TransferTypeStream {
  110. return NewStreamReader(reader)
  111. }
  112. return NewPacketReader(reader)
  113. }