forked from u-root/u-root
/
grub.go
248 lines (233 loc) · 7.32 KB
/
grub.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
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
// Copyright 2017-2019 the u-root Authors. All rights reserved
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"encoding/hex"
"io/ioutil"
"log"
"os"
"path"
"path/filepath"
"strings"
"unicode"
"golang.org/x/text/transform"
"golang.org/x/text/unicode/norm"
"github.com/u-root/u-root/pkg/bootconfig"
"github.com/u-root/u-root/pkg/storage"
)
// List of directories where to recursively look for grub config files. The root dorectory
// of each mountpoint, these folders inside the mountpoint and all subfolders
// of these folders are searched
var (
GrubSearchDirectories = []string{
"boot",
"EFI",
"efi",
"grub",
"grub2",
}
)
// Limits rekursive search of grub files. It is the maximum directory depth
// that is searched through. Since on efi partitions grub files reside usually
// at /boot/efi/EFI/distro/ , 4 might be a good choice.
const searchDepth = 4
type grubVersion int
var (
grubV1 grubVersion = 1
grubV2 grubVersion = 2
)
func isGrubSearchDir(dirname string) bool {
for _, dir := range GrubSearchDirectories {
if dirname == dir {
return true
}
}
return false
}
// ParseGrubCfg parses the content of a grub.cfg and returns a list of
// BootConfig structures, one for each menuentry, in the same order as they
// appear in grub.cfg. All opened kernel and initrd files are relative to
// basedir.
func ParseGrubCfg(ver grubVersion, devices []storage.BlockDev, grubcfg string, basedir string) []bootconfig.BootConfig {
// This parser sucks. It's not even a parser, it just looks for lines
// starting with menuentry, linux or initrd.
// TODO use a parser, e.g. https://github.com/alecthomas/participle
if ver != grubV1 && ver != grubV2 {
log.Printf("Warning: invalid GRUB version: %d", ver)
return nil
}
kernelBasedir := basedir
bootconfigs := make([]bootconfig.BootConfig, 0)
inMenuEntry := false
var cfg *bootconfig.BootConfig
for _, line := range strings.Split(grubcfg, "\n") {
// remove all leading spaces as they are not relevant for the config
// line
line = strings.TrimLeft(line, " ")
sline := strings.Fields(line)
if len(sline) == 0 {
continue
}
if sline[0] == "menuentry" {
// if a "menuentry", start a new boot config
if cfg != nil {
// save the previous boot config, if any
if cfg.IsValid() {
// only consider valid boot configs, i.e. the ones that have
// both kernel and initramfs
bootconfigs = append(bootconfigs, *cfg)
}
// reset kernelBaseDir
kernelBasedir = basedir
}
inMenuEntry = true
cfg = new(bootconfig.BootConfig)
name := ""
if len(sline) > 1 {
name = strings.Join(sline[1:], " ")
name = unquote(ver, name)
name = strings.Split(name, "--")[0]
}
cfg.Name = name
} else if inMenuEntry {
// check if location of kernel is at an other partition
// see https://www.gnu.org/software/grub/manual/grub/html_node/search.html
if sline[0] == "search" {
for _, str1 := range sline {
if str1 == "--set=root" {
log.Printf("Kernel seems to be on an other partitioin then the grub.cfg file")
for _, str2 := range sline {
if isValidFsUUID(str2) {
kernelFsUUID := str2
log.Printf("fs-uuid: %s", kernelFsUUID)
partitions := storage.PartitionsByFsUUID(devices, kernelFsUUID)
if len(partitions) == 0 {
log.Printf("WARNING: No partition found with filesystem UUID:'%s' to load kernel from!", kernelFsUUID) // TODO throw error ?
continue
}
if len(partitions) > 1 {
log.Printf("WARNING: more than one partition found with the given filesystem UUID. Using the first one")
}
dev := partitions[0]
kernelBasedir = path.Dir(kernelBasedir)
kernelBasedir = path.Join(kernelBasedir, dev.Name)
log.Printf("Kernel is on: %s", dev.Name)
}
}
}
}
}
// otherwise look for kernel and initramfs configuration
if len(sline) < 2 {
// surely not a valid linux or initrd directive, skip it
continue
}
if sline[0] == "linux" || sline[0] == "linux16" || sline[0] == "linuxefi" {
kernel := sline[1]
cmdline := strings.Join(sline[2:], " ")
cmdline = unquote(ver, cmdline)
cfg.Kernel = path.Join(kernelBasedir, kernel)
cfg.KernelArgs = cmdline
} else if sline[0] == "initrd" || sline[0] == "initrd16" || sline[0] == "initrdefi" {
initrd := sline[1]
cfg.Initramfs = path.Join(kernelBasedir, initrd)
} else if sline[0] == "multiboot" || sline[0] == "multiboot2" {
multiboot := sline[1]
cmdline := strings.Join(sline[2:], " ")
cmdline = unquote(ver, cmdline)
cfg.Multiboot = path.Join(kernelBasedir, multiboot)
cfg.MultibootArgs = cmdline
} else if sline[0] == "module" || sline[0] == "module2" {
module := sline[1]
cmdline := strings.Join(sline[2:], " ")
cmdline = unquote(ver, cmdline)
module = path.Join(kernelBasedir, module)
if cmdline != "" {
module = module + " " + cmdline
}
cfg.Modules = append(cfg.Modules, module)
}
}
}
// append last kernel config if it wasn't already
if inMenuEntry && cfg.IsValid() {
bootconfigs = append(bootconfigs, *cfg)
}
return bootconfigs
}
func isValidFsUUID(uuid string) bool {
for _, h := range strings.Split(uuid, "-") {
if _, err := hex.DecodeString(h); err != nil {
return false
}
}
return true
}
func unquote(ver grubVersion, text string) string {
if ver == grubV2 {
// if grub2, unquote the string, as directives could be quoted
// https://www.gnu.org/software/grub/manual/grub/grub.html#Quoting
// TODO unquote everything, not just \$
return strings.Replace(text, `\$`, "$", -1)
}
// otherwise return the unmodified string
return text
}
func isMn(r rune) bool {
return unicode.Is(unicode.Mn, r) // Mn: nonspacing marks
}
// ScanGrubConfigs looks for grub2 and grub legacy config files in the known
// locations and returns a list of boot configurations.
func ScanGrubConfigs(devices []storage.BlockDev, basedir string) []bootconfig.BootConfig {
bootconfigs := make([]bootconfig.BootConfig, 0)
err := filepath.Walk(basedir, func(currentPath string, info os.FileInfo, err error) error {
if err != nil {
return err
}
t := transform.Chain(norm.NFD, transform.RemoveFunc(isMn), norm.NFC)
currentPath, _, _ = transform.String(t, currentPath)
if info.IsDir() {
if path.Dir(currentPath) == basedir && !isGrubSearchDir(path.Base(currentPath)) {
debug("Skip %s: not significant", currentPath)
// skip irrelevant toplevel directories
return filepath.SkipDir
}
p, err := filepath.Rel(basedir, currentPath)
if err != nil {
return err
}
depth := len(strings.Split(p, string(os.PathSeparator)))
if depth > searchDepth {
debug("Skip %s, depth limit", currentPath)
// skip
return filepath.SkipDir
}
debug("Step into %s", currentPath)
// continue
return nil
}
cfgname := info.Name()
var ver grubVersion
switch cfgname {
case "grub.cfg":
ver = grubV1
case "grub2.cfg":
ver = grubV2
default:
return nil
}
log.Printf("Parsing %s", currentPath)
data, err := ioutil.ReadFile(currentPath)
if err != nil {
return err
}
cfgs := ParseGrubCfg(ver, devices, string(data), basedir)
bootconfigs = append(bootconfigs, cfgs...)
return nil
})
if err != nil {
log.Printf("filepath.Walk error: %v", err)
}
return bootconfigs
}