id.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package protocol
  2. import (
  3. "crypto/hmac"
  4. "crypto/md5"
  5. "hash"
  6. "github.com/xtls/xray-core/common"
  7. "github.com/xtls/xray-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 a 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 nextID(u *uuid.UUID) uuid.UUID {
  47. md5hash := md5.New()
  48. common.Must2(md5hash.Write(u.Bytes()))
  49. common.Must2(md5hash.Write([]byte("16167dc8-16b6-4e6d-b8bb-65dd68113a81")))
  50. var newid uuid.UUID
  51. for {
  52. md5hash.Sum(newid[:0])
  53. if !newid.Equals(u) {
  54. return newid
  55. }
  56. common.Must2(md5hash.Write([]byte("533eff8a-4113-4b10-b5ce-0f5d76b98cd2")))
  57. }
  58. }
  59. func NewAlterIDs(primary *ID, alterIDCount uint16) []*ID {
  60. alterIDs := make([]*ID, alterIDCount)
  61. prevID := primary.UUID()
  62. for idx := range alterIDs {
  63. newid := nextID(&prevID)
  64. alterIDs[idx] = NewID(newid)
  65. prevID = newid
  66. }
  67. return alterIDs
  68. }