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

110 lines
2.0 KiB

8 years ago
package protocol
import (
"sync"
"time"
"v2ray.com/core/common/dice"
v2net "v2ray.com/core/common/net"
8 years ago
)
type ValidationStrategy interface {
IsValid() bool
Invalidate()
}
type AlwaysValidStrategy struct{}
func AlwaysValid() ValidationStrategy {
return AlwaysValidStrategy{}
}
func (this AlwaysValidStrategy) IsValid() bool {
return true
}
func (this AlwaysValidStrategy) Invalidate() {}
type TimeoutValidStrategy struct {
until time.Time
}
func BeforeTime(t time.Time) ValidationStrategy {
return &TimeoutValidStrategy{
until: t,
}
}
8 years ago
func (this *TimeoutValidStrategy) IsValid() bool {
return this.until.After(time.Now())
}
func (this *TimeoutValidStrategy) Invalidate() {
this.until = time.Time{}
}
8 years ago
type ServerSpec struct {
sync.RWMutex
dest v2net.Destination
users []*User
valid ValidationStrategy
8 years ago
}
func NewServerSpec(dest v2net.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 {
dest := v2net.TCPDestination(spec.Address.AsAddress(), v2net.Port(spec.Port))
return NewServerSpec(dest, AlwaysValid(), spec.User...)
}
func (this *ServerSpec) Destination() v2net.Destination {
return this.dest
}
8 years ago
func (this *ServerSpec) HasUser(user *User) bool {
this.RLock()
defer this.RUnlock()
accountA, err := user.GetTypedAccount()
if err != nil {
return false
}
8 years ago
for _, u := range this.users {
accountB, err := u.GetTypedAccount()
if err == nil && accountA.Equals(accountB) {
8 years ago
return true
}
}
return false
}
func (this *ServerSpec) AddUser(user *User) {
if this.HasUser(user) {
return
}
this.Lock()
defer this.Unlock()
this.users = append(this.users, user)
}
func (this *ServerSpec) PickUser() *User {
userCount := len(this.users)
return this.users[dice.Roll(userCount)]
}
func (this *ServerSpec) IsValid() bool {
return this.valid.IsValid()
8 years ago
}
func (this *ServerSpec) Invalidate() {
this.valid.Invalidate()
8 years ago
}