use std::io::{BufRead as _, BufReader, ErrorKind, Read as _, Write as _};
use std::os::unix::net::{UnixListener, UnixStream};
use std::path::Path;
use std::process::{Child, Command, ExitStatus};
use std::time::{Duration, Instant};
use anyhow::{Context as _, Result, bail};
use openmoat_core::boundary::LaunchCheck;
use super::tree;
use crate::guard_relay::random_hex;
pub const NONCE_ENV: &str = "MOAT_LAUNCH_NONCE";
pub const WAIT: Duration = Duration::from_secs(60);
const GO: u8 = b'1';
const STOP: u8 = b'0';
pub struct Reports {
listener: UnixListener,
nonce: String,
wait: Duration,
}
impl Reports {
pub fn bind(path: &Path) -> Result<Self> {
let listener =
UnixListener::bind(path).with_context(|| format!("listening on {}", path.display()))?;
listener.set_nonblocking(true)?;
let nonce = random_hex(16)?.as_str().to_owned();
Ok(Self {
listener,
nonce,
wait: WAIT,
})
}
pub fn start(
self,
mut command: Command,
on_launch: impl FnOnce(Option<LaunchCheck>) -> Result<()>,
) -> Result<ExitStatus> {
command.env(NONCE_ENV, &self.nonce);
let mut child = command.spawn().context("starting bubblewrap")?;
let (check, stream) = match self.receive(&mut child) {
Ok(Some((check, stream))) => (Some(check), Some(stream)),
Ok(None) => (None, None),
Err(error) => (
Some(LaunchCheck {
in_bubblewrap: true,
failure: Some(format!("{error:#}")),
..LaunchCheck::default()
}),
None,
),
};
let verdict = on_launch(check);
if let Some(mut stream) = stream {
let reply = if verdict.is_ok() { GO } else { STOP };
let _ = stream.write_all(&[reply]);
}
if let Err(error) = verdict {
tree::stop(&mut child);
return Err(error);
}
child.wait().context("waiting for bubblewrap")
}
fn receive(&self, child: &mut Child) -> Result<Option<(LaunchCheck, UnixStream)>> {
let deadline = Instant::now() + self.wait;
loop {
match self.listener.accept() {
Ok((stream, _)) => {
if let Some(check) = self.read(&stream)? {
return Ok(Some((check, stream)));
}
}
Err(error) if error.kind() == ErrorKind::WouldBlock => {
if child.try_wait()?.is_some() {
let Ok((stream, _)) = self.listener.accept() else {
return Ok(None);
};
return Ok(self.read(&stream)?.map(|check| (check, stream)));
}
if Instant::now() > deadline {
bail!("`openmoat isolated` did not report the agent's start");
}
std::thread::sleep(Duration::from_millis(5));
}
Err(error) => return Err(error).context("accepting the launch report"),
}
}
}
fn read(&self, stream: &UnixStream) -> Result<Option<LaunchCheck>> {
stream.set_nonblocking(false)?;
stream.set_read_timeout(Some(self.wait))?;
let mut line = String::new();
BufReader::new(stream).read_line(&mut line)?;
let Some((nonce, json)) = line.trim_end().split_once(' ') else {
bail!("`openmoat isolated` ended before it reported the agent's start");
};
if nonce != self.nonce {
return Ok(None);
}
let mut check: LaunchCheck = serde_json::from_str(json)?;
check.in_bubblewrap = true;
check.failure = check.linux_failure();
Ok(Some(check))
}
}
pub fn reporter(path: &Path) -> Result<impl FnOnce(Option<LaunchCheck>) -> Result<()>> {
let nonce = std::env::var(NONCE_ENV).context("no launch nonce from `openmoat run`")?;
let stream =
UnixStream::connect(path).with_context(|| format!("connecting to {}", path.display()))?;
Ok(
move |check: Option<LaunchCheck>| {
exchange(stream, &nonce, &check.unwrap_or_default(), WAIT)
},
)
}
fn exchange(
mut stream: UnixStream,
nonce: &str,
check: &LaunchCheck,
wait: Duration,
) -> Result<()> {
let json = serde_json::to_string(check)?;
writeln!(stream, "{nonce} {json}").context("reporting the agent's start")?;
stream.set_read_timeout(Some(wait))?;
let mut reply = [0u8; 1];
match stream.read(&mut reply) {
Ok(1) if reply[0] == GO => Ok(()),
Ok(1) => bail!("`openmoat run` could not keep the run on record and stops the agent"),
Ok(_) => bail!("`openmoat run` ended without a reply, so the agent is stopped"),
Err(error) => {
Err(error).context("waiting for `openmoat run`'s reply; the agent is stopped")
}
}
}
#[cfg(test)]
mod tests;