server_spec.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  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 (alwaysValidStrategy) IsValid() bool {
  17. return true
  18. }
  19. func (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 (s *timeoutValidStrategy) IsValid() bool {
  29. return s.until.After(time.Now())
  30. }
  31. func (s *timeoutValidStrategy) Invalidate() {
  32. s.until = time.Time{}
  33. }
  34. type ServerSpec struct {
  35. sync.RWMutex
  36. dest net.Destination
  37. users []*MemoryUser
  38. valid ValidationStrategy
  39. }
  40. func NewServerSpec(dest net.Destination, valid ValidationStrategy, users ...*MemoryUser) *ServerSpec {
  41. return &ServerSpec{
  42. dest: dest,
  43. users: users,
  44. valid: valid,
  45. }
  46. }
  47. func NewServerSpecFromPB(spec ServerEndpoint) (*ServerSpec, error) {
  48. dest := net.TCPDestination(spec.Address.AsAddress(), net.Port(spec.Port))
  49. mUsers := make([]*MemoryUser, len(spec.User))
  50. for idx, u := range spec.User {
  51. mUser, err := u.ToMemoryUser()
  52. if err != nil {
  53. return nil, err
  54. }
  55. mUsers[idx] = mUser
  56. }
  57. return NewServerSpec(dest, AlwaysValid(), mUsers...), nil
  58. }
  59. func (s *ServerSpec) Destination() net.Destination {
  60. return s.dest
  61. }
  62. func (s *ServerSpec) HasUser(user *MemoryUser) bool {
  63. s.RLock()
  64. defer s.RUnlock()
  65. for _, u := range s.users {
  66. if u.Account.Equals(user.Account) {
  67. return true
  68. }
  69. }
  70. return false
  71. }
  72. func (s *ServerSpec) AddUser(user *MemoryUser) {
  73. if s.HasUser(user) {
  74. return
  75. }
  76. s.Lock()
  77. defer s.Unlock()
  78. s.users = append(s.users, user)
  79. }
  80. func (s *ServerSpec) PickUser() *MemoryUser {
  81. s.RLock()
  82. defer s.RUnlock()
  83. userCount := len(s.users)
  84. switch userCount {
  85. case 0:
  86. return nil
  87. case 1:
  88. return s.users[0]
  89. default:
  90. return s.users[dice.Roll(userCount)]
  91. }
  92. }
  93. func (s *ServerSpec) IsValid() bool {
  94. return s.valid.IsValid()
  95. }
  96. func (s *ServerSpec) Invalidate() {
  97. s.valid.Invalidate()
  98. }