You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

uuid.go 8.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. // Copyright (C) 2013 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 uuid
  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. "strings"
  37. "sync"
  38. "time"
  39. )
  40. // UUID layout variants.
  41. const (
  42. VariantNCS = iota
  43. VariantRFC4122
  44. VariantMicrosoft
  45. VariantFuture
  46. )
  47. // UUID DCE domains.
  48. const (
  49. DomainPerson = iota
  50. DomainGroup
  51. DomainOrg
  52. )
  53. // Difference in 100-nanosecond intervals between
  54. // UUID epoch (October 15, 1582) and Unix epoch (January 1, 1970).
  55. const epochStart = 122192928000000000
  56. // UUID v1/v2 storage.
  57. var (
  58. storageMutex sync.Mutex
  59. clockSequence uint16
  60. lastTime uint64
  61. hardwareAddr [6]byte
  62. posixUID = uint32(os.Getuid())
  63. posixGID = uint32(os.Getgid())
  64. )
  65. // Epoch calculation function
  66. var epochFunc func() uint64
  67. // Initialize storage
  68. func init() {
  69. buf := make([]byte, 2)
  70. rand.Read(buf)
  71. clockSequence = binary.BigEndian.Uint16(buf)
  72. // Initialize hardwareAddr randomly in case
  73. // of real network interfaces absence
  74. rand.Read(hardwareAddr[:])
  75. // Set multicast bit as recommended in RFC 4122
  76. hardwareAddr[0] |= 0x01
  77. interfaces, err := net.Interfaces()
  78. if err == nil {
  79. for _, iface := range interfaces {
  80. if len(iface.HardwareAddr) >= 6 {
  81. copy(hardwareAddr[:], iface.HardwareAddr)
  82. break
  83. }
  84. }
  85. }
  86. epochFunc = unixTimeFunc
  87. }
  88. // Returns difference in 100-nanosecond intervals between
  89. // UUID epoch (October 15, 1582) and current time.
  90. // This is default epoch calculation function.
  91. func unixTimeFunc() uint64 {
  92. return epochStart + uint64(time.Now().UnixNano()/100)
  93. }
  94. // UUID representation compliant with specification
  95. // described in RFC 4122.
  96. type UUID [16]byte
  97. // Predefined namespace UUIDs.
  98. var (
  99. NamespaceDNS, _ = FromString("6ba7b810-9dad-11d1-80b4-00c04fd430c8")
  100. NamespaceURL, _ = FromString("6ba7b811-9dad-11d1-80b4-00c04fd430c8")
  101. NamespaceOID, _ = FromString("6ba7b812-9dad-11d1-80b4-00c04fd430c8")
  102. NamespaceX500, _ = FromString("6ba7b814-9dad-11d1-80b4-00c04fd430c8")
  103. )
  104. // And returns result of binary AND of two UUIDs.
  105. func And(u1 UUID, u2 UUID) UUID {
  106. u := UUID{}
  107. for i := 0; i < 16; i++ {
  108. u[i] = u1[i] & u2[i]
  109. }
  110. return u
  111. }
  112. // Or returns result of binary OR of two UUIDs.
  113. func Or(u1 UUID, u2 UUID) UUID {
  114. u := UUID{}
  115. for i := 0; i < 16; i++ {
  116. u[i] = u1[i] | u2[i]
  117. }
  118. return u
  119. }
  120. // Equal returns true if u1 and u2 equals, otherwise returns false.
  121. func Equal(u1 UUID, u2 UUID) bool {
  122. return bytes.Equal(u1[:], u2[:])
  123. }
  124. // Version returns algorithm version used to generate UUID.
  125. func (u UUID) Version() uint {
  126. return uint(u[6] >> 4)
  127. }
  128. // Variant returns UUID layout variant.
  129. func (u UUID) Variant() uint {
  130. switch {
  131. case (u[8] & 0x80) == 0x00:
  132. return VariantNCS
  133. case (u[8]&0xc0)|0x80 == 0x80:
  134. return VariantRFC4122
  135. case (u[8]&0xe0)|0xc0 == 0xc0:
  136. return VariantMicrosoft
  137. }
  138. return VariantFuture
  139. }
  140. // Bytes returns bytes slice representation of UUID.
  141. func (u UUID) Bytes() []byte {
  142. return u[:]
  143. }
  144. // Returns canonical string representation of UUID:
  145. // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.
  146. func (u UUID) String() string {
  147. return fmt.Sprintf("%x-%x-%x-%x-%x",
  148. u[:4], u[4:6], u[6:8], u[8:10], u[10:])
  149. }
  150. // SetVersion sets version bits.
  151. func (u *UUID) SetVersion(v byte) {
  152. u[6] = (u[6] & 0x0f) | (v << 4)
  153. }
  154. // SetVariant sets variant bits as described in RFC 4122.
  155. func (u *UUID) SetVariant() {
  156. u[8] = (u[8] & 0xbf) | 0x80
  157. }
  158. // MarshalText implements the encoding.TextMarshaler interface.
  159. // The encoding is the same as returned by String.
  160. func (u UUID) MarshalText() (text []byte, err error) {
  161. text = []byte(u.String())
  162. return
  163. }
  164. // UnmarshalText implements the encoding.TextUnmarshaler interface.
  165. // UUID is expected in a form accepted by FromString.
  166. func (u *UUID) UnmarshalText(text []byte) error {
  167. s := string(text)
  168. u2, err := FromString(s)
  169. if err != nil {
  170. return err
  171. }
  172. *u = u2
  173. return nil
  174. }
  175. // MarshalBinary implements the encoding.BinaryMarshaler interface.
  176. func (u UUID) MarshalBinary() (data []byte, err error) {
  177. data = u.Bytes()
  178. return
  179. }
  180. // UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.
  181. func (u *UUID) UnmarshalBinary(data []byte) error {
  182. u2, err := FromBytes(data)
  183. if err != nil {
  184. return err
  185. }
  186. *u = u2
  187. return nil
  188. }
  189. // FromBytes returns UUID converted from raw byte slice input.
  190. // It will return error if the slice isn't 16 bytes long.
  191. func FromBytes(input []byte) (u UUID, err error) {
  192. if len(input) != 16 {
  193. err = fmt.Errorf("uuid: UUID must be exactly 16 bytes long, got %d bytes", len(input))
  194. return
  195. }
  196. copy(u[:], input)
  197. return
  198. }
  199. // FromString returns UUID parsed from string input.
  200. // Following formats are supported:
  201. // "6ba7b810-9dad-11d1-80b4-00c04fd430c8",
  202. // "{6ba7b810-9dad-11d1-80b4-00c04fd430c8}",
  203. // "urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8"
  204. func FromString(input string) (u UUID, err error) {
  205. s := strings.Replace(input, "-", "", -1)
  206. if len(s) == 41 && s[:9] == "urn:uuid:" {
  207. s = s[9:]
  208. } else if len(s) == 34 && s[0] == '{' && s[33] == '}' {
  209. s = s[1:33]
  210. }
  211. if len(s) != 32 {
  212. err = fmt.Errorf("uuid: invalid UUID string: %s", input)
  213. return
  214. }
  215. b := []byte(s)
  216. _, err = hex.Decode(u[:], b)
  217. return
  218. }
  219. // Returns UUID v1/v2 storage state.
  220. // Returns epoch timestamp and clock sequence.
  221. func getStorage() (uint64, uint16) {
  222. storageMutex.Lock()
  223. defer storageMutex.Unlock()
  224. timeNow := epochFunc()
  225. // Clock changed backwards since last UUID generation.
  226. // Should increase clock sequence.
  227. if timeNow <= lastTime {
  228. clockSequence++
  229. }
  230. lastTime = timeNow
  231. return timeNow, clockSequence
  232. }
  233. // NewV1 returns UUID based on current timestamp and MAC address.
  234. func NewV1() UUID {
  235. u := UUID{}
  236. timeNow, clockSeq := getStorage()
  237. binary.BigEndian.PutUint32(u[0:], uint32(timeNow))
  238. binary.BigEndian.PutUint16(u[4:], uint16(timeNow>>32))
  239. binary.BigEndian.PutUint16(u[6:], uint16(timeNow>>48))
  240. binary.BigEndian.PutUint16(u[8:], clockSeq)
  241. copy(u[10:], hardwareAddr[:])
  242. u.SetVersion(1)
  243. u.SetVariant()
  244. return u
  245. }
  246. // NewV2 returns DCE Security UUID based on POSIX UID/GID.
  247. func NewV2(domain byte) UUID {
  248. u := UUID{}
  249. switch domain {
  250. case DomainPerson:
  251. binary.BigEndian.PutUint32(u[0:], posixUID)
  252. case DomainGroup:
  253. binary.BigEndian.PutUint32(u[0:], posixGID)
  254. }
  255. timeNow, clockSeq := getStorage()
  256. binary.BigEndian.PutUint16(u[4:], uint16(timeNow>>32))
  257. binary.BigEndian.PutUint16(u[6:], uint16(timeNow>>48))
  258. binary.BigEndian.PutUint16(u[8:], clockSeq)
  259. u[9] = domain
  260. copy(u[10:], hardwareAddr[:])
  261. u.SetVersion(2)
  262. u.SetVariant()
  263. return u
  264. }
  265. // NewV3 returns UUID based on MD5 hash of namespace UUID and name.
  266. func NewV3(ns UUID, name string) UUID {
  267. u := newFromHash(md5.New(), ns, name)
  268. u.SetVersion(3)
  269. u.SetVariant()
  270. return u
  271. }
  272. // NewV4 returns random generated UUID.
  273. func NewV4() UUID {
  274. u := UUID{}
  275. rand.Read(u[:])
  276. u.SetVersion(4)
  277. u.SetVariant()
  278. return u
  279. }
  280. // NewV5 returns UUID based on SHA-1 hash of namespace UUID and name.
  281. func NewV5(ns UUID, name string) UUID {
  282. u := newFromHash(sha1.New(), ns, name)
  283. u.SetVersion(5)
  284. u.SetVariant()
  285. return u
  286. }
  287. // Returns UUID based on hashing of namespace UUID and name.
  288. func newFromHash(h hash.Hash, ns UUID, name string) UUID {
  289. u := UUID{}
  290. h.Write(ns[:])
  291. h.Write([]byte(name))
  292. copy(u[:], h.Sum(nil))
  293. return u
  294. }