1
0

generator.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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. // HWAddrFunc is the function type used to provide hardware (MAC) addresses.
  40. type HWAddrFunc func() (net.HardwareAddr, error)
  41. // DefaultGenerator is the default UUID Generator used by this package.
  42. var DefaultGenerator Generator = NewGen()
  43. var (
  44. posixUID = uint32(os.Getuid())
  45. posixGID = uint32(os.Getgid())
  46. )
  47. // NewV1 returns a UUID based on the current timestamp and MAC address.
  48. func NewV1() (UUID, error) {
  49. return DefaultGenerator.NewV1()
  50. }
  51. // NewV2 returns a DCE Security UUID based on the POSIX UID/GID.
  52. func NewV2(domain byte) (UUID, error) {
  53. return DefaultGenerator.NewV2(domain)
  54. }
  55. // NewV3 returns a UUID based on the MD5 hash of the namespace UUID and name.
  56. func NewV3(ns UUID, name string) UUID {
  57. return DefaultGenerator.NewV3(ns, name)
  58. }
  59. // NewV4 returns a randomly generated UUID.
  60. func NewV4() (UUID, error) {
  61. return DefaultGenerator.NewV4()
  62. }
  63. // NewV5 returns a UUID based on SHA-1 hash of the namespace UUID and name.
  64. func NewV5(ns UUID, name string) UUID {
  65. return DefaultGenerator.NewV5(ns, name)
  66. }
  67. // Generator provides an interface for generating UUIDs.
  68. type Generator interface {
  69. NewV1() (UUID, error)
  70. NewV2(domain byte) (UUID, error)
  71. NewV3(ns UUID, name string) UUID
  72. NewV4() (UUID, error)
  73. NewV5(ns UUID, name string) UUID
  74. }
  75. // Gen is a reference UUID generator based on the specifications laid out in
  76. // RFC-4122 and DCE 1.1: Authentication and Security Services. This type
  77. // satisfies the Generator interface as defined in this package.
  78. //
  79. // For consumers who are generating V1 UUIDs, but don't want to expose the MAC
  80. // address of the node generating the UUIDs, the NewGenWithHWAF() function has been
  81. // provided as a convenience. See the function's documentation for more info.
  82. //
  83. // The authors of this package do not feel that the majority of users will need
  84. // to obfuscate their MAC address, and so we recommend using NewGen() to create
  85. // a new generator.
  86. type Gen struct {
  87. clockSequenceOnce sync.Once
  88. hardwareAddrOnce sync.Once
  89. storageMutex sync.Mutex
  90. rand io.Reader
  91. epochFunc epochFunc
  92. hwAddrFunc HWAddrFunc
  93. lastTime uint64
  94. clockSequence uint16
  95. hardwareAddr [6]byte
  96. }
  97. // interface check -- build will fail if *Gen doesn't satisfy Generator
  98. var _ Generator = (*Gen)(nil)
  99. // NewGen returns a new instance of Gen with some default values set. Most
  100. // people should use this.
  101. func NewGen() *Gen {
  102. return NewGenWithHWAF(defaultHWAddrFunc)
  103. }
  104. // NewGenWithHWAF builds a new UUID generator with the HWAddrFunc provided. Most
  105. // consumers should use NewGen() instead.
  106. //
  107. // This is used so that consumers can generate their own MAC addresses, for use
  108. // in the generated UUIDs, if there is some concern about exposing the physical
  109. // address of the machine generating the UUID.
  110. //
  111. // The Gen generator will only invoke the HWAddrFunc once, and cache that MAC
  112. // address for all the future UUIDs generated by it. If you'd like to switch the
  113. // MAC address being used, you'll need to create a new generator using this
  114. // function.
  115. func NewGenWithHWAF(hwaf HWAddrFunc) *Gen {
  116. return &Gen{
  117. epochFunc: time.Now,
  118. hwAddrFunc: hwaf,
  119. rand: rand.Reader,
  120. }
  121. }
  122. // NewV1 returns a UUID based on the current timestamp and MAC address.
  123. func (g *Gen) NewV1() (UUID, error) {
  124. u := UUID{}
  125. timeNow, clockSeq, err := g.getClockSequence()
  126. if err != nil {
  127. return Nil, err
  128. }
  129. binary.BigEndian.PutUint32(u[0:], uint32(timeNow))
  130. binary.BigEndian.PutUint16(u[4:], uint16(timeNow>>32))
  131. binary.BigEndian.PutUint16(u[6:], uint16(timeNow>>48))
  132. binary.BigEndian.PutUint16(u[8:], clockSeq)
  133. hardwareAddr, err := g.getHardwareAddr()
  134. if err != nil {
  135. return Nil, err
  136. }
  137. copy(u[10:], hardwareAddr)
  138. u.SetVersion(V1)
  139. u.SetVariant(VariantRFC4122)
  140. return u, nil
  141. }
  142. // NewV2 returns a DCE Security UUID based on the POSIX UID/GID.
  143. func (g *Gen) NewV2(domain byte) (UUID, error) {
  144. u, err := g.NewV1()
  145. if err != nil {
  146. return Nil, err
  147. }
  148. switch domain {
  149. case DomainPerson:
  150. binary.BigEndian.PutUint32(u[:], posixUID)
  151. case DomainGroup:
  152. binary.BigEndian.PutUint32(u[:], posixGID)
  153. }
  154. u[9] = domain
  155. u.SetVersion(V2)
  156. u.SetVariant(VariantRFC4122)
  157. return u, nil
  158. }
  159. // NewV3 returns a UUID based on the MD5 hash of the namespace UUID and name.
  160. func (g *Gen) NewV3(ns UUID, name string) UUID {
  161. u := newFromHash(md5.New(), ns, name)
  162. u.SetVersion(V3)
  163. u.SetVariant(VariantRFC4122)
  164. return u
  165. }
  166. // NewV4 returns a randomly generated UUID.
  167. func (g *Gen) NewV4() (UUID, error) {
  168. u := UUID{}
  169. if _, err := io.ReadFull(g.rand, u[:]); err != nil {
  170. return Nil, err
  171. }
  172. u.SetVersion(V4)
  173. u.SetVariant(VariantRFC4122)
  174. return u, nil
  175. }
  176. // NewV5 returns a UUID based on SHA-1 hash of the namespace UUID and name.
  177. func (g *Gen) NewV5(ns UUID, name string) UUID {
  178. u := newFromHash(sha1.New(), ns, name)
  179. u.SetVersion(V5)
  180. u.SetVariant(VariantRFC4122)
  181. return u
  182. }
  183. // Returns the epoch and clock sequence.
  184. func (g *Gen) getClockSequence() (uint64, uint16, error) {
  185. var err error
  186. g.clockSequenceOnce.Do(func() {
  187. buf := make([]byte, 2)
  188. if _, err = io.ReadFull(g.rand, buf); err != nil {
  189. return
  190. }
  191. g.clockSequence = binary.BigEndian.Uint16(buf)
  192. })
  193. if err != nil {
  194. return 0, 0, err
  195. }
  196. g.storageMutex.Lock()
  197. defer g.storageMutex.Unlock()
  198. timeNow := g.getEpoch()
  199. // Clock didn't change since last UUID generation.
  200. // Should increase clock sequence.
  201. if timeNow <= g.lastTime {
  202. g.clockSequence++
  203. }
  204. g.lastTime = timeNow
  205. return timeNow, g.clockSequence, nil
  206. }
  207. // Returns the hardware address.
  208. func (g *Gen) getHardwareAddr() ([]byte, error) {
  209. var err error
  210. g.hardwareAddrOnce.Do(func() {
  211. var hwAddr net.HardwareAddr
  212. if hwAddr, err = g.hwAddrFunc(); err == nil {
  213. copy(g.hardwareAddr[:], hwAddr)
  214. return
  215. }
  216. // Initialize hardwareAddr randomly in case
  217. // of real network interfaces absence.
  218. if _, err = io.ReadFull(g.rand, g.hardwareAddr[:]); err != nil {
  219. return
  220. }
  221. // Set multicast bit as recommended by RFC-4122
  222. g.hardwareAddr[0] |= 0x01
  223. })
  224. if err != nil {
  225. return []byte{}, err
  226. }
  227. return g.hardwareAddr[:], nil
  228. }
  229. // Returns the difference between UUID epoch (October 15, 1582)
  230. // and current time in 100-nanosecond intervals.
  231. func (g *Gen) getEpoch() uint64 {
  232. return epochStart + uint64(g.epochFunc().UnixNano()/100)
  233. }
  234. // Returns the UUID based on the hashing of the namespace UUID and name.
  235. func newFromHash(h hash.Hash, ns UUID, name string) UUID {
  236. u := UUID{}
  237. h.Write(ns[:])
  238. h.Write([]byte(name))
  239. copy(u[:], h.Sum(nil))
  240. return u
  241. }
  242. // Returns the hardware address.
  243. func defaultHWAddrFunc() (net.HardwareAddr, error) {
  244. ifaces, err := net.Interfaces()
  245. if err != nil {
  246. return []byte{}, err
  247. }
  248. for _, iface := range ifaces {
  249. if len(iface.HardwareAddr) >= 6 {
  250. return iface.HardwareAddr, nil
  251. }
  252. }
  253. return []byte{}, fmt.Errorf("uuid: no HW address found")
  254. }