|
| 1 | +use std::borrow::Cow; |
| 2 | + |
1 | 3 | use anyhow::Result; |
2 | | -use fn_error_context::context; |
3 | 4 |
|
4 | 5 | /// This is used by dracut. |
5 | | -pub(crate) const INITRD_ARG_PREFIX: &str = "rd."; |
| 6 | +pub(crate) const INITRD_ARG_PREFIX: &[u8] = b"rd."; |
6 | 7 | /// The kernel argument for configuring the rootfs flags. |
7 | | -pub(crate) const ROOTFLAGS: &str = "rootflags="; |
8 | | - |
9 | | -/// Parse the kernel command line. This is strictly |
10 | | -/// speaking not a correct parser, as the Linux kernel |
11 | | -/// supports quotes. However, we don't yet need that here. |
12 | | -/// |
13 | | -/// See systemd's code for one userspace parser. |
14 | | -#[context("Reading /proc/cmdline")] |
15 | | -pub(crate) fn parse_cmdline() -> Result<Vec<String>> { |
16 | | - let cmdline = std::fs::read_to_string("/proc/cmdline")?; |
17 | | - let r = cmdline |
18 | | - .split_ascii_whitespace() |
19 | | - .map(ToOwned::to_owned) |
20 | | - .collect(); |
21 | | - Ok(r) |
22 | | -} |
23 | | - |
24 | | -/// Return the value for the string in the vector which has the form target_key=value |
25 | | -pub(crate) fn find_first_cmdline_arg<'a>( |
26 | | - args: impl Iterator<Item = &'a str>, |
27 | | - target_key: &str, |
28 | | -) -> Option<&'a str> { |
29 | | - args.filter_map(|arg| { |
30 | | - if let Some((k, v)) = arg.split_once('=') { |
31 | | - if target_key == k { |
32 | | - return Some(v); |
| 8 | +pub(crate) const ROOTFLAGS: &[u8] = b"rootflags"; |
| 9 | + |
| 10 | +const DASH: u8 = 0x2d; |
| 11 | +const UNDERSCORE: u8 = 0x5f; |
| 12 | +const DOUBLE_QUOTE: u8 = 0x22; |
| 13 | +const EQUALS: u8 = 0x3d; |
| 14 | + |
| 15 | +pub(crate) struct Cmdline<'a>(Cow<'a, [u8]>); |
| 16 | + |
| 17 | +impl<'a, T: AsRef<[u8]> + ?Sized> From<&'a T> for Cmdline<'a> { |
| 18 | + fn from(input: &'a T) -> Self { |
| 19 | + Self(Cow::Borrowed(input.as_ref())) |
| 20 | + } |
| 21 | +} |
| 22 | + |
| 23 | +impl<'a> Cmdline<'a> { |
| 24 | + pub fn from_proc() -> Result<Self> { |
| 25 | + Ok(Self(Cow::Owned(std::fs::read("/proc/cmdline")?))) |
| 26 | + } |
| 27 | + |
| 28 | + pub fn iter(&'a self) -> impl Iterator<Item = Parameter<'a>> { |
| 29 | + let mut in_quotes = false; |
| 30 | + |
| 31 | + self.0 |
| 32 | + .split(move |c| { |
| 33 | + if *c == DOUBLE_QUOTE { |
| 34 | + in_quotes = !in_quotes; |
| 35 | + } |
| 36 | + !in_quotes && c.is_ascii_whitespace() |
| 37 | + }) |
| 38 | + .map(Parameter::from) |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +#[derive(Debug, Eq)] |
| 43 | +pub(crate) struct Parameter<'a> { |
| 44 | + pub key: &'a [u8], |
| 45 | + pub value: Option<&'a [u8]>, |
| 46 | +} |
| 47 | + |
| 48 | +impl<'a> Parameter<'a> { |
| 49 | + pub fn key_lossy(&self) -> String { |
| 50 | + String::from_utf8_lossy(self.key).to_string() |
| 51 | + } |
| 52 | + |
| 53 | + pub fn value_lossy(&self) -> String { |
| 54 | + if let Some(v) = self.value { |
| 55 | + String::from_utf8_lossy(v).to_string() |
| 56 | + } else { |
| 57 | + String::from("") |
| 58 | + } |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +impl<'a, T: AsRef<[u8]> + ?Sized> From<&'a T> for Parameter<'a> { |
| 63 | + fn from(input: &'a T) -> Self { |
| 64 | + let input = input.as_ref(); |
| 65 | + let equals = input.iter().position(|b| *b == EQUALS); |
| 66 | + |
| 67 | + match equals { |
| 68 | + None => Self { |
| 69 | + key: input, |
| 70 | + value: None, |
| 71 | + }, |
| 72 | + Some(i) => { |
| 73 | + let (key, mut value) = input.split_at(i); |
| 74 | + |
| 75 | + // skip `=`, we know it's the first byte because we |
| 76 | + // found it above |
| 77 | + value = &value[1..]; |
| 78 | + |
| 79 | + // *Only* the first and last double quotes are stripped |
| 80 | + if let Some(&DOUBLE_QUOTE) = value.first() { |
| 81 | + value = &value[1..]; |
| 82 | + } |
| 83 | + if let Some(&DOUBLE_QUOTE) = value.last() { |
| 84 | + value = &value[..value.len() - 1]; |
| 85 | + } |
| 86 | + |
| 87 | + Self { |
| 88 | + key, |
| 89 | + value: Some(value), |
| 90 | + } |
| 91 | + } |
| 92 | + } |
| 93 | + } |
| 94 | +} |
| 95 | + |
| 96 | +impl PartialEq for Parameter<'_> { |
| 97 | + fn eq(&self, other: &Self) -> bool { |
| 98 | + let dedashed = |&c: &u8| { |
| 99 | + if c == DASH { |
| 100 | + UNDERSCORE |
| 101 | + } else { |
| 102 | + c |
33 | 103 | } |
| 104 | + }; |
| 105 | + |
| 106 | + // We can't just zip() because leading substrings will match |
| 107 | + // |
| 108 | + // For example, "foo" == "foobar" since the zipped iterator |
| 109 | + // only compares the first three chars. |
| 110 | + let our_iter = self.key.iter().map(dedashed); |
| 111 | + let other_iter = other.key.iter().map(dedashed); |
| 112 | + if !our_iter.eq(other_iter) { |
| 113 | + return false; |
| 114 | + } |
| 115 | + |
| 116 | + match (self.value, other.value) { |
| 117 | + (Some(ours), Some(other)) => ours == other, |
| 118 | + (None, None) => true, |
| 119 | + _ => false, |
34 | 120 | } |
35 | | - None |
36 | | - }) |
37 | | - .next() |
| 121 | + } |
| 122 | +} |
| 123 | + |
| 124 | +impl std::fmt::Display for Parameter<'_> { |
| 125 | + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { |
| 126 | + let key = self.key_lossy(); |
| 127 | + |
| 128 | + if self.value.is_some() { |
| 129 | + let value = self.value_lossy(); |
| 130 | + |
| 131 | + if value.chars().any(|c| c.is_ascii_whitespace()) { |
| 132 | + write!(f, "{key}=\"{value}\"") |
| 133 | + } else { |
| 134 | + write!(f, "{key}={value}") |
| 135 | + } |
| 136 | + } else { |
| 137 | + write!(f, "{key}") |
| 138 | + } |
| 139 | + } |
38 | 140 | } |
39 | 141 |
|
40 | 142 | #[cfg(test)] |
41 | 143 | mod tests { |
42 | 144 | use super::*; |
43 | 145 |
|
44 | 146 | #[test] |
45 | | - fn test_find_first() { |
46 | | - let kargs = &["foo=bar", "root=/dev/vda", "blah", "root=/dev/other"]; |
47 | | - let kargs = || kargs.iter().copied(); |
48 | | - assert_eq!(find_first_cmdline_arg(kargs(), "root"), Some("/dev/vda")); |
49 | | - assert_eq!(find_first_cmdline_arg(kargs(), "nonexistent"), None); |
| 147 | + fn test_constants() { |
| 148 | + assert_eq!(DASH, u8::try_from('-').unwrap()); |
| 149 | + assert_eq!(UNDERSCORE, u8::try_from('_').unwrap()); |
| 150 | + assert_eq!(DOUBLE_QUOTE, u8::try_from('"').unwrap()); |
| 151 | + assert_eq!(EQUALS, u8::try_from('=').unwrap()); |
| 152 | + } |
| 153 | + |
| 154 | + #[test] |
| 155 | + fn test_parameter_simple() { |
| 156 | + let switch = Parameter::from("foo"); |
| 157 | + assert_eq!(switch.key, b"foo"); |
| 158 | + assert_eq!(switch.value, None); |
| 159 | + |
| 160 | + let kv = Parameter::from("bar=baz"); |
| 161 | + assert_eq!(kv.key, b"bar"); |
| 162 | + assert_eq!(kv.value, Some(b"baz".as_slice())); |
| 163 | + } |
| 164 | + |
| 165 | + #[test] |
| 166 | + fn test_parameter_quoted() { |
| 167 | + let p = Parameter::from("foo=\"quoted value\""); |
| 168 | + assert_eq!(p.value, Some(b"quoted value".as_slice())); |
| 169 | + } |
| 170 | + |
| 171 | + #[test] |
| 172 | + fn test_parameter_pathological() { |
| 173 | + // valid things that certified insane people would do |
| 174 | + |
| 175 | + // quotes don't get removed from keys |
| 176 | + let p = Parameter::from("\"\"\""); |
| 177 | + assert_eq!(p.key, b"\"\"\""); |
| 178 | + |
| 179 | + // quotes only get stripped from the absolute ends of values |
| 180 | + let p = Parameter::from("foo=\"internal \" quotes \" are ok\""); |
| 181 | + assert_eq!(p.value, Some(b"internal \" quotes \" are ok".as_slice())); |
| 182 | + |
| 183 | + // non-UTF8 things are in fact valid |
| 184 | + let non_utf8_byte = b"\xff"; |
| 185 | + #[allow(invalid_from_utf8)] |
| 186 | + let failed_conversion = str::from_utf8(non_utf8_byte); |
| 187 | + assert!(failed_conversion.is_err()); |
| 188 | + let mut p = b"foo=".to_vec(); |
| 189 | + p.push(non_utf8_byte[0]); |
| 190 | + let p = Parameter::from(&p); |
| 191 | + assert_eq!(p.value, Some(non_utf8_byte.as_slice())); |
| 192 | + |
| 193 | + // lossy replacement sanity check |
| 194 | + assert_eq!(p.value_lossy(), char::REPLACEMENT_CHARACTER.to_string()); |
| 195 | + } |
| 196 | + |
| 197 | + #[test] |
| 198 | + fn test_parameter_equality() { |
| 199 | + // substrings are not equal |
| 200 | + let foo = Parameter::from("foo"); |
| 201 | + let bar = Parameter::from("foobar"); |
| 202 | + assert_ne!(foo, bar); |
| 203 | + assert_ne!(bar, foo); |
| 204 | + |
| 205 | + // dashes and underscores are treated equally |
| 206 | + let dashes = Parameter::from("a-delimited-param"); |
| 207 | + let underscores = Parameter::from("a_delimited_param"); |
| 208 | + assert_eq!(dashes, underscores); |
| 209 | + |
| 210 | + // same key, same values is equal |
| 211 | + let dashes = Parameter::from("a-delimited-param=same_values"); |
| 212 | + let underscores = Parameter::from("a_delimited_param=same_values"); |
| 213 | + assert_eq!(dashes, underscores); |
| 214 | + |
| 215 | + // same key, different values is not equal |
| 216 | + let dashes = Parameter::from("a-delimited-param=different_values"); |
| 217 | + let underscores = Parameter::from("a_delimited_param=DiFfErEnT_valUEZ"); |
| 218 | + assert_ne!(dashes, underscores); |
| 219 | + |
| 220 | + // mixed variants are never equal |
| 221 | + let switch = Parameter::from("same_key"); |
| 222 | + let keyvalue = Parameter::from("same_key=but_with_a_value"); |
| 223 | + assert_ne!(switch, keyvalue); |
| 224 | + } |
| 225 | + |
| 226 | + #[test] |
| 227 | + fn test_kargs_simple() { |
| 228 | + // example taken lovingly from: |
| 229 | + // https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/kernel/params.c?id=89748acdf226fd1a8775ff6fa2703f8412b286c8#n160 |
| 230 | + let kargs = Cmdline::from(b"foo=bar,bar2 baz=fuz wiz".as_slice()); |
| 231 | + let mut iter = kargs.iter(); |
| 232 | + |
| 233 | + assert_eq!( |
| 234 | + iter.next(), |
| 235 | + Some(Parameter { |
| 236 | + key: b"foo", |
| 237 | + value: Some(b"bar,bar2".as_slice()) |
| 238 | + }) |
| 239 | + ); |
| 240 | + |
| 241 | + assert_eq!( |
| 242 | + iter.next(), |
| 243 | + Some(Parameter { |
| 244 | + key: b"baz", |
| 245 | + value: Some(b"fuz".as_slice()) |
| 246 | + }) |
| 247 | + ); |
| 248 | + |
| 249 | + assert_eq!( |
| 250 | + iter.next(), |
| 251 | + Some(Parameter { |
| 252 | + key: b"wiz", |
| 253 | + value: None, |
| 254 | + }) |
| 255 | + ); |
| 256 | + |
| 257 | + assert_eq!(iter.next(), None); |
| 258 | + } |
| 259 | + |
| 260 | + #[test] |
| 261 | + fn test_kargs_from_proc() { |
| 262 | + let kargs = Cmdline::from_proc().unwrap(); |
| 263 | + |
| 264 | + // Not really a good way to test this other than assume |
| 265 | + // there's at least one argument in /proc/cmdline wherever the |
| 266 | + // tests are running |
| 267 | + assert!(kargs.iter().count() > 0); |
50 | 268 | } |
51 | 269 | } |
0 commit comments