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