uuid.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. // Copyright (C) 2013-2015 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. "database/sql/driver"
  31. "encoding/binary"
  32. "encoding/hex"
  33. "fmt"
  34. "hash"
  35. "net"
  36. "os"
  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. // Used in string method conversion
  57. const dash byte = '-'
  58. // UUID v1/v2 storage.
  59. var (
  60. storageMutex sync.Mutex
  61. storageOnce sync.Once
  62. epochFunc = unixTimeFunc
  63. clockSequence uint16
  64. lastTime uint64
  65. hardwareAddr [6]byte
  66. posixUID = uint32(os.Getuid())
  67. posixGID = uint32(os.Getgid())
  68. )
  69. // String parse helpers.
  70. var (
  71. urnPrefix = []byte("urn:uuid:")
  72. byteGroups = []int{8, 4, 4, 4, 12}
  73. )
  74. func initClockSequence() {
  75. buf := make([]byte, 2)
  76. safeRandom(buf)
  77. clockSequence = binary.BigEndian.Uint16(buf)
  78. }
  79. func initHardwareAddr() {
  80. interfaces, err := net.Interfaces()
  81. if err == nil {
  82. for _, iface := range interfaces {
  83. if len(iface.HardwareAddr) >= 6 {
  84. copy(hardwareAddr[:], iface.HardwareAddr)
  85. return
  86. }
  87. }
  88. }
  89. // Initialize hardwareAddr randomly in case
  90. // of real network interfaces absence
  91. safeRandom(hardwareAddr[:])
  92. // Set multicast bit as recommended in RFC 4122
  93. hardwareAddr[0] |= 0x01
  94. }
  95. func initStorage() {
  96. initClockSequence()
  97. initHardwareAddr()
  98. }
  99. func safeRandom(dest []byte) {
  100. if _, err := rand.Read(dest); err != nil {
  101. panic(err)
  102. }
  103. }
  104. // Returns difference in 100-nanosecond intervals between
  105. // UUID epoch (October 15, 1582) and current time.
  106. // This is default epoch calculation function.
  107. func unixTimeFunc() uint64 {
  108. return epochStart + uint64(time.Now().UnixNano()/100)
  109. }
  110. // UUID representation compliant with specification
  111. // described in RFC 4122.
  112. type UUID [16]byte
  113. // NullUUID can be used with the standard sql package to represent a
  114. // UUID value that can be NULL in the database
  115. type NullUUID struct {
  116. UUID UUID
  117. Valid bool
  118. }
  119. // The nil UUID is special form of UUID that is specified to have all
  120. // 128 bits set to zero.
  121. var Nil = UUID{}
  122. // Predefined namespace UUIDs.
  123. var (
  124. NamespaceDNS, _ = FromString("6ba7b810-9dad-11d1-80b4-00c04fd430c8")
  125. NamespaceURL, _ = FromString("6ba7b811-9dad-11d1-80b4-00c04fd430c8")
  126. NamespaceOID, _ = FromString("6ba7b812-9dad-11d1-80b4-00c04fd430c8")
  127. NamespaceX500, _ = FromString("6ba7b814-9dad-11d1-80b4-00c04fd430c8")
  128. )
  129. // And returns result of binary AND of two UUIDs.
  130. func And(u1 UUID, u2 UUID) UUID {
  131. u := UUID{}
  132. for i := 0; i < 16; i++ {
  133. u[i] = u1[i] & u2[i]
  134. }
  135. return u
  136. }
  137. // Or returns result of binary OR of two UUIDs.
  138. func Or(u1 UUID, u2 UUID) UUID {
  139. u := UUID{}
  140. for i := 0; i < 16; i++ {
  141. u[i] = u1[i] | u2[i]
  142. }
  143. return u
  144. }
  145. // Equal returns true if u1 and u2 equals, otherwise returns false.
  146. func Equal(u1 UUID, u2 UUID) bool {
  147. return bytes.Equal(u1[:], u2[:])
  148. }
  149. // Version returns algorithm version used to generate UUID.
  150. func (u UUID) Version() uint {
  151. return uint(u[6] >> 4)
  152. }
  153. // Variant returns UUID layout variant.
  154. func (u UUID) Variant() uint {
  155. switch {
  156. case (u[8] & 0x80) == 0x00:
  157. return VariantNCS
  158. case (u[8]&0xc0)|0x80 == 0x80:
  159. return VariantRFC4122
  160. case (u[8]&0xe0)|0xc0 == 0xc0:
  161. return VariantMicrosoft
  162. }
  163. return VariantFuture
  164. }
  165. // Bytes returns bytes slice representation of UUID.
  166. func (u UUID) Bytes() []byte {
  167. return u[:]
  168. }
  169. // Returns canonical string representation of UUID:
  170. // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.
  171. func (u UUID) String() string {
  172. buf := make([]byte, 36)
  173. hex.Encode(buf[0:8], u[0:4])
  174. buf[8] = dash
  175. hex.Encode(buf[9:13], u[4:6])
  176. buf[13] = dash
  177. hex.Encode(buf[14:18], u[6:8])
  178. buf[18] = dash
  179. hex.Encode(buf[19:23], u[8:10])
  180. buf[23] = dash
  181. hex.Encode(buf[24:], u[10:])
  182. return string(buf)
  183. }
  184. // SetVersion sets version bits.
  185. func (u *UUID) SetVersion(v byte) {
  186. u[6] = (u[6] & 0x0f) | (v << 4)
  187. }
  188. // SetVariant sets variant bits as described in RFC 4122.
  189. func (u *UUID) SetVariant() {
  190. u[8] = (u[8] & 0xbf) | 0x80
  191. }
  192. // MarshalText implements the encoding.TextMarshaler interface.
  193. // The encoding is the same as returned by String.
  194. func (u UUID) MarshalText() (text []byte, err error) {
  195. text = []byte(u.String())
  196. return
  197. }
  198. // UnmarshalText implements the encoding.TextUnmarshaler interface.
  199. // Following formats are supported:
  200. // "6ba7b810-9dad-11d1-80b4-00c04fd430c8",
  201. // "{6ba7b810-9dad-11d1-80b4-00c04fd430c8}",
  202. // "urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8"
  203. func (u *UUID) UnmarshalText(text []byte) (err error) {
  204. if len(text) < 32 {
  205. err = fmt.Errorf("uuid: UUID string too short: %s", text)
  206. return
  207. }
  208. t := text[:]
  209. braced := false
  210. if bytes.Equal(t[:9], urnPrefix) {
  211. t = t[9:]
  212. } else if t[0] == '{' {
  213. braced = true
  214. t = t[1:]
  215. }
  216. b := u[:]
  217. for i, byteGroup := range byteGroups {
  218. if i > 0 && t[0] == '-' {
  219. t = t[1:]
  220. } else if i > 0 && t[0] != '-' {
  221. err = fmt.Errorf("uuid: invalid string format")
  222. return
  223. }
  224. if i == 2 {
  225. if !bytes.Contains([]byte("012345"), []byte{t[0]}) {
  226. err = fmt.Errorf("uuid: invalid version number: %s", t[0])
  227. return
  228. }
  229. }
  230. if len(t) < byteGroup {
  231. err = fmt.Errorf("uuid: UUID string too short: %s", text)
  232. return
  233. }
  234. if i == 4 && len(t) > byteGroup &&
  235. ((braced && t[byteGroup] != '}') || len(t[byteGroup:]) > 1 || !braced) {
  236. err = fmt.Errorf("uuid: UUID string too long: %s", t)
  237. return
  238. }
  239. _, err = hex.Decode(b[:byteGroup/2], t[:byteGroup])
  240. if err != nil {
  241. return
  242. }
  243. t = t[byteGroup:]
  244. b = b[byteGroup/2:]
  245. }
  246. return
  247. }
  248. // MarshalBinary implements the encoding.BinaryMarshaler interface.
  249. func (u UUID) MarshalBinary() (data []byte, err error) {
  250. data = u.Bytes()
  251. return
  252. }
  253. // UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.
  254. // It will return error if the slice isn't 16 bytes long.
  255. func (u *UUID) UnmarshalBinary(data []byte) (err error) {
  256. if len(data) != 16 {
  257. err = fmt.Errorf("uuid: UUID must be exactly 16 bytes long, got %d bytes", len(data))
  258. return
  259. }
  260. copy(u[:], data)
  261. return
  262. }
  263. // Value implements the driver.Valuer interface.
  264. func (u UUID) Value() (driver.Value, error) {
  265. return u.String(), nil
  266. }
  267. // Scan implements the sql.Scanner interface.
  268. // A 16-byte slice is handled by UnmarshalBinary, while
  269. // a longer byte slice or a string is handled by UnmarshalText.
  270. func (u *UUID) Scan(src interface{}) error {
  271. switch src := src.(type) {
  272. case []byte:
  273. if len(src) == 16 {
  274. return u.UnmarshalBinary(src)
  275. }
  276. return u.UnmarshalText(src)
  277. case string:
  278. return u.UnmarshalText([]byte(src))
  279. }
  280. return fmt.Errorf("uuid: cannot convert %T to UUID", src)
  281. }
  282. // Value implements the driver.Valuer interface.
  283. func (u NullUUID) Value() (driver.Value, error) {
  284. if !u.Valid {
  285. return nil, nil
  286. }
  287. // Delegate to UUID Value function
  288. return u.UUID.Value()
  289. }
  290. // Scan implements the sql.Scanner interface.
  291. func (u *NullUUID) Scan(src interface{}) error {
  292. if src == nil {
  293. u.UUID, u.Valid = Nil, false
  294. return nil
  295. }
  296. // Delegate to UUID Scan function
  297. u.Valid = true
  298. return u.UUID.Scan(src)
  299. }
  300. // FromBytes returns UUID converted from raw byte slice input.
  301. // It will return error if the slice isn't 16 bytes long.
  302. func FromBytes(input []byte) (u UUID, err error) {
  303. err = u.UnmarshalBinary(input)
  304. return
  305. }
  306. // FromBytesOrNil returns UUID converted from raw byte slice input.
  307. // Same behavior as FromBytes, but returns a Nil UUID on error.
  308. func FromBytesOrNil(input []byte) UUID {
  309. uuid, err := FromBytes(input)
  310. if err != nil {
  311. return Nil
  312. }
  313. return uuid
  314. }
  315. // FromString returns UUID parsed from string input.
  316. // Input is expected in a form accepted by UnmarshalText.
  317. func FromString(input string) (u UUID, err error) {
  318. err = u.UnmarshalText([]byte(input))
  319. return
  320. }
  321. // FromStringOrNil returns UUID parsed from string input.
  322. // Same behavior as FromString, but returns a Nil UUID on error.
  323. func FromStringOrNil(input string) UUID {
  324. uuid, err := FromString(input)
  325. if err != nil {
  326. return Nil
  327. }
  328. return uuid
  329. }
  330. // Returns UUID v1/v2 storage state.
  331. // Returns epoch timestamp, clock sequence, and hardware address.
  332. func getStorage() (uint64, uint16, []byte) {
  333. storageOnce.Do(initStorage)
  334. storageMutex.Lock()
  335. defer storageMutex.Unlock()
  336. timeNow := epochFunc()
  337. // Clock changed backwards since last UUID generation.
  338. // Should increase clock sequence.
  339. if timeNow <= lastTime {
  340. clockSequence++
  341. }
  342. lastTime = timeNow
  343. return timeNow, clockSequence, hardwareAddr[:]
  344. }
  345. // NewV1 returns UUID based on current timestamp and MAC address.
  346. func NewV1() UUID {
  347. u := UUID{}
  348. timeNow, clockSeq, hardwareAddr := getStorage()
  349. binary.BigEndian.PutUint32(u[0:], uint32(timeNow))
  350. binary.BigEndian.PutUint16(u[4:], uint16(timeNow>>32))
  351. binary.BigEndian.PutUint16(u[6:], uint16(timeNow>>48))
  352. binary.BigEndian.PutUint16(u[8:], clockSeq)
  353. copy(u[10:], hardwareAddr)
  354. u.SetVersion(1)
  355. u.SetVariant()
  356. return u
  357. }
  358. // NewV2 returns DCE Security UUID based on POSIX UID/GID.
  359. func NewV2(domain byte) UUID {
  360. u := UUID{}
  361. timeNow, clockSeq, hardwareAddr := getStorage()
  362. switch domain {
  363. case DomainPerson:
  364. binary.BigEndian.PutUint32(u[0:], posixUID)
  365. case DomainGroup:
  366. binary.BigEndian.PutUint32(u[0:], posixGID)
  367. }
  368. binary.BigEndian.PutUint16(u[4:], uint16(timeNow>>32))
  369. binary.BigEndian.PutUint16(u[6:], uint16(timeNow>>48))
  370. binary.BigEndian.PutUint16(u[8:], clockSeq)
  371. u[9] = domain
  372. copy(u[10:], hardwareAddr)
  373. u.SetVersion(2)
  374. u.SetVariant()
  375. return u
  376. }
  377. // NewV3 returns UUID based on MD5 hash of namespace UUID and name.
  378. func NewV3(ns UUID, name string) UUID {
  379. u := newFromHash(md5.New(), ns, name)
  380. u.SetVersion(3)
  381. u.SetVariant()
  382. return u
  383. }
  384. // NewV4 returns random generated UUID.
  385. func NewV4() UUID {
  386. u := UUID{}
  387. safeRandom(u[:])
  388. u.SetVersion(4)
  389. u.SetVariant()
  390. return u
  391. }
  392. // NewV5 returns UUID based on SHA-1 hash of namespace UUID and name.
  393. func NewV5(ns UUID, name string) UUID {
  394. u := newFromHash(sha1.New(), ns, name)
  395. u.SetVersion(5)
  396. u.SetVariant()
  397. return u
  398. }
  399. // Returns UUID based on hashing of namespace UUID and name.
  400. func newFromHash(h hash.Hash, ns UUID, name string) UUID {
  401. u := UUID{}
  402. h.Write(ns[:])
  403. h.Write([]byte(name))
  404. copy(u[:], h.Sum(nil))
  405. return u
  406. }