use super::*;
pub fn launch_croft(host: &str, path: Option<&str>, solo: bool) -> Result<RemoteOutcome> {
launch_croft_with(host, path, None, solo)
}
pub const DROP_TO_LOCAL_EXIT_CODE: i32 = 88;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RemoteOutcome {
ReturnToLocal,
Exited,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum RemoteStatusClass {
ReturnToLocal,
Exited,
NotInstalled,
Failed,
}
pub(super) fn classify_remote_status(code: Option<i32>) -> RemoteStatusClass {
match code {
Some(DROP_TO_LOCAL_EXIT_CODE) => RemoteStatusClass::ReturnToLocal,
Some(0) => RemoteStatusClass::Exited,
Some(127) => RemoteStatusClass::NotInstalled,
_ => RemoteStatusClass::Failed,
}
}
pub(super) fn outcome_or_bail(status: ExitStatus) -> Result<RemoteOutcome> {
match classify_remote_status(status.code()) {
RemoteStatusClass::ReturnToLocal => Ok(RemoteOutcome::ReturnToLocal),
RemoteStatusClass::Exited => Ok(RemoteOutcome::Exited),
_ => anyhow::bail!("ssh exited with {status}"),
}
}
pub(super) fn remote_has_session_supervisor(ssh: &SshControl) -> bool {
ssh.command()
.arg(&ssh.host)
.arg(session_supervisor_check_command())
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.map(|s| s.success())
.unwrap_or(false)
}
pub(super) fn session_supervisor_check_command() -> &'static str {
"export PATH=\"$HOME/.cargo/bin:$PATH\"; croft session-host --probe >/dev/null 2>&1 || command -v dtach >/dev/null 2>&1"
}
pub(super) fn lost_session_release_seq() -> String {
let mut seq = String::from(concat!(
"\x1b[<u\x1b[=0;1u",
"\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?1015l",
"\x1b[?2004l\x1b[?1004l",
"\x1b[0m\x1b[0 q\x1b[?25h",
));
seq.push_str(crate::app::reset_host_colors_seq());
if crate::iterm2_inline::detect_iterm2_inline_support() {
seq.push_str(&crate::app::reset_session_bg_seq());
}
seq.push_str("\x1b7\x1b[?1049l");
seq
}
pub(super) fn release_lost_session_terminal() {
use std::io::Write;
let mut out = std::io::stdout();
let _ = out.write_all(lost_session_release_seq().as_bytes());
let _ = out.flush();
#[cfg(unix)]
{
std::thread::sleep(std::time::Duration::from_millis(50));
unsafe {
libc::tcflush(libc::STDIN_FILENO, libc::TCIFLUSH);
}
}
}
pub(super) fn reconnect_master(host: &str) -> Option<SshControl> {
const MAX_ATTEMPTS: u32 = 30;
for attempt in 1..=MAX_ATTEMPTS {
println!(
"Connection lost. Reconnecting to {host}\u{2026} (attempt {attempt}; Ctrl+C to stop)"
);
match SshControl::start(host) {
Ok(ssh) => {
println!("Reconnected to {host}; resuming session.");
return Some(ssh);
}
Err(_) => std::thread::sleep(std::time::Duration::from_secs(2)),
}
}
eprintln!("Could not reconnect to {host}; returning to the local shell.");
None
}
pub(super) fn run_croft_session(
mut ssh: SshControl,
host: &str,
path: Option<&str>,
persistent: bool,
solo: bool,
) -> Result<RemoteOutcome> {
let repush_watch =
crate::config_sync::ConfigWatch::new(crate::config_sync::watched_local_paths());
push_config_files(&ssh, &SyncResolution::default(), &mut |msg| {
println!("{msg}")
});
let repush = ConfigRepush::start(&ssh, repush_watch);
let mut bootstrapped = false;
let relay_id = relay_session_id(path.unwrap_or(""));
let client_nonce = client_process_nonce();
loop {
let pump = match DropPump::start(&ssh, &relay_id) {
Ok(p) => Some(p),
Err(e) => {
eprintln!("Drag-drop relay disabled: {e}");
None
}
};
let env = vec![
(String::from("CROFT_RELAY_KEY"), relay_id.clone()),
(String::from("CROFT_CLIENT_NONCE"), client_nonce.clone()),
];
let status = run_remote_croft(&ssh, path, &env, solo)?;
if classify_remote_status(status.code()) == RemoteStatusClass::Failed {
release_lost_session_terminal();
}
match classify_remote_status(status.code()) {
RemoteStatusClass::ReturnToLocal => return Ok(RemoteOutcome::ReturnToLocal),
RemoteStatusClass::Exited => return Ok(RemoteOutcome::Exited),
RemoteStatusClass::NotInstalled if !bootstrapped => {
println!("Croft is not installed on {host}; bootstrapping from local source");
if let Some(warning) = source_snapshot_warning() {
eprintln!("{warning}");
}
install_remote_croft(&ssh, &local_source_stamp()?)?;
bootstrapped = true;
}
RemoteStatusClass::Failed if persistent && is_transport_failure(status.code()) => {
drop(pump);
match reconnect_master(host) {
Some(new_ssh) => {
ssh = new_ssh;
repush.retarget(&ssh);
}
None => return Ok(RemoteOutcome::Exited),
}
}
_ => return outcome_or_bail(status),
}
}
}
pub fn launch_only(adopted: AdoptedMaster, path: Option<&str>) -> Result<RemoteOutcome> {
let ssh = SshControl::adopt(adopted);
let host = ssh.host.clone();
let persistent = remote_has_session_supervisor(&ssh);
run_croft_session(ssh, &host, path, persistent, false)
}
pub fn launch_croft_with(
host: &str,
path: Option<&str>,
adopted: Option<AdoptedMaster>,
solo: bool,
) -> Result<RemoteOutcome> {
println!("Connecting to {host}");
let ssh = match adopted {
Some(a) => SshControl::adopt(a),
None => SshControl::start(host)?,
};
if remote_croft_present(&ssh).unwrap_or(false) {
spawn_background_install(&ssh);
} else {
let local_stamp = local_source_stamp()?;
println!("Installing Croft on {host}");
if let Some(warning) = source_snapshot_warning() {
eprintln!("{warning}");
}
install_remote_croft(&ssh, &local_stamp)?;
}
let persistent = remote_has_session_supervisor(&ssh);
run_croft_session(ssh, host, path, persistent, solo)
}
pub(super) fn run_remote_croft(
ssh: &SshControl,
path: Option<&str>,
env: &[(String, String)],
solo: bool,
) -> Result<ExitStatus> {
let mut command = ssh.command();
command
.arg("-tt")
.arg(&ssh.host)
.arg(remote_croft_command(path, env, solo));
command.status().context("starting ssh")
}
pub(super) fn is_transport_failure(code: Option<i32>) -> bool {
code == Some(255)
}
pub fn running_over_ssh() -> bool {
std::env::var_os("SSH_CONNECTION").is_some()
|| std::env::var_os("SSH_TTY").is_some()
|| std::env::var_os("SSH_CLIENT").is_some()
}