id.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package protocol
  2. import (
  3. "crypto/hmac"
  4. "crypto/md5"
  5. "hash"
  6. "v2ray.com/core/common"
  7. "v2ray.com/core/common/uuid"
  8. )
  9. const (
  10. IDBytesLen = 16
  11. )
  12. type IDHash func(key []byte) hash.Hash
  13. func DefaultIDHash(key []byte) hash.Hash {
  14. return hmac.New(md5.New, key)
  15. }
  16. // The ID of en entity, in the form of an UUID.
  17. type ID struct {
  18. uuid *uuid.UUID
  19. cmdKey [IDBytesLen]byte
  20. }
  21. // Equals returns true if this ID equals to the other one.
  22. func (id *ID) Equals(another *ID) bool {
  23. return id.uuid.Equals(another.uuid)
  24. }
  25. func (id *ID) Bytes() []byte {
  26. return id.uuid.Bytes()
  27. }
  28. func (id *ID) String() string {
  29. return id.uuid.String()
  30. }
  31. func (id *ID) UUID() *uuid.UUID {
  32. return id.uuid
  33. }
  34. func (id ID) CmdKey() []byte {
  35. return id.cmdKey[:]
  36. }
  37. // NewID returns an ID with given UUID.
  38. func NewID(uuid *uuid.UUID) *ID {
  39. id := &ID{uuid: uuid}
  40. md5hash := md5.New()
  41. common.Must2(md5hash.Write(uuid.Bytes()))
  42. common.Must2(md5hash.Write([]byte("c48619fe-8f02-49e0-b9e9-edf763e17e21")))
  43. md5hash.Sum(id.cmdKey[:0])
  44. return id
  45. }
  46. func NewAlterIDs(primary *ID, alterIDCount uint16) []*ID {
  47. alterIDs := make([]*ID, alterIDCount)
  48. prevID := primary.UUID()
  49. for idx := range alterIDs {
  50. newid := prevID.Next()
  51. // TODO: check duplicates
  52. alterIDs[idx] = NewID(newid)
  53. prevID = newid
  54. }
  55. return alterIDs
  56. }