server_spec.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  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. newAccount NewAccountFactory
  40. }
  41. func NewServerSpec(newAccount NewAccountFactory, dest v2net.Destination, valid ValidationStrategy, users ...*User) *ServerSpec {
  42. return &ServerSpec{
  43. dest: dest,
  44. users: users,
  45. valid: valid,
  46. newAccount: newAccount,
  47. }
  48. }
  49. func NewServerSpecFromPB(newAccount NewAccountFactory, spec ServerEndpoint) *ServerSpec {
  50. dest := v2net.TCPDestination(spec.Address.AsAddress(), v2net.Port(spec.Port))
  51. return NewServerSpec(newAccount, dest, AlwaysValid(), spec.User...)
  52. }
  53. func (this *ServerSpec) Destination() v2net.Destination {
  54. return this.dest
  55. }
  56. func (this *ServerSpec) HasUser(user *User) bool {
  57. this.RLock()
  58. defer this.RUnlock()
  59. accountA, err := user.GetTypedAccount()
  60. if err != nil {
  61. return false
  62. }
  63. for _, u := range this.users {
  64. accountB, err := u.GetTypedAccount()
  65. if err == nil && accountA.Equals(accountB) {
  66. return true
  67. }
  68. }
  69. return false
  70. }
  71. func (this *ServerSpec) AddUser(user *User) {
  72. if this.HasUser(user) {
  73. return
  74. }
  75. this.Lock()
  76. defer this.Unlock()
  77. this.users = append(this.users, user)
  78. }
  79. func (this *ServerSpec) PickUser() *User {
  80. userCount := len(this.users)
  81. return this.users[dice.Roll(userCount)]
  82. }
  83. func (this *ServerSpec) IsValid() bool {
  84. return this.valid.IsValid()
  85. }
  86. func (this *ServerSpec) Invalidate() {
  87. this.valid.Invalidate()
  88. }