virtfw-efi-tools 0.1.9

efi related linux applications
Documentation
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
use clap::Parser;
use log::{debug, error, info, warn};
use std::io;
use std::io::Cursor;
use std::process::ExitCode;

use virtfw_libefi::bootcfg::BootConfig;
use virtfw_libefi::distro::LinuxOsInfo;
use virtfw_libefi::efifile::EfiFile;
use virtfw_libefi::efivar::boot;
use virtfw_libefi::efivar::devpath as dp;
use virtfw_libefi::efivar::ids;
use virtfw_libefi::efivar::io::ReadEfiExt;
use virtfw_libefi::efivar::io::WriteEfiExt;
use virtfw_libefi::efivar::types::EfiVar;
use virtfw_libefi::efivar::types::EfiVarAttr;
use virtfw_libefi::efivar::types::EfiVarId;
use virtfw_libefi::guids;
use virtfw_libefi::nocasestr::NoCaseString;
use virtfw_libefi::varstore::sysfs;

use virtfw_efi_tools::shimcsv::write_boot_csv;

#[derive(Parser, Debug)]
#[command(version, name = "mini-bootcfg", about = "show and manage uefi boot entries", long_about = None)]
struct Args {
    /// set loglevel
    #[arg(short, long, value_name = "LEVEL", default_value = "info")]
    loglevel: log::Level,

    /// print boot configuration
    #[arg(short, long)]
    show: bool,

    /// more verbose output
    #[arg(short, long)]
    verbose: bool,

    /// add boot entry for UKI image FILE
    #[arg(long, value_name = "FILE", help_heading = "Update UKI boot entries")]
    add_uki: Option<String>,

    /// remove boot entry for UKI image FILE
    #[arg(long, value_name = "FILE", help_heading = "Update UKI boot entries")]
    remove_uki: Option<String>,

    /// override cmd line for boot entry
    #[arg(long, value_name = "CMDLINE", help_heading = "Update UKI boot entries")]
    cmdline: Option<String>,

    /// boot is successful.
    #[arg(
        long = "boot-ok",
        visible_alias = "boot-successful",
        help_heading = "Update UKI boot entries"
    )]
    boot_successful: bool,

    /// update BOOT.CSV
    #[arg(long, help_heading = "Update UKI boot entries")]
    update_csv: bool,

    /// add boot entry to netboot URI
    #[arg(long, value_name = "URI", help_heading = "Update other boot entries")]
    add_uri: Option<String>,

    /// remove boot entry NNNN
    #[arg(long, value_name = "NNNN", help_heading = "Update other boot entries")]
    remove_entry: Option<String>,

    /// boot added entry once (via BootNext)
    #[arg(
        long = "boot-next",
        visible_alias = "once",
        help_heading = "Options for entry updates"
    )]
    boot_next: bool,

    /// place added entry at POS to BootOrder
    #[arg(long, value_name = "POS", help_heading = "Options for entry updates")]
    boot_order: Option<String>,

    /// do not actually update the configuration
    #[arg(long, help_heading = "Options for entry updates")]
    dry_run: bool,

    /// set title for boot entry
    #[arg(long, value_name = "TITLE", help_heading = "Options for entry updates")]
    title: Option<String>,

    /// print boot loader name
    #[arg(long, help_heading = "Print system information")]
    print_loader: bool,

    /// print efi stub info
    #[arg(long, help_heading = "Print system information")]
    print_stub_info: bool,

    /// print efi stub image
    #[arg(long, help_heading = "Print system information")]
    print_stub_image: bool,
}

fn create_file_boot_entry(
    bootcfg: &BootConfig,
    shim_opt: Option<&EfiFile>,
    uki: &EfiFile,
    title: Option<&String>,
    cmdline: Option<&String>,
) -> Option<boot::BootEntry> {
    let devpath;
    let optdata;

    if let Some(shim) = shim_opt {
        if shim.devpathnode_hd() != uki.devpathnode_hd() {
            error!("shim and uki are on different partitions");
            return None;
        }
        devpath = shim.devpath();
        let Some(efipath) = uki.efi_name() else {
            error!("failed to format efi filename");
            return None;
        };
        optdata = match cmdline {
            Some(c) => Some(format!("{efipath} {c}")),
            None => Some(efipath.0),
        }
    } else {
        if bootcfg.sb {
            error!("shim not found and secure boot enabled");
            return None;
        }
        devpath = uki.devpath();
        optdata = cmdline.map(|c| c.to_string());
    };

    let t = match title {
        Some(t) => t.clone(),
        None => uki.basename().unwrap(),
    };

    Some(boot::BootEntry::new_boot(&t, devpath.unwrap(), optdata))
}

