use std::fs;
use std::io::Read as _;
use std::path::{Path, PathBuf};
use anyhow::{Context as _, Result};
use serde::{Deserialize, Serialize};
use sha2::{Digest as _, Sha256};
use crate::home::Home;
pub const CACHE_FILE: &str = "binary-hash.json";
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SelfCheck {
Same,
NotRecorded,
OtherFile,
Upgraded {
recorded: String,
},
Changed {
path: PathBuf,
},
Unreadable(String),
}
impl SelfCheck {
pub fn deny_reason(&self) -> Option<String> {
match self {
Self::Changed { path } => Some(format!(
"the openmoat binary {} changed since the lock recorded it, though it reports \
the same release ({VERSION}): run `openmoat init` from your own terminal if you \
rebuilt or reinstalled it yourself",
path.display()
)),
Self::Unreadable(why) => Some(format!(
"the openmoat binary could not be checked against the lock: {why}"
)),
Self::Same | Self::NotRecorded | Self::OtherFile | Self::Upgraded { .. } => None,
}
}
pub fn note(&self) -> Option<String> {
match self {
Self::Upgraded { recorded } => Some(format!(
"binary is release {VERSION}, the lock recorded {recorded}; run `openmoat init` \
to record it"
)),
Self::NotRecorded => Some(
"the lock records no digest of the binary (written by an older OpenMoat); run \
`openmoat init`"
.to_owned(),
),
Self::Changed { .. } | Self::Unreadable(_) => self.deny_reason(),
Self::Same | Self::OtherFile => None,
}
}
}
pub fn record(home: &Home, binary: &Path) -> Option<(String, String)> {
let file = fs::canonicalize(binary).ok()?;
let digest = cached_digest(&home.root().join(CACHE_FILE), &file).ok()?;
Some((digest, VERSION.to_owned()))
}
pub fn check(home: &Home, lock: &super::Lock) -> SelfCheck {
let (Some(recorded), Some(version)) = (&lock.binary_sha256, &lock.binary_version) else {
return SelfCheck::NotRecorded;
};
let Ok(exe) = std::env::current_exe().and_then(fs::canonicalize) else {
return SelfCheck::OtherFile;
};
if fs::canonicalize(&lock.binary).ok().as_ref() != Some(&exe) {
return SelfCheck::OtherFile;
}
if version != VERSION {
return SelfCheck::Upgraded {
recorded: version.clone(),
};
}
match cached_digest(&home.root().join(CACHE_FILE), &exe) {
Ok(digest) if digest == *recorded => SelfCheck::Same,
Ok(_) => SelfCheck::Changed { path: exe },
Err(error) => SelfCheck::Unreadable(format!("{error:#}")),
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct Cached {
path: String,
stamp: Stamp,
sha256: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct Stamp {
len: u64,
modified_ns: u128,
id: (u64, u64),
}
impl Stamp {
fn of(meta: &fs::Metadata) -> Self {
let modified_ns = meta
.modified()
.ok()
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map_or(0, |d| d.as_nanos());
Self {
len: meta.len(),
modified_ns,
id: file_id(meta),
}
}
}
#[cfg(unix)]
fn file_id(meta: &fs::Metadata) -> (u64, u64) {
use std::os::unix::fs::MetadataExt as _;
(meta.dev(), meta.ino())
}
#[cfg(not(unix))]
fn file_id(_: &fs::Metadata) -> (u64, u64) {
(0, 0)
}
fn cached_digest(cache: &Path, exe: &Path) -> Result<String> {
let stamp =
Stamp::of(&fs::metadata(exe).with_context(|| format!("reading {}", exe.display()))?);
let path = exe.to_string_lossy().into_owned();
let kept = fs::read(cache)
.ok()
.and_then(|bytes| serde_json::from_slice::<Cached>(&bytes).ok())
.filter(|c| c.path == path && c.stamp == stamp);
if let Some(kept) = kept {
return Ok(kept.sha256);
}
let sha256 = sha256_file(exe)?;
let fresh = Cached {
path,
stamp,
sha256: sha256.clone(),
};
if let Ok(text) = serde_json::to_vec(&fresh) {
let _ = crate::home::write_private(cache, &text);
}
Ok(sha256)
}
fn sha256_file(path: &Path) -> Result<String> {
let mut file = fs::File::open(path).with_context(|| format!("reading {}", path.display()))?;
let mut hasher = Sha256::new();
let mut buffer = vec![0u8; 1 << 16];
loop {
let read = file
.read(&mut buffer)
.with_context(|| format!("reading {}", path.display()))?;
if read == 0 {
break;
}
hasher.update(&buffer[..read]);
}
Ok(hex(&hasher.finalize()))
}
fn hex(bytes: &[u8]) -> String {
use std::fmt::Write as _;
bytes.iter().fold(String::new(), |mut out, b| {
let _ = write!(out, "{b:02x}");
out
})
}
#[cfg(test)]
mod tests;