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
// bls.rs
//
// Copyright 2022 Alberto Ruiz <aruiz@gnome.org>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//
// SPDX-License-Identifier: MPL-2.0

//! Implements systemd's [Boot Loader Specification](https://systemd.io/BOOT_LOADER_SPECIFICATION/)
//!
//! This API can parse and modify a Boot Loader Spec entry file.
//! It supports the [Fedora/GRUB specific commands](https://fedoraproject.org/wiki/Changes/BootLoaderSpecByDefault).
//!
//! This library can be used in a no_std environment that
//! supports dynamic memory allocation by disabling
//! the "std" feature using --no-default-features.
//!
//! NOTE: At the moment, if you parse a BLSEntry with full-line
//! comments and write it back, all comment lines will be consolidated
//! in the header.

#![cfg_attr(not(feature = "std"), no_std)]
#![cfg(not(feature = "std"))]
extern crate alloc;

#[cfg(not(feature = "std"))]
use alloc::format;
#[cfg(not(feature = "std"))]
use alloc::string::String;
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;

/// BLSValue generalizes a value that may have an inline comment
///
/// - ```BLSValue::Value(String)```: the string represent the argument string for the BLS command
/// - ```BLSValue::ValueWithComment(String, String)```: holds string that represents the BLS command argument as well as a comment string at the end of the line
#[derive(Debug, PartialEq)]
pub enum BLSValue {
    Value(String),
    ValueWithComment(String, String),
}

#[derive(Debug, PartialEq)]
pub enum ValueSetPolicy {
    ReplaceAll,
    Append,
    Prepend,
    InsertAt(usize),
}

/// BLSEntry represents the contents of a BLS entry file
#[derive(Debug)]
pub struct BLSEntry {
    pub title: Option<BLSValue>,
    pub version: Option<BLSValue>,
    pub machine_id: Option<BLSValue>,
    pub sort_key: Option<BLSValue>,
    pub linux: BLSValue,
    pub efi: Option<BLSValue>,
    pub initrd: Vec<BLSValue>,
    pub options: Vec<BLSValue>,
    pub devicetree: Option<BLSValue>,
    pub devicetree_overlay: Option<BLSValue>,
    pub architecture: Option<BLSValue>,
    pub grub_hotkey: Option<BLSValue>,
    pub grub_users: Option<BLSValue>,
    pub grub_class: Vec<BLSValue>,
    pub grub_arg: Option<BLSValue>,
    // NOTE: All comments are moved to the header of the file upon rendering back the content
    pub comments: Vec<String>,
}

impl BLSEntry {
    /// Allocates a new instance of BLSEntry, all optional members are initialized to None and ```linux``` is set with an empty string
    pub fn new() -> BLSEntry {
        BLSEntry {
            title: None,
            version: None,
            machine_id: None,
            sort_key: None,
            linux: BLSValue::Value(String::new()),
            efi: None,
            initrd: Vec::new(),
            options: Vec::new(),
            devicetree: None,
            devicetree_overlay: None,
            architecture: None,
            grub_hotkey: None,
            grub_users: None,
            grub_class: Vec::new(),
            grub_arg: None,
            comments: Vec::new(),
        }
    }

    /// Parses a Boot Loader Spec entry UTF-8 buffer, returns a BLSEntry instance if successful, an error String if there was an error
    /// Note that any comment lines that are then rendered using BLSEntry::parse() will be pushed to the header of the file as the
    /// order commands and comments are not preserved.
    pub fn parse(buffer: &str) -> Result<BLSEntry, String> {
        let mut entry = BLSEntry::new();
        let mut has_kernel = false;

        for line in buffer.lines() {
            let mut comment = None;
            // Extract the comment string from the line
            let line = if line.contains("#") {
                let split: Vec<_> = line.splitn(2, "#").collect();
                comment = Some(String::from(split[1]));
                split[0]
            } else {
                line
            };

            // NOTE: For now we put all comment lines in the header
            if line.trim().contains(" ") {
                let key_value: Vec<&str> = line.trim().splitn(2, " ").collect();
                if key_value[0] == "linux" {
                    has_kernel = true;
                }
                if let Err(error) = entry.set(
                    key_value[0],
                    String::from(key_value[1]),
                    comment,
                    ValueSetPolicy::Append,
                ) {
                    return Err(error);
                }
            } else {
                match comment {
                    Some(comment) => {
                        entry.comments.push(comment);
                    }
                    None => {}
                }
            }
        }

        if has_kernel {
            Ok(entry)
        } else {
            Err(String::from("No 'linux' command found."))
        }
    }

