blob: e7310699f0715c583d4dfbfeaaeb1fd0c2f3a296 [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"
Mateusz Zalega5b60e582021-11-10 19:57:17 +010025 "os"
Mateusz Zalegac6c092b2021-11-09 13:09:37 +010026 "path/filepath"
27 "strings"
28
29 "golang.org/x/text/encoding/unicode"
30)
31
32const (
33 Path = "/sys/firmware/efi/efivars"
34 GlobalGuid = "8be4df61-93ca-11d2-aa0d-00e098032b8c"
35)
36
Mateusz Zalega6cefe512021-11-08 18:19:42 +010037// Encoding defines the Unicode encoding used by UEFI, which is UCS-2 Little
38// Endian. For BMP characters UTF-16 is equivalent to UCS-2. See the UEFI
39// Spec 2.9, Sections 33.2.6 and 1.8.1.
40var Encoding = unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM)
41
Mateusz Zalegac6c092b2021-11-09 13:09:37 +010042// ExtractString returns EFI variable data based on raw variable file contents.
43// It returns string-represented data, or an error.
44func ExtractString(contents []byte) (string, error) {
45 // Fail if total length is shorter than attribute length.
46 if len(contents) < 4 {
47 return "", fmt.Errorf("contents too short.")
48 }
Mateusz Zalegac6c092b2021-11-09 13:09:37 +010049 // Skip attributes, see @linux//Documentation/filesystems:efivarfs.rst for format
50 efiVarData := contents[4:]
Mateusz Zalega6cefe512021-11-08 18:19:42 +010051 espUUIDNullTerminated, err := Encoding.NewDecoder().Bytes(efiVarData)
Mateusz Zalegac6c092b2021-11-09 13:09:37 +010052 if err != nil {
53 // Pass the decoding error unwrapped.
54 return "", err
55 }
56 // Remove the null suffix.
57 return string(bytes.TrimSuffix(espUUIDNullTerminated, []byte{0})), nil
58}
59
60// ReadLoaderDevicePartUUID reads the ESP UUID from an EFI variable. It
61// depends on efivarfs being already mounted. It returns a correct lowercase
62// UUID, or an error.
63func ReadLoaderDevicePartUUID() (string, error) {
64 // Read the EFI variable file containing the ESP UUID.
65 espUuidPath := filepath.Join(Path, "LoaderDevicePartUUID-4a67b082-0a4c-41cf-b6c7-440b29bb8c4f")
Lorenz Brun764a2de2021-11-22 16:26:36 +010066 efiVar, err := os.ReadFile(espUuidPath)
Mateusz Zalegac6c092b2021-11-09 13:09:37 +010067 if err != nil {
68 return "", fmt.Errorf("couldn't read the LoaderDevicePartUUID file at %q: %w", espUuidPath, err)
69 }
70 contents, err := ExtractString(efiVar)
71 if err != nil {
72 return "", fmt.Errorf("couldn't decode an EFI variable: %w", err)
73 }
74 return strings.ToLower(contents), nil
75}
Mateusz Zalega5b60e582021-11-10 19:57:17 +010076
77// CreateBootEntry creates an EFI boot entry variable and returns its
78// non-negative index on success. It may return an io error.
79func CreateBootEntry(be *BootEntry) (int, error) {
80 // Find the index by looking up the first empty slot.
81 var ep string
82 var n int
83 for ; ; n++ {
84 en := fmt.Sprintf("Boot%04x-%s", n, GlobalGuid)
85 ep = filepath.Join(Path, en)
86 _, err := os.Stat(ep)
87 if os.IsNotExist(err) {
88 break
89 }
90 if err != nil {
91 return -1, err
92 }
93 }
94
95 // Create the boot variable.
96 bem, err := be.Marshal()
97 if err != nil {
98 return -1, fmt.Errorf("while marshaling the EFI boot entry: %w", err)
99 }
Lorenz Brun764a2de2021-11-22 16:26:36 +0100100 if err := os.WriteFile(ep, bem, 0644); err != nil {
Mateusz Zalega5b60e582021-11-10 19:57:17 +0100101 return -1, fmt.Errorf("while creating a boot entry variable: %w", err)
102 }
103 return n, nil
104}
105
106// SetBootOrder replaces contents of the boot order variable with the order
107// specified in ord. It may return an io error.
108func SetBootOrder(ord *BootOrder) error {
109 op := filepath.Join(Path, fmt.Sprintf("BootOrder-%s", GlobalGuid))
Lorenz Brun764a2de2021-11-22 16:26:36 +0100110 if err := os.WriteFile(op, ord.Marshal(), 0644); err != nil {
Mateusz Zalega5b60e582021-11-10 19:57:17 +0100111 return fmt.Errorf("while creating a boot order variable: %w", err)
112 }
113 return nil
114}