session.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package mux
  2. import (
  3. "sync"
  4. "v2ray.com/core/transport/ray"
  5. )
  6. type SessionManager struct {
  7. sync.RWMutex
  8. count uint16
  9. sessions map[uint16]*Session
  10. }
  11. func NewSessionManager() *SessionManager {
  12. return &SessionManager{
  13. count: 0,
  14. sessions: make(map[uint16]*Session, 32),
  15. }
  16. }
  17. func (m *SessionManager) Size() int {
  18. m.RLock()
  19. defer m.RUnlock()
  20. return len(m.sessions)
  21. }
  22. func (m *SessionManager) Allocate(s *Session) {
  23. m.Lock()
  24. defer m.Unlock()
  25. m.count++
  26. s.ID = m.count
  27. m.sessions[s.ID] = s
  28. }
  29. func (m *SessionManager) Add(s *Session) {
  30. m.Lock()
  31. defer m.Unlock()
  32. m.sessions[s.ID] = s
  33. }
  34. func (m *SessionManager) Remove(id uint16) {
  35. m.Lock()
  36. defer m.Unlock()
  37. delete(m.sessions, id)
  38. }
  39. func (m *SessionManager) Get(id uint16) (*Session, bool) {
  40. m.RLock()
  41. defer m.RUnlock()
  42. s, found := m.sessions[id]
  43. return s, found
  44. }
  45. func (m *SessionManager) Close() {
  46. m.RLock()
  47. defer m.RUnlock()
  48. for _, s := range m.sessions {
  49. s.output.CloseError()
  50. }
  51. }
  52. type Session struct {
  53. sync.Mutex
  54. input ray.InputStream
  55. output ray.OutputStream
  56. parent *SessionManager
  57. ID uint16
  58. uplinkClosed bool
  59. downlinkClosed bool
  60. }
  61. func (s *Session) CloseUplink() {
  62. var allDone bool
  63. s.Lock()
  64. s.uplinkClosed = true
  65. allDone = s.uplinkClosed && s.downlinkClosed
  66. s.Unlock()
  67. if allDone {
  68. s.parent.Remove(s.ID)
  69. }
  70. }
  71. func (s *Session) CloseDownlink() {
  72. var allDone bool
  73. s.Lock()
  74. s.downlinkClosed = true
  75. allDone = s.uplinkClosed && s.downlinkClosed
  76. s.Unlock()
  77. if allDone {
  78. s.parent.Remove(s.ID)
  79. }
  80. }