use std::io::BufReader; use std::net::TcpStream; use std::path::{Path, PathBuf}; use std::process::Stdio; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; use crossbeam_channel::unbounded; use crate::error::{Error, Result}; use crate::sandbox::wire::{self, Frame}; #[derive(Debug, Clone)] pub struct AgentOptions { pub hub: String, pub token: String, pub profile: String, pub ttl: Duration, pub agent_id: Option, } pub fn serve(opts: &AgentOptions) -> Result<()> { let stream = connect_with_retry(&opts.hub, Duration::from_secs(15))?; let agent_id = opts .agent_id .clone() .unwrap_or_else(|| format!("sandbox-{}", std::process::id())); wire::write_frame( &mut stream.try_clone()?, &Frame::Hello { token: opts.token.clone(), agent_id: agent_id.clone(), profiles: vec![opts.profile.clone()], }, )?; let mut reader = BufReader::new(stream.try_clone()?); let writer = Arc::new(Mutex::new(stream)); let ttl = match wire::read_frame(&mut reader)? { Some(Frame::HelloAck { ttl_secs }) => Duration::from_secs(ttl_secs.max(1)), Some(other) => return Err(Error::invalid(format!("agent: expected hello_ack, got {other:?}"))), None => return Err(Error::other("agent: hub closed the connection at rendezvous")), }; let blobs = blob_dir(&agent_id); std::fs::create_dir_all(&blobs)?; let last_inbound = Arc::new(Mutex::new(Instant::now())); let child = Arc::new(Mutex::new(None::)); let alive = Arc::new(AtomicBool::new(true)); { let (last, child, alive, ttl) = (last_inbound.clone(), child.clone(), alive.clone(), ttl); std::thread::spawn(move || loop { std::thread::sleep(Duration::from_millis(1000)); let quiet = last.lock().unwrap().elapsed(); if quiet > ttl { eprintln!("agent: hub silent for {quiet:?} past the TTL; dying"); if let Some(pid) = *child.lock().unwrap() { unsafe { libc::kill(pid as i32, libc::SIGKILL); } } std::process::exit(1); } if !alive.load(Ordering::Relaxed) { return; } }); } let mut outcome = Ok(()); loop { let frame = match wire::read_frame(&mut reader) { Ok(Some(f)) => f, Ok(None) => break, Err(e) => { outcome = Err(e.into()); break; } }; *last_inbound.lock().unwrap() = Instant::now(); let stop = match handle(frame, &writer, &blobs, &child) { Ok(stop) => stop, Err(e) => { outcome = Err(e); break; } }; if stop { break; } } alive.store(false, Ordering::Relaxed); if let Some(pid) = *child.lock().unwrap() { unsafe { libc::kill(pid as i32, libc::SIGKILL); } } let _ = std::fs::remove_dir_all(&blobs); outcome } fn handle( frame: Frame, writer: &Arc>, blobs: &Path, child: &Arc>>, ) -> Result { match frame { Frame::Destroy {} => Ok(true), Frame::Ping {} => Ok(false), Frame::Put { req, digest, data } => { let bytes = wire::unhex(&data).map_err(io_err)?; if crate::hash::hex(&bytes) != digest { reply(writer, req, Err("put: data does not hash to the claimed digest"))?; return Ok(false); } std::fs::write(safe_blob_path(blobs, &digest)?, &bytes)?; reply(writer, req, Ok(()))?; Ok(false) } Frame::Get { req, digest } => match std::fs::read(safe_blob_path(blobs, &digest)?) { Ok(bytes) => { wire::write_frame(writer.lock().unwrap().deref_mut(), &Frame::Blob { req, data: wire::hex_bytes(&bytes) })?; Ok(false) } Err(_) => { reply(writer, req, Err("get: no such blob"))?; Ok(false) } }, Frame::Run { req, argv, cwd, env } => { run_child(req, argv, cwd, env, writer, blobs, child)?; Ok(false) } other => Err(Error::invalid(format!("agent: unexpected frame {other:?}"))), } } fn run_child( req: u64, argv: Vec, cwd: Option, env: Vec<(String, String)>, writer: &Arc>, blobs: &Path, child: &Arc>>, ) -> Result<()> { let mut argv = argv; for a in argv.iter_mut() { if let Some(digest) = a.strip_prefix("blob:") { *a = safe_blob_path(blobs, digest)?.display().to_string(); } } let program = argv.first().ok_or_else(|| Error::invalid("run: empty argv"))?; let mut c = std::process::Command::new(program); c.args(&argv[1..]) .stdout(Stdio::piped()) .stderr(Stdio::piped()); if let Some(dir) = cwd { c.current_dir(dir); } for (k, v) in env { c.env(k, v); } let mut proc = c.spawn()?; *child.lock().unwrap() = Some(proc.id()); let (tx, rx) = unbounded::<(&'static str, Vec)>(); let mut pipes = Vec::new(); let pipes_spec: [(&'static str, Option>); 2] = [ ("stdout", proc.stdout.take().map(|r| Box::new(r) as Box)), ("stderr", proc.stderr.take().map(|r| Box::new(r) as Box)), ]; for (name, pipe) in pipes_spec { if let Some(mut pipe) = pipe { let tx = tx.clone(); pipes.push(std::thread::spawn(move || { use std::io::Read; let mut buf = [0u8; 8192]; loop { match pipe.read(&mut buf) { Ok(0) | Err(_) => break, Ok(n) => { if tx.send((name, buf[..n].to_vec())).is_err() { break; } } } } })); } } drop(tx); while let Ok((stream, bytes)) = rx.recv() { wire::write_frame( writer.lock().unwrap().deref_mut(), &Frame::Log { req, stream: stream.to_string(), data: wire::hex_bytes(&bytes) }, )?; } for p in pipes { let _ = p.join(); } let status = proc.wait()?; *child.lock().unwrap() = None; wire::write_frame( writer.lock().unwrap().deref_mut(), &Frame::Exit { req, code: status.code() }, )?; Ok(()) } fn reply(writer: &Arc>, req: u64, result: std::result::Result<(), &str>) -> Result<()> { let frame = match result { Ok(()) => Frame::Ok { req }, Err(msg) => Frame::Err { req, msg: msg.to_string() }, }; wire::write_frame(writer.lock().unwrap().deref_mut(), &frame)?; Ok(()) } fn connect_with_retry(hub: &str, for_long: Duration) -> std::result::Result { let deadline = Instant::now() + for_long; loop { match TcpStream::connect(hub) { Ok(s) => return Ok(s), Err(_) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(100)), Err(e) => return Err(Error::other(format!("agent: cannot reach hub {hub}: {e}"))), } } } fn blob_dir(agent_id: &str) -> PathBuf { std::env::temp_dir().join(format!("aur-{agent_id}-blobs")) } fn safe_blob_path(blobs: &Path, digest: &str) -> Result { if digest.is_empty() || digest.len() > 128 || !digest.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') { return Err(Error::fail_closed(format!("blob digest {digest:?} is not usable"))); } Ok(blobs.join(digest)) } fn io_err(e: std::io::Error) -> Error { Error::other(e.to_string()) } use std::ops::DerefMut;