node.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // Copyright 2016 Google Inc. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package uuid
  5. import (
  6. "sync"
  7. )
  8. var (
  9. nodeMu sync.Mutex
  10. ifname string // name of interface being used
  11. nodeID [6]byte // hardware for version 1 UUIDs
  12. zeroID [6]byte // nodeID with only 0's
  13. )
  14. // NodeInterface returns the name of the interface from which the NodeID was
  15. // derived. The interface "user" is returned if the NodeID was set by
  16. // SetNodeID.
  17. func NodeInterface() string {
  18. defer nodeMu.Unlock()
  19. nodeMu.Lock()
  20. return ifname
  21. }
  22. // SetNodeInterface selects the hardware address to be used for Version 1 UUIDs.
  23. // If name is "" then the first usable interface found will be used or a random
  24. // Node ID will be generated. If a named interface cannot be found then false
  25. // is returned.
  26. //
  27. // SetNodeInterface never fails when name is "".
  28. func SetNodeInterface(name string) bool {
  29. defer nodeMu.Unlock()
  30. nodeMu.Lock()
  31. return setNodeInterface(name)
  32. }
  33. func setNodeInterface(name string) bool {
  34. iname, addr := getHardwareInterface(name) // null implementation for js
  35. if iname != "" && addr != nil {
  36. ifname = iname
  37. copy(nodeID[:], addr)
  38. return true
  39. }
  40. // We found no interfaces with a valid hardware address. If name
  41. // does not specify a specific interface generate a random Node ID
  42. // (section 4.1.6)
  43. if name == "" {
  44. randomBits(nodeID[:])
  45. return true
  46. }
  47. return false
  48. }
  49. // NodeID returns a slice of a copy of the current Node ID, setting the Node ID
  50. // if not already set.
  51. func NodeID() []byte {
  52. defer nodeMu.Unlock()
  53. nodeMu.Lock()
  54. if nodeID == zeroID {
  55. setNodeInterface("")
  56. }
  57. nid := nodeID
  58. return nid[:]
  59. }
  60. // SetNodeID sets the Node ID to be used for Version 1 UUIDs. The first 6 bytes
  61. // of id are used. If id is less than 6 bytes then false is returned and the
  62. // Node ID is not set.
  63. func SetNodeID(id []byte) bool {
  64. if len(id) < 6 {
  65. return false
  66. }
  67. defer nodeMu.Unlock()
  68. nodeMu.Lock()
  69. copy(nodeID[:], id)
  70. ifname = "user"
  71. return true
  72. }
  73. // NodeID returns the 6 byte node id encoded in uuid. It returns nil if uuid is
  74. // not valid. The NodeID is only well defined for version 1 and 2 UUIDs.
  75. func (uuid UUID) NodeID() []byte {
  76. var node [6]byte
  77. copy(node[:], uuid[10:])
  78. return node[:]
  79. }