forked from v2ray/v2ray-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server_spec.go
109 lines (86 loc) · 1.98 KB
/
server_spec.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package protocol
import (
"sync"
"time"
"v2ray.com/core/common/dice"
v2net "v2ray.com/core/common/net"
)
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,
}
}
func (this *TimeoutValidStrategy) IsValid() bool {
return this.until.After(time.Now())
}
func (this *TimeoutValidStrategy) Invalidate() {
this.until = time.Time{}
}
type ServerSpec struct {
sync.RWMutex
dest v2net.Destination
users []*User
valid ValidationStrategy
}
func NewServerSpec(dest v2net.Destination, valid ValidationStrategy, users ...*User) *ServerSpec {
return &ServerSpec{
dest: dest,
users: users,
valid: valid,
}
}
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
}
func (this *ServerSpec) HasUser(user *User) bool {
this.RLock()
defer this.RUnlock()
accountA, err := user.GetTypedAccount()
if err != nil {
return false
}
for _, u := range this.users {
accountB, err := u.GetTypedAccount()
if err == nil && accountA.Equals(accountB) {
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()
}
func (this *ServerSpec) Invalidate() {
this.valid.Invalidate()
}