use std::path::Path;
use serde::Deserialize;
use serde::Serialize;
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub struct HostFileIdentity {
pub dev: u64,
pub ino: u64,
pub size: i64,
pub mtime_sec: i64,
pub mtime_nsec: i64,
#[serde(default, rename = "snapshot_content")]
pub content: Option<u64>,
}
impl HostFileIdentity {
pub fn from_stat(stat: &libc::stat) -> Self {
Self {
dev: stat.st_dev,
ino: stat.st_ino,
size: stat.st_size,
mtime_sec: stat.st_mtime,
mtime_nsec: stat.st_mtime_nsec,
content: None,
}
}
pub fn of_snapshot(size: i64, content: u64) -> Self {
Self {
dev: 0,
ino: 0,
size,
mtime_sec: 0,
mtime_nsec: 0,
content: Some(content),
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct HostInputSnapshot {
pub physical: HostFileIdentity,
pub origin: HostFileIdentity,
pub content: String,
}
impl std::fmt::Display for HostFileIdentity {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if let Some(content) = self.content {
return write!(f, "snapshot size {} content {:016x}", self.size, content);
}
write!(
f,
"dev:ino {}:{}:{} size {} mtime {}.{:09}",
libc::major(self.dev),
libc::minor(self.dev),
self.ino,
self.size,
self.mtime_sec,
self.mtime_nsec
)
}
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct HostInputRecord {
pub path: String,
pub dtid: u64,
pub syscall: u64,
#[serde(flatten)]
pub identity: HostFileIdentity,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub content: Option<String>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub exec: bool,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub kernel_object: bool,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct HostMutationRecord {
pub mutated: String,
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct HostInputLogEnd {
pub records: u64,
}
#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct HostInput {
pub path: String,
#[serde(flatten)]
pub identity: HostFileIdentity,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub content: Option<String>,
}
pub const HOST_INPUT_CONTENT_LIMIT: u64 = 32 << 20;
pub fn host_input_changed(recorded: &HostInput, now: &HostInput) -> bool {
match (&recorded.content, &now.content) {
(Some(recorded), Some(now)) => recorded != now,
_ => recorded.identity != now.identity,
}
}
#[derive(Clone, Debug, Default, Deserialize, Eq, Hash, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct HostInputSet {
pub digest: String,
pub files: Vec<HostInput>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub stdio: Option<StdioKinds>,
}
impl HostInputSet {
pub fn file(&self, path: &str) -> Option<&HostInput> {
self.files
.binary_search_by(|file| file.path.as_str().cmp(path))
.ok()
.map(|index| &self.files[index])
}
pub fn normalized(mut self) -> Self {
self.files.sort_by(|a, b| a.path.cmp(&b.path));
self.files
.dedup_by(|later, earlier| later.path == earlier.path);
self
}
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct HostInputChange {
pub path: String,
pub recorded: HostFileIdentity,
pub now: HostFileIdentity,
}
impl std::fmt::Display for HostInputChange {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"host input {} changed since the recording ({} then, {} now); the run may diverge where the guest reads it",
self.path, self.recorded, self.now
)
}
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum StdioKind {
File,
Pipe,
Socket,
Tty,
CharDevice,
BlockDevice,
Directory,
Closed,
Other,
Unknown,
}
pub const LOCAL_KERNEL_FILESYSTEMS: [&str; 11] = [
"ext2", "ext3", "ext4", "xfs", "btrfs", "tmpfs", "ramfs", "devtmpfs", "devpts", "proc", "sysfs",
];
pub fn mount_types(mountinfo: &str) -> Vec<(u64, String)> {
mountinfo
.lines()
.filter_map(|line| {
let mut fields = line.split_whitespace();
let id = fields.next()?.parse::<u64>().ok()?;
let fstype = fields.skip_while(|field| *field != "-").nth(1)?;
Some((id, fstype.to_owned()))
})
.collect()
}
#[derive(Clone, Default, Eq, PartialEq)]
pub struct LaunchNamespaceMounts(pub Vec<(u64, String)>);
impl std::fmt::Debug for LaunchNamespaceMounts {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("LaunchNamespaceMounts")
.field("mounts", &self.0.len())
.finish()
}
}
pub fn maps_name_image(maps: &str, exe: &[u8], ino: u64) -> bool {
ino != 0
&& maps.lines().any(|line| {
let mut rest = line;
let mut fields = Vec::with_capacity(5);
for _ in 0..5 {
rest = rest.trim_start();
let end = rest.find(char::is_whitespace).unwrap_or(rest.len());
fields.push(&rest[..end]);
rest = &rest[end..];
}
fields[4].parse::<u64>().is_ok_and(|inode| inode == ino)
&& rest.trim_start().as_bytes() == exe
})
}
impl StdioKind {
pub fn from_mode(mode: libc::mode_t, terminal: bool) -> Self {
match mode & libc::S_IFMT {
libc::S_IFREG => Self::File,
libc::S_IFIFO => Self::Pipe,
libc::S_IFSOCK => Self::Socket,
libc::S_IFCHR if terminal => Self::Tty,
libc::S_IFCHR => Self::CharDevice,
libc::S_IFBLK => Self::BlockDevice,
libc::S_IFDIR => Self::Directory,
_ => Self::Other,
}
}
pub fn is_terminal_device(rdev: u64, drivers: &str) -> bool {
let major = ((rdev >> 8) & 0xfff) | ((rdev >> 32) & !0xfff);
let minor = (rdev & 0xff) | ((rdev >> 12) & !0xff);
drivers.lines().any(|line| {
let mut fields = line.split_whitespace().rev();
let (Some(_kind), Some(minors), Some(driver_major)) =
(fields.next(), fields.next(), fields.next())
else {
return false;
};
let (first, last) = minors.split_once('-').unwrap_or((minors, minors));
driver_major.parse() == Ok(major)
&& first.parse().is_ok_and(|first: u64| first <= minor)
&& last.parse().is_ok_and(|last: u64| minor <= last)
})
}
pub fn of_guest_descriptor(
link: &[u8],
fdinfo: Option<&str>,
mounts: &[(u64, String)],
drivers: Option<&str>,
stat: impl FnOnce() -> Option<(libc::mode_t, u64)>,
) -> Self {
if !link.starts_with(b"/") {
return if link.starts_with(b"pipe:[") {
Self::Pipe
} else if link.starts_with(b"socket:[") {
Self::Socket
} else {
Self::Other
};
}
let local = fdinfo.is_some_and(|fdinfo| {
let Some(mount) = fdinfo
.lines()
.find_map(|line| line.strip_prefix("mnt_id:"))
.and_then(|id| id.trim().parse::<u64>().ok())
else {
return false;
};
mounts.iter().any(|(id, fstype)| {
*id == mount && LOCAL_KERNEL_FILESYSTEMS.contains(&fstype.as_str())
})
});
if !local {
return Self::Unknown;
}
let Some((mode, rdev)) = stat() else {
return Self::Unknown;
};
if mode & libc::S_IFMT == libc::S_IFCHR {
return match drivers {
Some(drivers) => Self::from_mode(mode, Self::is_terminal_device(rdev, drivers)),
None => Self::Unknown,
};
}
Self::from_mode(mode, false)
}
fn describe(self) -> &'static str {
match self {
Self::File => "a regular file",
Self::Pipe => "a pipe",
Self::Socket => "a socket",
Self::Tty => "a terminal",
Self::CharDevice => "a character device",
Self::BlockDevice => "a block device",
Self::Directory => "a directory",
Self::Closed => "closed",
Self::Other => "a file of another kind (such as an anonymous inode)",
Self::Unknown => "of a kind not read",
}
}
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct StdioKinds {
pub stdin: StdioKind,
pub stdout: StdioKind,
pub stderr: StdioKind,
}
impl StdioKinds {
pub fn changes(recorded: &Self, now: &Self) -> Vec<StdioChange> {
[
(0, recorded.stdin, now.stdin),
(1, recorded.stdout, now.stdout),
(2, recorded.stderr, now.stderr),
]
.into_iter()
.filter(|(_, recorded, now)| {
recorded != now && *recorded != StdioKind::Unknown && *now != StdioKind::Unknown
})
.map(|(fd, recorded, now)| StdioChange { fd, recorded, now })
.collect()
}
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct StdioChange {
pub fd: u8,
pub recorded: StdioKind,
pub now: StdioKind,
}
impl std::fmt::Display for StdioChange {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let name = match self.fd {
0 => "stdin",
1 => "stdout",
_ => "stderr",
};
write!(
f,
"{name} (fd {}) was {} in the recording and is {} now; the run may diverge where the guest checks it (fstat, isatty, fsync, lseek)",
self.fd,
self.recorded.describe(),
self.now.describe()
)
}
}
pub const HOST_INPUT_CHANGED_SINCE_RECORDING_MARKER: &str =
"HERMIT_HOST_INPUT_CHANGED_SINCE_RECORDING";
pub fn is_kernel_object(path: &str) -> bool {
["/proc", "/sys", "/dev"].iter().any(|root| {
path == *root
|| path
.strip_prefix(root)
.is_some_and(|rest| rest.starts_with('/'))
})
}
pub fn guest_rebound<'a>(mutated: impl IntoIterator<Item = &'a String>, path: &str) -> bool {
let path = Path::new(path);
!path.is_absolute()
|| mutated
.into_iter()
.any(|rebound| path.starts_with(Path::new(rebound)))
}
#[cfg(test)]
mod tests {
use super::*;
fn identity(ino: u64, size: i64) -> HostFileIdentity {
HostFileIdentity {
dev: 33,
ino,
size,
mtime_sec: 1_700_000_000,
mtime_nsec: 5,
content: None,
}
}
fn set(files: &[(&str, HostFileIdentity)]) -> HostInputSet {
HostInputSet {
stdio: None,
digest: String::new(),
files: files
.iter()
.map(|(path, identity)| HostInput {
path: (*path).to_owned(),
identity: *identity,
content: None,
})
.collect(),
}
}
#[test]
fn a_guest_descriptor_is_statted_only_on_a_local_kernel_filesystem() {
let guest_mounts = "\
22 1 0:21 / /proc rw,nosuid shared:5 - proc proc rw
23 29 0:5 / /dev rw,nosuid shared:2 - devtmpfs devtmpfs rw,size=4096k
24 23 0:22 / /dev/pts rw,nosuid,noexec shared:3 - devpts devpts rw,gid=5,mode=620
40 29 0:45 / /mnt/remote rw,nosuid,nodev shared:30 - fuse.sshfs host:/ rw,user_id=0
41 29 0:46 / /mnt/plain rw - fuse fuse rw
42 29 8:1 / /mnt/disk rw - fuseblk /dev/sda1 rw
43 29 0:47 / /mnt/nfs rw shared:31 - nfs4 server:/export rw,vers=4.2
44 29 0:48 / /mnt/smb rw - cifs //server/share rw
45 29 0:49 / /mnt/9p rw - 9p hostshare rw,trans=virtio
46 29 0:50 / / rw - overlay overlay rw,lowerdir=/l,upperdir=/u,workdir=/w
47 29 0:51 / /mnt/ceph rw - ceph mon:/ rw
48 29 0:52 / /sys/fs/fuse/connections rw - fusectl fusectl rw
49 29 0:53 / /dev/shm rw - tmpfs tmpfs rw
";
let host_mounts = "29 1 8:2 / / rw,relatime shared:1 - ext4 /dev/sda2 rw\n";
let mut mounts = mount_types(guest_mounts);
mounts.extend(mount_types(host_mounts));
assert_eq!(mounts.len(), 14);
assert!(mounts.contains(&(46, "overlay".to_owned())));
let fdinfo = |id: u64| format!("pos:\t0\nflags:\t0100002\nmnt_id:\t{id}\nino:\t5\n");
let no_stat =
|| -> Option<(libc::mode_t, u64)> { panic!("stat'ed a file it must not reach") };
let classify = |link: &str, fdinfo: Option<&str>| {
StdioKind::of_guest_descriptor(link.as_bytes(), fdinfo, &mounts, None, no_stat)
};
for (link, kind) in [
("pipe:[1234]", StdioKind::Pipe),
("socket:[99]", StdioKind::Socket),
("anon_inode:[eventfd]", StdioKind::Other),
("net:[4026531840]", StdioKind::Other),
] {
assert_eq!(classify(link, None), kind, "{link}");
}
for (link, mount) in [
("/dev/null", 46),
("/dev/pts/3", 46),
("/dev/console", 46),
("/mnt/remote/out.log", 40),
] {
assert_eq!(
classify(link, Some(&fdinfo(mount))),
StdioKind::Unknown,
"{link}"
);
}
for id in 40..=48 {
assert_eq!(
classify("/mnt/remote/out.log", Some(&fdinfo(id))),
StdioKind::Unknown,
"mount {id}"
);
}
let pty = (136 << 8) | 3;
let null = (1 << 8) | 3;
let drivers = "pty_slave /dev/pts 136 0-1048575 pty:slave\n";
let stat_once =
|link: &str, mount: u64, mode: libc::mode_t, rdev: u64, drivers: Option<&str>| {
let mut stats = 0;
let kind = StdioKind::of_guest_descriptor(
link.as_bytes(),
Some(&fdinfo(mount)),
&mounts,
drivers,
|| {
stats += 1;
Some((mode, rdev))
},
);
assert_eq!(stats, 1, "{link}");
kind
};
let file = libc::S_IFREG | 0o644;
let chr = libc::S_IFCHR | 0o666;
for (link, mount, mode, rdev, kind) in [
("/home/user/out.log", 29, file, 0, StdioKind::File),
("/dev/shm/out", 49, file, 0, StdioKind::File),
("/home/user/fifo", 29, libc::S_IFIFO, 0, StdioKind::Pipe),
("/dev/null", 23, chr, null, StdioKind::CharDevice),
("/dev/pts/3", 24, chr, pty, StdioKind::Tty),
("/dev/null", 29, file, 0, StdioKind::File),
("/dev/pts/3", 49, file, 0, StdioKind::File),
("/home/user/tty", 29, chr, pty, StdioKind::Tty),
] {
assert_eq!(
stat_once(link, mount, mode, rdev, Some(drivers)),
kind,
"{link} on {mount}"
);
}
assert_eq!(
stat_once("/dev/pts/3", 24, chr, pty, None),
StdioKind::Unknown
);
assert_eq!(
stat_once("/dev/null", 23, chr, null, None),
StdioKind::Unknown
);
assert_eq!(classify("/home/user/out.log", None), StdioKind::Unknown);
assert_eq!(
classify("/memfd:input (deleted)", Some(&fdinfo(7))),
StdioKind::Unknown
);
assert_eq!(
StdioKind::of_guest_descriptor(b"/x", Some(&fdinfo(29)), &mounts, None, || None),
StdioKind::Unknown
);
}
#[test]
fn an_unknown_stdio_kind_is_never_compared() {
let read = StdioKinds {
stdin: StdioKind::CharDevice,
stdout: StdioKind::File,
stderr: StdioKind::Other,
};
let unread = StdioKinds {
stdin: StdioKind::Unknown,
stdout: StdioKind::Unknown,
stderr: StdioKind::Unknown,
};
assert!(StdioKinds::changes(&read, &unread).is_empty());
assert!(StdioKinds::changes(&unread, &read).is_empty());
assert!(StdioKinds::changes(&unread, &unread).is_empty());
let now = StdioKinds {
stdin: StdioKind::Unknown,
stdout: StdioKind::Pipe,
stderr: StdioKind::File,
};
assert_eq!(
StdioKinds::changes(&read, &now),
vec![
StdioChange {
fd: 1,
recorded: StdioKind::File,
now: StdioKind::Pipe,
},
StdioChange {
fd: 2,
recorded: StdioKind::Other,
now: StdioKind::File,
},
]
);
assert_eq!(
serde_json::to_string(&StdioKind::Unknown).unwrap(),
"\"unknown\""
);
assert_eq!(
serde_json::from_str::<StdioKind>("\"other\"").unwrap(),
StdioKind::Other
);
}
#[test]
fn the_root_is_known_by_its_mapped_image() {
let maps = "\
55d0c8a00000-55d0c8a02000 r--p 00000000 00:2a 100483 /usr/bin/echo
55d0c8a02000-55d0c8a06000 r-xp 00002000 00:2a 100483 /usr/bin/echo
7f1e2c000000-7f1e2c022000 r--p 00000000 00:2a 160034633 /usr/lib64/ld-linux-x86-64.so.2
7ffc1a000000-7ffc1a021000 rw-p 00000000 00:00 0 [stack]
7f1e2d000000-7f1e2d001000 r-xp 00000000 00:2a 77 /opt/my tools/run me (deleted)
";
assert!(maps_name_image(maps, b"/usr/bin/echo", 100483));
assert!(!maps_name_image(maps, b"/usr/bin/echo", 100484));
assert!(!maps_name_image(maps, b"/usr/bin/true", 100483));
assert!(maps_name_image(maps, b"/opt/my tools/run me (deleted)", 77));
assert!(!maps_name_image(maps, b"[stack]", 0));
assert!(!maps_name_image("", b"/usr/bin/echo", 100483));
}
#[test]
fn terminal_devices_follow_the_kernels_driver_list() {
let drivers = "\
/dev/tty /dev/tty 5 0 system:/dev/tty
/dev/console /dev/console 5 1 system:console
/dev/vc/0 /dev/vc/0 4 0 system:vtmaster
serial /dev/ttyS 4 64-95 serial
pty_slave /dev/pts 136 0-1048575 pty:slave
";
let device = |major: u64, minor: u64| {
((major & 0xfff) << 8)
| ((major & !0xfff) << 32)
| (minor & 0xff)
| ((minor & !0xff) << 12)
};
for (major, minor, terminal) in [
(136, 3, true),
(136, 1_000_000, true),
(4, 64, true),
(4, 95, true),
(4, 96, false),
(5, 1, true),
(1, 3, false),
] {
assert_eq!(
StdioKind::is_terminal_device(device(major, minor), drivers),
terminal,
"{major}:{minor}"
);
}
assert!(!StdioKind::is_terminal_device(device(136, 3), ""));
assert_eq!(StdioKind::from_mode(libc::S_IFLNK, false), StdioKind::Other);
}
#[test]
fn stdio_kinds_name_each_changed_descriptor() {
assert_eq!(
StdioKind::from_mode(libc::S_IFREG | 0o644, false),
StdioKind::File
);
assert_eq!(StdioKind::from_mode(libc::S_IFIFO, false), StdioKind::Pipe);
assert_eq!(StdioKind::from_mode(libc::S_IFCHR, true), StdioKind::Tty);
assert_eq!(
StdioKind::from_mode(libc::S_IFCHR, false),
StdioKind::CharDevice
);
let recorded = StdioKinds {
stdin: StdioKind::CharDevice,
stdout: StdioKind::Pipe,
stderr: StdioKind::File,
};
let now = StdioKinds {
stdin: StdioKind::Closed,
stderr: StdioKind::Pipe,
..recorded
};
assert!(StdioKinds::changes(&recorded, &recorded).is_empty());
let changes = StdioKinds::changes(&recorded, &now);
assert_eq!(
changes,
vec![
StdioChange {
fd: 0,
recorded: StdioKind::CharDevice,
now: StdioKind::Closed,
},
StdioChange {
fd: 2,
recorded: StdioKind::File,
now: StdioKind::Pipe,
},
]
);
assert_eq!(
changes[1].to_string(),
"stderr (fd 2) was a regular file in the recording and is a pipe now; the run may \
diverge where the guest checks it (fstat, isatty, fsync, lseek)"
);
let without = set(&[]);
assert!(!serde_json::to_string(&without).unwrap().contains("stdio"));
let with = HostInputSet {
stdio: Some(now),
..set(&[])
};
let json = serde_json::to_string(&with).unwrap();
assert!(json.contains(r#""stderr":"pipe""#), "{json}");
assert_eq!(serde_json::from_str::<HostInputSet>(&json).unwrap(), with);
}
#[test]
fn a_rebound_ancestor_or_a_relative_path_counts_as_rebound() {
let mutated = vec!["/work".to_owned()];
assert!(guest_rebound(&mutated, "/work/out.txt"));
assert!(guest_rebound(&mutated, "/work"));
assert!(!guest_rebound(&mutated, "/workspace/in.txt"));
assert!(guest_rebound(&mutated, "relative.txt"));
assert!(guest_rebound(&["/".to_owned()], "/etc/ld.so.cache"));
}
#[test]
fn a_set_finds_each_file_by_its_path() {
let recorded = set(&[
("/etc/ld.so.cache", identity(9, 36887)),
("/lib64/libc.so.6", identity(10, 2_000_000)),
]);
assert_eq!(
recorded.file("/etc/ld.so.cache").map(|file| file.identity),
Some(identity(9, 36887))
);
assert_eq!(
recorded.file("/lib64/libc.so.6").map(|file| file.identity),
Some(identity(10, 2_000_000))
);
assert_eq!(recorded.file("/etc"), None);
}
#[test]
fn hashed_content_decides_over_identity() {
let file = |ino: u64, content: Option<&str>| HostInput {
path: "/etc/ld.so.cache".to_owned(),
identity: identity(ino, 36887),
content: content.map(str::to_owned),
};
assert!(!host_input_changed(
&file(9, Some("aa")),
&file(11, Some("aa"))
));
assert!(host_input_changed(
&file(9, Some("aa")),
&file(9, Some("bb"))
));
assert!(host_input_changed(&file(9, None), &file(11, Some("aa"))));
assert!(!host_input_changed(&file(9, Some("aa")), &file(9, None)));
}
#[test]
fn the_change_line_names_the_path_and_both_identities() {
let change = HostInputChange {
path: "/etc/ld.so.cache".to_owned(),
recorded: identity(9, 36887),
now: identity(11, 36839),
};
let line = change.to_string();
assert!(line.starts_with("host input /etc/ld.so.cache changed since the recording"));
assert!(line.contains("size 36887"), "{line}");
assert!(line.contains("size 36839"), "{line}");
}
#[test]
fn host_file_identities_without_and_with_contents() {
let old = r#"{"dev":33,"ino":7,"size":100,"mtime_sec":1,"mtime_nsec":2}"#;
let identity: HostFileIdentity = serde_json::from_str(old).unwrap();
assert_eq!(identity.content, None);
let snapshot = HostFileIdentity::of_snapshot(131072, 0x0123_4567_89ab_cdef);
for value in [identity, snapshot] {
let json = serde_json::to_string(&value).unwrap();
assert_eq!(
serde_json::from_str::<HostFileIdentity>(&json).unwrap(),
value
);
let config = bincode::config::legacy();
let bytes = bincode::serde::encode_to_vec(value, config).unwrap();
let (decoded, read): (HostFileIdentity, usize) =
bincode::serde::decode_from_slice(&bytes, config).unwrap();
assert_eq!((decoded, read), (value, bytes.len()));
}
assert_eq!(
snapshot.to_string(),
"snapshot size 131072 content 0123456789abcdef"
);
assert_ne!(snapshot, HostFileIdentity::of_snapshot(131072, 1));
}
#[test]
fn a_flattened_identity_does_not_clash_with_a_records_own_content() {
let snapshot = HostFileIdentity::of_snapshot(131072, 0x0123_4567_89ab_cdef);
let plain: HostFileIdentity =
serde_json::from_str(r#"{"dev":33,"ino":7,"size":100,"mtime_sec":1,"mtime_nsec":2}"#)
.unwrap();
let keys = |json: &str| -> serde_json::Map<String, serde_json::Value> {
serde_json::from_str(json).unwrap()
};
for (identity, content) in [
(snapshot, Some("ab".repeat(32))),
(snapshot, None),
(plain, Some("cd".repeat(32))),
(plain, None),
] {
let record = HostInputRecord {
path: "/dev/__properties__/properties_serial".to_owned(),
dtid: 3,
syscall: 9,
identity,
content: content.clone(),
exec: false,
kernel_object: false,
};
let json = serde_json::to_string(&record).unwrap();
let fields = keys(&json);
assert_eq!(fields.contains_key("content"), content.is_some(), "{json}");
assert!(fields.contains_key("snapshot_content"), "{json}");
assert_eq!(
serde_json::from_str::<HostInputRecord>(&json).unwrap(),
record,
"{json}"
);
let entry = HostInput {
path: record.path.clone(),
identity,
content,
};
let json = serde_json::to_string(&entry).unwrap();
assert_eq!(
serde_json::from_str::<HostInput>(&json).unwrap(),
entry,
"{json}"
);
let unknown = json.replacen('{', r#"{"other":1,"#, 1);
assert!(serde_json::from_str::<HostInput>(&unknown).is_err());
}
let record = HostInputRecord {
path: "/dev/__properties__/properties_serial".to_owned(),
dtid: 3,
syscall: 9,
identity: snapshot,
content: None,
exec: false,
kernel_object: false,
};
let json = serde_json::to_string(&record).unwrap();
assert!(
json.contains(r#""snapshot_content":81985529216486895"#),
"{json}"
);
}
}