| 1 |
package uuid |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"crypto/rand" |
| 6 |
"encoding/binary" |
| 7 |
"log" |
| 8 |
"net" |
| 9 |
"os" |
| 10 |
"sync" |
| 11 |
) |
| 12 |
|
| 13 |
var ( |
| 14 |
once *sync.Once = new(sync.Once) |
| 15 |
generator *Generator = newGenerator(GeneratorConfig{}) |
| 16 |
) |
| 17 |
|
| 18 |
// Random provides a CPRNG which reads into the given []byte, the package |
| 19 |
// uses crypto/rand.Read by default. You can supply your own CPRNG. The |
| 20 |
// function is used by V4 UUIDs and for setting up V1 and V2 UUIDs via the |
| 21 |
// Generator Init or Register* functions. |
| 22 |
type Random func([]byte) (int, error) |
| 23 |
|
| 24 |
// Next provides the next Timestamp value to be used by the next V1 or V2 UUID. |
| 25 |
// The default uses the uuid.spinner which spins at a resolution of |
| 26 |
// 100ns ticks and provides a spin resolution redundancy of 1024 |
| 27 |
// cycles. This ensures that the system is not too quick when |
| 28 |
// generating V1 or V2 UUIDs. Each system requires a tuned Resolution to |
| 29 |
// enhance performance. |
| 30 |
type Next func() Timestamp |
| 31 |
|
| 32 |
// Id provides the Node to be used during the life of a uuid.Generator. If |
| 33 |
// it cannot be determined nil should be returned, the package will |
| 34 |
// then provide a crypto-random node id. The default generator gets a MAC |
| 35 |
// address from the first interface that is up checking net.FlagUp. |
| 36 |
type Id func() Node |
| 37 |
|
| 38 |
// HandleError provides the user the ability to manage any serious |
| 39 |
// error that may be caused by accessing the standard crypto/rand |
| 40 |
// library. Due to the rarity of this occurrence the error is swallowed |
| 41 |
// by NewV4 functions, which rely on random numbers, the package will then |
| 42 |
// panic. You can change this behaviour by passing in your own HandleError |
| 43 |
// function. With this function you can attempt to fix your CPRNG and then |
| 44 |
// return true to try again. If another error occurs the function will return |
| 45 |
// nil and you can then handle the error by calling uuid.Error or calling Error |
| 46 |
// from your standalone Generator. |
| 47 |
type HandleError func(error) bool |
| 48 |
|
| 49 |
// Generator is used to create and monitor the running of V1 and V2, and V4 |
| 50 |
// UUIDs. It can be setup to take different implementations for Timestamp, Node |
| 51 |
// and CPRNG retrieval. This is also where the Saver implementation can be |
| 52 |
// given and your error policy for V4 Uuids can be setup. |
| 53 |
type Generator struct { |
| 54 |
// Access to the store needs to be maintained |
| 55 |
sync.Mutex |
| 56 |
|
| 57 |
// Once ensures that the generator is only setup and initialised once. |
| 58 |
// This will occur either when you explicitly call the |
| 59 |
// uuid.Generator.Init function or when a V1 or V2 id is generated. |
| 60 |
sync.Once |
| 61 |
|
| 62 |
err error |
| 63 |
|
| 64 |
// Store contains the current values being used by the Generator. |
| 65 |
*Store |
| 66 |
|
| 67 |
// Id as per the type Id func() Node |
| 68 |
Id |
| 69 |
|
| 70 |
// HandleError as per the type HandleError func(error) bool |
| 71 |
HandleError HandleError |
| 72 |
|
| 73 |
// Next as per the type Next func() Timestamp |
| 74 |
Next Next |
| 75 |
|
| 76 |
// Random as per the type Random func([]byte) (int, error) |
| 77 |
Random |
| 78 |
|
| 79 |
// Intended to provide a non-volatile store to save the state of the |
| 80 |
// generator, the default is nil and to therefore generate a timestamp |
| 81 |
// clock sequence with random data. You can register your own save by |
| 82 |
// using the uuid.RegisterSaver function or by creating your own |
| 83 |
// uuid.Generator instance from which to generate your V1, V2 or V4 |
| 84 |
// UUIDs. |
| 85 |
Saver |
| 86 |
} |
| 87 |
|
| 88 |
// GeneratorConfig allows you to setup a new uuid.Generator using |
| 89 |
// uuid.NewGenerator or RegisterGenerator. You can supply your own |
| 90 |
// implementations for CPRNG, Node Id and Timestamp retrieval. You can also |
| 91 |
// adjust the resolution of the default Timestamp spinner and supply your own |
| 92 |
// error handler CPRNG failures. |
| 93 |
type GeneratorConfig struct { |
| 94 |
Saver |
| 95 |
Next |
| 96 |
Resolution uint |
| 97 |
Id |
| 98 |
Random |
| 99 |
HandleError |
| 100 |
} |
| 101 |
|
| 102 |
// NewGenerator will create a new uuid.Generator with the given functions. |
| 103 |
func NewGenerator(pConfig GeneratorConfig) (gen *Generator) { |
| 104 |
gen = newGenerator(pConfig) |
| 105 |
generator.Do(generator.init) |
| 106 |
return |
| 107 |
} |
| 108 |
|
| 109 |
func newGenerator(pConfig GeneratorConfig) (gen *Generator) { |
| 110 |
gen = new(Generator) |
| 111 |
if pConfig.Next == nil { |
| 112 |
if pConfig.Resolution == 0 { |
| 113 |
pConfig.Resolution = defaultSpinResolution |
| 114 |
} |
| 115 |
gen.Next = (&spinner{ |
| 116 |
Resolution: pConfig.Resolution, |
| 117 |
Count: 0, |
| 118 |
Timestamp: Now(), |
| 119 |
}).next |
| 120 |
} else { |
| 121 |
gen.Next = pConfig.Next |
| 122 |
} |
| 123 |
if pConfig.Id == nil { |
| 124 |
gen.Id = findFirstHardwareAddress |
| 125 |
} else { |
| 126 |
gen.Id = pConfig.Id |
| 127 |
} |
| 128 |
if pConfig.Random == nil { |
| 129 |
gen.Random = rand.Read |
| 130 |
} else { |
| 131 |
gen.Random = pConfig.Random |
| 132 |
} |
| 133 |
if pConfig.HandleError == nil { |
| 134 |
gen.HandleError = runHandleError |
| 135 |
} else { |
| 136 |
gen.HandleError = pConfig.HandleError |
| 137 |
} |
| 138 |
gen.Saver = pConfig.Saver |
| 139 |
gen.Store = new(Store) |
| 140 |
return |
| 141 |
} |
| 142 |
|
| 143 |
// Init will initialise the default generator with default settings |
| 144 |
func Init() error { |
| 145 |
return RegisterGenerator(GeneratorConfig{}) |
| 146 |
} |
| 147 |
|
| 148 |
// RegisterGenerator will set the default generator to the given generator |
| 149 |
// Like uuid.Init this can only be called once. Any subsequent calls will have no |
| 150 |
// effect. If you call this you do not need to call uuid.Init |
| 151 |
func RegisterGenerator(pConfig GeneratorConfig) (err error) { |
| 152 |
gen := newGenerator(pConfig) |
| 153 |
|
| 154 |
notOnce := true |
| 155 |
once.Do(func() { |
| 156 |
generator = gen |
| 157 |
generator.Do(generator.init) |
| 158 |
err = generator.Error() |
| 159 |
notOnce = false |
| 160 |
return |
| 161 |
}) |
| 162 |
if notOnce { |
| 163 |
log.Panicf("A uuid.Register* method cannot be called more than once.") |
| 164 |
} |
| 165 |
return |
| 166 |
} |
| 167 |
|
| 168 |
// Error will return any error from the uuid.Generator if a UUID returns as Nil |
| 169 |
// or nil |
| 170 |
func (o *Generator) Error() (err error) { |
| 171 |
err = o.err |
| 172 |
o.err = nil |
| 173 |
return |
| 174 |
} |
| 175 |
|
| 176 |
func (o *Generator) read() { |
| 177 |
|
| 178 |
// Save the state (current timestamp, clock sequence, and node ID) |
| 179 |
// back to the stable store |
| 180 |
if o.Saver != nil { |
| 181 |
defer o.save() |
| 182 |
} |
| 183 |
|
| 184 |
// Obtain a lock |
| 185 |
o.Lock() |
| 186 |
defer o.Unlock() |
| 187 |
|
| 188 |
// Get the current time as a 60-bit count of 100-nanosecond intervals |
| 189 |
// since 00:00:00.00, 15 October 1582. |
| 190 |
now := o.Next() |
| 191 |
|
| 192 |
// If the last timestamp is later than |
| 193 |
// the current timestamp, increment the clock sequence value. |
| 194 |
if now <= o.Timestamp { |
| 195 |
o.Sequence++ |
| 196 |
} |
| 197 |
|
| 198 |
// Update the timestamp |
| 199 |
o.Timestamp = now |
| 200 |
} |
| 201 |
|
| 202 |
func (o *Generator) init() { |
| 203 |
// From a system-wide shared stable store (e.g., a file), read the |
| 204 |
// UUID generator state: the values of the timestamp, clock sequence, |
| 205 |
// and node ID used to generate the last UUID. |
| 206 |
var ( |
| 207 |
storage Store |
| 208 |
err error |
| 209 |
) |
| 210 |
|
| 211 |
o.Lock() |
| 212 |
defer o.Unlock() |
| 213 |
|
| 214 |
if o.Saver != nil { |
| 215 |
err, storage = o.Read() |
| 216 |
if err != nil { |
| 217 |
o.Saver = nil |
| 218 |
} |
| 219 |
} |
| 220 |
|
| 221 |
// Get the current time as a 60-bit count of 100-nanosecond intervals |
| 222 |
// since 00:00:00.00, 15 October 1582. |
| 223 |
now := o.Next() |
| 224 |
|
| 225 |
// Get the current node id |
| 226 |
node := o.Id() |
| 227 |
|
| 228 |
if node == nil { |
| 229 |
log.Println("uuid.Generator.init: address error: will generate random node id instead") |
| 230 |
|
| 231 |
node = make([]byte, 6) |
| 232 |
n, err := o.Random(node) |
| 233 |
if err != nil { |
| 234 |
log.Printf("uuid.Generator.init: could not read random bytes into node - read [%d] %s", n, err) |
| 235 |
o.err = err |
| 236 |
return |
| 237 |
} |
| 238 |
// Mark as randomly generated |
| 239 |
node[0] |= 0x01 |
| 240 |
} |
| 241 |
|
| 242 |
// If the state was unavailable (e.g., non-existent or corrupted), or |
| 243 |
// the saved node ID is different than the current node ID, generate |
| 244 |
// a random clock sequence value. |
| 245 |
if o.Saver == nil || !bytes.Equal(storage.Node, node) { |
| 246 |
|
| 247 |
// 4.1.5. Clock Sequence https://www.ietf.org/rfc/rfc4122.txt |
| 248 |
// |
| 249 |
// For UUID version 1, the clock sequence is used to help avoid |
| 250 |
// duplicates that could arise when the clock is set backwards in time |
| 251 |
// or if the node ID changes. |
| 252 |
// |
| 253 |
// If the clock is set backwards, or might have been set backwards |
| 254 |
// (e.g., while the system was powered off), and the UUID generator can |
| 255 |
// not be sure that no UUIDs were generated with timestamps larger than |
| 256 |
// the value to which the clock was set, then the clock sequence has to |
| 257 |
// be changed. If the previous value of the clock sequence is known, it |
| 258 |
// can just be incremented; otherwise it should be set to a random or |
| 259 |
// high-quality pseudo-random value. |
| 260 |
|
| 261 |
// The clock sequence MUST be originally (i.e., once in the lifetime of |
| 262 |
// a system) initialized to a random number to minimize the correlation |
| 263 |
// across systems. This provides maximum protection against node |
| 264 |
// identifiers that may move or switch from system to system rapidly. |
| 265 |
// The initial value MUST NOT be correlated to the node identifier. |
| 266 |
b := make([]byte, 2) |
| 267 |
n, err := o.Random(b) |
| 268 |
if err == nil { |
| 269 |
storage.Sequence = Sequence(binary.BigEndian.Uint16(b)) |
| 270 |
log.Printf("uuid.Generator.init initialised random sequence: [%d]", storage.Sequence) |
| 271 |
|
| 272 |
} else { |
| 273 |
log.Printf("uuid.Generator.init: could not read random bytes into sequence - read [%d] %s", n, err) |
| 274 |
o.err = err |
| 275 |
return |
| 276 |
} |
| 277 |
} else if now < storage.Timestamp { |
| 278 |
// If the state was available, but the saved timestamp is later than |
| 279 |
// the current timestamp, increment the clock sequence value. |
| 280 |
storage.Sequence++ |
| 281 |
} |
| 282 |
|
| 283 |
storage.Timestamp = now |
| 284 |
storage.Node = node |
| 285 |
|
| 286 |
o.Store = &storage |
| 287 |
} |
| 288 |
|
| 289 |
func (o *Generator) save() { |
| 290 |
func(pState *Generator) { |
| 291 |
if pState.Saver != nil { |
| 292 |
pState.Lock() |
| 293 |
defer pState.Unlock() |
| 294 |
pState.Save(*pState.Store) |
| 295 |
} |
| 296 |
}(o) |
| 297 |
} |
| 298 |
|
| 299 |
// NewV1 generates a new RFC4122 version 1 UUID based on a 60 bit timestamp and |
| 300 |
// node id |
| 301 |
func (o *Generator) NewV1() Uuid { |
| 302 |
o.read() |
| 303 |
id := array{} |
| 304 |
|
| 305 |
makeUuid(&id, |
| 306 |
uint32(o.Timestamp), |
| 307 |
uint16(o.Timestamp>>32), |
| 308 |
uint16(o.Timestamp>>48), |
| 309 |
uint16(o.Sequence), |
| 310 |
o.Node) |
| 311 |
|
| 312 |
id.setRFC4122Version(1) |
| 313 |
return id[:] |
| 314 |
} |
| 315 |
|
| 316 |
// NewV2 generates a new DCE version 2 UUID based on a 60 bit timestamp, node id |
| 317 |
// and POSIX UID or GID |
| 318 |
func (o *Generator) NewV2(pDomain Domain) Uuid { |
| 319 |
o.read() |
| 320 |
|
| 321 |
id := array{} |
| 322 |
|
| 323 |
var domain uint32 |
| 324 |
|
| 325 |
switch pDomain { |
| 326 |
case DomainUser: |
| 327 |
domain = uint32(os.Getuid()) |
| 328 |
case DomainGroup: |
| 329 |
domain = uint32(os.Getgid()) |
| 330 |
} |
| 331 |
|
| 332 |
makeUuid(&id, |
| 333 |
domain, |
| 334 |
uint16(o.Timestamp>>32), |
| 335 |
uint16(o.Timestamp>>48), |
| 336 |
uint16(o.Sequence), |
| 337 |
o.Node) |
| 338 |
|
| 339 |
id[9] = byte(pDomain) |
| 340 |
id.setRFC4122Version(2) |
| 341 |
return id[:] |
| 342 |
} |
| 343 |
|
| 344 |
func makeUuid(pId *array, pLow uint32, pMid, pHiAndV, seq uint16, pNode Node) { |
| 345 |
|
| 346 |
pId[0] = byte(pLow >> 24) |
| 347 |
pId[1] = byte(pLow >> 16) |
| 348 |
pId[2] = byte(pLow >> 8) |
| 349 |
pId[3] = byte(pLow) |
| 350 |
|
| 351 |
pId[4] = byte(pMid >> 8) |
| 352 |
pId[5] = byte(pMid) |
| 353 |
|
| 354 |
pId[6] = byte(pHiAndV >> 8) |
| 355 |
pId[7] = byte(pHiAndV) |
| 356 |
|
| 357 |
pId[8] = byte(seq >> 8) |
| 358 |
pId[9] = byte(seq) |
| 359 |
|
| 360 |
copy(pId[10:], pNode) |
| 361 |
} |
| 362 |
|
| 363 |
func findFirstHardwareAddress() (node Node) { |
| 364 |
interfaces, err := net.Interfaces() |
| 365 |
if err == nil { |
| 366 |
for _, i := range interfaces { |
| 367 |
if i.Flags&net.FlagUp != 0 && bytes.Compare(i.HardwareAddr, nil) != 0 { |
| 368 |
// Don't use random as we have a real address |
| 369 |
node = Node(i.HardwareAddr) |
| 370 |
log.Println("uuid.findFirstHardwareAddress:", node) |
| 371 |
break |
| 372 |
} |
| 373 |
} |
| 374 |
} |
| 375 |
return |
| 376 |
} |
| 377 |
|
| 378 |
func runHandleError(pErr error) bool { |
| 379 |
log.Panicln("uuid.Generator ran into a serious problem with the random generator", pErr) |
| 380 |
return false |
| 381 |
} |