1 /* SPDX-License-Identifier: LGPL-2.1+ */
16 #include "alloc-util.h"
17 #include "chattr-util.h"
18 #include "dirent-util.h"
23 #include "parse-util.h"
24 #include "sort-util.h"
25 #include "stdio-util.h"
27 #include "time-util.h"
33 #define LOAD_OPTION_ACTIVE 0x00000001
34 #define MEDIA_DEVICE_PATH 0x04
35 #define MEDIA_HARDDRIVE_DP 0x01
36 #define MEDIA_FILEPATH_DP 0x04
37 #define SIGNATURE_TYPE_GUID 0x02
38 #define MBR_TYPE_EFI_PARTITION_TABLE_HEADER 0x02
39 #define END_DEVICE_PATH_TYPE 0x7f
40 #define END_ENTIRE_DEVICE_PATH_SUBTYPE 0xff
41 #define EFI_OS_INDICATIONS_BOOT_TO_FW_UI 0x0000000000000001
43 #define boot_option__contents { \
49 struct boot_option boot_option__contents
;
50 struct boot_option__packed boot_option__contents _packed_
;
51 assert_cc(offsetof(struct boot_option
, title
) == offsetof(struct boot_option__packed
, title
));
52 /* sizeof(struct boot_option) != sizeof(struct boot_option__packed), so
53 * the *size* of the structure should not be used anywhere below. */
61 uint8_t signature_type
;
64 #define device_path__contents { \
70 struct drive_path drive; \
74 struct device_path device_path__contents
;
75 struct device_path__packed device_path__contents _packed_
;
76 assert_cc(sizeof(struct device_path
) == sizeof(struct device_path__packed
));
78 bool is_efi_boot(void) {
79 if (detect_container() > 0)
82 return access("/sys/firmware/efi/", F_OK
) >= 0;
85 static int read_flag(const char *varname
) {
86 _cleanup_free_
void *v
= NULL
;
91 if (!is_efi_boot()) /* If this is not an EFI boot, assume the queried flags are zero */
94 r
= efi_get_variable(EFI_VENDOR_GLOBAL
, varname
, NULL
, &v
, &s
);
105 bool is_efi_secure_boot(void) {
106 return read_flag("SecureBoot") > 0;
109 bool is_efi_secure_boot_setup_mode(void) {
110 return read_flag("SetupMode") > 0;
113 int efi_reboot_to_firmware_supported(void) {
114 _cleanup_free_
void *v
= NULL
;
122 r
= efi_get_variable(EFI_VENDOR_GLOBAL
, "OsIndicationsSupported", NULL
, &v
, &s
);
123 if (r
== -ENOENT
) /* variable doesn't exist? it's not supported then */
127 if (s
!= sizeof(uint64_t))
131 if (!(b
& EFI_OS_INDICATIONS_BOOT_TO_FW_UI
))
132 return -EOPNOTSUPP
; /* bit unset? it's not supported then */
137 static int get_os_indications(uint64_t *os_indication
) {
138 _cleanup_free_
void *v
= NULL
;
142 /* Let's verify general support first */
143 r
= efi_reboot_to_firmware_supported();
147 r
= efi_get_variable(EFI_VENDOR_GLOBAL
, "OsIndications", NULL
, &v
, &s
);
149 /* Some firmware implementations that do support OsIndications and report that with
150 * OsIndicationsSupported will remove the OsIndications variable when it is unset. Let's pretend it's 0
151 * then, to hide this implementation detail. Note that this call will return -ENOENT then only if the
152 * support for OsIndications is missing entirely, as determined by efi_reboot_to_firmware_supported()
158 else if (s
!= sizeof(uint64_t))
161 *os_indication
= *(uint64_t *)v
;
165 int efi_get_reboot_to_firmware(void) {
169 r
= get_os_indications(&b
);
173 return !!(b
& EFI_OS_INDICATIONS_BOOT_TO_FW_UI
);
176 int efi_set_reboot_to_firmware(bool value
) {
180 r
= get_os_indications(&b
);
185 b_new
= b
| EFI_OS_INDICATIONS_BOOT_TO_FW_UI
;
187 b_new
= b
& ~EFI_OS_INDICATIONS_BOOT_TO_FW_UI
;
189 /* Avoid writing to efi vars store if we can due to firmware bugs. */
191 return efi_set_variable(EFI_VENDOR_GLOBAL
, "OsIndications", &b_new
, sizeof(uint64_t));
196 char* efi_variable_path(sd_id128_t vendor
, const char *name
) {
200 "/sys/firmware/efi/efivars/%s-" SD_ID128_UUID_FORMAT_STR
,
201 name
, SD_ID128_FORMAT_VAL(vendor
)) < 0)
207 int efi_get_variable(
210 uint32_t *ret_attribute
,
214 _cleanup_close_
int fd
= -1;
215 _cleanup_free_
char *p
= NULL
;
216 _cleanup_free_
void *buf
= NULL
;
223 p
= efi_variable_path(vendor
, name
);
227 if (!ret_value
&& !ret_size
&& !ret_attribute
) {
228 /* If caller is not interested in anything, just check if the variable exists and is readable
230 if (access(p
, R_OK
) < 0)
236 fd
= open(p
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
240 if (fstat(fd
, &st
) < 0)
244 if (st
.st_size
> 4*1024*1024 + 4)
247 if (ret_value
|| ret_attribute
) {
248 n
= read(fd
, &a
, sizeof(a
));
256 buf
= malloc(st
.st_size
- 4 + 2);
260 n
= read(fd
, buf
, (size_t) st
.st_size
- 4);
263 if (n
!= st
.st_size
- 4)
266 /* Always NUL terminate (2 bytes, to protect UTF-16) */
267 ((char*) buf
)[st
.st_size
- 4] = 0;
268 ((char*) buf
)[st
.st_size
- 4 + 1] = 0;
271 /* Note that efivarfs interestingly doesn't require ftruncate() to update an existing EFI variable
272 * with a smaller value. */
278 *ret_value
= TAKE_PTR(buf
);
281 *ret_size
= (size_t) st
.st_size
- 4;
286 int efi_get_variable_string(sd_id128_t vendor
, const char *name
, char **p
) {
287 _cleanup_free_
void *s
= NULL
;
292 r
= efi_get_variable(vendor
, name
, NULL
, &s
, &ss
);
296 x
= utf16_to_utf8(s
, ss
);
304 int efi_set_variable(
313 } _packed_
* _cleanup_free_ buf
= NULL
;
314 _cleanup_free_
char *p
= NULL
;
315 _cleanup_close_
int fd
= -1;
316 bool saved_flags_valid
= false;
317 unsigned saved_flags
;
321 assert(value
|| size
== 0);
323 p
= efi_variable_path(vendor
, name
);
327 /* Newer efivarfs protects variables that are not in a whitelist with FS_IMMUTABLE_FL by default, to protect
328 * them for accidental removal and modification. We are not changing these variables accidentally however,
329 * hence let's unset the bit first. */
331 r
= chattr_path(p
, 0, FS_IMMUTABLE_FL
, &saved_flags
);
332 if (r
< 0 && r
!= -ENOENT
)
333 log_debug_errno(r
, "Failed to drop FS_IMMUTABLE_FL flag from '%s', ignoring: %m", p
);
335 saved_flags_valid
= r
>= 0;
346 fd
= open(p
, O_WRONLY
|O_CREAT
|O_NOCTTY
|O_CLOEXEC
, 0644);
352 buf
= malloc(sizeof(uint32_t) + size
);
358 buf
->attr
= EFI_VARIABLE_NON_VOLATILE
|EFI_VARIABLE_BOOTSERVICE_ACCESS
|EFI_VARIABLE_RUNTIME_ACCESS
;
359 memcpy(buf
->buf
, value
, size
);
361 r
= loop_write(fd
, buf
, sizeof(uint32_t) + size
, false);
368 if (saved_flags_valid
) {
371 /* Restore the original flags field, just in case */
373 q
= chattr_path(p
, saved_flags
, FS_IMMUTABLE_FL
, NULL
);
375 q
= chattr_fd(fd
, saved_flags
, FS_IMMUTABLE_FL
, NULL
);
377 log_debug_errno(q
, "Failed to restore FS_IMMUTABLE_FL on '%s', ignoring: %m", p
);
383 int efi_set_variable_string(sd_id128_t vendor
, const char *name
, const char *v
) {
384 _cleanup_free_ char16_t
*u16
= NULL
;
386 u16
= utf8_to_utf16(v
, strlen(v
));
390 return efi_set_variable(vendor
, name
, u16
, (char16_strlen(u16
) + 1) * sizeof(char16_t
));
393 static ssize_t
utf16_size(const uint16_t *s
, size_t buf_len_bytes
) {
396 /* Returns the size of the string in bytes without the terminating two zero bytes */
398 if (buf_len_bytes
% sizeof(uint16_t) != 0)
401 while (l
< buf_len_bytes
/ sizeof(uint16_t)) {
403 return (l
+ 1) * sizeof(uint16_t);
407 return -EINVAL
; /* The terminator was not found */
417 static void efi_guid_to_id128(const void *guid
, sd_id128_t
*id128
) {
420 const struct guid
*uuid
= guid
;
422 memcpy(&u1
, &uuid
->u1
, sizeof(uint32_t));
423 id128
->bytes
[0] = (u1
>> 24) & 0xff;
424 id128
->bytes
[1] = (u1
>> 16) & 0xff;
425 id128
->bytes
[2] = (u1
>> 8) & 0xff;
426 id128
->bytes
[3] = u1
& 0xff;
427 memcpy(&u2
, &uuid
->u2
, sizeof(uint16_t));
428 id128
->bytes
[4] = (u2
>> 8) & 0xff;
429 id128
->bytes
[5] = u2
& 0xff;
430 memcpy(&u3
, &uuid
->u3
, sizeof(uint16_t));
431 id128
->bytes
[6] = (u3
>> 8) & 0xff;
432 id128
->bytes
[7] = u3
& 0xff;
433 memcpy(&id128
->bytes
[8], uuid
->u4
, sizeof(uuid
->u4
));
436 int efi_get_boot_option(
439 sd_id128_t
*part_uuid
,
444 _cleanup_free_
uint8_t *buf
= NULL
;
446 struct boot_option
*header
;
448 _cleanup_free_
char *s
= NULL
, *p
= NULL
;
449 sd_id128_t p_uuid
= SD_ID128_NULL
;
455 xsprintf(boot_id
, "Boot%04X", id
);
456 r
= efi_get_variable(EFI_VENDOR_GLOBAL
, boot_id
, NULL
, (void **)&buf
, &l
);
459 if (l
< offsetof(struct boot_option
, title
))
462 header
= (struct boot_option
*)buf
;
463 title_size
= utf16_size(header
->title
, l
- offsetof(struct boot_option
, title
));
468 s
= utf16_to_utf8(header
->title
, title_size
);
473 if (header
->path_len
> 0) {
477 doff
= offsetof(struct boot_option
, title
) + title_size
;
479 if (header
->path_len
> l
- doff
)
483 while (dnext
< header
->path_len
) {
484 struct device_path
*dpath
;
486 dpath
= (struct device_path
*)(dbuf
+ dnext
);
487 if (dpath
->length
< 4)
490 /* Type 0x7F – End of Hardware Device Path, Sub-Type 0xFF – End Entire Device Path */
491 if (dpath
->type
== END_DEVICE_PATH_TYPE
&& dpath
->sub_type
== END_ENTIRE_DEVICE_PATH_SUBTYPE
)
494 dnext
+= dpath
->length
;
496 /* Type 0x04 – Media Device Path */
497 if (dpath
->type
!= MEDIA_DEVICE_PATH
)
500 /* Sub-Type 1 – Hard Drive */
501 if (dpath
->sub_type
== MEDIA_HARDDRIVE_DP
) {
502 /* 0x02 – GUID Partition Table */
503 if (dpath
->drive
.mbr_type
!= MBR_TYPE_EFI_PARTITION_TABLE_HEADER
)
506 /* 0x02 – GUID signature */
507 if (dpath
->drive
.signature_type
!= SIGNATURE_TYPE_GUID
)
511 efi_guid_to_id128(dpath
->drive
.signature
, &p_uuid
);
515 /* Sub-Type 4 – File Path */
516 if (dpath
->sub_type
== MEDIA_FILEPATH_DP
&& !p
&& path
) {
517 p
= utf16_to_utf8(dpath
->path
, dpath
->length
-4);
521 efi_tilt_backslashes(p
);
528 *title
= TAKE_PTR(s
);
534 *active
= header
->attr
& LOAD_OPTION_ACTIVE
;
539 static void to_utf16(uint16_t *dest
, const char *src
) {
542 for (i
= 0; src
[i
] != '\0'; i
++)
547 static void id128_to_efi_guid(sd_id128_t id
, void *guid
) {
549 .u1
= id
.bytes
[0] << 24 | id
.bytes
[1] << 16 | id
.bytes
[2] << 8 | id
.bytes
[3],
550 .u2
= id
.bytes
[4] << 8 | id
.bytes
[5],
551 .u3
= id
.bytes
[6] << 8 | id
.bytes
[7],
553 memcpy(uuid
.u4
, id
.bytes
+8, sizeof(uuid
.u4
));
554 memcpy(guid
, &uuid
, sizeof(uuid
));
557 static uint16_t *tilt_slashes(uint16_t *s
) {
567 int efi_add_boot_option(
573 sd_id128_t part_uuid
,
576 size_t size
, title_len
, path_len
;
577 _cleanup_free_
char *buf
= NULL
;
578 struct boot_option
*option
;
579 struct device_path
*devicep
;
585 title_len
= (strlen(title
)+1) * 2;
586 path_len
= (strlen(path
)+1) * 2;
588 buf
= malloc0(offsetof(struct boot_option
, title
) + title_len
+
589 sizeof(struct drive_path
) +
590 sizeof(struct device_path
) + path_len
);
595 option
= (struct boot_option
*)buf
;
596 option
->attr
= LOAD_OPTION_ACTIVE
;
597 option
->path_len
= offsetof(struct device_path
, drive
) + sizeof(struct drive_path
) +
598 offsetof(struct device_path
, path
) + path_len
+
599 offsetof(struct device_path
, path
);
600 to_utf16(option
->title
, title
);
601 size
= offsetof(struct boot_option
, title
) + title_len
;
604 devicep
= (struct device_path
*)(buf
+ size
);
605 devicep
->type
= MEDIA_DEVICE_PATH
;
606 devicep
->sub_type
= MEDIA_HARDDRIVE_DP
;
607 devicep
->length
= offsetof(struct device_path
, drive
) + sizeof(struct drive_path
);
608 memcpy(&devicep
->drive
.part_nr
, &part
, sizeof(uint32_t));
609 memcpy(&devicep
->drive
.part_start
, &pstart
, sizeof(uint64_t));
610 memcpy(&devicep
->drive
.part_size
, &psize
, sizeof(uint64_t));
611 id128_to_efi_guid(part_uuid
, devicep
->drive
.signature
);
612 devicep
->drive
.mbr_type
= MBR_TYPE_EFI_PARTITION_TABLE_HEADER
;
613 devicep
->drive
.signature_type
= SIGNATURE_TYPE_GUID
;
614 size
+= devicep
->length
;
617 devicep
= (struct device_path
*)(buf
+ size
);
618 devicep
->type
= MEDIA_DEVICE_PATH
;
619 devicep
->sub_type
= MEDIA_FILEPATH_DP
;
620 devicep
->length
= offsetof(struct device_path
, path
) + path_len
;
621 to_utf16(devicep
->path
, path
);
622 tilt_slashes(devicep
->path
);
623 size
+= devicep
->length
;
626 devicep
= (struct device_path
*)(buf
+ size
);
627 devicep
->type
= END_DEVICE_PATH_TYPE
;
628 devicep
->sub_type
= END_ENTIRE_DEVICE_PATH_SUBTYPE
;
629 devicep
->length
= offsetof(struct device_path
, path
);
630 size
+= devicep
->length
;
632 xsprintf(boot_id
, "Boot%04X", id
);
633 return efi_set_variable(EFI_VENDOR_GLOBAL
, boot_id
, buf
, size
);
636 int efi_remove_boot_option(uint16_t id
) {
642 xsprintf(boot_id
, "Boot%04X", id
);
643 return efi_set_variable(EFI_VENDOR_GLOBAL
, boot_id
, NULL
, 0);
646 int efi_get_boot_order(uint16_t **order
) {
647 _cleanup_free_
void *buf
= NULL
;
654 r
= efi_get_variable(EFI_VENDOR_GLOBAL
, "BootOrder", NULL
, &buf
, &l
);
661 if (l
% sizeof(uint16_t) > 0 ||
662 l
/ sizeof(uint16_t) > INT_MAX
)
665 *order
= TAKE_PTR(buf
);
666 return (int) (l
/ sizeof(uint16_t));
669 int efi_set_boot_order(uint16_t *order
, size_t n
) {
674 return efi_set_variable(EFI_VENDOR_GLOBAL
, "BootOrder", order
, n
* sizeof(uint16_t));
677 static int boot_id_hex(const char s
[static 4]) {
682 for (i
= 0; i
< 4; i
++)
683 if (s
[i
] >= '0' && s
[i
] <= '9')
684 id
|= (s
[i
] - '0') << (3 - i
) * 4;
685 else if (s
[i
] >= 'A' && s
[i
] <= 'F')
686 id
|= (s
[i
] - 'A' + 10) << (3 - i
) * 4;
693 static int cmp_uint16(const uint16_t *a
, const uint16_t *b
) {
697 int efi_get_boot_options(uint16_t **options
) {
698 _cleanup_closedir_
DIR *dir
= NULL
;
699 _cleanup_free_
uint16_t *list
= NULL
;
709 dir
= opendir("/sys/firmware/efi/efivars/");
713 FOREACH_DIRENT(de
, dir
, return -errno
) {
716 if (strncmp(de
->d_name
, "Boot", 4) != 0)
719 if (strlen(de
->d_name
) != 45)
722 if (strcmp(de
->d_name
+ 8, "-8be4df61-93ca-11d2-aa0d-00e098032b8c") != 0)
725 id
= boot_id_hex(de
->d_name
+ 4);
729 if (!GREEDY_REALLOC(list
, alloc
, count
+ 1))
735 typesafe_qsort(list
, count
, cmp_uint16
);
737 *options
= TAKE_PTR(list
);
742 static int read_usec(sd_id128_t vendor
, const char *name
, usec_t
*u
) {
743 _cleanup_free_
char *j
= NULL
;
750 r
= efi_get_variable_string(EFI_VENDOR_LOADER
, name
, &j
);
754 r
= safe_atou64(j
, &x
);
762 int efi_loader_get_boot_usec(usec_t
*firmware
, usec_t
*loader
) {
772 r
= read_usec(EFI_VENDOR_LOADER
, "LoaderTimeInitUSec", &x
);
776 r
= read_usec(EFI_VENDOR_LOADER
, "LoaderTimeExecUSec", &y
);
783 if (y
> USEC_PER_HOUR
)
792 int efi_loader_get_device_part_uuid(sd_id128_t
*u
) {
793 _cleanup_free_
char *p
= NULL
;
799 r
= efi_get_variable_string(EFI_VENDOR_LOADER
, "LoaderDevicePartUUID", &p
);
803 if (sscanf(p
, SD_ID128_UUID_FORMAT_STR
,
804 &parsed
[0], &parsed
[1], &parsed
[2], &parsed
[3],
805 &parsed
[4], &parsed
[5], &parsed
[6], &parsed
[7],
806 &parsed
[8], &parsed
[9], &parsed
[10], &parsed
[11],
807 &parsed
[12], &parsed
[13], &parsed
[14], &parsed
[15]) != 16)
813 for (i
= 0; i
< ELEMENTSOF(parsed
); i
++)
814 u
->bytes
[i
] = parsed
[i
];
820 int efi_loader_get_entries(char ***ret
) {
821 _cleanup_free_ char16_t
*entries
= NULL
;
822 _cleanup_strv_free_
char **l
= NULL
;
823 size_t size
, i
, start
;
831 r
= efi_get_variable(EFI_VENDOR_LOADER
, "LoaderEntries", NULL
, (void**) &entries
, &size
);
835 /* The variable contains a series of individually NUL terminated UTF-16 strings. */
837 for (i
= 0, start
= 0;; i
++) {
838 _cleanup_free_
char *decoded
= NULL
;
841 /* Is this the end of the variable's data? */
842 end
= i
* sizeof(char16_t
) >= size
;
844 /* Are we in the middle of a string? (i.e. not at the end of the variable, nor at a NUL terminator?) If
845 * so, let's go to the next entry. */
846 if (!end
&& entries
[i
] != 0)
849 /* We reached the end of a string, let's decode it into UTF-8 */
850 decoded
= utf16_to_utf8(entries
+ start
, (i
- start
) * sizeof(char16_t
));
854 if (efi_loader_entry_name_valid(decoded
)) {
855 r
= strv_consume(&l
, TAKE_PTR(decoded
));
859 log_debug("Ignoring invalid loader entry '%s'.", decoded
);
861 /* We reached the end of the variable */
865 /* Continue after the NUL byte */
873 int efi_loader_get_features(uint64_t *ret
) {
874 _cleanup_free_
void *v
= NULL
;
878 if (!is_efi_boot()) {
883 r
= efi_get_variable(EFI_VENDOR_LOADER
, "LoaderFeatures", NULL
, &v
, &s
);
885 _cleanup_free_
char *info
= NULL
;
887 /* The new (v240+) LoaderFeatures variable is not supported, let's see if it's systemd-boot at all */
888 r
= efi_get_variable_string(EFI_VENDOR_LOADER
, "LoaderInfo", &info
);
893 /* Variable not set, definitely means not systemd-boot */
895 } else if (first_word(info
, "systemd-boot")) {
897 /* An older systemd-boot version. Let's hardcode the feature set, since it was pretty
898 * static in all its versions. */
900 *ret
= EFI_LOADER_FEATURE_CONFIG_TIMEOUT
|
901 EFI_LOADER_FEATURE_ENTRY_DEFAULT
|
902 EFI_LOADER_FEATURE_ENTRY_ONESHOT
;
907 /* No features supported */
914 if (s
!= sizeof(uint64_t))
915 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
916 "LoaderFeatures EFI variable doesn't have the right size.");
918 memcpy(ret
, v
, sizeof(uint64_t));
924 bool efi_loader_entry_name_valid(const char *s
) {
928 if (strlen(s
) > FILENAME_MAX
) /* Make sure entry names fit in filenames */
931 return in_charset(s
, ALPHANUMERICAL
"+-_.");
934 char *efi_tilt_backslashes(char *s
) {