You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
v2ray-core/common/protocol/server_spec.go

120 lines
2.0 KiB

8 years ago
package protocol
import (
"sync"
"time"
"v2ray.com/core/common/dice"
8 years ago
"v2ray.com/core/common/net"
8 years ago
)
type ValidationStrategy interface {
IsValid() bool
Invalidate()
}
8 years ago
type alwaysValidStrategy struct{}
func AlwaysValid() ValidationStrategy {
8 years ago
return alwaysValidStrategy{}
}
8 years ago
func (alwaysValidStrategy) IsValid() bool {
return true
}
8 years ago
func (alwaysValidStrategy) Invalidate() {}
8 years ago
type timeoutValidStrategy struct {
until time.Time
}
func BeforeTime(t time.Time) ValidationStrategy {
8 years ago
return &timeoutValidStrategy{
until: t,
}
}
8 years ago
func (s *timeoutValidStrategy) IsValid() bool {
return s.until.After(time.Now())
}
8 years ago
func (s *timeoutValidStrategy) Invalidate() {
s.until = time.Time{}
}
8 years ago
type ServerSpec struct {
sync.RWMutex
8 years ago
dest net.Destination
users []*User
valid ValidationStrategy
8 years ago
}
8 years ago
func NewServerSpec(dest net.Destination, valid ValidationStrategy, users ...*User) *ServerSpec {
8 years ago
return &ServerSpec{
dest: dest,
users: users,
valid: valid,
8 years ago
}
}
func NewServerSpecFromPB(spec ServerEndpoint) *ServerSpec {
8 years ago
dest := net.TCPDestination(spec.Address.AsAddress(), net.Port(spec.Port))
return NewServerSpec(dest, AlwaysValid(), spec.User...)
}
8 years ago
func (s *ServerSpec) Destination() net.Destination {
return s.dest
}
8 years ago
func (s *ServerSpec) HasUser(user *User) bool {
s.RLock()
defer s.RUnlock()
8 years ago
accountA, err := user.GetTypedAccount()
if err != nil {
return false
}
8 years ago
for _, u := range s.users {
accountB, err := u.GetTypedAccount()
if err == nil && accountA.Equals(accountB) {
8 years ago
return true
}
}
return false
}
8 years ago
func (s *ServerSpec) AddUser(user *User) {
if s.HasUser(user) {
8 years ago
return
}
8 years ago
s.Lock()
defer s.Unlock()
8 years ago
8 years ago
s.users = append(s.users, user)
8 years ago
}
8 years ago
func (s *ServerSpec) PickUser() *User {
s.RLock()
defer s.RUnlock()
userCount := len(s.users)
8 years ago
switch userCount {
case 0:
return nil
case 1:
8 years ago
return s.users[0]
8 years ago
default:
8 years ago
return s.users[dice.Roll(userCount)]
8 years ago
}
8 years ago
}
func (s *ServerSpec) IsValid() bool {
return s.valid.IsValid()
8 years ago
}
func (s *ServerSpec) Invalidate() {
s.valid.Invalidate()
8 years ago
}