use std::{
collections::HashMap,
path::PathBuf,
sync::{Arc, Mutex, MutexGuard},
};
use rho_protocol::{
methods::{
HostShellForegroundParams, HostShellForegroundResponse, HostShellInputParams,
HostShellInputResponse, HostShellOpenParams, HostShellOpenResponse, HostShellResizeParams,
HostShellResizeResponse, HostStreamId, ShellInputLimit, HOST_SHELL_INPUT_MAX_BYTES,
HOST_SHELL_OPEN,
},
Caller, ClientEnvironment, ConnectionId, ErrorCode, RpcError, ShellService, StreamPacing,
};
use super::machine::{absolute, blocking, failed, log_call, Machine};
mod terminal;
use terminal::{Ending, Handle, InputFull, Spawn, Terminal};
impl ShellService for Machine {
async fn open(
&self,
caller: Caller,
params: HostShellOpenParams,
) -> Result<HostShellOpenResponse, RpcError> {
let HostShellOpenParams {
cwd,
term,
columns,
rows,
variables,
..
} = params;
log_call(&caller, HOST_SHELL_OPEN, [&cwd]);
let folder = absolute(&cwd)?.to_path_buf();
let login = self.login_environment().await;
let (program, args) = self.shell_program(&login);
let environment: ClientEnvironment = login
.into_iter()
.chain([("TERM".to_owned(), term)])
.chain(variables)
.collect();
let output = caller.open_stream_paced(StreamPacing::Interactive)?;
let shell = output.id().clone();
let spawn = Spawn {
program,
args,
folder,
environment,
columns: columns.get(),
rows: rows.get(),
};
let (terminal, handle) = blocking(move || {
if !spawn.folder.is_dir() {
anyhow::bail!("it isn't a folder");
}
Terminal::start(spawn)
})
.await?
.map_err(|error| failed(format!("the shell did not start in {cwd}: {error:#}")))?;
let key = (caller.connection, shell.clone());
self.shells()
.lock()
.insert(key.clone(), Shell::Running(handle));
let shells = self.shells().clone();
tokio::spawn(async move {
let ending = terminal.run(output).await;
log_end(&caller, &key.1, &ending);
shells.lock().insert(key.clone(), Shell::Ended);
caller.left().await;
shells.lock().remove(&key);
});
Ok(HostShellOpenResponse::new(shell))
}
fn input(
&self,
caller: &Caller,
params: HostShellInputParams,
) -> Result<HostShellInputResponse, RpcError> {
let bytes = params.bytes().map_err(|error| {
RpcError::new(
ErrorCode::InvalidParams,
format!("`data` isn't base64: {error}"),
)
})?;
if let Some(shell) = self.shells().running(caller.connection, ¶ms.shell)? {
shell.write(bytes).map_err(input_full)?;
}
Ok(HostShellInputResponse::default())
}
fn resize(
&self,
caller: &Caller,
params: HostShellResizeParams,
) -> Result<HostShellResizeResponse, RpcError> {
if let Some(shell) = self.shells().running(caller.connection, ¶ms.shell)? {
shell.resize(params.columns.get(), params.rows.get());
}
Ok(HostShellResizeResponse::default())
}
fn foreground(
&self,
caller: &Caller,
params: HostShellForegroundParams,
) -> Result<HostShellForegroundResponse, RpcError> {
let shell = self.shells().running(caller.connection, ¶ms.shell)?;
Ok(HostShellForegroundResponse::new(
shell.and_then(|shell| shell.foreground()),
))
}
}
impl Machine {
fn shell_program(&self, environment: &ClientEnvironment) -> (PathBuf, &'static [&'static str]) {
let named = |wanted: &str| {
environment
.iter()
.find(|(name, value)| {
let same = if cfg!(windows) {
name.eq_ignore_ascii_case(wanted)
} else {
*name == wanted
};
same && !value.is_empty()
})
.map(|(_, value)| PathBuf::from(value))
};
if cfg!(windows) {
let program = named("ComSpec").unwrap_or_else(|| PathBuf::from("cmd.exe"));
(program, &[])
} else {
let program = self
.login_shell()
.or_else(|| named("SHELL"))
.unwrap_or_else(|| PathBuf::from("/bin/sh"));
(program, &["-l"])
}
}
}
fn input_full(InputFull { queued, asked }: InputFull) -> RpcError {
RpcError::new(
ErrorCode::ShellInputFull,
format!(
"the shell holds {queued} bytes of input it hasn't read, and {asked} more would pass the {HOST_SHELL_INPUT_MAX_BYTES}-byte limit (HOST_SHELL_INPUT_MAX_BYTES); send it again once the shell reads"
),
)
.with_data(
serde_json::to_value(ShellInputLimit::new(HOST_SHELL_INPUT_MAX_BYTES, asked))
.expect("a limit is JSON"),
)
}
#[derive(Clone, Default)]
pub(super) struct Shells(Arc<Mutex<HashMap<(ConnectionId, HostStreamId), Shell>>>);
enum Shell {
Running(Handle),
Ended,
}
impl Shells {
fn lock(&self) -> MutexGuard<'_, HashMap<(ConnectionId, HostStreamId), Shell>> {
self.0
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
fn running(
&self,
connection: ConnectionId,
shell: &HostStreamId,
) -> Result<Option<Handle>, RpcError> {
match self.lock().get(&(connection, shell.clone())) {
Some(Shell::Running(handle)) => Ok(Some(handle.clone())),
Some(Shell::Ended) => Ok(None),
None => Err(RpcError::new(
ErrorCode::InvalidParams,
format!("host stream {shell} isn't a shell of this connection"),
)),
}
}
}
fn log_end(caller: &Caller, shell: &HostStreamId, ending: &Ending) {
tracing::info!(
connection = ?caller.connection,
client = ?caller.client.name,
client_version = ?caller.client.version,
%shell,
ending = ?ending,
"host shell ended"
);
}
#[cfg(test)]
#[path = "machine_shell_tests.rs"]
mod tests;