|
10 | 10 |
|
11 | 11 | use super::cmdline; |
12 | 12 | use super::{ProtocolError, violation}; |
13 | | -use crate::hex::hex; |
| 13 | +use crate::hex::{hex, parse_hex}; |
14 | 14 |
|
15 | 15 | /// The longest hostname, in bytes: Linux's `HOST_NAME_MAX`, which the guest's entry applies. |
16 | 16 | pub const MAX_HOSTNAME_BYTES: usize = 64; |
@@ -121,29 +121,24 @@ pub fn parse(command_line: &[u8]) -> Result<Option<View>, ProtocolError> { |
121 | 121 |
|
122 | 122 | /// Decodes a bounded, canonical hostname value, refusing a decoded NUL. |
123 | 123 | fn parse_hostname(value: &[u8]) -> Result<Vec<u8>, ProtocolError> { |
| 124 | + let malformed = || { |
| 125 | + violation(format!( |
| 126 | + "the nvx_hostname kernel parameter must encode 1 to {MAX_HOSTNAME_BYTES} bytes \ |
| 127 | + as lowercase hexadecimal" |
| 128 | + )) |
| 129 | + }; |
| 130 | + // `parse_hex` reads either case, and the token is lowercase. |
124 | 131 | if value.is_empty() |
125 | 132 | || value.len() > 2 * MAX_HOSTNAME_BYTES |
126 | | - || !value.len().is_multiple_of(2) |
127 | | - || !value |
128 | | - .iter() |
129 | | - .all(|byte| byte.is_ascii_digit() || matches!(byte, b'a'..=b'f')) |
| 133 | + || value.iter().any(u8::is_ascii_uppercase) |
130 | 134 | { |
131 | | - return Err(violation(format!( |
132 | | - "the nvx_hostname kernel parameter must encode 1 to {MAX_HOSTNAME_BYTES} bytes \ |
133 | | - as lowercase hexadecimal" |
134 | | - ))); |
| 135 | + return Err(malformed()); |
135 | 136 | } |
136 | | - let digit = |byte: u8| { |
137 | | - if byte.is_ascii_digit() { |
138 | | - byte - b'0' |
139 | | - } else { |
140 | | - byte - b'a' + 10 |
141 | | - } |
142 | | - }; |
143 | 137 | let hostname: Vec<u8> = value |
144 | | - .chunks_exact(2) |
145 | | - .map(|pair| digit(pair[0]) * 16 + digit(pair[1])) |
146 | | - .collect(); |
| 138 | + .chunks(2) |
| 139 | + .map(|pair| parse_hex::<1>(pair).map(|[byte]| byte)) |
| 140 | + .collect::<Option<_>>() |
| 141 | + .ok_or_else(malformed)?; |
147 | 142 | if !is_hostname(&hostname) { |
148 | 143 | return Err(violation("the nvx_hostname kernel parameter encodes a NUL")); |
149 | 144 | } |
|
0 commit comments