1 /*-
2  * Copyright (c) 2017-2018 Netflix, Inc.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer
9  *    in this position and unchanged.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
15  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
18  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  *
25  * $FreeBSD: head/usr.sbin/efibootmgr/efibootmgr.c 364818 2020-08-26 14:02:38Z tsoome $
26  */
27 
28 #include <sys/stat.h>
29 #include <sys/param.h>
30 #include <sys/queue.h>
31 #include <assert.h>
32 #include <ctype.h>
33 #include <err.h>
34 #include <errno.h>
35 #include <fcntl.h>
36 #include <paths.h>
37 #include <signal.h>
38 #include <stdint.h>
39 #include <stdio.h>
40 #include <stdlib.h>
41 #include <getopt.h>
42 #include <limits.h>
43 #include <inttypes.h>
44 #include <stdbool.h>
45 #include <string.h>
46 #include <strings.h>
47 #include <unistd.h>
48 
49 #include <efivar.h>
50 #include <efiutil.h>
51 #include <efivar-dp.h>
52 
53 #include "libefivar_int.h"
54 
55 #ifndef LOAD_OPTION_ACTIVE
56 #define LOAD_OPTION_ACTIVE 0x00000001
57 #endif
58 
59 #ifndef LOAD_OPTION_CATEGORY_BOOT
60 #define LOAD_OPTION_CATEGORY_BOOT 0x00000000
61 #endif
62 
63 #define BAD_LENGTH	((size_t)-1)
64 
65 #define EFI_OS_INDICATIONS_BOOT_TO_FW_UI 0x0000000000000001
66 
67 typedef struct _bmgr_opts {
68 	char	*env;
69 	char	*loader;
70 	char	*label;
71 	char	*kernel;
72 	char	*name;
73 	char	*order;
74 	int     bootnum;
75 	bool	copy;
76 	bool    create;
77 	bool    delete;
78 	bool    delete_bootnext;
79 	bool    del_timeout;
80 	bool    dry_run;
81 	bool	device_path;
82 	bool	esp_device;
83 	bool    fw_ui;
84 	bool    no_fw_ui;
85 	bool	has_bootnum;
86 	bool    once;
87 	int	cp_src;
88 	bool    set_active;
89 	bool    set_bootnext;
90 	bool    set_inactive;
91 	bool    set_timeout;
92 	int     timeout;
93 	bool	unix_path;
94 	bool    verbose;
95 } bmgr_opts_t;
96 
97 static struct option lopts[] = {
98 	{"activate", no_argument, NULL, 'a'},
99 	{"bootnext", no_argument, NULL, 'n'}, /* set bootnext */
100 	{"bootnum", required_argument, NULL, 'b'},
101 	{"bootorder", required_argument, NULL, 'o'}, /* set order */
102 	{"copy", required_argument, NULL, 'C'},		/* Copy boot method */
103 	{"create", no_argument, NULL, 'c'},
104 	{"deactivate", no_argument, NULL, 'A'},
105 	{"del-timeout", no_argument, NULL, 'T'},
106 	{"delete", no_argument, NULL, 'B'},
107 	{"delete-bootnext", no_argument, NULL, 'N'},
108 	{"device-path", no_argument, NULL, 'd'},
109 	{"dry-run", no_argument, NULL, 'D'},
110 	{"env", required_argument, NULL, 'e'},
111 	{"esp", no_argument, NULL, 'E'},
112 	{"fw-ui", no_argument, NULL, 'f'},
113 	{"no-fw-ui", no_argument, NULL, 'F'},
114 	{"help", no_argument, NULL, 'h'},
115 	{"kernel", required_argument, NULL, 'k'},
116 	{"label", required_argument, NULL, 'L'},
117 	{"loader", required_argument, NULL, 'l'},
118 	{"once", no_argument, NULL, 'O'},
119 	{"set-timeout", required_argument, NULL, 't'},
120 	{"unix-path", no_argument, NULL, 'p'},
121 	{"verbose", no_argument, NULL, 'v'},
122 	{ NULL, 0, NULL, 0}
123 };
124 
125 /* global efibootmgr opts */
126 static bmgr_opts_t opts;
127 
128 static LIST_HEAD(efivars_head, entry) efivars =
129 	LIST_HEAD_INITIALIZER(efivars);
130 
131 struct entry {
132 	efi_guid_t	guid;
133 	uint32_t	attrs;
134 	uint8_t		*data;
135 	size_t		size;
136 	char		*name;
137 	char		*label;
138 	int		idx;
139 	int		flags;
140 #define SEEN	1
141 
142 	LIST_ENTRY(entry) entries;
143 };
144 
145 #define MAX_DP_LEN	4096
146 #define MAX_LOADOPT_LEN	8192
147 
148 
149 static char *
150 mangle_loader(char *loader)
151 {
152 	char *c;
153 
154 	for (c = loader; *c; c++)
155 		if (*c == '/')
156 			*c = '\\';
157 
158 	return loader;
159 }
160 
161 
162 #define COMMON_ATTRS EFI_VARIABLE_NON_VOLATILE | \
163 	EFI_VARIABLE_BOOTSERVICE_ACCESS | \
164 	EFI_VARIABLE_RUNTIME_ACCESS
165 
166 /*
167  * We use global guid, and common var attrs and
168  * find it better to just delete and re-create a var.
169  */
170 static int
171 set_bootvar(const char *name, uint8_t *data, size_t size)
172 {
173 
174 	return efi_set_variable(EFI_GLOBAL_GUID, name, data, size,
175 	    COMMON_ATTRS);
176 }
177 
178 
179 #define USAGE \
180 	"   [-aAnB -b bootnum] [-N] [-t timeout] [-T] [-o bootorder] [-O] [--verbose] [--help]\n\
181   [-c -l loader [-k kernel] [-L label] [--dry-run] [-b bootnum]]"
182 
183 #define CREATE_USAGE \
184 	"       efibootmgr -c -l loader [-k kernel] [-L label] [--dry-run] [-b bootnum] [-a]"
185 #define ORDER_USAGE \
186 	"       efibootmgr -o bootvarnum1,bootvarnum2,..."
187 #define TIMEOUT_USAGE \
188 	"       efibootmgr -t seconds"
189 #define DELETE_USAGE \
190 	"       efibootmgr -B -b bootnum"
191 #define ACTIVE_USAGE \
192 	"       efibootmgr [-a | -A] -b bootnum"
193 #define BOOTNEXT_USAGE \
194 	"       efibootmgr [-n | -N] -b bootnum"
195 
196 static void
197 parse_args(int argc, char *argv[])
198 {
199 	int ch;
200 
201 	while ((ch = getopt_long(argc, argv, "AaBb:C:cdDe:EFfhk:L:l:NnOo:pTt:v",
202 		    lopts, NULL)) != -1) {
203 		switch (ch) {
204 		case 'A':
205 			opts.set_inactive = true;
206 			break;
207 		case 'a':
208 			opts.set_active = true;
209 			break;
210 		case 'b':
211 			opts.has_bootnum = true;
212 			opts.bootnum = strtoul(optarg, NULL, 16);
213 			break;
214 		case 'B':
215 			opts.delete = true;
216 			break;
217 		case 'C':
218 			opts.copy = true;
219 			opts.cp_src = strtoul(optarg, NULL, 16);
220 			/* FALLTHROUGH */
221 		case 'c':
222 			opts.create = true;
223 			break;
224 		case 'D': /* should be remove dups XXX */
225 			opts.dry_run = true;
226 			break;
227 		case 'd':
228 			opts.device_path = true;
229 			break;
230 		case 'e':
231 			free(opts.env);
232 			opts.env = strdup(optarg);
233 			break;
234 		case 'E':
235 			opts.esp_device = true;
236 			break;
237 		case 'F':
238 			opts.no_fw_ui = true;
239 			break;
240 		case 'f':
241 			opts.fw_ui = true;
242 			break;
243 		case 'h':
244 		default:
245 			errx(1, "%s", USAGE);
246 			break;
247 		case 'k':
248 			free(opts.kernel);
249 			opts.kernel = strdup(optarg);
250 			break;
251 		case 'L':
252 			free(opts.label);
253 			opts.label = strdup(optarg);
254 			break;
255 		case 'l':
256 			free(opts.loader);
257 			opts.loader = strdup(optarg);
258 			opts.loader = mangle_loader(opts.loader);
259 			break;
260 		case 'N':
261 			opts.delete_bootnext = true;
262 			break;
263 		case 'n':
264 			opts.set_bootnext = true;
265 			break;
266 		case 'O':
267 			opts.once = true;
268 			break;
269 		case 'o':
270 			free(opts.order);
271 			opts.order = strdup(optarg);
272 			break;
273 		case 'p':
274 			opts.unix_path = true;
275 			break;
276 		case 'T':
277 			opts.del_timeout = true;
278 			break;
279 		case 't':
280 			opts.set_timeout = true;
281 			opts.timeout = strtoul(optarg, NULL, 10);
282 			break;
283 		case 'v':
284 			opts.verbose = true;
285 			break;
286 		}
287 	}
288 	if (opts.create) {
289 		if (!opts.loader)
290 			errx(1, "%s",CREATE_USAGE);
291 		return;
292 	}
293 
294 	if (opts.order != NULL && *opts.order == '\0')
295 		errx(1, "%s", ORDER_USAGE);
296 
297 	if ((opts.set_inactive || opts.set_active) && !opts.has_bootnum)
298 		errx(1, "%s", ACTIVE_USAGE);
299 
300 	if (opts.delete && !opts.has_bootnum)
301 		errx(1, "%s", DELETE_USAGE);
302 
303 	if (opts.set_bootnext && !opts.has_bootnum)
304 		errx(1, "%s", BOOTNEXT_USAGE);
305 }
306 
307 
308 static void
309 read_vars(void)
310 {
311 
312 	efi_guid_t *guid;
313 	char *next_name = NULL;
314 	int ret = 0;
315 
316 	struct entry *nent;
317 
318 	LIST_INIT(&efivars);
319 	while ((ret = efi_get_next_variable_name(&guid, &next_name)) > 0) {
320 		/*
321 		 * Only pay attention to EFI:BootXXXX variables to get the list.
322 		 */
323 		if (efi_guid_cmp(guid, &EFI_GLOBAL_GUID) != 0 ||
324 		    strlen(next_name) != 8 ||
325 		    strncmp(next_name, "Boot", 4) != 0 ||
326 		    !isxdigit(next_name[4]) ||
327 		    !isxdigit(next_name[5]) ||
328 		    !isxdigit(next_name[6]) ||
329 		    !isxdigit(next_name[7]))
330 			continue;
331 		nent = malloc(sizeof(struct entry));
332 		nent->name = strdup(next_name);
333 
334 		ret = efi_get_variable(*guid, next_name, &nent->data,
335 		    &nent->size, &nent->attrs);
336 		if (ret < 0)
337 			err(1, "efi_get_variable");
338 		nent->guid = *guid;
339 		nent->idx = strtoul(&next_name[4], NULL, 16);
340 		LIST_INSERT_HEAD(&efivars, nent, entries);
341 	}
342 }
343 
344 
345 static void
346 set_boot_order(char *order)
347 {
348 	uint16_t *new_data;
349 	size_t size;
350 	char *next, *cp;
351 	int cnt;
352 	int i;
353 
354 	cp = order;
355 	cnt = 1;
356 	while (*cp) {
357 		if (*cp++ == ',')
358 			cnt++;
359 	}
360 	size = sizeof(uint16_t) * cnt;
361 	new_data = malloc(size);
362 
363 	i = 0;
364 	cp = strdup(order);
365 	while ((next = strsep(&cp, ",")) != NULL) {
366 		new_data[i] = strtoul(next, NULL, 16);
367 		if (new_data[i] == 0 && errno == EINVAL) {
368 			warnx("can't parse %s as a numb", next);
369 			errx(1, "%s", ORDER_USAGE);
370 		}
371 		i++;
372 	}
373 	free(cp);
374 	if (set_bootvar("BootOrder", (uint8_t*)new_data, size) < 0)
375 		err(1, "Unabke to set BootOrder to %s", order);
376 	free(new_data);
377 }
378 
379 static void
380 handle_activity(int bootnum, bool active)
381 {
382 	uint32_t attrs, load_attrs;
383 	uint8_t *data;
384 	size_t size;
385 	char *name;
386 
387 	asprintf(&name, "%s%04X", "Boot", bootnum);
388 	if (name == NULL)
389 		err(1, "asprintf");
390 	if (efi_get_variable(EFI_GLOBAL_GUID, name, &data, &size, &attrs) < 0)
391 		err(1, "No such bootvar %s\n", name);
392 
393 	load_attrs = le32dec(data);
394 
395 	if (active)
396 		load_attrs |= LOAD_OPTION_ACTIVE;
397 	else
398 		load_attrs &= ~LOAD_OPTION_ACTIVE;
399 
400 	le32enc(data, load_attrs);
401 
402 	if (set_bootvar(name, data, size) < 0)
403 		err(1, "handle activity efi_set_variable");
404 }
405 
406 
407 /*
408  * add boot var to boot order.
409  * called by create boot var. There is no option
410  * to add one independent of create.
411  *
412  * Note: we currently don't support where it goes
413  * so it goes on the front, inactive.
414  * use -o 2,3,7 etc to affect order, -a to activate.
415  */
416 static void
417 add_to_boot_order(char *bootvar)
418 {
419 	size_t size;
420 	uint32_t attrs;
421 	uint16_t val;
422 	uint8_t *data, *new;
423 
424 	val = strtoul(&bootvar[4], NULL, 16);
425 
426 	if (efi_get_variable(EFI_GLOBAL_GUID, "BootOrder", &data, &size, &attrs) < 0) {
427 		if (errno == ENOENT) { /* create it and set this bootvar to active */
428 			size = 0;
429 			data = NULL;
430 		} else
431 			err(1, "efi_get_variable BootOrder");
432 	}
433 
434 	/*
435 	 * We have BootOrder with the current order
436 	 * so grow the array by one, add the value
437 	 * and write the new variable value.
438 	 */
439 	size += sizeof(uint16_t);
440 	new = malloc(size);
441 	if (!new)
442 		err(1, "malloc");
443 
444 	le16enc(new, val);
445 	if (size > sizeof(uint16_t))
446 		memcpy(new + sizeof(uint16_t), data, size - sizeof(uint16_t));
447 
448 	if (set_bootvar("BootOrder", new, size) < 0)
449 		err(1, "set_bootvar");
450 	free(new);
451 }
452 
453 
454 static void
455 remove_from_order(uint16_t bootnum)
456 {
457 	uint32_t attrs;
458 	size_t size, i, j;
459 	uint8_t *new, *data;
460 
461 	if (efi_get_variable(EFI_GLOBAL_GUID, "BootOrder", &data, &size, &attrs) < 0)
462 		return;
463 
464 	new = malloc(size);
465 	if (new == NULL)
466 		err(1, "malloc");
467 
468 	for (j = i = 0; i < size; i += sizeof(uint16_t)) {
469 		if (le16dec(data + i) == bootnum)
470 			continue;
471 		memcpy(new + j, data + i, sizeof(uint16_t));
472 		j += sizeof(uint16_t);
473 	}
474 	if (i == j)
475 		warnx("Boot variable %04x not in BootOrder", bootnum);
476 	else if (set_bootvar("BootOrder", new, j) < 0)
477 		err(1, "Unable to update BootOrder with new value");
478 	free(new);
479 }
480 
481 
482 static void
483 delete_bootvar(int bootnum)
484 {
485 	char *name;
486 	int defer = 0;
487 
488 	/*
489 	 * Try to delete the boot variable and remocve it
490 	 * from the boot order. We always do both actions
491 	 * to make it easy to clean up from oopses.
492 	 */
493 	if (bootnum < 0 || bootnum > 0xffff)
494 		errx(1, "Bad boot variable %#x", bootnum);
495 	asprintf(&name, "%s%04X", "Boot", bootnum);
496 	if (name == NULL)
497 		err(1, "asprintf");
498 	printf("Removing boot variable '%s'\n", name);
499 	if (efi_del_variable(EFI_GLOBAL_GUID, name) < 0) {
500 		defer = 1;
501 		warn("cannot delete variable %s", name);
502 	}
503 	printf("Removing 0x%x from BootOrder\n", bootnum);
504 	remove_from_order(bootnum);
505 	free(name);
506 	if (defer)
507 		exit(defer);
508 }
509 
510 
511 static void
512 del_bootnext(void)
513 {
514 
515 	if (efi_del_variable(EFI_GLOBAL_GUID, "BootNext") < 0)
516 		err(1, "efi_del_variable");
517 }
518 
519 static void
520 handle_bootnext(uint16_t bootnum)
521 {
522 	uint16_t num;
523 
524 	le16enc(&num, bootnum);
525 	if (set_bootvar("BootNext", (uint8_t*)&bootnum, sizeof(uint16_t)) < 0)
526 		err(1, "set_bootvar");
527 }
528 
529 
530 static int
531 compare(const void *a, const void *b)
532 {
533 	uint16_t c;
534 	uint16_t d;
535 
536 	memcpy(&c, a, sizeof(uint16_t));
537 	memcpy(&d, b, sizeof(uint16_t));
538 
539 	if (c < d)
540 		return -1;
541 	if (c == d)
542 		return  0;
543 	return  1;
544 }
545 
546 static char *
547 make_next_boot_var_name(void)
548 {
549 	struct entry *v;
550 	uint16_t *vals, next_free = 0;
551 	char *name;
552 	int cnt = 0;
553 	int i;
554 
555 	LIST_FOREACH(v, &efivars, entries) {
556 		cnt++;
557 	}
558 
559 	vals = malloc(sizeof(uint16_t) * cnt);
560 	if (!vals)
561 		return NULL;
562 
563 	i = 0;
564 	LIST_FOREACH(v, &efivars, entries) {
565 		vals[i++] = v->idx;
566 	}
567 	qsort(vals, cnt, sizeof(uint16_t), compare);
568 	/* if the hole is at the beginning, just return zero */
569 	if (vals[0] > 0) {
570 		next_free = 0;
571 	} else {
572 		/* now just run the list looking for the first hole */
573 		for (i = 0; i < cnt - 1 && next_free == 0; i++)
574 			if (vals[i] + 1 != vals[i + 1])
575 				next_free = vals[i] + 1;
576 		if (next_free == 0)
577 			next_free = vals[cnt - 1] + 1;
578 		/* In theory we could have used all 65k slots -- what to do? */
579 	}
580 	free(vals);
581 
582 	asprintf(&name, "%s%04X", "Boot", next_free);
583 	if (name == NULL)
584 		err(1, "asprintf");
585 	return name;
586 }
587 
588 static char *
589 make_boot_var_name(uint16_t bootnum)
590 {
591 	struct entry *v;
592 	char *name;
593 
594 	LIST_FOREACH(v, &efivars, entries) {
595 		if (v->idx == bootnum)
596 			return NULL;
597 	}
598 
599 	asprintf(&name, "%s%04X", "Boot", bootnum);
600 	if (name == NULL)
601 		err(1, "asprintf");
602 	return name;
603 }
604 
605 static size_t
606 create_loadopt(uint8_t *buf, size_t bufmax, uint32_t attributes, efidp dp, size_t dp_size,
607     const char *description, const uint8_t *optional_data, size_t optional_data_size)
608 {
609 	efi_char *bbuf = NULL;
610 	uint8_t *pos = buf;
611 	size_t desc_len = 0;
612 	size_t len;
613 
614 	if (optional_data == NULL && optional_data_size != 0)
615 		return BAD_LENGTH;
616 	if (dp == NULL && dp_size != 0)
617 		return BAD_LENGTH;
618 
619 	/*
620 	 * Compute the length to make sure the passed in buffer is long enough.
621 	 */
622 	utf8_to_ucs2(description, &bbuf, &desc_len);
623 	len = sizeof(uint32_t) + sizeof(uint16_t) + desc_len + dp_size + optional_data_size;
624 	if (len > bufmax) {
625 		free(bbuf);
626 		return BAD_LENGTH;
627 	}
628 
629 	le32enc(pos, attributes);
630 	pos += sizeof (attributes);
631 
632 	le16enc(pos, dp_size);
633 	pos += sizeof (uint16_t);
634 
635 	memcpy(pos, bbuf, desc_len);	/* NB:desc_len includes strailing NUL */
636 	pos += desc_len;
637 	free(bbuf);
638 
639 	memcpy(pos, dp, dp_size);
640 	pos += dp_size;
641 
642 	if (optional_data && optional_data_size > 0) {
643 		memcpy(pos, optional_data, optional_data_size);
644 		pos += optional_data_size;
645 	}
646 
647 	return pos - buf;
648 }
649 
650 
651 static int
652 make_boot_var(const char *label, const char *loader, const char *kernel, const char *env, bool dry_run,
653     int bootnum, bool activate)
654 {
655 	struct entry *new_ent;
656 	uint32_t load_attrs = 0;
657 	uint8_t *load_opt_buf;
658 	size_t lopt_size, llen, klen;
659 	efidp dp, loaderdp, kerneldp;
660 	char *bootvar = NULL;
661 	int ret;
662 
663 	assert(label != NULL);
664 
665 	if (bootnum == -1)
666 		bootvar = make_next_boot_var_name();
667 	else
668 		bootvar = make_boot_var_name((uint16_t)bootnum);
669 	if (bootvar == NULL)
670 		err(1, "bootvar creation");
671 	if (loader == NULL)
672 		errx(1, "Must specify boot loader");
673 	if (efivar_unix_path_to_device_path(loader, &loaderdp) != 0)
674 		err(1, "Cannot translate unix loader path '%s' to UEFI", loader);
675 	if (kernel != NULL) {
676 		if (efivar_unix_path_to_device_path(kernel, &kerneldp) != 0)
677 			err(1, "Cannot translate unix kernel path '%s' to UEFI", kernel);
678 	} else {
679 		kerneldp = NULL;
680 	}
681 	llen = efidp_size(loaderdp);
682 	if (llen > MAX_DP_LEN)
683 		errx(1, "Loader path too long.");
684 	klen = efidp_size(kerneldp);
685 	if (klen > MAX_DP_LEN)
686 		errx(1, "Kernel path too long.");
687 	dp = malloc(llen + klen);
688 	if (dp == NULL)
689 		errx(1, "Can't allocate memory for new device paths");
690 	memcpy(dp, loaderdp, llen);
691 	if (kerneldp != NULL)
692 		memcpy((char *)dp + llen, kerneldp, klen);
693 
694 	/* don't make the new bootvar active by default, use the -a option later */
695 	load_attrs = LOAD_OPTION_CATEGORY_BOOT;
696 	if (activate)
697 		load_attrs |= LOAD_OPTION_ACTIVE;
698 	load_opt_buf = malloc(MAX_LOADOPT_LEN);
699 	if (load_opt_buf == NULL)
700 		err(1, "malloc");
701 
702 	lopt_size = create_loadopt(load_opt_buf, MAX_LOADOPT_LEN, load_attrs,
703 	    dp, llen + klen, label, env, env ? strlen(env) + 1 : 0);
704 	if (lopt_size == BAD_LENGTH)
705 		errx(1, "Can't create loadopt");
706 
707 	ret = 0;
708 	if (!dry_run) {
709 		ret = efi_set_variable(EFI_GLOBAL_GUID, bootvar,
710 		    (uint8_t*)load_opt_buf, lopt_size, COMMON_ATTRS);
711 	}
712 
713 	if (ret)
714 		err(1, "efi_set_variable");
715 
716 	if (!dry_run)
717 		add_to_boot_order(bootvar); /* first, still not active */
718 	new_ent = malloc(sizeof(struct entry));
719 	if (new_ent == NULL)
720 		err(1, "malloc");
721 	memset(new_ent, 0, sizeof(struct entry));
722 	new_ent->name = bootvar;
723 	new_ent->guid = EFI_GLOBAL_GUID;
724 	LIST_INSERT_HEAD(&efivars, new_ent, entries);
725 	free(load_opt_buf);
726 	free(dp);
727 
728 	return 0;
729 }
730 
731 
732 static void
733 print_loadopt_str(uint8_t *data, size_t datalen)
734 {
735 	char *dev, *relpath, *abspath;
736 	uint32_t attr;
737 	uint16_t fplen;
738 	efi_char *descr;
739 	uint8_t *ep = data + datalen;
740 	uint8_t *walker = data;
741 	efidp dp, edp;
742 	char buf[1024];
743 	int len;
744 	int rv;
745 	int indent;
746 
747 	if (datalen < sizeof(attr) + sizeof(fplen) + sizeof(efi_char))
748 		return;
749 	// First 4 bytes are attribute flags
750 	attr = le32dec(walker);
751 	walker += sizeof(attr);
752 	// Next two bytes are length of the file paths
753 	fplen = le16dec(walker);
754 	walker += sizeof(fplen);
755 	// Next we have a 0 terminated UCS2 string that we know to be aligned
756 	descr = (efi_char *)(intptr_t)(void *)walker;
757 	len = ucs2len(descr); // XXX need to sanity check that len < (datalen - (ep - walker) / 2)
758 	walker += (len + 1) * sizeof(efi_char);
759 	if (walker > ep)
760 		return;
761 	// Now we have fplen bytes worth of file path stuff
762 	dp = (efidp)walker;
763 	walker += fplen;
764 	if (walker > ep)
765 		return;
766 	edp = (efidp)walker;
767 	/*
768 	 * Everything left is the binary option args
769 	 * opt = walker;
770 	 * optlen = ep - walker;
771 	 */
772 	indent = 1;
773 	while (dp < edp) {
774 		efidp_format_device_path(buf, sizeof(buf), dp,
775 		    (intptr_t)(void *)edp - (intptr_t)(void *)dp);
776 		printf("%*s%s\n", indent, "", buf);
777 		indent = 10 + len + 1;
778 		rv = efivar_device_path_to_unix_path(dp, &dev, &relpath, &abspath);
779 		if (rv == 0) {
780 			printf("%*s%s:%s %s\n", indent + 4, "", dev, relpath, abspath);
781 			free(dev);
782 			free(relpath);
783 			free(abspath);
784 		}
785 		dp = (efidp)((char *)dp + efidp_size(dp));
786 	}
787 }
788 
789 static char *
790 get_descr(uint8_t *data)
791 {
792 	uint8_t *pos = data;
793 	efi_char *desc;
794 	int  len;
795 	char *buf;
796 	int i = 0;
797 
798 	pos += sizeof(uint32_t) + sizeof(uint16_t);
799 	desc = (efi_char*)(intptr_t)(void *)pos;
800 	len = ucs2len(desc);
801 	buf = malloc(len + 1);
802 	memset(buf, 0, len + 1);
803 	while (desc[i]) {
804 		buf[i] = desc[i];
805 		i++;
806 	}
807 	return (char*)buf;
808 }
809 
810 
811 static bool
812 print_boot_var(const char *name, bool verbose, bool curboot)
813 {
814 	size_t size;
815 	uint32_t load_attrs;
816 	uint8_t *data;
817 	int ret;
818 	char *d;
819 
820 	ret = efi_get_variable(EFI_GLOBAL_GUID, name, &data, &size, NULL);
821 	if (ret < 0)
822 		return false;
823 	load_attrs = le32dec(data);
824 	d = get_descr(data);
825 	printf("%c%s%c %s", curboot ? '+' : ' ', name,
826 	    ((load_attrs & LOAD_OPTION_ACTIVE) ? '*': ' '), d);
827 	free(d);
828 	if (verbose)
829 		print_loadopt_str(data, size);
830 	else
831 		printf("\n");
832 	return true;
833 }
834 
835 
836 static bool
837 os_indication_supported(uint64_t indication)
838 {
839 	uint8_t *data;
840 	size_t size;
841 	uint32_t attrs;
842 	int ret;
843 
844 	ret = efi_get_variable(EFI_GLOBAL_GUID, "OsIndicationsSupported", &data,
845 	    &size, &attrs);
846 	if (ret < 0)
847 		return false;
848 	return (le64dec(data) & indication) == indication;
849 }
850 
851 static uint64_t
852 os_indications(void)
853 {
854 	uint8_t *data;
855 	size_t size;
856 	uint32_t attrs;
857 	int ret;
858 
859 	ret = efi_get_variable(EFI_GLOBAL_GUID, "OsIndications", &data, &size,
860 	    &attrs);
861 	if (ret < 0)
862 		return 0;
863 	return le64dec(data);
864 }
865 
866 static int
867 os_indications_set(uint64_t mask, uint64_t val)
868 {
869 	uint8_t new[sizeof(uint64_t)];
870 
871 	le64enc(&new, (os_indications() & ~mask) | (val & mask));
872 	return set_bootvar("OsIndications", new, sizeof(new));
873 }
874 
875 /* Cmd epilogue, or just the default with no args.
876  * The order is [bootnext] bootcurrent, timeout, order, and the bootvars [-v]
877  */
878 static int
879 print_boot_vars(bool verbose)
880 {
881 	/*
882 	 * just read and print the current values
883 	 * as a command epilogue
884 	 */
885 	struct entry *v;
886 	uint8_t *data;
887 	size_t size;
888 	uint32_t attrs;
889 	int ret, bolen;
890 	uint16_t *boot_order = NULL, current;
891 	bool boot_to_fw_ui;
892 
893 	if (os_indication_supported(EFI_OS_INDICATIONS_BOOT_TO_FW_UI)) {
894 		boot_to_fw_ui =
895 		    (os_indications() & EFI_OS_INDICATIONS_BOOT_TO_FW_UI) != 0;
896 		printf("Boot to FW : %s\n", boot_to_fw_ui != 0 ?
897 		    "true" : "false");
898 	}
899 
900 	ret = efi_get_variable(EFI_GLOBAL_GUID, "BootNext", &data, &size, &attrs);
901 	if (ret > 0) {
902 		printf("BootNext : %04x\n", le16dec(data));
903 	}
904 
905 	ret = efi_get_variable(EFI_GLOBAL_GUID, "BootCurrent", &data, &size, &attrs);
906 	current = le16dec(data);
907 	printf("BootCurrent: %04x\n", current);
908 
909 	ret = efi_get_variable(EFI_GLOBAL_GUID, "Timeout", &data, &size, &attrs);
910 	if (ret > 0) {
911 		printf("Timeout    : %d seconds\n", le16dec(data));
912 	}
913 
914 	if (efi_get_variable(EFI_GLOBAL_GUID, "BootOrder", &data, &size, &attrs) > 0) {
915 		if (size % 2 == 1)
916 			warn("Bad BootOrder variable: odd length %d", (int)size);
917 		boot_order = malloc(size);
918 		bolen = size / 2;
919 		printf("BootOrder  : ");
920 		for (size_t i = 0; i < size; i += 2) {
921 			boot_order[i / 2] = le16dec(data + i);
922 			printf("%04X%s", boot_order[i / 2], i == size - 2 ? "\n" : ", ");
923 		}
924 	}
925 
926 	if (boot_order == NULL) {
927 		/*
928 		 * now we want to fetch 'em all fresh again
929 		 * which possibly includes a newly created bootvar
930 		 */
931 		LIST_FOREACH(v, &efivars, entries) {
932 			print_boot_var(v->name, verbose, v->idx == current);
933 		}
934 	} else {
935 		LIST_FOREACH(v, &efivars, entries) {
936 			v->flags = 0;
937 		}
938 		for (int i = 0; i < bolen; i++) {
939 			char buffer[10];
940 
941 			snprintf(buffer, sizeof(buffer), "Boot%04X", boot_order[i]);
942 			if (!print_boot_var(buffer, verbose, boot_order[i] == current))
943 				printf("%s: MISSING!\n", buffer);
944 			LIST_FOREACH(v, &efivars, entries) {
945 				if (v->idx == boot_order[i]) {
946 					v->flags |= SEEN;
947 					break;
948 				}
949 			}
950 		}
951 		if (verbose) {
952 			printf("\n\nUnreferenced Variables:\n");
953 			LIST_FOREACH(v, &efivars, entries) {
954 				if (v->flags == 0)
955 					print_boot_var(v->name, verbose, v->idx == current);
956 			}
957 		}
958 	}
959 	return 0;
960 }
961 
962 static void
963 delete_timeout(void)
964 {
965 
966 	efi_del_variable(EFI_GLOBAL_GUID,"Timeout");
967 }
968 
969 static void
970 handle_timeout(int to)
971 {
972 	uint16_t timeout;
973 
974 	le16enc(&timeout, to);
975 	if (set_bootvar("Timeout", (uint8_t *)&timeout, sizeof(timeout)) < 0)
976 		errx(1, "Can't set Timeout for booting.");
977 }
978 
979 static void
980 report_esp_device(bool do_dp, bool do_unix)
981 {
982 	uint8_t *data;
983 	size_t size, len;
984 	uint32_t attrs;
985 	int ret;
986 	uint16_t current, fplen;
987 	char *name, *dev, *relpath, *abspath;
988 	uint8_t *walker, *ep;
989 	efi_char *descr;
990 	efidp dp;
991 	char buf[PATH_MAX];
992 
993 	if (do_dp && do_unix)
994 		errx(1, "Can't report both UEFI device-path and Unix path together");
995 
996 	ret = efi_get_variable(EFI_GLOBAL_GUID, "BootCurrent", &data, &size, &attrs);
997 	if (ret < 0)
998 		err(1, "Can't get BootCurrent");
999 	current = le16dec(data);
1000 	if (asprintf(&name, "Boot%04X", current) < 0)
1001 		err(1, "Can't format boot var\n");
1002 	if (efi_get_variable(EFI_GLOBAL_GUID, name, &data, &size, NULL) < 0)
1003 		err(1, "Can't retrieve EFI var %s", name);
1004 	// First 4 bytes are attribute flags
1005 	walker = data;
1006 	ep = walker + size;
1007 	walker += sizeof(uint32_t);
1008 	// Next two bytes are length of the file paths
1009 	fplen = le16dec(walker);
1010 	walker += sizeof(fplen);
1011 	// Next we have a 0 terminated UCS2 string that we know to be aligned
1012 	descr = (efi_char *)(intptr_t)(void *)walker;
1013 	len = ucs2len(descr); // XXX need to sanity check that len < (datalen - (ep - walker) / 2)
1014 	walker += (len + 1) * sizeof(efi_char);
1015 	if (walker > ep)
1016 		errx(1, "malformed boot variable %s", name);
1017 	// Now we have fplen bytes worth of file path stuff
1018 	dp = (efidp)walker;
1019 	walker += fplen;
1020 	if (walker > ep)
1021 		errx(1, "malformed boot variable %s", name);
1022 	if (do_dp) {
1023 		efidp_format_device_path_node(buf, sizeof(buf), dp);
1024 		printf("%s\n", buf);
1025 		exit(0);
1026 	}
1027 	if (efivar_device_path_to_unix_path(dp, &dev, &relpath, &abspath) < 0)
1028 		errx(1, "Can't convert to unix path");
1029 	if (do_unix) {
1030 		if (abspath == NULL)
1031 			errx(1, "Can't find where %s:%s is mounted",
1032 			    dev, relpath);
1033 		abspath[strlen(abspath) - strlen(relpath) - 1] = '\0';
1034 		printf("%s\n", abspath);
1035 	} else {
1036 		printf("%s\n", dev);
1037 	}
1038 	free(dev);
1039 	free(relpath);
1040 	free(abspath);
1041 	exit(0);
1042 }
1043 
1044 static void
1045 set_boot_to_fw_ui(bool to_fw)
1046 {
1047 	int ret;
1048 
1049 	if (!os_indication_supported(EFI_OS_INDICATIONS_BOOT_TO_FW_UI)) {
1050 		if (to_fw)
1051 			errx(1, "boot to fw ui not supported");
1052 		else
1053 			return;
1054 	}
1055 	ret = os_indications_set(EFI_OS_INDICATIONS_BOOT_TO_FW_UI,
1056 	    to_fw ? ~0 : 0);
1057 	if (ret < 0)
1058 		errx(1, "failed to set boot to fw ui");
1059 }
1060 
1061 int
1062 main(int argc, char *argv[])
1063 {
1064 
1065 	if (!efi_variables_supported())
1066 		errx(1, "efi variables not supported on this system. root? kldload efirt?");
1067 
1068 	memset(&opts, 0, sizeof (bmgr_opts_t));
1069 	parse_args(argc, argv);
1070 	read_vars();
1071 
1072 	if (opts.create)
1073 		/*
1074 		 * side effect, adds to boot order, but not yet active.
1075 		 */
1076 		make_boot_var(opts.label ? opts.label : "",
1077 		    opts.loader, opts.kernel, opts.env, opts.dry_run,
1078 		    opts.has_bootnum ? opts.bootnum : -1, opts.set_active);
1079 	else if (opts.set_active || opts.set_inactive )
1080 		handle_activity(opts.bootnum, opts.set_active);
1081 	else if (opts.order != NULL)
1082 		set_boot_order(opts.order); /* create a new bootorder with opts.order */
1083 	else if (opts.set_bootnext)
1084 		handle_bootnext(opts.bootnum);
1085 	else if (opts.delete_bootnext)
1086 		del_bootnext();
1087 	else if (opts.delete)
1088 		delete_bootvar(opts.bootnum);
1089 	else if (opts.del_timeout)
1090 		delete_timeout();
1091 	else if (opts.set_timeout)
1092 		handle_timeout(opts.timeout);
1093 	else if (opts.esp_device)
1094 		report_esp_device(opts.device_path, opts.unix_path);
1095 	else if (opts.fw_ui)
1096 		set_boot_to_fw_ui(true);
1097 	else if (opts.no_fw_ui)
1098 		set_boot_to_fw_ui(false);
1099 
1100 	print_boot_vars(opts.verbose);
1101 }
1102