fn create_uri_boot_entry(
    uri: &str,
    title: Option<&String>,
    cmdline: Option<&String>,
) -> Option<boot::BootEntry> {
    let mut devpath = dp::DevPath::new();
    devpath.push(dp::DevPathNode::MsgUri(Some(uri.to_string())));
    let optdata = cmdline.map(|c| c.to_string());
    let t = match title {
        Some(t) => t.clone(),
        None => uri.split('/').next_back().unwrap().to_string(),
    };
    Some(boot::BootEntry::new_boot(&t, devpath, optdata))
}

fn find_boot_entry_for_file<'cfg>(
    bootcfg: &'cfg BootConfig,
    shim_opt: Option<&EfiFile>,
    uki: &EfiFile,
) -> Option<&'cfg boot::BootIndex> {
    for (i, e) in &bootcfg.entries {
        if let Some(dp) = uki.devpath() {
            if e.devpath == dp {
                // entry device path matches uki
                return Some(i);
            }
        }
        if let Some(shim) = shim_opt {
            if let Some(dp) = shim.devpath() {
                if e.devpath == dp {
                    // entry device path matches shim, and ...
                    if let boot::BootEntryOptData::String { string: cmdline } = &e.optdata {
                        let mut iter = cmdline.split_ascii_whitespace();
                        let binary = NoCaseString::new(iter.next().unwrap());
                        if let Some(uki_path) = uki.efi_name() {
                            if uki_path == binary {
                                // ... entry optdata matches uki path
                                return Some(i);
                            }
                        }
                    }
                }
            }
        }
    }
    None
}

fn write_variable(var: &EfiVar, dryrun: bool) -> io::Result<()> {
    if dryrun {
        info!("skip update efivar: {} (dry-run)", var.name());
    } else {
        info!("update efivar: {}", var.name());
        sysfs::varstore_write(var)?;
    }
    Ok(())
}

fn delete_variable(name: &str, dryrun: bool) -> io::Result<()> {
    if dryrun {
        info!("skip delete efivar: {name} (dry-run)");
    } else {
        info!("delete efivar: {name}");
        sysfs::varstore_delete(name, &guids::EfiGlobalVariable)?;
    }
    Ok(())
}

fn write_bootentry(
    index: &boot::BootIndex,
    entry: boot::BootEntry,
    dryrun: bool,
) -> io::Result<()> {
    let mut wr = Cursor::new(Vec::new());
    wr.write_boot_entry(&entry)?;

    let id = EfiVarId::new(format!("Boot{index}"), guids::EfiGlobalVariable);
    let be = EfiVar::new_with_vec(id, EfiVarAttr::new_nv_bs_rt(), wr.into_inner());

    info!(
        "set efivar: {} = \"{}\" {} {}",
        be.name(),
        entry.title,
        entry.devpath,
        entry.optdata
    );
    write_variable(&be, dryrun)?;
    Ok(())
}

fn write_bootnext(index: &boot::BootIndex, dryrun: bool) -> io::Result<()> {
    let bn = EfiVar::new_with_vec(
        ids::BOOT_NEXT.into(),
        EfiVarAttr::new_nv_bs_rt(),
        Vec::from(index),
    );

    debug!("set efivar: {} = {}", bn.name(), index);
    write_variable(&bn, dryrun)?;
    Ok(())
}

fn update_bootorder(
    new_order: &boot::BootOrder,
    old_order: &boot::BootOrder,
    dryrun: bool,
) -> io::Result<()> {
    let bo = EfiVar::new_with_vec(
        ids::BOOT_ORDER.into(),
        EfiVarAttr::new_nv_bs_rt(),
        Vec::from(new_order),
    );

    debug!("old efivar: {} = {}", bo.name(), old_order);
    debug!("set efivar: {} = {}", bo.name(), new_order);
    if new_order.is_empty() {
        delete_variable("BootOrder", dryrun)?;
    } else {
        write_variable(&bo, dryrun)?;
    }
    Ok(())
}

fn add_bootindex(bootcfg: &BootConfig, index: &boot::BootIndex, cfg: &Args) -> io::Result<()> {
    let dryrun = cfg.dry_run;
    if cfg.boot_next {
        write_bootnext(index, dryrun)?;
    }
    if let Some(posstr) = &cfg.boot_order {
        let old_order = if let Some(o) = &bootcfg.order {
            o
        } else {
            &boot::BootOrder::empty()
        };

        let pos = if posstr == "last" {
            old_order.len()
        } else {
            let Ok(p) = posstr.parse::<usize>() else {
                return Err(io::Error::other(format!("failed to parse pos: {posstr}")));
            };
            if p > old_order.len() {
                return Err(io::Error::other(format!(
                    "pos is too big: {} > {}",
                    p,
                    old_order.len()
                )));
            }
            p
        };

        let new_order = old_order.insert(pos, index);
        update_bootorder(&new_order, old_order, dryrun)?;
    }
    Ok(())
}

