server_spec.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. package protocol
  2. import (
  3. "sync"
  4. "time"
  5. "v2ray.com/core/common/dice"
  6. "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 (v AlwaysValidStrategy) IsValid() bool {
  17. return true
  18. }
  19. func (v 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 (v *TimeoutValidStrategy) IsValid() bool {
  29. return v.until.After(time.Now())
  30. }
  31. func (v *TimeoutValidStrategy) Invalidate() {
  32. v.until = time.Time{}
  33. }
  34. type ServerSpec struct {
  35. sync.RWMutex
  36. dest net.Destination
  37. users []*User
  38. valid ValidationStrategy
  39. }
  40. func NewServerSpec(dest net.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 := net.TCPDestination(spec.Address.AsAddress(), net.Port(spec.Port))
  49. return NewServerSpec(dest, AlwaysValid(), spec.User...)
  50. }
  51. func (v *ServerSpec) Destination() net.Destination {
  52. return v.dest
  53. }
  54. func (v *ServerSpec) HasUser(user *User) bool {
  55. v.RLock()
  56. defer v.RUnlock()
  57. accountA, err := user.GetTypedAccount()
  58. if err != nil {
  59. return false
  60. }
  61. for _, u := range v.users {
  62. accountB, err := u.GetTypedAccount()
  63. if err == nil && accountA.Equals(accountB) {
  64. return true
  65. }
  66. }
  67. return false
  68. }
  69. func (v *ServerSpec) AddUser(user *User) {
  70. if v.HasUser(user) {
  71. return
  72. }
  73. v.Lock()
  74. defer v.Unlock()
  75. v.users = append(v.users, user)
  76. }
  77. func (v *ServerSpec) PickUser() *User {
  78. userCount := len(v.users)
  79. switch userCount {
  80. case 0:
  81. return nil
  82. case 1:
  83. return v.users[0]
  84. default:
  85. return v.users[dice.Roll(userCount)]
  86. }
  87. }
  88. func (v *ServerSpec) IsValid() bool {
  89. return v.valid.IsValid()
  90. }
  91. func (v *ServerSpec) Invalidate() {
  92. v.valid.Invalidate()
  93. }