summaryrefslogtreecommitdiff
path: root/src/shared/efivars.c
blob: 3597ddf4a7522d5511bd7089e87ff6a83fd70682 (plain)
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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
/* SPDX-License-Identifier: LGPL-2.1+ */

#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <linux/fs.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>

#include "sd-id128.h"

#include "alloc-util.h"
#include "chattr-util.h"
#include "dirent-util.h"
#include "efivars.h"
#include "fd-util.h"
#include "io-util.h"
#include "macro.h"
#include "parse-util.h"
#include "sort-util.h"
#include "stdio-util.h"
#include "strv.h"
#include "time-util.h"
#include "utf8.h"
#include "virt.h"

#if ENABLE_EFI

#define LOAD_OPTION_ACTIVE            0x00000001
#define MEDIA_DEVICE_PATH                   0x04
#define MEDIA_HARDDRIVE_DP                  0x01
#define MEDIA_FILEPATH_DP                   0x04
#define SIGNATURE_TYPE_GUID                 0x02
#define MBR_TYPE_EFI_PARTITION_TABLE_HEADER 0x02
#define END_DEVICE_PATH_TYPE                0x7f
#define END_ENTIRE_DEVICE_PATH_SUBTYPE      0xff
#define EFI_OS_INDICATIONS_BOOT_TO_FW_UI    0x0000000000000001

#define boot_option__contents {                 \
        uint32_t attr;                          \
        uint16_t path_len;                      \
        uint16_t title[];                       \
        }

struct boot_option boot_option__contents;
struct boot_option__packed boot_option__contents _packed_;
assert_cc(offsetof(struct boot_option, title) == offsetof(struct boot_option__packed, title));
/* sizeof(struct boot_option) != sizeof(struct boot_option__packed), so
 * the *size* of the structure should not be used anywhere below. */

struct drive_path {
        uint32_t part_nr;
        uint64_t part_start;
        uint64_t part_size;
        char signature[16];
        uint8_t mbr_type;
        uint8_t signature_type;
} _packed_;

#define device_path__contents {                 \
        uint8_t type;                           \
        uint8_t sub_type;                       \
        uint16_t length;                        \
        union {                                 \
                uint16_t path[0];               \
                struct drive_path drive;        \
        };                                      \
        }

struct device_path device_path__contents;
struct device_path__packed device_path__contents _packed_;
assert_cc(sizeof(struct device_path) == sizeof(struct device_path__packed));

bool is_efi_boot(void) {
        if (detect_container() > 0)
                return false;

        return access("/sys/firmware/efi/", F_OK) >= 0;
}

static int read_flag(const char *varname) {
        _cleanup_free_ void *v = NULL;
        uint8_t b;
        size_t s;
        int r;

        if (!is_efi_boot()) /* If this is not an EFI boot, assume the queried flags are zero */
                return 0;

        r = efi_get_variable(EFI_VENDOR_GLOBAL, varname, NULL, &v, &s);
        if (r < 0)
                return r;

        if (s != 1)
                return -EINVAL;

        b = *(uint8_t *)v;
        return !!b;
}

bool is_efi_secure_boot(void) {
        return read_flag("SecureBoot") > 0;
}

bool is_efi_secure_boot_setup_mode(void) {
        return read_flag("SetupMode") > 0;
}

int efi_reboot_to_firmware_supported(void) {
        _cleanup_free_ void *v = NULL;
        uint64_t b;
        size_t s;
        int r;

        if (!is_efi_boot())
                return -EOPNOTSUPP;

        r = efi_get_variable(EFI_VENDOR_GLOBAL, "OsIndicationsSupported", NULL, &v, &s);
        if (r == -ENOENT) /* variable doesn't exist? it's not supported then */
                return -EOPNOTSUPP;
        if (r < 0)
                return r;
        if (s != sizeof(uint64_t))
                return -EINVAL;

        b = *(uint64_t*) v;
        if (!(b & EFI_OS_INDICATIONS_BOOT_TO_FW_UI))
                return -EOPNOTSUPP; /* bit unset? it's not supported then */

        return 0;
}

