podman
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
5package uuid6
7import (8"sync"9)
10
11var (12nodeMu sync.Mutex13ifname string // name of interface being used14nodeID [6]byte // hardware for version 1 UUIDs15zeroID [6]byte // nodeID with only 0's16)
17
18// NodeInterface returns the name of the interface from which the NodeID was
19// derived. The interface "user" is returned if the NodeID was set by
20// SetNodeID.
21func NodeInterface() string {22defer nodeMu.Unlock()23nodeMu.Lock()24return ifname25}
26
27// SetNodeInterface selects the hardware address to be used for Version 1 UUIDs.
28// If name is "" then the first usable interface found will be used or a random
29// Node ID will be generated. If a named interface cannot be found then false
30// is returned.
31//
32// SetNodeInterface never fails when name is "".
33func SetNodeInterface(name string) bool {34defer nodeMu.Unlock()35nodeMu.Lock()36return setNodeInterface(name)37}
38
39func setNodeInterface(name string) bool {40iname, addr := getHardwareInterface(name) // null implementation for js41if iname != "" && addr != nil {42ifname = iname43copy(nodeID[:], addr)44return true45}46
47// We found no interfaces with a valid hardware address. If name48// does not specify a specific interface generate a random Node ID49// (section 4.1.6)50if name == "" {51ifname = "random"52randomBits(nodeID[:])53return true54}55return false56}
57
58// NodeID returns a slice of a copy of the current Node ID, setting the Node ID
59// if not already set.
60func NodeID() []byte {61defer nodeMu.Unlock()62nodeMu.Lock()63if nodeID == zeroID {64setNodeInterface("")65}66nid := nodeID67return nid[:]68}
69
70// SetNodeID sets the Node ID to be used for Version 1 UUIDs. The first 6 bytes
71// of id are used. If id is less than 6 bytes then false is returned and the
72// Node ID is not set.
73func SetNodeID(id []byte) bool {74if len(id) < 6 {75return false76}77defer nodeMu.Unlock()78nodeMu.Lock()79copy(nodeID[:], id)80ifname = "user"81return true82}
83
84// NodeID returns the 6 byte node id encoded in uuid. It returns nil if uuid is
85// not valid. The NodeID is only well defined for version 1 and 2 UUIDs.
86func (uuid UUID) NodeID() []byte {87var node [6]byte88copy(node[:], uuid[10:])89return node[:]90}
91