uuid.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. // Copyright (C) 2013-2014 by Maxim Bublis <b@codemonkey.ru>
  2. //
  3. // Permission is hereby granted, free of charge, to any person obtaining
  4. // a copy of this software and associated documentation files (the
  5. // "Software"), to deal in the Software without restriction, including
  6. // without limitation the rights to use, copy, modify, merge, publish,
  7. // distribute, sublicense, and/or sell copies of the Software, and to
  8. // permit persons to whom the Software is furnished to do so, subject to
  9. // the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be
  12. // included in all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  15. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  16. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  17. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  18. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  19. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  20. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  21. // Package uuid provides implementation of Universally Unique Identifier (UUID).
  22. // Supported versions are 1, 3, 4 and 5 (as specified in RFC 4122) and
  23. // version 2 (as specified in DCE 1.1).
  24. package utils
  25. import (
  26. "bytes"
  27. "crypto/md5"
  28. "crypto/rand"
  29. "crypto/sha1"
  30. "encoding/binary"
  31. "encoding/hex"
  32. "fmt"
  33. "hash"
  34. "net"
  35. "os"
  36. "sync"
  37. "time"
  38. )
  39. // UUID layout variants.
  40. const (
  41. VariantNCS = iota
  42. VariantRFC4122
  43. VariantMicrosoft
  44. VariantFuture
  45. )
  46. // UUID DCE domains.
  47. const (
  48. DomainPerson = iota
  49. DomainGroup
  50. DomainOrg
  51. )
  52. // Difference in 100-nanosecond intervals between
  53. // UUID epoch (October 15, 1582) and Unix epoch (January 1, 1970).
  54. const epochStart = 122192928000000000
  55. // UUID v1/v2 storage.
  56. var (
  57. storageMutex sync.Mutex
  58. clockSequence uint16
  59. lastTime uint64
  60. hardwareAddr [6]byte
  61. posixUID = uint32(os.Getuid())
  62. posixGID = uint32(os.Getgid())
  63. )
  64. // String parse helpers.
  65. var (
  66. urnPrefix = []byte("urn:uuid:")
  67. byteGroups = []int{8, 4, 4, 4, 12}
  68. )
  69. // Epoch calculation function
  70. var epochFunc func() uint64
  71. // Initialize storage
  72. func init() {
  73. buf := make([]byte, 2)
  74. rand.Read(buf)
  75. clockSequence = binary.BigEndian.Uint16(buf)
  76. // Initialize hardwareAddr randomly in case
  77. // of real network interfaces absence
  78. rand.Read(hardwareAddr[:])
  79. // Set multicast bit as recommended in RFC 4122
  80. hardwareAddr[0] |= 0x01
  81. interfaces, err := net.Interfaces()
  82. if err == nil {
  83. for _, iface := range interfaces {
  84. if len(iface.HardwareAddr) >= 6 {
  85. copy(hardwareAddr[:], iface.HardwareAddr)
  86. break
  87. }
  88. }
  89. }
  90. epochFunc = unixTimeFunc
  91. }
  92. // Returns difference in 100-nanosecond intervals between
  93. // UUID epoch (October 15, 1582) and current time.
  94. // This is default epoch calculation function.
  95. func unixTimeFunc() uint64 {
  96. return epochStart + uint64(time.Now().UnixNano()/100)
  97. }
  98. // UUID representation compliant with specification
  99. // described in RFC 4122.
  100. type UUID [16]byte
  101. // Predefined namespace UUIDs.
  102. var (
  103. NamespaceDNS, _ = FromString("6ba7b810-9dad-11d1-80b4-00c04fd430c8")
  104. NamespaceURL, _ = FromString("6ba7b811-9dad-11d1-80b4-00c04fd430c8")
  105. NamespaceOID, _ = FromString("6ba7b812-9dad-11d1-80b4-00c04fd430c8")
  106. NamespaceX500, _ = FromString("6ba7b814-9dad-11d1-80b4-00c04fd430c8")
  107. )
  108. // And returns result of binary AND of two UUIDs.
  109. func And(u1 UUID, u2 UUID) UUID {
  110. u := UUID{}
  111. for i := 0; i < 16; i++ {
  112. u[i] = u1[i] & u2[i]
  113. }
  114. return u
  115. }
  116. // Or returns result of binary OR of two UUIDs.
  117. func Or(u1 UUID, u2 UUID) UUID {
  118. u := UUID{}
  119. for i := 0; i < 16; i++ {
  120. u[i] = u1[i] | u2[i]
  121. }
  122. return u
  123. }
  124. // Equal returns true if u1 and u2 equals, otherwise returns false.
  125. func Equal(u1 UUID, u2 UUID) bool {
  126. return bytes.Equal(u1[:], u2[:])
  127. }
  128. // Version returns algorithm version used to generate UUID.
  129. func (u UUID) Version() uint {
  130. return uint(u[6] >> 4)
  131. }
  132. // Variant returns UUID layout variant.
  133. func (u UUID) Variant() uint {
  134. switch {
  135. case (u[8] & 0x80) == 0x00:
  136. return VariantNCS
  137. case (u[8]&0xc0)|0x80 == 0x80:
  138. return VariantRFC4122
  139. case (u[8]&0xe0)|0xc0 == 0xc0:
  140. return VariantMicrosoft
  141. }
  142. return VariantFuture
  143. }
  144. // Bytes returns bytes slice representation of UUID.
  145. func (u UUID) Bytes() []byte {
  146. return u[:]
  147. }
  148. // Returns canonical string representation of UUID:
  149. // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.
  150. func (u UUID) String() string {
  151. return fmt.Sprintf("%x-%x-%x-%x-%x",
  152. u[:4], u[4:6], u[6:8], u[8:10], u[10:])
  153. }
  154. // SetVersion sets version bits.
  155. func (u *UUID) SetVersion(v byte) {
  156. u[6] = (u[6] & 0x0f) | (v << 4)
  157. }
  158. // SetVariant sets variant bits as described in RFC 4122.
  159. func (u *UUID) SetVariant() {
  160. u[8] = (u[8] & 0xbf) | 0x80
  161. }
  162. // MarshalText implements the encoding.TextMarshaler interface.
  163. // The encoding is the same as returned by String.
  164. func (u UUID) MarshalText() (text []byte, err error) {
  165. text = []byte(u.String())
  166. return
  167. }
  168. // UnmarshalText implements the encoding.TextUnmarshaler interface.
  169. // Following formats are supported:
  170. // "6ba7b810-9dad-11d1-80b4-00c04fd430c8",
  171. // "{6ba7b810-9dad-11d1-80b4-00c04fd430c8}",
  172. // "urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8"
  173. func (u *UUID) UnmarshalText(text []byte) (err error) {
  174. if len(text) < 32 {
  175. err = fmt.Errorf("uuid: invalid UUID string: %s", text)
  176. return
  177. }
  178. if bytes.Equal(text[:9], urnPrefix) {
  179. text = text[9:]
  180. } else if text[0] == '{' {
  181. text = text[1:]
  182. }
  183. b := u[:]
  184. for _, byteGroup := range byteGroups {
  185. if text[0] == '-' {
  186. text = text[1:]
  187. }
  188. _, err = hex.Decode(b[:byteGroup/2], text[:byteGroup])
  189. if err != nil {
  190. return
  191. }
  192. text = text[byteGroup:]
  193. b = b[byteGroup/2:]
  194. }
  195. return
  196. }
  197. // MarshalBinary implements the encoding.BinaryMarshaler interface.
  198. func (u UUID) MarshalBinary() (data []byte, err error) {
  199. data = u.Bytes()
  200. return
  201. }
  202. // UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.
  203. // It will return error if the slice isn't 16 bytes long.
  204. func (u *UUID) UnmarshalBinary(data []byte) (err error) {
  205. if len(data) != 16 {
  206. err = fmt.Errorf("uuid: UUID must be exactly 16 bytes long, got %d bytes", len(data))
  207. return
  208. }
  209. copy(u[:], data)
  210. return
  211. }
  212. // FromBytes returns UUID converted from raw byte slice input.
  213. // It will return error if the slice isn't 16 bytes long.
  214. func FromBytes(input []byte) (u UUID, err error) {
  215. err = u.UnmarshalBinary(input)
  216. return
  217. }
  218. // FromString returns UUID parsed from string input.
  219. // Input is expected in a form accepted by UnmarshalText.
  220. func FromString(input string) (u UUID, err error) {
  221. err = u.UnmarshalText([]byte(input))
  222. return
  223. }
  224. // Returns UUID v1/v2 storage state.
  225. // Returns epoch timestamp and clock sequence.
  226. func getStorage() (uint64, uint16) {
  227. storageMutex.Lock()
  228. defer storageMutex.Unlock()
  229. timeNow := epochFunc()
  230. // Clock changed backwards since last UUID generation.
  231. // Should increase clock sequence.
  232. if timeNow <= lastTime {
  233. clockSequence++
  234. }
  235. lastTime = timeNow
  236. return timeNow, clockSequence
  237. }
  238. // NewV1 returns UUID based on current timestamp and MAC address.
  239. func NewV1() UUID {
  240. u := UUID{}
  241. timeNow, clockSeq := getStorage()
  242. binary.BigEndian.PutUint32(u[0:], uint32(timeNow))
  243. binary.BigEndian.PutUint16(u[4:], uint16(timeNow>>32))
  244. binary.BigEndian.PutUint16(u[6:], uint16(timeNow>>48))
  245. binary.BigEndian.PutUint16(u[8:], clockSeq)
  246. copy(u[10:], hardwareAddr[:])
  247. u.SetVersion(1)
  248. u.SetVariant()
  249. return u
  250. }
  251. // NewV2 returns DCE Security UUID based on POSIX UID/GID.
  252. func NewV2(domain byte) UUID {
  253. u := UUID{}
  254. switch domain {
  255. case DomainPerson:
  256. binary.BigEndian.PutUint32(u[0:], posixUID)
  257. case DomainGroup:
  258. binary.BigEndian.PutUint32(u[0:], posixGID)
  259. }
  260. timeNow, clockSeq := getStorage()
  261. binary.BigEndian.PutUint16(u[4:], uint16(timeNow>>32))
  262. binary.BigEndian.PutUint16(u[6:], uint16(timeNow>>48))
  263. binary.BigEndian.PutUint16(u[8:], clockSeq)
  264. u[9] = domain
  265. copy(u[10:], hardwareAddr[:])
  266. u.SetVersion(2)
  267. u.SetVariant()
  268. return u
  269. }
  270. // NewV3 returns UUID based on MD5 hash of namespace UUID and name.
  271. func NewV3(ns UUID, name string) UUID {
  272. u := newFromHash(md5.New(), ns, name)
  273. u.SetVersion(3)
  274. u.SetVariant()
  275. return u
  276. }
  277. // NewV4 returns random generated UUID.
  278. func NewV4() UUID {
  279. u := UUID{}
  280. rand.Read(u[:])
  281. u.SetVersion(4)
  282. u.SetVariant()
  283. return u
  284. }
  285. // NewV5 returns UUID based on SHA-1 hash of namespace UUID and name.
  286. func NewV5(ns UUID, name string) UUID {
  287. u := newFromHash(sha1.New(), ns, name)
  288. u.SetVersion(5)
  289. u.SetVariant()
  290. return u
  291. }
  292. // Returns UUID based on hashing of namespace UUID and name.
  293. func newFromHash(h hash.Hash, ns UUID, name string) UUID {
  294. u := UUID{}
  295. h.Write(ns[:])
  296. h.Write([]byte(name))
  297. copy(u[:], h.Sum(nil))
  298. return u
  299. }