static int get_os_indications(uint64_t *os_indication) {
        _cleanup_free_ void *v = NULL;
        size_t s;
        int r;

        /* Let's verify general support first */
        r = efi_reboot_to_firmware_supported();
        if (r < 0)
                return r;

        r = efi_get_variable(EFI_VENDOR_GLOBAL, "OsIndications", NULL, &v, &s);
        if (r == -ENOENT) {
                /* Some firmware implementations that do support OsIndications and report that with
                 * OsIndicationsSupported will remove the OsIndications variable when it is unset. Let's pretend it's 0
                 * then, to hide this implementation detail. Note that this call will return -ENOENT then only if the
                 * support for OsIndications is missing entirely, as determined by efi_reboot_to_firmware_supported()
                 * above. */
                *os_indication = 0;
                return 0;
        } else if (r < 0)
                return r;
        else if (s != sizeof(uint64_t))
                return -EINVAL;

        *os_indication = *(uint64_t *)v;
        return 0;
}

int efi_get_reboot_to_firmware(void) {
        int r;
        uint64_t b;

        r = get_os_indications(&b);
        if (r < 0)
                return r;

        return !!(b & EFI_OS_INDICATIONS_BOOT_TO_FW_UI);
}

int efi_set_reboot_to_firmware(bool value) {
        int r;
        uint64_t b, b_new;

        r = get_os_indications(&b);
        if (r < 0)
                return r;

        if (value)
                b_new = b | EFI_OS_INDICATIONS_BOOT_TO_FW_UI;
        else
                b_new = b & ~EFI_OS_INDICATIONS_BOOT_TO_FW_UI;

        /* Avoid writing to efi vars store if we can due to firmware bugs. */
        if (b != b_new)
                return efi_set_variable(EFI_VENDOR_GLOBAL, "OsIndications", &b_new, sizeof(uint64_t));

        return 0;
}

char* efi_variable_path(sd_id128_t vendor, const char *name) {
        char *p;

        if (asprintf(&p,
                     "/sys/firmware/efi/efivars/%s-" SD_ID128_UUID_FORMAT_STR,
                     name, SD_ID128_FORMAT_VAL(vendor)) < 0)
                return NULL;

        return p;
}

int efi_get_variable(
                sd_id128_t vendor,
                const char *name,
                uint32_t *ret_attribute,
                void **ret_value,
                size_t *ret_size) {

        _cleanup_close_ int fd = -1;
        _cleanup_free_ char *p = NULL;
        _cleanup_free_ void *buf = NULL;
        struct stat st;
        uint32_t a;
        ssize_t n;

        assert(name);

        p = efi_variable_path(vendor, name);
        if (!p)
                return -ENOMEM;

        if (!ret_value && !ret_size && !ret_attribute) {
                /* If caller is not interested in anything, just check if the variable exists and is readable
                 * to us. */
                if (access(p, R_OK) < 0)
                        return -errno;

                return 0;
        }

        fd = open(p, O_RDONLY|O_NOCTTY|O_CLOEXEC);
        if (fd < 0)
                return -errno;

        if (fstat(fd, &st) < 0)
                return -errno;
        if (st.st_size < 4)
                return -ENODATA;
        if (st.st_size > 4*1024*1024 + 4)
                return -E2BIG;

        if (ret_value || ret_attribute) {
                n = read(fd, &a, sizeof(a));
                if (n < 0)
                        return -errno;
                if (n != sizeof(a))
                        return -EIO;
        }

        if (ret_value) {
                buf = malloc(st.st_size - 4 + 2);
                if (!buf)
                        return -ENOMEM;

                n = read(fd, buf, (size_t) st.st_size - 4);
                if (n < 0)
                        return -errno;
                if (n != st.st_size - 4)
                        return -EIO;

                /* Always NUL terminate (2 bytes, to protect UTF-16) */
                ((char*) buf)[st.st_size - 4] = 0;
                ((char*) buf)[st.st_size - 4 + 1] = 0;
        }

        /* Note that efivarfs interestingly doesn't require ftruncate() to update an existing EFI variable
         * with a smaller value. */

        if (ret_attribute)
                *ret_attribute = a;

        if (ret_value)
                *ret_value = TAKE_PTR(buf);

        if (ret_size)
                *ret_size = (size_t) st.st_size - 4;

        return 0;
}

