File: guid.go

package info (click to toggle)
golang-github-canonical-go-efilib 1.6.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 6,836 kB
  • sloc: makefile: 3
file content (101 lines) | stat: -rw-r--r-- 2,370 bytes parent folder | download
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
// Copyright 2020 Canonical Ltd.
// Licensed under the LGPLv3 with static-linking exception.
// See LICENCE file for details.

package efi

import (
	"encoding/binary"
	"encoding/hex"
	"errors"
	"fmt"
	"io"
	"regexp"

	"github.com/canonical/go-efilib/internal/uefi"
)

// GUID corresponds to the EFI_GUID type.
type GUID [16]byte

func (guid GUID) A() uint32 {
	return binary.LittleEndian.Uint32(guid[0:4])
}

func (guid GUID) B() uint16 {
	return binary.LittleEndian.Uint16(guid[4:6])
}

func (guid GUID) C() uint16 {
	return binary.LittleEndian.Uint16(guid[6:8])
}

func (guid GUID) D() uint16 {
	return binary.BigEndian.Uint16(guid[8:10])
}

func (guid GUID) E() [6]uint8 {
	var out [6]uint8
	copy(out[:], guid[10:16])
	return out
}

// String implements [fmt.Stringer].
func (guid GUID) String() string {
	return fmt.Sprintf("%08x-%04x-%04x-%04x-%012x", guid.A(), guid.B(), guid.C(), guid.D(), guid.E())
}

// MakeGUID makes a new GUID from the supplied arguments.
func MakeGUID(a uint32, b, c, d uint16, e [6]uint8) GUID {
	return GUID(uefi.New_EFI_GUID(a, b, c, d, e))
}

// ReadGUID reads a EFI_GUID from the supplied io.Reader.
func ReadGUID(r io.Reader) (out GUID, err error) {
	_, err = io.ReadFull(r, out[:])
	return
}

var guidRe = regexp.MustCompile(`\{?([[:xdigit:]]{8})-([[:xdigit:]]{4})-([[:xdigit:]]{4})-([[:xdigit:]]{4})-([[:xdigit:]]{12})\}?`)

func decodeStringUint32(s string) (uint32, error) {
	h, err := hex.DecodeString(s)
	if err != nil {
		return 0, err
	}
	if len(h) > 4 {
		return 0, errors.New("invalid length")
	}
	return binary.BigEndian.Uint32(h), nil
}

func decodeStringUint16(s string) (uint16, error) {
	h, err := hex.DecodeString(s)
	if err != nil {
		return 0, err
	}
	if len(h) > 2 {
		return 0, errors.New("invalid length")
	}
	return binary.BigEndian.Uint16(h), nil
}

// DecodeGUIDString decodes the supplied GUID string. The string must have
// the format "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" and may be surrounded
// by curly braces.
func DecodeGUIDString(s string) (GUID, error) {
	m := guidRe.FindStringSubmatch(s)
	if m == nil {
		return GUID{}, errors.New("invalid format")
	}

	a, _ := decodeStringUint32(m[1])
	b, _ := decodeStringUint16(m[2])
	c, _ := decodeStringUint16(m[3])
	d, _ := decodeStringUint16(m[4])
	e, _ := hex.DecodeString(m[5])

	var e2 [6]uint8
	copy(e2[:], e)
	return MakeGUID(a, b, c, d, e2), nil
}