use std::{num::NonZeroU16, num::NonZeroU32, path::Path, time::Duration};
use base64::Engine as _;
use pretty_assertions::assert_eq;
#[cfg(target_os = "linux")]
use rho_protocol::methods::HostShellForegroundParams;
#[cfg(unix)]
use rho_protocol::methods::{HostShellResizeParams, ShellInputLimit, HOST_SHELL_INPUT_MAX_BYTES};
use rho_protocol::{
methods::{
HostPath, HostShellInputParams, HostShellOpenParams, HostStreamEnd, HostStreamId,
HostStreamReadParams,
},
Caller, ClientEnvironment, ErrorCode, ShellService as _,
};
use super::super::{
machine::Machine,
machine_test_support::{caller, caller_on, host, machine_in},
};
use crate::pty::{QueryReply, QueryWatch};
const DEADLINE: Duration = Duration::from_secs(20);
const CURSOR_QUERY: &[u8] = b"\x1b[6n";
const CURSOR_ANSWER: &[u8] = b"\x1b[1;1R";
fn shell_machine(home: &Path) -> Machine {
if cfg!(windows) {
return Machine::with_environment(
Path::new("/nonexistent/.rho"),
ClientEnvironment::of_this_process(),
);
}
let path = std::env::var("PATH").unwrap();
machine_in(&[
("PATH", &path),
("SHELL", "/bin/sh"),
("HOME", home.to_str().unwrap()),
])
}
struct Shell<'a> {
machine: &'a Machine,
caller: Caller,
id: HostStreamId,
printed: Vec<u8>,
queries: QueryWatch,
}
impl<'a> Shell<'a> {
async fn open(machine: &'a Machine, caller: Caller, folder: &Path) -> Self {
let variables = [("GREETING".to_owned(), "hi".to_owned())]
.into_iter()
.collect();
let params = HostShellOpenParams::new(host(folder), "xterm-test", cells(80), cells(24))
.with_variables(variables);
let id = machine.open(caller.clone(), params).await.unwrap().shell;
Self {
machine,
caller,
id,
printed: Vec::new(),
queries: QueryWatch::new(vec![QueryReply {
query: CURSOR_QUERY.to_vec(),
reply: CURSOR_ANSWER.to_vec(),
}]),
}
}
fn type_in(&self, text: &str) {
self.machine
.input(
&self.caller,
HostShellInputParams::new(self.id.clone(), text.as_bytes()),
)
.unwrap();
}
async fn read(&mut self) -> Option<HostStreamEnd> {
let params = HostStreamReadParams::new(
self.id.clone(),
self.printed.len() as u64,
NonZeroU32::new(1 << 20).unwrap(),
);
let read = tokio::time::timeout(DEADLINE, self.caller.read_stream(params))
.await
.unwrap_or_else(|_| {
panic!(
"the shell printed nothing more in {DEADLINE:?}; so far: {}",
self.text()
)
})
.unwrap();
let bytes = base64::engine::general_purpose::STANDARD
.decode(read.data)
.unwrap();
self.printed.extend(&bytes);
let replies = self.queries.replies_for(&bytes);
if !replies.is_empty() && read.end.is_none() {
self.machine
.input(
&self.caller,
HostShellInputParams::new(self.id.clone(), &replies),
)
.unwrap();
}
read.end
}
async fn wait_for(&mut self, wanted: &str) {
while !self.text().contains(wanted) {
let end = self.read().await;
assert!(
end.is_none(),
"the shell ended {end:?} before printing {wanted:?}: {}",
self.text()
);
}
}
async fn ending(&mut self) -> HostStreamEnd {
loop {
if let Some(end) = self.read().await {
return end;
}
}
}
fn text(&self) -> String {
String::from_utf8_lossy(&self.printed).into_owned()
}
}
fn cells(count: u16) -> NonZeroU16 {
NonZeroU16::new(count).unwrap()
}
fn echo_then_exit() -> [&'static str; 2] {
if cfg!(windows) {
["echo %TERM% %GREETING%\r", "exit 7\r"]
} else {
["echo \"$TERM $GREETING\"\r", "exit 7\r"]
}
}
#[tokio::test]
async fn a_shell_runs_what_is_typed_and_ends_with_its_exit_code() {
let home = tempfile::tempdir().unwrap();
let machine = shell_machine(home.path());
let mut shell = Shell::open(&machine, caller(), home.path()).await;
let [echo, exit] = echo_then_exit();
shell.type_in(echo);
shell.wait_for("xterm-test hi").await;
shell.type_in(exit);
assert_eq!(shell.ending().await, HostStreamEnd::exited(7));
}
#[cfg(unix)]
#[tokio::test]
async fn a_resize_reaches_the_shells_terminal_before_later_input() {
let home = tempfile::tempdir().unwrap();
let machine = shell_machine(home.path());
let mut shell = Shell::open(&machine, caller(), home.path()).await;
machine
.resize(
&shell.caller,
HostShellResizeParams::new(shell.id.clone(), cells(100), cells(30)),
)
.unwrap();
shell.type_in("echo \"size: $(stty size)\"\r");
shell.wait_for("size: 30 100").await;
}
#[cfg(unix)]
#[tokio::test]
async fn a_shell_ends_on_exit_though_a_background_job_holds_its_terminal() {
let home = tempfile::tempdir().unwrap();
let machine = shell_machine(home.path());
let mut shell = Shell::open(&machine, caller(), home.path()).await;
shell.type_in("sleep 1000 & echo job=$! ; exit 3\r");
let end = shell.ending().await;
let job = printed_pid(&shell.text(), "job");
let job_ran = running(job);
unsafe { libc::kill(job, libc::SIGKILL) };
assert_eq!(end, HostStreamEnd::exited(3));
assert!(job_ran, "the job should still hold the terminal");
}
#[cfg(target_os = "linux")]
#[tokio::test]
async fn a_shell_that_ended_lets_go_of_the_terminal_a_job_it_left_holds() {
let home = tempfile::tempdir().unwrap();
let machine = shell_machine(home.path());
let mut shell = Shell::open(&machine, caller(), home.path()).await;
std::fs::write(
home.path().join("job.sh"),
"trap '' HUP\n\
exec 3<>\"$1\"\n\
stty raw -echo <&3\n\
touch ready\n\
cat <&3 >/dev/null\n\
echo let-go > hung\n",
)
.unwrap();
shell.type_in(
"setsid sh job.sh \"$(tty)\" & while [ ! -e ready ]; do sleep 0.01; done; exit 4\r",
);
let end = shell.ending().await;
let hung = home.path().join("hung");
let deadline = tokio::time::Instant::now() + DEADLINE;
while !hung.exists() {
assert!(
tokio::time::Instant::now() < deadline,
"the job's terminal is still open"
);
tokio::time::sleep(Duration::from_millis(10)).await;
}
assert_eq!(end, HostStreamEnd::exited(4));
}
#[cfg(target_os = "linux")]
impl Shell<'_> {
fn foreground(&self) -> Option<String> {
self.machine
.foreground(
&self.caller,
HostShellForegroundParams::new(self.id.clone()),
)
.unwrap()
.program
}
async fn wait_for_foreground(&self, wanted: &str) {
let deadline = tokio::time::Instant::now() + DEADLINE;
loop {
let program = self.foreground();
if program.as_deref() == Some(wanted) {
return;
}
assert!(
tokio::time::Instant::now() < deadline,
"the foreground is {program:?}, not {wanted}"
);
tokio::time::sleep(Duration::from_millis(10)).await;
}
}
}
#[cfg(target_os = "linux")]
#[tokio::test]
async fn the_daemon_names_the_program_in_a_shells_foreground() {
let home = tempfile::tempdir().unwrap();
let machine = shell_machine(home.path());
let mut shell = Shell::open(&machine, caller(), home.path()).await;
shell.type_in("echo \"ready$((6*7))\"\r");
shell.wait_for("ready42").await;
shell.wait_for_foreground("sh").await;
shell.type_in("sleep 1000\r");
shell.wait_for_foreground("sleep").await;
shell.type_in("\x03");
shell.wait_for_foreground("sh").await;
shell.type_in("exit 0\r");
let end = shell.ending().await;
assert_eq!(end, HostStreamEnd::exited(0));
assert_eq!(shell.foreground(), None);
}
#[cfg(unix)]
fn running(pid: i32) -> bool {
let exists = unsafe { libc::kill(pid, 0) } == 0;
let zombie = cfg!(target_os = "linux")
&& std::fs::read_to_string(format!("/proc/{pid}/stat")).is_ok_and(|stat| {
stat.rsplit(") ")
.next()
.is_some_and(|rest| rest.starts_with('Z'))
});
exists && !zombie
}
#[cfg(unix)]
fn printed_pid(text: &str, label: &str) -> i32 {
let marker = format!("{label}=");
text.match_indices(&marker)
.filter_map(|(at, _)| {
let digits: String = text[at + marker.len()..]
.chars()
.take_while(char::is_ascii_digit)
.collect();
digits.parse().ok()
})
.next()
.unwrap_or_else(|| panic!("no {marker} in {text}"))
}
#[cfg(unix)]
#[tokio::test]
async fn closing_a_shells_stream_hangs_up_on_the_shell_and_its_foreground_job() {
let home = tempfile::tempdir().unwrap();
let machine = shell_machine(home.path());
let mut shell = Shell::open(&machine, caller(), home.path()).await;
std::fs::write(
home.path().join("job.sh"),
"trap 'sleep 0.2; echo done > cleaned; trap \"\" HUP; sleep 1000' HUP\n\
echo \"job=$$.\"\n\
sleep 1000\n",
)
.unwrap();
shell.type_in("echo \"shell=$$\"; sh job.sh\r");
shell.wait_for(".\r\n").await;
let text = shell.text();
let pids = [printed_pid(&text, "shell"), printed_pid(&text, "job")];
assert!(pids.iter().all(|pid| running(*pid)), "{text}");
shell.caller.close_stream(&shell.id);
let deadline = tokio::time::Instant::now() + DEADLINE;
while pids.iter().any(|pid| running(*pid)) {
assert!(tokio::time::Instant::now() < deadline, "{pids:?} still run");
tokio::time::sleep(Duration::from_millis(10)).await;
}
assert_eq!(
std::fs::read_to_string(home.path().join("cleaned")).ok(),
Some("done\n".to_owned())
);
}
#[cfg(unix)]
#[tokio::test]
async fn input_past_what_the_daemon_holds_unread_is_refused() {
let home = tempfile::tempdir().unwrap();
let machine = shell_machine(home.path());
let mut shell = Shell::open(&machine, caller(), home.path()).await;
shell.type_in("echo \"ready$((6*7))\"; sleep 1000\r");
shell.wait_for("ready42").await;
let paste = vec![b'x'; HOST_SHELL_INPUT_MAX_BYTES as usize];
let input = |bytes: &[u8]| {
machine.input(
&shell.caller,
HostShellInputParams::new(shell.id.clone(), bytes),
)
};
let first = input(&paste);
let second = input(&paste).unwrap_err();
shell.caller.close_stream(&shell.id);
assert!(first.is_ok(), "{first:?}");
assert_eq!(second.error_code(), Some(ErrorCode::ShellInputFull));
assert_eq!(
second.data,
Some(
serde_json::to_value(ShellInputLimit::new(
HOST_SHELL_INPUT_MAX_BYTES,
u64::from(HOST_SHELL_INPUT_MAX_BYTES)
))
.unwrap()
)
);
}
#[tokio::test]
async fn input_reaches_only_the_shell_of_its_own_connection() {
let home = tempfile::tempdir().unwrap();
let machine = shell_machine(home.path());
let mut mine = Shell::open(&machine, caller_on(1), home.path()).await;
let mut theirs = Shell::open(&machine, caller_on(2), home.path()).await;
assert_eq!(mine.id, theirs.id);
let [_, exit] = echo_then_exit();
mine.type_in("echo mine\r");
theirs.type_in(exit);
let their_end = theirs.ending().await;
mine.wait_for("mine").await;
let file = theirs.caller.open_stream().unwrap();
let not_a_shell = machine
.input(
&theirs.caller,
HostShellInputParams::new(file.id().clone(), b"x"),
)
.unwrap_err();
let after_exit = machine.input(
&theirs.caller,
HostShellInputParams::new(theirs.id.clone(), b"x"),
);
mine.caller.close_stream(&mine.id);
assert_eq!(their_end, HostStreamEnd::exited(7));
assert!(!theirs.text().contains("mine"), "{}", theirs.text());
assert_eq!(not_a_shell.error_code(), Some(ErrorCode::InvalidParams));
assert!(after_exit.is_ok(), "{after_exit:?}");
}
#[tokio::test]
async fn a_shell_outside_a_folder_does_not_start() {
let home = tempfile::tempdir().unwrap();
let machine = shell_machine(home.path());
let missing = home.path().join("missing");
let caller = caller();
let mut refused = Vec::new();
for folder in [HostPath::new("relative"), host(&missing)] {
let params = HostShellOpenParams::new(folder, "xterm", cells(80), cells(24));
refused.push(
machine
.open(caller.clone(), params)
.await
.unwrap_err()
.error_code(),
);
}
assert_eq!(
refused,
[
Some(ErrorCode::InvalidParams),
Some(ErrorCode::HostCallFailed)
]
);
}