int efi_get_variable_string(sd_id128_t vendor, const char *name, char **p) {
        _cleanup_free_ void *s = NULL;
        size_t ss = 0;
        int r;
        char *x;

        r = efi_get_variable(vendor, name, NULL, &s, &ss);
        if (r < 0)
                return r;

        x = utf16_to_utf8(s, ss);
        if (!x)
                return -ENOMEM;

        *p = x;
        return 0;
}

int efi_set_variable(
                sd_id128_t vendor,
                const char *name,
                const void *value,
                size_t size) {

        struct var {
                uint32_t attr;
                char buf[];
        } _packed_ * _cleanup_free_ buf = NULL;
        _cleanup_free_ char *p = NULL;
        _cleanup_close_ int fd = -1;
        bool saved_flags_valid = false;
        unsigned saved_flags;
        int r;

        assert(name);
        assert(value || size == 0);

        p = efi_variable_path(vendor, name);
        if (!p)
                return -ENOMEM;

        /* Newer efivarfs protects variables that are not in a whitelist with FS_IMMUTABLE_FL by default, to protect
         * them for accidental removal and modification. We are not changing these variables accidentally however,
         * hence let's unset the bit first. */

        r = chattr_path(p, 0, FS_IMMUTABLE_FL, &saved_flags);
        if (r < 0 && r != -ENOENT)
                log_debug_errno(r, "Failed to drop FS_IMMUTABLE_FL flag from '%s', ignoring: %m", p);

        saved_flags_valid = r >= 0;

        if (size == 0) {
                if (unlink(p) < 0) {
                        r = -errno;
                        goto finish;
                }

                return 0;
        }

        fd = open(p, O_WRONLY|O_CREAT|O_NOCTTY|O_CLOEXEC, 0644);
        if (fd < 0) {
                r = -errno;
                goto finish;
        }

        buf = malloc(sizeof(uint32_t) + size);
        if (!buf) {
                r = -ENOMEM;
                goto finish;
        }

        buf->attr = EFI_VARIABLE_NON_VOLATILE|EFI_VARIABLE_BOOTSERVICE_ACCESS|EFI_VARIABLE_RUNTIME_ACCESS;
        memcpy(buf->buf, value, size);

        r = loop_write(fd, buf, sizeof(uint32_t) + size, false);
        if (r < 0)
                goto finish;

        r = 0;

finish:
        if (saved_flags_valid) {
                int q;

                /* Restore the original flags field, just in case */
                if (fd < 0)
                        q = chattr_path(p, saved_flags, FS_IMMUTABLE_FL, NULL);
                else
                        q = chattr_fd(fd, saved_flags, FS_IMMUTABLE_FL, NULL);
                if (q < 0)
                        log_debug_errno(q, "Failed to restore FS_IMMUTABLE_FL on '%s', ignoring: %m", p);
        }

        return r;
}

int efi_set_variable_string(sd_id128_t vendor, const char *name, const char *v) {
        _cleanup_free_ char16_t *u16 = NULL;

        u16 = utf8_to_utf16(v, strlen(v));
        if (!u16)
                return -ENOMEM;

        return efi_set_variable(vendor, name, u16, (char16_strlen(u16) + 1) * sizeof(char16_t));
}

static ssize_t utf16_size(const uint16_t *s, size_t buf_len_bytes) {
        size_t l = 0;

        /* Returns the size of the string in bytes without the terminating two zero bytes */

        if (buf_len_bytes % sizeof(uint16_t) != 0)
                return -EINVAL;

        while (l < buf_len_bytes / sizeof(uint16_t)) {
                if (s[l] == 0)
                        return (l + 1) * sizeof(uint16_t);
                l++;
        }

        return -EINVAL; /* The terminator was not found */
}

struct guid {
        uint32_t u1;
        uint16_t u2;
        uint16_t u3;
        uint8_t u4[8];
} _packed_;

