server_spec.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. package protocol
  2. import (
  3. "sync"
  4. "time"
  5. "v2ray.com/core/common/dice"
  6. v2net "v2ray.com/core/common/net"
  7. )
  8. type ValidationStrategy interface {
  9. IsValid() bool
  10. Invalidate()
  11. }
  12. type AlwaysValidStrategy struct{}
  13. func AlwaysValid() ValidationStrategy {
  14. return AlwaysValidStrategy{}
  15. }
  16. func (this AlwaysValidStrategy) IsValid() bool {
  17. return true
  18. }
  19. func (this AlwaysValidStrategy) Invalidate() {}
  20. type TimeoutValidStrategy struct {
  21. until time.Time
  22. }
  23. func BeforeTime(t time.Time) ValidationStrategy {
  24. return &TimeoutValidStrategy{
  25. until: t,
  26. }
  27. }
  28. func (this *TimeoutValidStrategy) IsValid() bool {
  29. return this.until.After(time.Now())
  30. }
  31. func (this *TimeoutValidStrategy) Invalidate() {
  32. this.until = time.Time{}
  33. }
  34. type ServerSpec struct {
  35. sync.RWMutex
  36. dest v2net.Destination
  37. users []*User
  38. valid ValidationStrategy
  39. }
  40. func NewServerSpec(dest v2net.Destination, valid ValidationStrategy, users ...*User) *ServerSpec {
  41. return &ServerSpec{
  42. dest: dest,
  43. users: users,
  44. valid: valid,
  45. }
  46. }
  47. func NewServerSpecFromPB(spec ServerEndpoint) *ServerSpec {
  48. dest := v2net.TCPDestination(spec.Address.AsAddress(), v2net.Port(spec.Port))
  49. return NewServerSpec(dest, AlwaysValid(), spec.User...)
  50. }
  51. func (this *ServerSpec) Destination() v2net.Destination {
  52. return this.dest
  53. }
  54. func (this *ServerSpec) HasUser(user *User) bool {
  55. this.RLock()
  56. defer this.RUnlock()
  57. accountA, err := user.GetTypedAccount()
  58. if err != nil {
  59. return false
  60. }
  61. for _, u := range this.users {
  62. accountB, err := u.GetTypedAccount()
  63. if err == nil && accountA.Equals(accountB) {
  64. return true
  65. }
  66. }
  67. return false
  68. }
  69. func (this *ServerSpec) AddUser(user *User) {
  70. if this.HasUser(user) {
  71. return
  72. }
  73. this.Lock()
  74. defer this.Unlock()
  75. this.users = append(this.users, user)
  76. }
  77. func (this *ServerSpec) PickUser() *User {
  78. userCount := len(this.users)
  79. return this.users[dice.Roll(userCount)]
  80. }
  81. func (this *ServerSpec) IsValid() bool {
  82. return this.valid.IsValid()
  83. }
  84. func (this *ServerSpec) Invalidate() {
  85. this.valid.Invalidate()
  86. }