use std::fs;
use std::path::{Path, PathBuf};
use anyhow::{Result, bail};
use openmoat_hosts::{Heartbeat, Host};
use serde::{Deserialize, Serialize};
use crate::home::{Home, write_private};
use crate::install::HostConfig;
mod hook;
mod scan;
mod wording;
pub use wording::{Mark, fix, line, not_loaded};
const DIR: &str = "loaded";
const MAX_BYTES: u64 = 4096;
#[derive(Debug, Serialize, Deserialize)]
struct Record {
host: String,
reported_ms: i64,
openmoat: String,
}
fn spec(host: Host) -> Option<&'static Heartbeat> {
host.spec().install.as_ref()?.heartbeat.as_ref()
}
fn path(home: &Home, host: Host) -> PathBuf {
home.root().join(DIR).join(format!("{}.json", host.id()))
}
pub fn report(home: &Home, host: Host, now_ms: i64) -> Result<()> {
if spec(host).is_none() {
bail!(
"{} runs a hook command, not a plugin of OpenMoat's",
host.display_name()
);
}
home.require_exists()?;
let record = Record {
host: host.id().to_owned(),
reported_ms: now_ms,
openmoat: env!("CARGO_PKG_VERSION").to_owned(),
};
write_private(&path(home, host), &serde_json::to_vec(&record)?)
}
fn last(home: &Home, host: Host) -> Option<i64> {
let path = path(home, host);
let meta = fs::symlink_metadata(&path).ok()?;
if !meta.is_file() || meta.len() > MAX_BYTES {
return None;
}
let record: Record = serde_json::from_slice(&fs::read(&path).ok()?).ok()?;
(record.host == host.id()).then_some(record.reported_ms)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum Change {
PluginWritten,
HostUpdated,
HookWritten,
SettingsChanged,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct Since {
pub change: Change,
pub at_ms: i64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(tag = "state", rename_all = "kebab-case")]
pub enum Loaded {
Reported { since: Since, at_ms: i64 },
NotYet { since: Since },
Missing {
since: Since,
active_ms: i64,
sessions: usize,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Active {
pub last_ms: i64,
pub sessions: usize,
}
#[derive(Debug, Clone, Copy)]
pub struct Facts {
pub since: Since,
pub reported_ms: Option<i64>,
pub decided_ms: Option<i64>,
pub active: Option<Active>,
}
pub fn judge(facts: &Facts) -> Loaded {
let since = facts.since;
let sign = [facts.reported_ms, facts.decided_ms]
.into_iter()
.flatten()
.filter(|at| *at >= since.at_ms)
.max();
match (sign, facts.active) {
(Some(at_ms), _) => Loaded::Reported { since, at_ms },
(None, Some(active)) if active.last_ms >= since.at_ms && active.sessions > 0 => {
Loaded::Missing {
since,
active_ms: active.last_ms,
sessions: active.sessions,
}
}
(None, _) => Loaded::NotYet { since },
}
}
fn decided_since(home: &Home, host: Host, since_ms: i64) -> Option<i64> {
openmoat_audit::Store::open_read_only(&home.audit_path())
.ok()
.and_then(|store| store.host_seen_since(host.id(), since_ms).ok())
.flatten()
}
pub fn check(home: &Home, config: &HostConfig) -> Option<Loaded> {
let Some(heartbeat) = spec(config.host) else {
return hook::check(home, config);
};
let since = since(config, heartbeat)?;
Some(judge(&Facts {
since,
reported_ms: last(home, config.host),
decided_ms: decided_since(home, config.host, since.at_ms),
active: scan::sessions(config.dir(), heartbeat.activity, since.at_ms, i64::MAX),
}))
}
fn since(config: &HostConfig, heartbeat: &Heartbeat) -> Option<Since> {
let written = scan::modified_ms(&fs::metadata(config.plugin_file()?).ok()?)?;
Some(match scan::program_ms(heartbeat.program) {
Some(at_ms) if at_ms > written => Since {
change: Change::HostUpdated,
at_ms,
},
_ => Since {
change: Change::PluginWritten,
at_ms: written,
},
})
}
pub fn reported_since_change(home: &Home, config: &HostConfig) -> bool {
let Some(heartbeat) = spec(config.host) else {
return true;
};
match (since(config, heartbeat), last(home, config.host)) {
(Some(since), Some(reported_ms)) => reported_ms >= since.at_ms,
_ => false,
}
}
#[derive(Debug, Clone, Serialize)]
pub struct HostLoaded {
pub host: &'static str,
#[serde(skip)]
pub of: Host,
#[serde(flatten)]
pub loaded: Loaded,
}
pub fn all(home: &Home, binary: &Path) -> Vec<HostLoaded> {
Host::ALL
.into_iter()
.filter_map(|host| {
let config = HostConfig::for_host(home, host).ok()?;
if !config.set_up(binary) {
return None;
}
Some(HostLoaded {
host: host.id(),
of: host,
loaded: check(home, &config)?,
})
})
.collect()
}
pub fn has_plugin(host: Host) -> bool {
spec(host).is_some()
}
#[cfg(test)]
mod tests;