v2ray-core/common/protocol/id.go

70 lines
1.3 KiB
Go
Raw Normal View History

package protocol
2015-09-05 15:48:38 +00:00
import (
2016-02-25 20:50:10 +00:00
"crypto/hmac"
2015-09-07 21:48:37 +00:00
"crypto/md5"
2016-02-25 20:50:10 +00:00
"hash"
2017-09-27 19:09:47 +00:00
"v2ray.com/core/common"
2016-08-20 18:55:45 +00:00
"v2ray.com/core/common/uuid"
2015-09-05 15:48:38 +00:00
)
2015-09-14 16:19:17 +00:00
const (
IDBytesLen = 16
)
2016-02-25 20:50:10 +00:00
type IDHash func(key []byte) hash.Hash
func DefaultIDHash(key []byte) hash.Hash {
return hmac.New(md5.New, key)
}
2015-09-07 10:00:46 +00:00
// The ID of en entity, in the form of an UUID.
2015-09-14 16:19:17 +00:00
type ID struct {
2015-12-12 20:40:16 +00:00
uuid *uuid.UUID
2015-09-26 20:32:45 +00:00
cmdKey [IDBytesLen]byte
2015-09-14 16:19:17 +00:00
}
2016-12-07 12:13:48 +00:00
// Equals returns true if this ID equals to the other one.
2017-09-27 19:09:47 +00:00
func (id *ID) Equals(another *ID) bool {
return id.uuid.Equals(another.uuid)
}
2017-09-27 19:09:47 +00:00
func (id *ID) Bytes() []byte {
return id.uuid.Bytes()
2015-12-12 20:40:16 +00:00
}
2017-09-27 19:09:47 +00:00
func (id *ID) String() string {
return id.uuid.String()
2015-12-12 20:40:16 +00:00
}
2015-09-15 22:06:22 +00:00
2017-09-27 19:09:47 +00:00
func (id *ID) UUID() *uuid.UUID {
return id.uuid
2016-01-08 23:10:57 +00:00
}
2017-09-27 19:09:47 +00:00
func (id ID) CmdKey() []byte {
return id.cmdKey[:]
}
2017-09-27 19:09:47 +00:00
// NewID returns an ID with given UUID.
2015-12-12 20:40:16 +00:00
func NewID(uuid *uuid.UUID) *ID {
id := &ID{uuid: uuid}
2015-09-15 22:06:22 +00:00
md5hash := md5.New()
2017-09-27 19:09:47 +00:00
common.Must2(md5hash.Write(uuid.Bytes()))
common.Must2(md5hash.Write([]byte("c48619fe-8f02-49e0-b9e9-edf763e17e21")))
2016-01-20 16:45:50 +00:00
md5hash.Sum(id.cmdKey[:0])
return id
2015-09-07 21:48:19 +00:00
}
2016-05-07 19:07:46 +00:00
func NewAlterIDs(primary *ID, alterIDCount uint16) []*ID {
alterIDs := make([]*ID, alterIDCount)
prevID := primary.UUID()
for idx := range alterIDs {
newid := prevID.Next()
// TODO: check duplicates
alterIDs[idx] = NewID(newid)
prevID = newid
}
return alterIDs
}