1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-06-30 19:15:23 +00:00
v2fly/app/proxyman/mux/session.go

138 lines
2.0 KiB
Go
Raw Normal View History

package mux
import (
2017-05-02 20:23:07 +00:00
"io"
"sync"
2017-05-02 20:23:07 +00:00
"v2ray.com/core/common/buf"
"v2ray.com/core/common/protocol"
"v2ray.com/core/transport/ray"
)
type SessionManager struct {
sync.RWMutex
sessions map[uint16]*Session
2017-04-19 19:27:21 +00:00
count uint16
2017-04-13 18:14:07 +00:00
closed bool
}
func NewSessionManager() *SessionManager {
return &SessionManager{
count: 0,
sessions: make(map[uint16]*Session, 32),
}
}
func (m *SessionManager) Size() int {
m.RLock()
defer m.RUnlock()
return len(m.sessions)
}
2017-04-19 19:27:21 +00:00
func (m *SessionManager) Count() int {
m.RLock()
defer m.RUnlock()
return int(m.count)
}
2017-04-13 18:14:07 +00:00
func (m *SessionManager) Allocate() *Session {
m.Lock()
defer m.Unlock()
2017-04-13 18:14:07 +00:00
if m.closed {
return nil
}
m.count++
2017-04-13 18:14:07 +00:00
s := &Session{
ID: m.count,
parent: m,
}
m.sessions[s.ID] = s
2017-04-13 18:14:07 +00:00
return s
}
func (m *SessionManager) Add(s *Session) {
m.Lock()
defer m.Unlock()
m.sessions[s.ID] = s
}
func (m *SessionManager) Remove(id uint16) {
m.Lock()
defer m.Unlock()
delete(m.sessions, id)
}
func (m *SessionManager) Get(id uint16) (*Session, bool) {
m.RLock()
defer m.RUnlock()
2017-04-13 18:14:07 +00:00
if m.closed {
return nil, false
}
s, found := m.sessions[id]
return s, found
}
2017-04-13 18:14:07 +00:00
func (m *SessionManager) CloseIfNoSession() bool {
2017-04-19 19:27:21 +00:00
m.Lock()
defer m.Unlock()
if m.closed {
return true
}
2017-04-19 10:36:04 +00:00
if len(m.sessions) != 0 {
2017-04-13 18:14:07 +00:00
return false
}
m.closed = true
return true
}
func (m *SessionManager) Close() {
2017-04-19 19:27:21 +00:00
m.Lock()
defer m.Unlock()
if m.closed {
return
}
2017-04-13 18:14:07 +00:00
m.closed = true
for _, s := range m.sessions {
2017-04-16 11:24:02 +00:00
s.input.Close()
s.output.Close()
}
2017-04-13 18:14:07 +00:00
m.sessions = make(map[uint16]*Session)
}
type Session struct {
2017-05-02 21:53:39 +00:00
input ray.InputStream
output ray.OutputStream
parent *SessionManager
ID uint16
transferType protocol.TransferType
}
2017-10-21 18:40:31 +00:00
// Close closes all resources associated with this session.
2017-05-02 21:53:39 +00:00
func (s *Session) Close() {
s.output.Close()
s.input.Close()
s.parent.Remove(s.ID)
}
2017-05-02 20:23:07 +00:00
func (s *Session) NewReader(reader io.Reader) buf.Reader {
if s.transferType == protocol.TransferTypeStream {
return NewStreamReader(reader)
}
return NewPacketReader(reader)
}