    /// Renders the BLSEntry content into a UTF-8 String
    pub fn render(&self) -> String {
        let mut content = String::new();

        fn render_value(content: &mut String, key: &str, value: &BLSValue) {
            content.push_str(key);
            content.push(' ');
            match value {
                BLSValue::Value(value) => content.push_str(&value),
                BLSValue::ValueWithComment(value, comment) => {
                    content.push_str(&value);
                    content.push_str(" #");
                    content.push_str(&comment);
                }
            }
        }

        fn render_single_value(content: &mut String, key: &str, value: &Option<BLSValue>) {
            if let Some(value) = value {
                render_value(content, key, &value)
            }
        }

        fn render_multiple_values(content: &mut String, key: &str, values: &Vec<BLSValue>) {
            for val in values {
                render_value(content, key, &val)
            }
        }

        // We push all comments in the header
        for comment in &self.comments {
            content.push_str("#");
            content.push_str(&comment)
        }

        // Mandatory commands
        render_value(&mut content, "linux", &self.linux);

        // Optional commands
        render_single_value(&mut content, "title", &self.title);
        render_single_value(&mut content, "version", &self.version);
        render_single_value(&mut content, "machine-id", &self.machine_id);
        render_single_value(&mut content, "sort-key", &self.sort_key);
        render_single_value(&mut content, "efi", &self.efi);
        render_single_value(&mut content, "devicetree", &self.devicetree);
        render_single_value(&mut content, "devicetree-overlay", &self.devicetree_overlay);
        render_single_value(&mut content, "architecture", &self.architecture);
        render_single_value(&mut content, "grub_hotkey", &self.devicetree_overlay);
        render_single_value(&mut content, "grub_users", &self.devicetree_overlay);
        render_single_value(&mut content, "grub_arg", &self.devicetree_overlay);

        // Commands with multiple values
        render_multiple_values(&mut content, "initrd", &self.initrd);
        render_multiple_values(&mut content, "options", &self.options);
        render_multiple_values(&mut content, "grub_class", &self.grub_class);

        content
    }

    /// Sets a value
    pub fn set(
        &mut self,
        key: &str,
        value: String,
        comment: Option<String>,
        set_policy: ValueSetPolicy,
    ) -> Result<(), String> {
        fn value_generator(value: String, comment: Option<String>) -> BLSValue {
            match comment {
                Some(comment) => BLSValue::ValueWithComment(value, comment),
                None => BLSValue::Value(value),
            }
        }

        fn push_value(values: &mut Vec<BLSValue>, val: BLSValue, policy: ValueSetPolicy) {
            match policy {
                ValueSetPolicy::Append => values.push(val),
                ValueSetPolicy::InsertAt(i) => values.insert(i, val),
                ValueSetPolicy::Prepend => values.insert(0, val),
                ValueSetPolicy::ReplaceAll => {
                    values.clear();
                    values.push(val);
                }
            }
        }

        match key {
            "title" => self.title = Some(value_generator(value, comment)),
            "version" => self.version = Some(value_generator(value, comment)),
            "machine-id" => self.machine_id = Some(value_generator(value, comment)),
            "sort-key" => self.sort_key = Some(value_generator(value, comment)),
            "linux" => self.linux = value_generator(value, comment),
            "efi" => self.efi = Some(value_generator(value, comment)),
            "devicetree" => self.devicetree = Some(value_generator(value, comment)),
            "devicetree-overlay" => self.devicetree_overlay = Some(value_generator(value, comment)),
            "architecture" => self.architecture = Some(value_generator(value, comment)),
            "grub_hotkey" => self.grub_hotkey = Some(value_generator(value, comment)),
            "grub_users" => self.grub_users = Some(value_generator(value, comment)),
            "grub_arg" => self.grub_arg = Some(value_generator(value, comment)),

            "initrd" => push_value(
                &mut self.initrd,
                value_generator(value, comment),
                set_policy,
            ),
            "options" => push_value(
                &mut self.options,
                value_generator(value, comment),
                set_policy,
            ),
            "grub_class" => push_value(
                &mut self.grub_class,
                value_generator(value, comment),
                set_policy,
            ),
            _ => return Err(format!("Invalid key {}", key)),
        }

        Ok(())
    }
}