static void efi_guid_to_id128(const void *guid, sd_id128_t *id128) {
        uint32_t u1;
        uint16_t u2, u3;
        const struct guid *uuid = guid;

        memcpy(&u1, &uuid->u1, sizeof(uint32_t));
        id128->bytes[0] = (u1 >> 24) & 0xff;
        id128->bytes[1] = (u1 >> 16) & 0xff;
        id128->bytes[2] = (u1 >> 8) & 0xff;
        id128->bytes[3] = u1 & 0xff;
        memcpy(&u2, &uuid->u2, sizeof(uint16_t));
        id128->bytes[4] = (u2 >> 8) & 0xff;
        id128->bytes[5] = u2 & 0xff;
        memcpy(&u3, &uuid->u3, sizeof(uint16_t));
        id128->bytes[6] = (u3 >> 8) & 0xff;
        id128->bytes[7] = u3 & 0xff;
        memcpy(&id128->bytes[8], uuid->u4, sizeof(uuid->u4));
}

int efi_get_boot_option(
                uint16_t id,
                char **title,
                sd_id128_t *part_uuid,
                char **path,
                bool *active) {

        char boot_id[9];
        _cleanup_free_ uint8_t *buf = NULL;
        size_t l;
        struct boot_option *header;
        ssize_t title_size;
        _cleanup_free_ char *s = NULL, *p = NULL;
        sd_id128_t p_uuid = SD_ID128_NULL;
        int r;

        if (!is_efi_boot())
                return -EOPNOTSUPP;

        xsprintf(boot_id, "Boot%04X", id);
        r = efi_get_variable(EFI_VENDOR_GLOBAL, boot_id, NULL, (void **)&buf, &l);
        if (r < 0)
                return r;
        if (l < offsetof(struct boot_option, title))
                return -ENOENT;

        header = (struct boot_option *)buf;
        title_size = utf16_size(header->title, l - offsetof(struct boot_option, title));
        if (title_size < 0)
                return title_size;

        if (title) {
                s = utf16_to_utf8(header->title, title_size);
                if (!s)
                        return -ENOMEM;
        }

        if (header->path_len > 0) {
                uint8_t *dbuf;
                size_t dnext, doff;

                doff = offsetof(struct boot_option, title) + title_size;
                dbuf = buf + doff;
                if (header->path_len > l - doff)
                        return -EINVAL;

                dnext = 0;
                while (dnext < header->path_len) {
                        struct device_path *dpath;

                        dpath = (struct device_path *)(dbuf + dnext);
                        if (dpath->length < 4)
                                break;

                        /* Type 0x7F – End of Hardware Device Path, Sub-Type 0xFF – End Entire Device Path */
                        if (dpath->type == END_DEVICE_PATH_TYPE && dpath->sub_type == END_ENTIRE_DEVICE_PATH_SUBTYPE)
                                break;

                        dnext += dpath->length;

                        /* Type 0x04 – Media Device Path */
                        if (dpath->type != MEDIA_DEVICE_PATH)
                                continue;

                        /* Sub-Type 1 – Hard Drive */
                        if (dpath->sub_type == MEDIA_HARDDRIVE_DP) {
                                /* 0x02 – GUID Partition Table */
                                if (dpath->drive.mbr_type != MBR_TYPE_EFI_PARTITION_TABLE_HEADER)
                                        continue;

                                /* 0x02 – GUID signature */
                                if (dpath->drive.signature_type != SIGNATURE_TYPE_GUID)
                                        continue;

                                if (part_uuid)
                                        efi_guid_to_id128(dpath->drive.signature, &p_uuid);
                                continue;
                        }

                        /* Sub-Type 4 – File Path */
                        if (dpath->sub_type == MEDIA_FILEPATH_DP && !p && path) {
                                p = utf16_to_utf8(dpath->path, dpath->length-4);
                                if (!p)
                                        return  -ENOMEM;

                                efi_tilt_backslashes(p);
                                continue;
                        }
                }
        }

        if (title)
                *title = TAKE_PTR(s);
        if (part_uuid)
                *part_uuid = p_uuid;
        if (path)
                *path = TAKE_PTR(p);
        if (active)
                *active = header->attr & LOAD_OPTION_ACTIVE;

        return 0;
}

