session.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  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, 32),
  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. m.sessions[s.ID] = s
  49. }
  50. func (m *SessionManager) Remove(id uint16) {
  51. m.Lock()
  52. defer m.Unlock()
  53. delete(m.sessions, id)
  54. }
  55. func (m *SessionManager) Get(id uint16) (*Session, bool) {
  56. m.RLock()
  57. defer m.RUnlock()
  58. if m.closed {
  59. return nil, false
  60. }
  61. s, found := m.sessions[id]
  62. return s, found
  63. }
  64. func (m *SessionManager) CloseIfNoSession() bool {
  65. m.Lock()
  66. defer m.Unlock()
  67. if m.closed {
  68. return true
  69. }
  70. if len(m.sessions) != 0 {
  71. return false
  72. }
  73. m.closed = true
  74. return true
  75. }
  76. func (m *SessionManager) Close() {
  77. m.Lock()
  78. defer m.Unlock()
  79. if m.closed {
  80. return
  81. }
  82. m.closed = true
  83. for _, s := range m.sessions {
  84. s.input.Close()
  85. s.output.Close()
  86. }
  87. m.sessions = make(map[uint16]*Session)
  88. }
  89. type Session struct {
  90. input ray.InputStream
  91. output ray.OutputStream
  92. parent *SessionManager
  93. ID uint16
  94. transferType protocol.TransferType
  95. }
  96. // Close closes all resources associated with this session.
  97. func (s *Session) Close() {
  98. s.output.Close()
  99. s.input.Close()
  100. s.parent.Remove(s.ID)
  101. }
  102. func (s *Session) NewReader(reader io.Reader) buf.Reader {
  103. if s.transferType == protocol.TransferTypeStream {
  104. return NewStreamReader(reader)
  105. }
  106. return NewPacketReader(reader)
  107. }