vmess.go 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. // Package vmess contains the implementation of VMess protocol and transportation.
  2. //
  3. // VMess contains both inbound and outbound connections. VMess inbound is usually used on servers
  4. // together with 'freedom' to talk to final destination, while VMess outbound is usually used on
  5. // clients with 'socks' for proxying.
  6. package vmess
  7. //go:generate go run $GOPATH/src/v2ray.com/core/common/errors/errorgen/main.go -pkg vmess -path Proxy,VMess
  8. import (
  9. "context"
  10. "sync"
  11. "time"
  12. "v2ray.com/core/common"
  13. "v2ray.com/core/common/protocol"
  14. )
  15. const (
  16. updateIntervalSec = 10
  17. cacheDurationSec = 120
  18. )
  19. type idEntry struct {
  20. id *protocol.ID
  21. userIdx int
  22. lastSec protocol.Timestamp
  23. }
  24. type TimedUserValidator struct {
  25. sync.RWMutex
  26. validUsers []*protocol.User
  27. userHash map[[16]byte]indexTimePair
  28. ids []*idEntry
  29. hasher protocol.IDHash
  30. baseTime protocol.Timestamp
  31. }
  32. type indexTimePair struct {
  33. index int
  34. timeInc uint32
  35. }
  36. func NewTimedUserValidator(ctx context.Context, hasher protocol.IDHash) protocol.UserValidator {
  37. tus := &TimedUserValidator{
  38. validUsers: make([]*protocol.User, 0, 16),
  39. userHash: make(map[[16]byte]indexTimePair, 512),
  40. ids: make([]*idEntry, 0, 512),
  41. hasher: hasher,
  42. baseTime: protocol.Timestamp(time.Now().Unix() - cacheDurationSec*3),
  43. }
  44. go tus.updateUserHash(ctx, updateIntervalSec*time.Second)
  45. return tus
  46. }
  47. func (v *TimedUserValidator) generateNewHashes(nowSec protocol.Timestamp, idx int, entry *idEntry) {
  48. var hashValue [16]byte
  49. idHash := v.hasher(entry.id.Bytes())
  50. for entry.lastSec <= nowSec {
  51. common.Must2(idHash.Write(entry.lastSec.Bytes(nil)))
  52. idHash.Sum(hashValue[:0])
  53. idHash.Reset()
  54. v.userHash[hashValue] = indexTimePair{
  55. index: idx,
  56. timeInc: uint32(entry.lastSec - v.baseTime),
  57. }
  58. entry.lastSec++
  59. }
  60. }
  61. func (v *TimedUserValidator) removeExpiredHashes(expire uint32) {
  62. for key, pair := range v.userHash {
  63. if pair.timeInc < expire {
  64. delete(v.userHash, key)
  65. }
  66. }
  67. }
  68. func (v *TimedUserValidator) updateUserHash(ctx context.Context, interval time.Duration) {
  69. for {
  70. select {
  71. case now := <-time.After(interval):
  72. nowSec := protocol.Timestamp(now.Unix() + cacheDurationSec)
  73. v.Lock()
  74. for _, entry := range v.ids {
  75. v.generateNewHashes(nowSec, entry.userIdx, entry)
  76. }
  77. expire := protocol.Timestamp(now.Unix() - cacheDurationSec*3)
  78. if expire > v.baseTime {
  79. v.removeExpiredHashes(uint32(expire - v.baseTime))
  80. }
  81. v.Unlock()
  82. case <-ctx.Done():
  83. return
  84. }
  85. }
  86. }
  87. func (v *TimedUserValidator) Add(user *protocol.User) error {
  88. v.Lock()
  89. defer v.Unlock()
  90. idx := len(v.validUsers)
  91. v.validUsers = append(v.validUsers, user)
  92. rawAccount, err := user.GetTypedAccount()
  93. if err != nil {
  94. return err
  95. }
  96. account := rawAccount.(*InternalAccount)
  97. nowSec := time.Now().Unix()
  98. entry := &idEntry{
  99. id: account.ID,
  100. userIdx: idx,
  101. lastSec: protocol.Timestamp(nowSec - cacheDurationSec),
  102. }
  103. v.generateNewHashes(protocol.Timestamp(nowSec+cacheDurationSec), idx, entry)
  104. v.ids = append(v.ids, entry)
  105. for _, alterid := range account.AlterIDs {
  106. entry := &idEntry{
  107. id: alterid,
  108. userIdx: idx,
  109. lastSec: protocol.Timestamp(nowSec - cacheDurationSec),
  110. }
  111. v.generateNewHashes(protocol.Timestamp(nowSec+cacheDurationSec), idx, entry)
  112. v.ids = append(v.ids, entry)
  113. }
  114. return nil
  115. }
  116. func (v *TimedUserValidator) Get(userHash []byte) (*protocol.User, protocol.Timestamp, bool) {
  117. defer v.RUnlock()
  118. v.RLock()
  119. var fixedSizeHash [16]byte
  120. copy(fixedSizeHash[:], userHash)
  121. pair, found := v.userHash[fixedSizeHash]
  122. if found {
  123. return v.validUsers[pair.index], protocol.Timestamp(pair.timeInc) + v.baseTime, true
  124. }
  125. return nil, 0, false
  126. }