2015-10-16 06:03:22 -04:00
|
|
|
package config
|
2015-09-05 11:48:38 -04:00
|
|
|
|
|
|
|
import (
|
2015-09-07 17:48:37 -04:00
|
|
|
"crypto/md5"
|
2015-09-06 16:10:42 -04:00
|
|
|
"encoding/hex"
|
2015-10-13 12:27:29 -04:00
|
|
|
"errors"
|
2015-09-11 11:27:36 -04:00
|
|
|
|
2015-09-19 18:50:21 -04:00
|
|
|
"github.com/v2ray/v2ray-core/common/log"
|
2015-09-05 11:48:38 -04:00
|
|
|
)
|
|
|
|
|
2015-09-14 12:19:17 -04:00
|
|
|
const (
|
|
|
|
IDBytesLen = 16
|
|
|
|
)
|
|
|
|
|
2015-10-13 12:27:29 -04:00
|
|
|
var (
|
|
|
|
InvalidID = errors.New("Invalid ID.")
|
|
|
|
)
|
|
|
|
|
2015-09-07 06:00:46 -04:00
|
|
|
// The ID of en entity, in the form of an UUID.
|
2015-09-14 12:19:17 -04:00
|
|
|
type ID struct {
|
|
|
|
String string
|
2015-09-26 16:32:45 -04:00
|
|
|
Bytes [IDBytesLen]byte
|
|
|
|
cmdKey [IDBytesLen]byte
|
2015-09-14 12:19:17 -04:00
|
|
|
}
|
|
|
|
|
2015-10-16 06:03:22 -04:00
|
|
|
func NewID(id string) (*ID, error) {
|
2015-09-14 12:19:17 -04:00
|
|
|
idBytes, err := UUIDToID(id)
|
|
|
|
if err != nil {
|
2015-10-13 12:27:29 -04:00
|
|
|
log.Error("Failed to parse id %s", id)
|
2015-10-16 06:03:22 -04:00
|
|
|
return &ID{}, InvalidID
|
2015-09-14 12:19:17 -04:00
|
|
|
}
|
2015-09-15 18:06:22 -04:00
|
|
|
|
|
|
|
md5hash := md5.New()
|
2015-09-23 16:17:25 -04:00
|
|
|
md5hash.Write(idBytes[:])
|
2015-09-14 15:59:44 -04:00
|
|
|
md5hash.Write([]byte("c48619fe-8f02-49e0-b9e9-edf763e17e21"))
|
|
|
|
cmdKey := md5.Sum(nil)
|
|
|
|
|
2015-10-16 06:03:22 -04:00
|
|
|
return &ID{
|
2015-09-16 15:13:13 -04:00
|
|
|
String: id,
|
|
|
|
Bytes: idBytes,
|
2015-09-23 16:17:25 -04:00
|
|
|
cmdKey: cmdKey,
|
2015-09-16 15:13:13 -04:00
|
|
|
}, nil
|
2015-09-14 15:59:44 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
func (v ID) CmdKey() []byte {
|
2015-09-23 16:17:25 -04:00
|
|
|
return v.cmdKey[:]
|
2015-09-07 17:48:19 -04:00
|
|
|
}
|
|
|
|
|
2015-09-05 11:48:38 -04:00
|
|
|
var byteGroups = []int{8, 4, 4, 4, 12}
|
|
|
|
|
|
|
|
// TODO: leverage a full functional UUID library
|
2015-09-26 16:32:45 -04:00
|
|
|
func UUIDToID(uuid string) (v [IDBytesLen]byte, err error) {
|
2015-09-06 16:10:42 -04:00
|
|
|
text := []byte(uuid)
|
|
|
|
if len(text) < 32 {
|
2015-10-13 12:27:29 -04:00
|
|
|
log.Error("uuid: invalid UUID string: %s", text)
|
|
|
|
err = InvalidID
|
2015-09-05 11:48:38 -04:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
b := v[:]
|
|
|
|
|
|
|
|
for _, byteGroup := range byteGroups {
|
|
|
|
if text[0] == '-' {
|
|
|
|
text = text[1:]
|
|
|
|
}
|
|
|
|
|
|
|
|
_, err = hex.Decode(b[:byteGroup/2], text[:byteGroup])
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
text = text[byteGroup:]
|
|
|
|
b = b[byteGroup/2:]
|
|
|
|
}
|
|
|
|
|
|
|
|
return
|
|
|
|
}
|