bootid.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package sysinfo
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io/ioutil"
  6. "runtime"
  7. )
  8. // BootID returns the boot ID of the executing kernel.
  9. func BootID() (string, error) {
  10. if "linux" != runtime.GOOS {
  11. return "", ErrFeatureUnsupported
  12. }
  13. data, err := ioutil.ReadFile("/proc/sys/kernel/random/boot_id")
  14. if err != nil {
  15. return "", err
  16. }
  17. return validateBootID(data)
  18. }
  19. type invalidBootID string
  20. func (e invalidBootID) Error() string {
  21. return fmt.Sprintf("Boot id has unrecognized format, id=%q", string(e))
  22. }
  23. func isASCIIByte(b byte) bool {
  24. return (b >= 0x20 && b <= 0x7f)
  25. }
  26. func validateBootID(data []byte) (string, error) {
  27. // We're going to go for the permissive reading of
  28. // https://source.datanerd.us/agents/agent-specs/blob/master/Utilization.md:
  29. // any ASCII (excluding control characters, because I'm pretty sure that's not
  30. // in the spirit of the spec) string will be sent up to and including 128
  31. // bytes in length.
  32. trunc := bytes.TrimSpace(data)
  33. if len(trunc) > 128 {
  34. trunc = trunc[:128]
  35. }
  36. for _, b := range trunc {
  37. if !isASCIIByte(b) {
  38. return "", invalidBootID(data)
  39. }
  40. }
  41. return string(trunc), nil
  42. }