forked from newrelic/go-agent
/
bootid.go
53 lines (44 loc) · 1.2 KB
/
bootid.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
51
52
53
// Copyright 2020 New Relic Corporation. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package sysinfo
import (
"bytes"
"fmt"
"io/ioutil"
"runtime"
)
// BootID returns the boot ID of the executing kernel.
func BootID() (string, error) {
if "linux" != runtime.GOOS {
return "", ErrFeatureUnsupported
}
data, err := ioutil.ReadFile("/proc/sys/kernel/random/boot_id")
if err != nil {
return "", err
}
return validateBootID(data)
}
type invalidBootID string
func (e invalidBootID) Error() string {
return fmt.Sprintf("Boot id has unrecognized format, id=%q", string(e))
}
func isASCIIByte(b byte) bool {
return (b >= 0x20 && b <= 0x7f)
}
func validateBootID(data []byte) (string, error) {
// We're going to go for the permissive reading of
// https://source.datanerd.us/agents/agent-specs/blob/master/Utilization.md:
// any ASCII (excluding control characters, because I'm pretty sure that's not
// in the spirit of the spec) string will be sent up to and including 128
// bytes in length.
trunc := bytes.TrimSpace(data)
if len(trunc) > 128 {
trunc = trunc[:128]
}
for _, b := range trunc {
if !isASCIIByte(b) {
return "", invalidBootID(data)
}
}
return string(trunc), nil
}