//! `wsbx exec`: shell or command in a running sandbox, via vfkit's exec.sock -> vsock -> guest helper. //! Protocol (see guest/exec.go): one JSON request line, then frames both ways: kind u8, len u32 BE, payload. use crate::sandbox::lock_stopped; use crate::util::sanitize; use crate::vm::{stty, term_size}; use anyhow::{Result, anyhow, bail}; use serde_json::json; use std::io::{self, IsTerminal, Read, Write}; use std::os::unix::net::UnixStream; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex}; use std::time::Duration; /// Guest vsock port of the exec server. pub const VPORT: u32 = 2222; /// exec.sock of a running sandbox. pub fn sock(h: &Path, name: &str) -> Result { let dir = h.join("sandboxes").join(name); if name.is_empty() || sanitize(name) != name || !dir.join("meta.json").exists() { bail!("no sandbox {name:?} (see wsbx ps)"); } if lock_stopped(&dir).is_ok() { bail!("sandbox {name} is not running"); } Ok(dir.join("exec.sock")) } pub fn connect(sock: &Path, name: &str) -> Result { UnixStream::connect(sock).map_err(|e| anyhow!("can't reach {name}: {e} (started by an older wsbx?)")) } pub fn frame(kind: u8, p: &[u8]) -> Vec { [&[kind][..], &(p.len() as u32).to_be_bytes(), p].concat() } pub fn exec(h: &Path, name: &str, user: Option, argv: Vec) -> Result<()> { let s = connect(&sock(h, name)?, name)?; // Like ssh: a pty only when we're interactive, so `wsbx exec x -- cat f > out` stays byte-exact. let tty = io::stdin().is_terminal() && io::stdout().is_terminal(); let (rows, cols) = if tty { term_size().unwrap_or((24, 80)) } else { (0, 0) }; let w = Arc::new(Mutex::new(s.try_clone()?)); let req = json!({"argv": argv, "user": user, "tty": tty, "term": std::env::var("TERM").ok(), "rows": rows, "cols": cols}); w.lock().unwrap().write_all(format!("{req}\n").as_bytes())?; let saved = if tty { stty(&["-g"]) } else { None }; if saved.is_some() { stty(&["raw", "-echo"]); } let wi = w.clone(); std::thread::spawn(move || { let (mut stdin, mut b) = (io::stdin().lock(), vec![0u8; 32 << 10]); loop { match stdin.read(&mut b) { Ok(0) => break, Ok(n) if send(&wi, b'd', &b[..n]).is_err() => return, Ok(_) => {} Err(e) if e.kind() == io::ErrorKind::Interrupted => {} Err(_) => break, } } let _ = send(&wi, b'e', &[]); }); if tty { // ponytail: polls instead of a SIGWINCH handler; resizes land within 250 ms. std::thread::spawn(move || { let mut last = (rows, cols); loop { std::thread::sleep(Duration::from_millis(250)); if let Some((r, c)) = term_size().filter(|&sz| sz != last) { last = (r, c); if send(&w, b'w', &[r.to_be_bytes(), c.to_be_bytes()].concat()).is_err() { return; } } } }); } let code = output(s, &mut io::stdout().lock(), &mut io::stderr().lock()); if let Some(s) = saved { stty(&[s.trim()]); } match code? { Some(c) => std::process::exit(c), None => bail!("lost connection to {name} (VM stopped?)"), } } fn send(w: &Mutex, kind: u8, p: &[u8]) -> io::Result<()> { w.lock().unwrap().write_all(&frame(kind, p)) } /// Run a command as root in a running sandbox (no tty, empty stdin) and return its stdout, at most 64 KiB. pub fn capture(sock: &Path, argv: &[&str]) -> Result { // uid 0, not "root": works even if the image has no /etc/passwd let s = start(sock, argv, Some("0"))?; s.set_read_timeout(Some(Duration::from_secs(2)))?; const CAP: usize = 64 << 10; let mut buf = vec![0u8; CAP]; let mut w = &mut buf[..]; // a slice writer errors once full: the guest can't make us buffer more match output(s, &mut w, &mut io::sink())? { Some(0) => { let n = CAP - w.len(); Ok(String::from_utf8_lossy(&buf[..n]).into_owned()) } c => bail!("guest command failed ({c:?})"), } } /// Start a command without tty, with empty stdin; user None: the image user. fn start(sock: &Path, argv: &[&str], user: Option<&str>) -> Result { let mut s = UnixStream::connect(sock)?; s.write_all(format!("{}\n", json!({"argv": argv, "user": user, "tty": false})).as_bytes())?; s.write_all(&frame(b'e', &[]))?; Ok(s) } /// Run a command as the image user, all its output to our stderr. None: the connection ended first. pub fn stream(sock: &Path, argv: &[&str]) -> Result> { Ok(output(start(sock, argv, None)?, &mut io::stderr(), &mut io::stderr())?) } /// Copy guest output frames to out/err until the exit status arrives (None: connection closed first). fn output(s: UnixStream, out: &mut impl Write, err: &mut impl Write) -> io::Result> { let mut r = io::BufReader::new(s); loop { let mut h = [0u8; 5]; if r.read_exact(&mut h).is_err() { return Ok(None); } let mut p = (&mut r).take(u32::from_be_bytes([h[1], h[2], h[3], h[4]]).into()); match h[0] { b'o' => { io::copy(&mut p, out)?; out.flush()?; } b'r' => { io::copy(&mut p, err)?; } b'x' => { let mut c = [0u8; 4]; p.read_exact(&mut c)?; return Ok(Some(i32::from_be_bytes(c))); } _ => { io::copy(&mut p, &mut io::sink())?; } } } }