fn remove_bootentry(bootcfg: &BootConfig, index: &boot::BootIndex, dryrun: bool) -> io::Result<()> {
    let name = format!("Boot{index}");
    delete_variable(&name, dryrun)?;

    if let Some(next) = bootcfg.next {
        if next == *index {
            delete_variable("BootNext", dryrun)?;
        }
    }

    if let Some(old_order) = &bootcfg.order {
        if let Some(pos) = old_order.position(index) {
            let new_order = old_order.remove(pos);
            update_bootorder(&new_order, old_order, dryrun)?;
        }
    }

    Ok(())
}

fn boot_successful(bootcfg: &BootConfig, dryrun: bool) -> io::Result<()> {
    let Some(current) = bootcfg.current else {
        warn!("BootCurrent not set");
        return Ok(());
    };

    let old_order = if let Some(o) = &bootcfg.order {
        o
    } else {
        &boot::BootOrder::empty()
    };

    if let Some(pos) = old_order.position(&current) {
        info!("BootCurrent ({current}) already in BootOrder (position {pos})");
        return Ok(());
    }

    let new_order = old_order.insert(0, &current);
    update_bootorder(&new_order, old_order, dryrun)?;
    Ok(())
}

fn update_csv(bootcfg: &BootConfig, shim_opt: Option<&EfiFile>) -> io::Result<()> {
    let Some(order) = &bootcfg.order else {
        warn!("BootOrder not set");
        return Ok(());
    };
    let Some(shim) = shim_opt else {
        warn!("shim.efi not found");
        return Ok(());
    };
    let Some(devpath) = shim.devpath() else {
        warn!("no efi device path for shim.efi");
        return Ok(());
    };
    let Some(basename) = shim.basename() else {
        warn!("no basename for shim.efi");
        return Ok(());
    };

    let mut csvname = shim.file.clone();
    csvname.pop();
    csvname.push(
        basename
            .to_uppercase()
            .replace("SHIM", "BOOT")
            .replace("EFI", "CSV"),
    );
    info!("updating {}", csvname.display());

    let mut csvdata = String::new();
    for index in &order.0 {
        let Some(entry) = bootcfg.entries.get(index) else {
            continue;
        };
        if devpath != entry.devpath {
            continue;
        };

        let args = match &entry.optdata {
            boot::BootEntryOptData::String { string } => string,
            _ => "",
        };

        let line = format!("{},{},{} ,Comment", basename, entry.title, args);
        debug!("{line}");
        csvdata.push_str(&line);
        csvdata.push('\n');
    }

    write_boot_csv(&csvname, &csvdata)?;
    Ok(())
}

fn show_bootcfg(bootcfg: &BootConfig, verbose: bool) {
    for i in bootcfg.index_list() {
        println!("{}", bootcfg.index_title(i));
        if verbose {
            if let Some(e) = bootcfg.entries.get(i) {
                println!("      devpath: {}", e.devpath);
                match &e.optdata {
                    boot::BootEntryOptData::String { string } => {
                        println!("      optdata/string: \"{string}\"")
                    }
                    boot::BootEntryOptData::Guid { guid } => {
                        println!("      optdata/guid: {guid}")
                    }
                    boot::BootEntryOptData::Data { bytes } => {
                        println!("      optdata/bytes: {:?}", bytes)
                    }
                    boot::BootEntryOptData::None => {}
                }
            }
            println!();
        }
    }
}

fn read_efi_var_str(name: &str) -> Option<String> {
    let variable = sysfs::varstore_read(name, &guids::LoaderInfo)?;
    let mut rd = Cursor::new(variable.data());
    let value = rd.read_efi_string().ok()?;
    Some(value)
}

