feat: implement exec and forward commands for running commands in sandboxes
- Added `exec` command to run a shell or command in a running sandbox, utilizing a new exec server. - Introduced `forward` command to expose ports of a running sandbox on the host's localhost. - Updated Cargo.toml and Cargo.lock to reflect version bump and new dependencies. - Enhanced README.md with usage instructions for new commands. - Refactored build.rs to include new guest helper files for exec functionality. - Created new source files for exec and forward logic, including protocol handling and connection management.
This commit is contained in:
+121
@@ -0,0 +1,121 @@
|
||||
//! `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<PathBuf> {
|
||||
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> {
|
||||
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<u8> {
|
||||
[&[kind][..], &(p.len() as u32).to_be_bytes(), p].concat()
|
||||
}
|
||||
|
||||
pub fn exec(h: &Path, name: &str, user: Option<String>, argv: Vec<String>) -> 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);
|
||||
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<UnixStream>, kind: u8, p: &[u8]) -> io::Result<()> {
|
||||
w.lock().unwrap().write_all(&frame(kind, p))
|
||||
}
|
||||
|
||||
/// Copy guest output frames to stdout/stderr until the exit status arrives (None: connection closed first).
|
||||
fn output(s: UnixStream) -> io::Result<Option<i32>> {
|
||||
let mut r = io::BufReader::new(s);
|
||||
let (mut out, mut err) = (io::stdout().lock(), io::stderr().lock());
|
||||
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, &mut out)?;
|
||||
out.flush()?;
|
||||
}
|
||||
b'r' => {
|
||||
io::copy(&mut p, &mut 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())?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user