static void to_utf16(uint16_t *dest, const char *src) {
        int i;

        for (i = 0; src[i] != '\0'; i++)
                dest[i] = src[i];
        dest[i] = '\0';
}

static void id128_to_efi_guid(sd_id128_t id, void *guid) {
        struct guid uuid = {
                .u1 = id.bytes[0] << 24 | id.bytes[1] << 16 | id.bytes[2] << 8 | id.bytes[3],
                .u2 = id.bytes[4] << 8 | id.bytes[5],
                .u3 = id.bytes[6] << 8 | id.bytes[7],
        };
        memcpy(uuid.u4, id.bytes+8, sizeof(uuid.u4));
        memcpy(guid, &uuid, sizeof(uuid));
}

static uint16_t *tilt_slashes(uint16_t *s) {
        uint16_t *p;

        for (p = s; *p; p++)
                if (*p == '/')
                        *p = '\\';

        return s;
}

int efi_add_boot_option(
                uint16_t id,
                const char *title,
                uint32_t part,
                uint64_t pstart,
                uint64_t psize,
                sd_id128_t part_uuid,
                const char *path) {

        size_t size, title_len, path_len;
        _cleanup_free_ char *buf = NULL;
        struct boot_option *option;
        struct device_path *devicep;
        char boot_id[9];

        if (!is_efi_boot())
                return -EOPNOTSUPP;

        title_len = (strlen(title)+1) * 2;
        path_len = (strlen(path)+1) * 2;

        buf = malloc0(offsetof(struct boot_option, title) + title_len +
                      sizeof(struct drive_path) +
                      sizeof(struct device_path) + path_len);
        if (!buf)
                return -ENOMEM;

        /* header */
        option = (struct boot_option *)buf;
        option->attr = LOAD_OPTION_ACTIVE;
        option->path_len = offsetof(struct device_path, drive) + sizeof(struct drive_path) +
                           offsetof(struct device_path, path) + path_len +
                           offsetof(struct device_path, path);
        to_utf16(option->title, title);
        size = offsetof(struct boot_option, title) + title_len;

        /* partition info */
        devicep = (struct device_path *)(buf + size);
        devicep->type = MEDIA_DEVICE_PATH;
        devicep->sub_type = MEDIA_HARDDRIVE_DP;
        devicep->length = offsetof(struct device_path, drive) + sizeof(struct drive_path);
        memcpy(&devicep->drive.part_nr, &part, sizeof(uint32_t));
        memcpy(&devicep->drive.part_start, &pstart, sizeof(uint64_t));
        memcpy(&devicep->drive.part_size, &psize, sizeof(uint64_t));
        id128_to_efi_guid(part_uuid, devicep->drive.signature);
        devicep->drive.mbr_type = MBR_TYPE_EFI_PARTITION_TABLE_HEADER;
        devicep->drive.signature_type = SIGNATURE_TYPE_GUID;
        size += devicep->length;

        /* path to loader */
        devicep = (struct device_path *)(buf + size);
        devicep->type = MEDIA_DEVICE_PATH;
        devicep->sub_type = MEDIA_FILEPATH_DP;
        devicep->length = offsetof(struct device_path, path) + path_len;
        to_utf16(devicep->path, path);
        tilt_slashes(devicep->path);
        size += devicep->length;

        /* end of path */
        devicep = (struct device_path *)(buf + size);
        devicep->type = END_DEVICE_PATH_TYPE;
        devicep->sub_type = END_ENTIRE_DEVICE_PATH_SUBTYPE;
        devicep->length = offsetof(struct device_path, path);
        size += devicep->length;

        xsprintf(boot_id, "Boot%04X", id);
        return efi_set_variable(EFI_VENDOR_GLOBAL, boot_id, buf, size);
}

int efi_remove_boot_option(uint16_t id) {
        char boot_id[9];

        if (!is_efi_boot())
                return -EOPNOTSUPP;

        xsprintf(boot_id, "Boot%04X", id);
        return efi_set_variable(EFI_VENDOR_GLOBAL, boot_id, NULL, 0);
}

