node.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. ifname = "random"
  45. randomBits(nodeID[:])
  46. return true
  47. }
  48. return false
  49. }
  50. // NodeID returns a slice of a copy of the current Node ID, setting the Node ID
  51. // if not already set.
  52. func NodeID() []byte {
  53. defer nodeMu.Unlock()
  54. nodeMu.Lock()
  55. if nodeID == zeroID {
  56. setNodeInterface("")
  57. }
  58. nid := nodeID
  59. return nid[:]
  60. }
  61. // SetNodeID sets the Node ID to be used for Version 1 UUIDs. The first 6 bytes
  62. // of id are used. If id is less than 6 bytes then false is returned and the
  63. // Node ID is not set.
  64. func SetNodeID(id []byte) bool {
  65. if len(id) < 6 {
  66. return false
  67. }
  68. defer nodeMu.Unlock()
  69. nodeMu.Lock()
  70. copy(nodeID[:], id)
  71. ifname = "user"
  72. return true
  73. }
  74. // NodeID returns the 6 byte node id encoded in uuid. It returns nil if uuid is
  75. // not valid. The NodeID is only well defined for version 1 and 2 UUIDs.
  76. func (uuid UUID) NodeID() []byte {
  77. var node [6]byte
  78. copy(node[:], uuid[10:])
  79. return node[:]
  80. }