blob: fc6100e0726ae81efc3cc0f1ade4a7f6922f1304 [file] [log] [blame]
Mateusz Zalegac6c092b2021-11-09 13:09:37 +01001// Copyright 2020 The Monogon Project Authors.
2//
3// SPDX-License-Identifier: Apache-2.0
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16
17// This package was written with the aim of easing efivarfs integration.
18//
19// https://www.kernel.org/doc/html/latest/filesystems/efivarfs.html
20package efivarfs
21
22import (
23 "bytes"
24 "fmt"
25 "io/ioutil"
Mateusz Zalega5b60e582021-11-10 19:57:17 +010026 "os"
Mateusz Zalegac6c092b2021-11-09 13:09:37 +010027 "path/filepath"
28 "strings"
29
30 "golang.org/x/text/encoding/unicode"
31)
32
33const (
34 Path = "/sys/firmware/efi/efivars"
35 GlobalGuid = "8be4df61-93ca-11d2-aa0d-00e098032b8c"
36)
37
Mateusz Zalega6cefe512021-11-08 18:19:42 +010038// Encoding defines the Unicode encoding used by UEFI, which is UCS-2 Little
39// Endian. For BMP characters UTF-16 is equivalent to UCS-2. See the UEFI
40// Spec 2.9, Sections 33.2.6 and 1.8.1.
41var Encoding = unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM)
42
Mateusz Zalegac6c092b2021-11-09 13:09:37 +010043// ExtractString returns EFI variable data based on raw variable file contents.
44// It returns string-represented data, or an error.
45func ExtractString(contents []byte) (string, error) {
46 // Fail if total length is shorter than attribute length.
47 if len(contents) < 4 {
48 return "", fmt.Errorf("contents too short.")
49 }
Mateusz Zalegac6c092b2021-11-09 13:09:37 +010050 // Skip attributes, see @linux//Documentation/filesystems:efivarfs.rst for format
51 efiVarData := contents[4:]
Mateusz Zalega6cefe512021-11-08 18:19:42 +010052 espUUIDNullTerminated, err := Encoding.NewDecoder().Bytes(efiVarData)
Mateusz Zalegac6c092b2021-11-09 13:09:37 +010053 if err != nil {
54 // Pass the decoding error unwrapped.
55 return "", err
56 }
57 // Remove the null suffix.
58 return string(bytes.TrimSuffix(espUUIDNullTerminated, []byte{0})), nil
59}
60
61// ReadLoaderDevicePartUUID reads the ESP UUID from an EFI variable. It
62// depends on efivarfs being already mounted. It returns a correct lowercase
63// UUID, or an error.
64func ReadLoaderDevicePartUUID() (string, error) {
65 // Read the EFI variable file containing the ESP UUID.
66 espUuidPath := filepath.Join(Path, "LoaderDevicePartUUID-4a67b082-0a4c-41cf-b6c7-440b29bb8c4f")
67 efiVar, err := ioutil.ReadFile(espUuidPath)
68 if err != nil {
69 return "", fmt.Errorf("couldn't read the LoaderDevicePartUUID file at %q: %w", espUuidPath, err)
70 }
71 contents, err := ExtractString(efiVar)
72 if err != nil {
73 return "", fmt.Errorf("couldn't decode an EFI variable: %w", err)
74 }
75 return strings.ToLower(contents), nil
76}
Mateusz Zalega5b60e582021-11-10 19:57:17 +010077
78// CreateBootEntry creates an EFI boot entry variable and returns its
79// non-negative index on success. It may return an io error.
80func CreateBootEntry(be *BootEntry) (int, error) {
81 // Find the index by looking up the first empty slot.
82 var ep string
83 var n int
84 for ; ; n++ {
85 en := fmt.Sprintf("Boot%04x-%s", n, GlobalGuid)
86 ep = filepath.Join(Path, en)
87 _, err := os.Stat(ep)
88 if os.IsNotExist(err) {
89 break
90 }
91 if err != nil {
92 return -1, err
93 }
94 }
95
96 // Create the boot variable.
97 bem, err := be.Marshal()
98 if err != nil {
99 return -1, fmt.Errorf("while marshaling the EFI boot entry: %w", err)
100 }
101 if err := ioutil.WriteFile(ep, bem, 0644); err != nil {
102 return -1, fmt.Errorf("while creating a boot entry variable: %w", err)
103 }
104 return n, nil
105}
106
107// SetBootOrder replaces contents of the boot order variable with the order
108// specified in ord. It may return an io error.
109func SetBootOrder(ord *BootOrder) error {
110 op := filepath.Join(Path, fmt.Sprintf("BootOrder-%s", GlobalGuid))
111 if err := ioutil.WriteFile(op, ord.Marshal(), 0644); err != nil {
112 return fmt.Errorf("while creating a boot order variable: %w", err)
113 }
114 return nil
115}