int efi_get_boot_order(uint16_t **order) {
        _cleanup_free_ void *buf = NULL;
        size_t l;
        int r;

        if (!is_efi_boot())
                return -EOPNOTSUPP;

        r = efi_get_variable(EFI_VENDOR_GLOBAL, "BootOrder", NULL, &buf, &l);
        if (r < 0)
                return r;

        if (l <= 0)
                return -ENOENT;

        if (l % sizeof(uint16_t) > 0 ||
            l / sizeof(uint16_t) > INT_MAX)
                return -EINVAL;

        *order = TAKE_PTR(buf);
        return (int) (l / sizeof(uint16_t));
}

int efi_set_boot_order(uint16_t *order, size_t n) {

        if (!is_efi_boot())
                return -EOPNOTSUPP;

        return efi_set_variable(EFI_VENDOR_GLOBAL, "BootOrder", order, n * sizeof(uint16_t));
}

static int boot_id_hex(const char s[static 4]) {
        int id = 0, i;

        assert(s);

        for (i = 0; i < 4; i++)
                if (s[i] >= '0' && s[i] <= '9')
                        id |= (s[i] - '0') << (3 - i) * 4;
                else if (s[i] >= 'A' && s[i] <= 'F')
                        id |= (s[i] - 'A' + 10) << (3 - i) * 4;
                else
                        return -EINVAL;

        return id;
}

static int cmp_uint16(const uint16_t *a, const uint16_t *b) {
        return CMP(*a, *b);
}

int efi_get_boot_options(uint16_t **options) {
        _cleanup_closedir_ DIR *dir = NULL;
        _cleanup_free_ uint16_t *list = NULL;
        struct dirent *de;
        size_t alloc = 0;
        int count = 0;

        assert(options);

        if (!is_efi_boot())
                return -EOPNOTSUPP;

        dir = opendir("/sys/firmware/efi/efivars/");
        if (!dir)
                return -errno;

        FOREACH_DIRENT(de, dir, return -errno) {
                int id;

                if (strncmp(de->d_name, "Boot", 4) != 0)
                        continue;

                if (strlen(de->d_name) != 45)
                        continue;

                if (strcmp(de->d_name + 8, "-8be4df61-93ca-11d2-aa0d-00e098032b8c") != 0)
                        continue;

                id = boot_id_hex(de->d_name + 4);
                if (id < 0)
                        continue;

                if (!GREEDY_REALLOC(list, alloc, count + 1))
                        return -ENOMEM;

                list[count++] = id;
        }

        typesafe_qsort(list, count, cmp_uint16);

        *options = TAKE_PTR(list);

        return count;
}

static int read_usec(sd_id128_t vendor, const char *name, usec_t *u) {
        _cleanup_free_ char *j = NULL;
        int r;
        uint64_t x = 0;

        assert(name);
        assert(u);

        r = efi_get_variable_string(EFI_VENDOR_LOADER, name, &j);
        if (r < 0)
                return r;

        r = safe_atou64(j, &x);
        if (r < 0)
                return r;

        *u = x;
        return 0;
}

int efi_loader_get_boot_usec(usec_t *firmware, usec_t *loader) {
        uint64_t x, y;
        int r;

        assert(firmware);
        assert(loader);

        if (!is_efi_boot())
                return -EOPNOTSUPP;

        r = read_usec(EFI_VENDOR_LOADER, "LoaderTimeInitUSec", &x);
        if (r < 0)
                return r;

        r = read_usec(EFI_VENDOR_LOADER, "LoaderTimeExecUSec", &y);
        if (r < 0)
                return r;

        if (y == 0 || y < x)
                return -EIO;

        if (y > USEC_PER_HOUR)
                return -EIO;

        *firmware = x;
        *loader = y;

        return 0;
}

