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
1.9 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{}
}
8 years ago
func (v AlwaysValidStrategy) IsValid() bool {
return true
}
8 years ago
func (v AlwaysValidStrategy) Invalidate() {}
type TimeoutValidStrategy struct {
until time.Time
}
func BeforeTime(t time.Time) ValidationStrategy {
return &TimeoutValidStrategy{
until: t,
}
}
8 years ago
func (v *TimeoutValidStrategy) IsValid() bool {
return v.until.After(time.Now())
}
8 years ago
func (v *TimeoutValidStrategy) Invalidate() {
v.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...)
}
8 years ago
func (v *ServerSpec) Destination() v2net.Destination {
return v.dest
}
8 years ago
func (v *ServerSpec) HasUser(user *User) bool {
v.RLock()
defer v.RUnlock()
8 years ago
accountA, err := user.GetTypedAccount()
if err != nil {
return false
}
8 years ago
for _, u := range v.users {
accountB, err := u.GetTypedAccount()
if err == nil && accountA.Equals(accountB) {
8 years ago
return true
}
}
return false
}
8 years ago
func (v *ServerSpec) AddUser(user *User) {
if v.HasUser(user) {
8 years ago
return
}
8 years ago
v.Lock()
defer v.Unlock()
8 years ago
8 years ago
v.users = append(v.users, user)
8 years ago
}
8 years ago
func (v *ServerSpec) PickUser() *User {
userCount := len(v.users)
return v.users[dice.Roll(userCount)]
8 years ago
}
8 years ago
func (v *ServerSpec) IsValid() bool {
return v.valid.IsValid()
8 years ago
}
8 years ago
func (v *ServerSpec) Invalidate() {
v.valid.Invalidate()
8 years ago
}