generator.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. // Copyright (C) 2013-2018 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
  22. import (
  23. "crypto/md5"
  24. "crypto/rand"
  25. "crypto/sha1"
  26. "encoding/binary"
  27. "fmt"
  28. "hash"
  29. "io"
  30. "net"
  31. "os"
  32. "sync"
  33. "time"
  34. )
  35. // Difference in 100-nanosecond intervals between
  36. // UUID epoch (October 15, 1582) and Unix epoch (January 1, 1970).
  37. const epochStart = 122192928000000000
  38. type epochFunc func() time.Time
  39. type hwAddrFunc func() (net.HardwareAddr, error)
  40. var (
  41. global = newRFC4122Generator()
  42. posixUID = uint32(os.Getuid())
  43. posixGID = uint32(os.Getgid())
  44. )
  45. // NewV1 returns UUID based on current timestamp and MAC address.
  46. func NewV1() (UUID, error) {
  47. return global.NewV1()
  48. }
  49. // NewV2 returns DCE Security UUID based on POSIX UID/GID.
  50. func NewV2(domain byte) (UUID, error) {
  51. return global.NewV2(domain)
  52. }
  53. // NewV3 returns UUID based on MD5 hash of namespace UUID and name.
  54. func NewV3(ns UUID, name string) UUID {
  55. return global.NewV3(ns, name)
  56. }
  57. // NewV4 returns random generated UUID.
  58. func NewV4() (UUID, error) {
  59. return global.NewV4()
  60. }
  61. // NewV5 returns UUID based on SHA-1 hash of namespace UUID and name.
  62. func NewV5(ns UUID, name string) UUID {
  63. return global.NewV5(ns, name)
  64. }
  65. // Generator provides interface for generating UUIDs.
  66. type Generator interface {
  67. NewV1() (UUID, error)
  68. NewV2(domain byte) (UUID, error)
  69. NewV3(ns UUID, name string) UUID
  70. NewV4() (UUID, error)
  71. NewV5(ns UUID, name string) UUID
  72. }
  73. // Default generator implementation.
  74. type rfc4122Generator struct {
  75. clockSequenceOnce sync.Once
  76. hardwareAddrOnce sync.Once
  77. storageMutex sync.Mutex
  78. rand io.Reader
  79. epochFunc epochFunc
  80. hwAddrFunc hwAddrFunc
  81. lastTime uint64
  82. clockSequence uint16
  83. hardwareAddr [6]byte
  84. }
  85. func newRFC4122Generator() Generator {
  86. return &rfc4122Generator{
  87. epochFunc: time.Now,
  88. hwAddrFunc: defaultHWAddrFunc,
  89. rand: rand.Reader,
  90. }
  91. }
  92. // NewV1 returns UUID based on current timestamp and MAC address.
  93. func (g *rfc4122Generator) NewV1() (UUID, error) {
  94. u := UUID{}
  95. timeNow, clockSeq, err := g.getClockSequence()
  96. if err != nil {
  97. return Nil, err
  98. }
  99. binary.BigEndian.PutUint32(u[0:], uint32(timeNow))
  100. binary.BigEndian.PutUint16(u[4:], uint16(timeNow>>32))
  101. binary.BigEndian.PutUint16(u[6:], uint16(timeNow>>48))
  102. binary.BigEndian.PutUint16(u[8:], clockSeq)
  103. hardwareAddr, err := g.getHardwareAddr()
  104. if err != nil {
  105. return Nil, err
  106. }
  107. copy(u[10:], hardwareAddr)
  108. u.SetVersion(V1)
  109. u.SetVariant(VariantRFC4122)
  110. return u, nil
  111. }
  112. // NewV2 returns DCE Security UUID based on POSIX UID/GID.
  113. func (g *rfc4122Generator) NewV2(domain byte) (UUID, error) {
  114. u, err := g.NewV1()
  115. if err != nil {
  116. return Nil, err
  117. }
  118. switch domain {
  119. case DomainPerson:
  120. binary.BigEndian.PutUint32(u[:], posixUID)
  121. case DomainGroup:
  122. binary.BigEndian.PutUint32(u[:], posixGID)
  123. }
  124. u[9] = domain
  125. u.SetVersion(V2)
  126. u.SetVariant(VariantRFC4122)
  127. return u, nil
  128. }
  129. // NewV3 returns UUID based on MD5 hash of namespace UUID and name.
  130. func (g *rfc4122Generator) NewV3(ns UUID, name string) UUID {
  131. u := newFromHash(md5.New(), ns, name)
  132. u.SetVersion(V3)
  133. u.SetVariant(VariantRFC4122)
  134. return u
  135. }
  136. // NewV4 returns random generated UUID.
  137. func (g *rfc4122Generator) NewV4() (UUID, error) {
  138. u := UUID{}
  139. if _, err := io.ReadFull(g.rand, u[:]); err != nil {
  140. return Nil, err
  141. }
  142. u.SetVersion(V4)
  143. u.SetVariant(VariantRFC4122)
  144. return u, nil
  145. }
  146. // NewV5 returns UUID based on SHA-1 hash of namespace UUID and name.
  147. func (g *rfc4122Generator) NewV5(ns UUID, name string) UUID {
  148. u := newFromHash(sha1.New(), ns, name)
  149. u.SetVersion(V5)
  150. u.SetVariant(VariantRFC4122)
  151. return u
  152. }
  153. // Returns epoch and clock sequence.
  154. func (g *rfc4122Generator) getClockSequence() (uint64, uint16, error) {
  155. var err error
  156. g.clockSequenceOnce.Do(func() {
  157. buf := make([]byte, 2)
  158. if _, err = io.ReadFull(g.rand, buf); err != nil {
  159. return
  160. }
  161. g.clockSequence = binary.BigEndian.Uint16(buf)
  162. })
  163. if err != nil {
  164. return 0, 0, err
  165. }
  166. g.storageMutex.Lock()
  167. defer g.storageMutex.Unlock()
  168. timeNow := g.getEpoch()
  169. // Clock didn't change since last UUID generation.
  170. // Should increase clock sequence.
  171. if timeNow <= g.lastTime {
  172. g.clockSequence++
  173. }
  174. g.lastTime = timeNow
  175. return timeNow, g.clockSequence, nil
  176. }
  177. // Returns hardware address.
  178. func (g *rfc4122Generator) getHardwareAddr() ([]byte, error) {
  179. var err error
  180. g.hardwareAddrOnce.Do(func() {
  181. if hwAddr, err := g.hwAddrFunc(); err == nil {
  182. copy(g.hardwareAddr[:], hwAddr)
  183. return
  184. }
  185. // Initialize hardwareAddr randomly in case
  186. // of real network interfaces absence.
  187. if _, err = io.ReadFull(g.rand, g.hardwareAddr[:]); err != nil {
  188. return
  189. }
  190. // Set multicast bit as recommended by RFC 4122
  191. g.hardwareAddr[0] |= 0x01
  192. })
  193. if err != nil {
  194. return []byte{}, err
  195. }
  196. return g.hardwareAddr[:], nil
  197. }
  198. // Returns difference in 100-nanosecond intervals between
  199. // UUID epoch (October 15, 1582) and current time.
  200. func (g *rfc4122Generator) getEpoch() uint64 {
  201. return epochStart + uint64(g.epochFunc().UnixNano()/100)
  202. }
  203. // Returns UUID based on hashing of namespace UUID and name.
  204. func newFromHash(h hash.Hash, ns UUID, name string) UUID {
  205. u := UUID{}
  206. h.Write(ns[:])
  207. h.Write([]byte(name))
  208. copy(u[:], h.Sum(nil))
  209. return u
  210. }
  211. // Returns hardware address.
  212. func defaultHWAddrFunc() (net.HardwareAddr, error) {
  213. ifaces, err := net.Interfaces()
  214. if err != nil {
  215. return []byte{}, err
  216. }
  217. for _, iface := range ifaces {
  218. if len(iface.HardwareAddr) >= 6 {
  219. return iface.HardwareAddr, nil
  220. }
  221. }
  222. return []byte{}, fmt.Errorf("uuid: no HW address found")
  223. }