int efi_loader_get_device_part_uuid(sd_id128_t *u) {
        _cleanup_free_ char *p = NULL;
        int r, parsed[16];

        if (!is_efi_boot())
                return -EOPNOTSUPP;

        r = efi_get_variable_string(EFI_VENDOR_LOADER, "LoaderDevicePartUUID", &p);
        if (r < 0)
                return r;

        if (sscanf(p, SD_ID128_UUID_FORMAT_STR,
                   &parsed[0], &parsed[1], &parsed[2], &parsed[3],
                   &parsed[4], &parsed[5], &parsed[6], &parsed[7],
                   &parsed[8], &parsed[9], &parsed[10], &parsed[11],
                   &parsed[12], &parsed[13], &parsed[14], &parsed[15]) != 16)
                return -EIO;

        if (u) {
                unsigned i;

                for (i = 0; i < ELEMENTSOF(parsed); i++)
                        u->bytes[i] = parsed[i];
        }

        return 0;
}

int efi_loader_get_entries(char ***ret) {
        _cleanup_free_ char16_t *entries = NULL;
        _cleanup_strv_free_ char **l = NULL;
        size_t size, i, start;
        int r;

        assert(ret);

        if (!is_efi_boot())
                return -EOPNOTSUPP;

        r = efi_get_variable(EFI_VENDOR_LOADER, "LoaderEntries", NULL, (void**) &entries, &size);
        if (r < 0)
                return r;

        /* The variable contains a series of individually NUL terminated UTF-16 strings. */

        for (i = 0, start = 0;; i++) {
                _cleanup_free_ char *decoded = NULL;
                bool end;

                /* Is this the end of the variable's data? */
                end = i * sizeof(char16_t) >= size;

                /* Are we in the middle of a string? (i.e. not at the end of the variable, nor at a NUL terminator?) If
                 * so, let's go to the next entry. */
                if (!end && entries[i] != 0)
                        continue;

                /* We reached the end of a string, let's decode it into UTF-8 */
                decoded = utf16_to_utf8(entries + start, (i - start) * sizeof(char16_t));
                if (!decoded)
                        return -ENOMEM;

                if (efi_loader_entry_name_valid(decoded)) {
                        r = strv_consume(&l, TAKE_PTR(decoded));
                        if (r < 0)
                                return r;
                } else
                        log_debug("Ignoring invalid loader entry '%s'.", decoded);

                /* We reached the end of the variable */
                if (end)
                        break;

                /* Continue after the NUL byte */
                start = i + 1;
        }

        *ret = TAKE_PTR(l);
        return 0;
}

int efi_loader_get_features(uint64_t *ret) {
        _cleanup_free_ void *v = NULL;
        size_t s;
        int r;

        if (!is_efi_boot()) {
                *ret = 0;
                return 0;
        }

        r = efi_get_variable(EFI_VENDOR_LOADER, "LoaderFeatures", NULL, &v, &s);
        if (r == -ENOENT) {
                _cleanup_free_ char *info = NULL;

                /* The new (v240+) LoaderFeatures variable is not supported, let's see if it's systemd-boot at all */
                r = efi_get_variable_string(EFI_VENDOR_LOADER, "LoaderInfo", &info);
                if (r < 0) {
                        if (r != -ENOENT)
                                return r;

                        /* Variable not set, definitely means not systemd-boot */

                } else if (first_word(info, "systemd-boot")) {

                        /* An older systemd-boot version. Let's hardcode the feature set, since it was pretty
                         * static in all its versions. */

                        *ret = EFI_LOADER_FEATURE_CONFIG_TIMEOUT |
                                EFI_LOADER_FEATURE_ENTRY_DEFAULT |
                                EFI_LOADER_FEATURE_ENTRY_ONESHOT;

                        return 0;
                }

                /* No features supported */
                *ret = 0;
                return 0;
        }
        if (r < 0)
                return r;

        if (s != sizeof(uint64_t))
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "LoaderFeatures EFI variable doesn't have the right size.");

        memcpy(ret, v, sizeof(uint64_t));
        return 0;
}

#endif

bool efi_loader_entry_name_valid(const char *s) {
        if (isempty(s))
                return false;

        if (strlen(s) > FILENAME_MAX) /* Make sure entry names fit in filenames */
                return false;

        return in_charset(s, ALPHANUMERICAL "+-_.");
}

char *efi_tilt_backslashes(char *s) {
        char *p;

        for (p = s; *p; p++)
                if (*p == '\\')
                        *p = '/';

        return s;
}