fn main() -> ExitCode {
    let cfg = Args::parse();

    let levelfilter = cfg.loglevel.to_level_filter();
    env_logger::Builder::from_default_env()
        .filter_module(module_path!(), levelfilter)
        .filter_module("libefi", levelfilter)
        .format_timestamp(None)
        .format_target(false)
        .init();

    let dryrun = cfg.dry_run;
    let verbose = cfg.verbose;

    let osinfo = LinuxOsInfo::new();
    let bootcfg = BootConfig::new();

    let shim = osinfo.shim_path().unwrap();
    let efi_shim = EfiFile::new(&shim);

    if cfg.show {
        show_bootcfg(&bootcfg, verbose);
        return ExitCode::from(0);
    }

    if let Some(ref uki) = cfg.add_uki {
        let efi_uki = match EfiFile::new(uki) {
            Err(e) => {
                error!("{uki}: {e}");
                return ExitCode::from(1);
            }
            Ok(u) => u,
        };

        let idx_opt = find_boot_entry_for_file(&bootcfg, efi_shim.as_ref().ok(), &efi_uki);
        let index = match idx_opt {
            Some(idx) => {
                info!("entry exists for {uki} (Boot{idx})");
                idx
            }
            None => &bootcfg.index_unused(),
        };
        let entry_opt = create_file_boot_entry(
            &bootcfg,
            efi_shim.as_ref().ok(),
            &efi_uki,
            cfg.title.as_ref(),
            cfg.cmdline.as_ref(),
        );
        let Some(entry) = entry_opt else {
            error!("failed to create boot entry for {uki}");
            return ExitCode::from(1);
        };
        if let Err(e) = write_bootentry(index, entry, dryrun) {
            error!("write boot entry: {e}");
            return ExitCode::from(1);
        };
        if let Err(e) = add_bootindex(&bootcfg, index, &cfg) {
            error!("add boot index: {e}");
            return ExitCode::from(1);
        };
        return ExitCode::from(0);
    }

    if let Some(ref uki) = cfg.remove_uki {
        let efi_uki = match EfiFile::new(uki) {
            Err(e) => {
                error!("{uki}: {e}");
                return ExitCode::from(1);
            }
            Ok(u) => u,
        };

        let idx_opt = find_boot_entry_for_file(&bootcfg, efi_shim.as_ref().ok(), &efi_uki);
        let Some(idx) = idx_opt else {
            warn!("no entry found for {uki}");
            return ExitCode::from(0);
        };
        if let Err(e) = remove_bootentry(&bootcfg, idx, dryrun) {
            error!("remove boot entry: {e}");
            return ExitCode::from(1);
        }
        return ExitCode::from(0);
    }

    if cfg.boot_successful {
        if let Err(e) = boot_successful(&bootcfg, dryrun) {
            error!("update boot order: {e}");
            return ExitCode::from(1);
        };
        if cfg.update_csv {
            // reload (updated) boot config
            let bootcfg = BootConfig::new();
            if let Err(e) = update_csv(&bootcfg, efi_shim.as_ref().ok()) {
                error!("update boot.csv: {e}");
                return ExitCode::from(1);
            }
        }
        return ExitCode::from(0);
    }

    if cfg.update_csv {
        if let Err(e) = update_csv(&bootcfg, efi_shim.as_ref().ok()) {
            error!("update boot.csv: {e}");
            return ExitCode::from(1);
        }
        return ExitCode::from(0);
    }

    if let Some(ref uri) = cfg.add_uri {
        let index = bootcfg.index_unused();
        let entry_opt = create_uri_boot_entry(uri, cfg.title.as_ref(), cfg.cmdline.as_ref());
        let Some(entry) = entry_opt else {
            error!("failed to create boot entry for {uri}");
            return ExitCode::from(1);
        };
        if let Err(e) = write_bootentry(&index, entry, dryrun) {
            error!("write boot entry: {e}");
            return ExitCode::from(1);
        };
        if let Err(e) = add_bootindex(&bootcfg, &index, &cfg) {
            error!("add boot index: {e}");
            return ExitCode::from(1);
        };
        return ExitCode::from(0);
    }

    if let Some(ref nr) = cfg.remove_entry {
        let i = u16::from_str_radix(nr, 16);
        if let Err(e) = i {
            error!("parse \"{nr}\": {e}");
            return ExitCode::from(1);
        }
        let index = boot::BootIndex(i.unwrap());
        if let Err(e) = remove_bootentry(&bootcfg, &index, dryrun) {
            error!("remove boot entry: {e}");
            return ExitCode::from(1);
        }
        return ExitCode::from(0);
    }

    if cfg.print_loader {
        match read_efi_var_str("LoaderInfo") {
            Some(s) => println!("{s}"),
            None => println!("unknown"),
        }
        return ExitCode::from(0);
    }

    if cfg.print_stub_info {
        match read_efi_var_str("StubInfo") {
            Some(s) => println!("{s}"),
            None => println!("unknown"),
        }
        return ExitCode::from(0);
    }

    if cfg.print_stub_image {
        if let Some(efipath) = read_efi_var_str("StubImageIdentifier") {
            let linuxpath = efipath.replace("\\", "/");
            println!("{linuxpath}");
        }
        return ExitCode::from(0);
    }

    show_bootcfg(&bootcfg, verbose);
    ExitCode::from(0)
}