feat: support a better ps command

This commit is contained in:
2026-10-21 18:10:56 +02:00
parent bc7512a373
commit 230927d8db
6 changed files with 203 additions and 31 deletions
+24 -6
View File
@@ -76,7 +76,7 @@ pub fn exec(h: &Path, name: &str, user: Option<String>, argv: Vec<String>) -> Re
}
});
}
let code = output(s);
let code = output(s, &mut io::stdout().lock(), &mut io::stderr().lock());
if let Some(s) = saved {
stty(&[s.trim()]);
}
@@ -90,10 +90,28 @@ 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>> {
/// 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<String> {
let mut s = UnixStream::connect(sock)?;
s.set_read_timeout(Some(Duration::from_secs(2)))?;
// uid 0, not "root": works even if the image has no /etc/passwd
s.write_all(format!("{}\n", json!({"argv": argv, "user": "0", "tty": false})).as_bytes())?;
s.write_all(&frame(b'e', &[]))?;
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:?})"),
}
}
/// 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<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() {
@@ -102,11 +120,11 @@ fn output(s: UnixStream) -> io::Result<Option<i32>> {
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)?;
io::copy(&mut p, out)?;
out.flush()?;
}
b'r' => {
io::copy(&mut p, &mut err)?;
io::copy(&mut p, err)?;
}
b'x' => {
let mut c = [0u8; 4];