-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhost_linux.go
50 lines (43 loc) · 1.27 KB
/
host_linux.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
//go:build linux
package uuid
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"os"
"strings"
)
const (
// dbusPath is the default path for dbus machine id.
dbusPath = "/var/lib/dbus/machine-id"
// dbusPathEtc is the default path for dbus machine id located in /etc.
// Some systems (like Fedora 20) only know this path.
// Sometimes it's the other way round.
dbusPathEtc = "/etc/machine-id"
)
// hostID returns the uuid specified at `/var/lib/dbus/machine-id` or `/etc/machine-id`.
// If there is an error reading the files an empty string is returned.
// See https://unix.stackexchange.com/questions/144812/generate-consistent-machine-unique-id
func hostID() (string, error) {
id, err := readFile(dbusPath)
if err != nil {
// try fallback path
id, err = readFile(dbusPathEtc)
}
if err != nil {
return "", err
}
return trim(string(id)), nil
}
// protect calculates HMAC-SHA256 of the application ID, keyed by the machine ID and returns a hex-encoded string.
func protect(appID, id string) string {
mac := hmac.New(sha256.New, []byte(id))
mac.Write([]byte(appID))
return hex.EncodeToString(mac.Sum(nil))
}
func readFile(filename string) ([]byte, error) {
return os.ReadFile(filename)
}
func trim(s string) string {
return strings.TrimSpace(strings.Trim(s, "\n"))
}