#[cfg(test)]
mod bls_tests {
    use super::String;

    #[cfg(not(feature = "std"))]
    use alloc::vec;

    use super::BLSEntry;
    use super::BLSValue;
    use super::ValueSetPolicy;

    #[test]
    fn new_entry() {
        let entry = BLSEntry::new();
        match entry.linux {
            BLSValue::Value(linux) => {
                assert_eq!(linux, "");
            }
            _ => {
                panic!("Invalid 'linux' value {:?}", entry.linux);
            }
        }
        assert_eq!(entry.initrd.len(), 0);
    }

    #[test]
    fn parse_entry() {
        let entry_txt = "#Comment\n\
                     linux foobar-2.4\n\
                     options foo=bar #Another Comment";
        let entry = BLSEntry::parse(entry_txt);

        assert!(entry.is_ok());
        let entry = entry.unwrap();
        assert_eq!(entry.comments.len(), 1);
        assert_eq!(entry.comments[0], "Comment");

        if let BLSValue::Value(linux) = entry.linux {
            assert_eq!(linux, "foobar-2.4");
        }

        assert_eq!(entry.options.len(), 1);
        match &entry.options[0] {
            BLSValue::ValueWithComment(option, comment) => {
                assert_eq!(option, "foo=bar");
                assert_eq!(comment, "Another Comment");
            }
            _ => {
                panic!("Invalid 'options' value {:?}", entry.options[0])
            }
        }
    }

    #[test]
    fn parse_errors() {
        // Missing 'linux' command
        let entry_txt = "options foo=bar";
        let entry = BLSEntry::parse(entry_txt);
        assert!(entry.is_err());

        // Invalid command
        let entry_txt = "linux asdasdasdas\n\
                     invalid_command foo=bar";
        let entry = BLSEntry::parse(entry_txt);
        assert!(entry.is_err());
    }

    #[test]
    fn set_value_policies() {
        // Append
        let mut entry = BLSEntry::new();
        let _ = entry.set("options", String::from("foo"), None, ValueSetPolicy::Append);
        let _ = entry.set("options", String::from("bar"), None, ValueSetPolicy::Append);
        let _ = entry.set("options", String::from("baz"), None, ValueSetPolicy::Append);

        assert_eq!(
            entry.options,
            vec![
                BLSValue::Value(String::from("foo")),
                BLSValue::Value(String::from("bar")),
                BLSValue::Value(String::from("baz"))
            ]
        );

        // InsertAt
        let _ = entry.set(
            "options",
            String::from("lol"),
            None,
            ValueSetPolicy::InsertAt(1),
        );
        assert_eq!(
            entry.options,
            vec![
                BLSValue::Value(String::from("foo")),
                BLSValue::Value(String::from("lol")),
                BLSValue::Value(String::from("bar")),
                BLSValue::Value(String::from("baz"))
            ]
        );

        // ReplaceAll
        let _ = entry.set(
            "options",
            String::from("wtf"),
            None,
            ValueSetPolicy::ReplaceAll,
        );
        assert_eq!(entry.options, vec![BLSValue::Value(String::from("wtf"))]);

        // Prepend
        let _ = entry.set(
            "options",
            String::from("uwu"),
            None,
            ValueSetPolicy::Prepend,
        );
        assert_eq!(
            entry.options,
            vec![
                BLSValue::Value(String::from("uwu")),
                BLSValue::Value(String::from("wtf"))
            ]
        );
    }
}