Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 3 additions & 5 deletions nvx/src/host/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use sha2::{Digest, Sha256};

use super::filesystem::{ExportPlan, ReservedTargets};
use super::network::{self, NetworkPolicy};
use super::platform::parse_hex32;
use super::platform::{parse_hex, write_hex};
use super::runtime::{GuestPowerAction, Hypervisor, Runtime};
use crate::error::{Error, Result};
use crate::guest_restore;
Expand Down Expand Up @@ -387,9 +387,7 @@ pub struct CaptureIdentity([u8; 32]);

impl fmt::Display for CaptureIdentity {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0
.iter()
.try_for_each(|byte| write!(formatter, "{byte:02x}"))
write_hex(formatter, &self.0)
}
}

Expand All @@ -408,7 +406,7 @@ impl serde::Serialize for CaptureIdentity {
impl<'de> serde::Deserialize<'de> for CaptureIdentity {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let text = <String as serde::Deserialize>::deserialize(deserializer)?;
parse_hex32(&text).map(Self).ok_or_else(|| {
parse_hex(&text).map(Self).ok_or_else(|| {
serde::de::Error::custom(format!(
"{text:?} is not a capture's identity, which is 64 hexadecimal digits"
))
Expand Down
4 changes: 2 additions & 2 deletions nvx/src/host/platform/linux/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use std::thread;
use std::time::{Duration, Instant};

use super::BOOT_ID_PATH;
use crate::host::platform::{parse_hex_id, parse_host_id, unless_exited};
use crate::host::platform::{parse_hex, parse_host_id, unless_exited};
use crate::host::sys::{self, Errno, PidFd};

/// Returns the start time of a live process, `None` if the process no longer exists, or an error
Expand Down Expand Up @@ -297,7 +297,7 @@ fn pidfds_unavailable(error: &io::Error) -> bool {
pub(crate) fn boot_id() -> io::Result<[u8; 16]> {
let text = fs::read_to_string(BOOT_ID_PATH)?;
let digits = text.trim_end().replace('-', "");
parse_hex_id(&digits).ok_or_else(|| {
parse_hex(&digits).ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidData,
format!("{BOOT_ID_PATH} has an unexpected format"),
Expand Down
31 changes: 12 additions & 19 deletions nvx/src/host/platform/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -323,34 +323,27 @@ pub(crate) fn unless_exited(
if exited()? { Ok(()) } else { Err(error) }
}

/// Parses exactly 32 hexadecimal digits, in either case, into the 16 bytes that they spell.
pub(crate) fn parse_hex_id(digits: &str) -> Option<[u8; 16]> {
let digits = digits.as_bytes();
if digits.len() != 32 {
return None;
}
let mut id = [0; 16];
for (byte, pair) in id.iter_mut().zip(digits.chunks_exact(2)) {
let nibble = |digit: u8| char::from(digit).to_digit(16);
*byte = u8::try_from(nibble(pair[0])? * 16 + nibble(pair[1])?).ok()?;
}
Some(id)
}

/// Parses 64 hexadecimal digits, in either case, into the 32 bytes that they spell.
pub(crate) fn parse_hex32(text: &str) -> Option<[u8; 32]> {
/// Parses exactly `2 * N` hexadecimal digits, in either case, into the `N` bytes that they spell.
pub(crate) fn parse_hex<const N: usize>(text: &str) -> Option<[u8; N]> {
let digits = text.as_bytes();
if digits.len() != 64 {
if digits.len() != 2 * N {
return None;
}
let mut bytes = [0; 32];
let mut bytes = [0; N];
for (byte, pair) in bytes.iter_mut().zip(digits.chunks_exact(2)) {
let nibble = |digit: u8| char::from(digit).to_digit(16);
*byte = u8::try_from(nibble(pair[0])? * 16 + nibble(pair[1])?).ok()?;
}
Some(bytes)
}

/// Writes `bytes` as lowercase hexadecimal digits, two for each byte.
pub(crate) fn write_hex(formatter: &mut fmt::Formatter<'_>, bytes: &[u8]) -> fmt::Result {
bytes
.iter()
.try_for_each(|byte| write!(formatter, "{byte:02x}"))
}

/// Parses the identity of a host as OpenVMM reads it: 32 hexadecimal digits, in either case,
/// between optional braces and surrounding whitespace, ignoring dashes, as in `/etc/machine-id`
/// and the Windows machine GUID.
Expand All @@ -363,7 +356,7 @@ fn parse_host_id(text: &str) -> Option<[u8; 16]> {
.chars()
.filter(|&character| character != '-')
.collect();
parse_hex_id(&digits)
parse_hex(&digits)
}

#[cfg(test)]
Expand Down
33 changes: 33 additions & 0 deletions nvx/src/host/platform/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,39 @@ fn host_identities_are_read_as_openvmm_reads_them() {
}
}

#[test]
fn hexadecimal_text_is_written_in_lowercase_and_read_in_either_case() {
struct Hex<'a>(&'a [u8]);

impl fmt::Display for Hex<'_> {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write_hex(formatter, self.0)
}
}

let bytes = [0x00, 0x0a, 0xb1, 0xff];
assert_eq!(Hex(&bytes).to_string(), "000ab1ff");
assert_eq!(parse_hex::<4>("000ab1ff"), Some(bytes));
assert_eq!(parse_hex::<4>("000AB1FF"), Some(bytes));
// An odd, short, or long length, a digit beyond `f`, a sign, and a non-ASCII byte.
for text in [
"000ab1f",
"000ab1",
"000ab1ff00",
"000ab1fg",
"+00ab1ff",
"000ab1\u{e9}",
"",
] {
assert_eq!(parse_hex::<4>(text), None, "{text:?}");
}
// The lengths of the host's identities: 32 digits for 16 bytes, 64 for 32.
assert_eq!(parse_hex::<16>(&"Ab".repeat(16)), Some([0xab; 16]));
assert_eq!(parse_hex::<16>(&"ab".repeat(32)), None);
assert_eq!(parse_hex::<32>(&"cD".repeat(32)), Some([0xcd; 32]));
assert_eq!(parse_hex::<32>(&"cd".repeat(16)), None);
}

#[cfg(any(target_os = "linux", windows))]
#[test]
fn the_hosts_identity_and_monotonic_time_are_read() {
Expand Down
6 changes: 2 additions & 4 deletions nvx/src/host/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,9 +93,7 @@ impl BootId {

impl fmt::Display for BootId {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0
.iter()
.try_for_each(|byte| write!(formatter, "{byte:02x}"))
platform::write_hex(formatter, &self.0)
}
}

Expand All @@ -111,7 +109,7 @@ impl FromStr for BootId {
/// Parses the text form of a boot identity, failing with
/// [`ErrorKind::Io`](crate::ErrorKind::Io) for anything other than 32 hexadecimal digits.
fn from_str(text: &str) -> crate::Result<Self> {
platform::parse_hex_id(text).map(Self).ok_or_else(|| {
platform::parse_hex(text).map(Self).ok_or_else(|| {
Error::io(format!(
"{text:?} is not a boot identity, which is 32 hexadecimal digits"
))
Expand Down
11 changes: 2 additions & 9 deletions nvx/src/host/snapshot/key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use super::manifest::{
use crate::error::{Error, Result};
use crate::guest_restore;
use crate::host::config::{DiskCapture, check_setting};
use crate::host::platform::parse_hex32;
use crate::host::platform::{parse_hex, write_hex};
use crate::host::process::BootId;
use crate::host::runtime::{
ArtifactIdentity, CompatibilityIdentity, Hypervisor, MAX_IDENTITY_LEN, RuntimeIdentity,
Expand Down Expand Up @@ -134,13 +134,6 @@ fn digest(domain: &[u8], bytes: &[u8]) -> [u8; 32] {
digest.finalize().into()
}

/// Writes `bytes` as lowercase hexadecimal digits.
fn write_hex(formatter: &mut fmt::Formatter<'_>, bytes: &[u8]) -> fmt::Result {
bytes
.iter()
.try_for_each(|byte| write!(formatter, "{byte:02x}"))
}

/// Declares a 32-byte identity: the domain-separated SHA-256 digest of a canonical encoding.
macro_rules! identity {
($(#[$attribute:meta])* $name:ident, $what:literal) => {
Expand Down Expand Up @@ -178,7 +171,7 @@ macro_rules! identity {
/// Parses the text form of the identity, 64 hexadecimal digits, failing with
/// [`ErrorKind::Unsupported`](crate::ErrorKind::Unsupported) for anything else.
fn from_str(text: &str) -> Result<Self> {
parse_hex32(text).map(Self).ok_or_else(|| {
parse_hex(text).map(Self).ok_or_else(|| {
Error::unsupported(format!(
concat!("{:?} is not ", $what, ", which is 64 hexadecimal digits"),
text
Expand Down
Loading