use anyhow::{Context, Result};
use std::collections::BTreeSet;
use std::ffi::{OsStr, OsString};
use std::hash::Hasher;
use std::io::{BufRead, BufReader};
use std::path::{Path, PathBuf};
use std::process::{Child, Command, ExitStatus, Stdio};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread::{self, JoinHandle};
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RemoteTarget {
pub alias: String,
pub host_name: Option<String>,
pub user: Option<String>,
}
impl RemoteTarget {
pub fn detail(&self) -> String {
match (&self.user, &self.host_name) {
(Some(user), Some(host)) => format!("{user}@{host}"),
(Some(user), None) => format!("{user}@{}", self.alias),
(None, Some(host)) if host != &self.alias => host.clone(),
_ => String::new(),
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct SshConfigState {
entries: Vec<SshConfigEntryState>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct SshConfigEntryState {
path: PathBuf,
modified: Option<std::time::SystemTime>,
len: Option<u64>,
}
pub fn ssh_config_state() -> SshConfigState {
SshConfigState {
entries: ssh_config_paths()
.into_iter()
.map(|path| {
let meta = std::fs::metadata(&path).ok();
SshConfigEntryState {
path,
modified: meta.as_ref().and_then(|m| m.modified().ok()),
len: meta.map(|m| m.len()),
}
})
.collect(),
}
}
#[derive(Default)]
struct HostBlock {
aliases: Vec<String>,
host_name: Option<String>,
user: Option<String>,
}
pub fn discover_ssh_targets() -> Vec<RemoteTarget> {
ssh_config_paths()
.into_iter()
.filter_map(|path| std::fs::read_to_string(path).ok())
.flat_map(|content| parse_ssh_config(&content))
.fold(
(BTreeSet::new(), Vec::new()),
|(mut seen, mut targets), target| {
if seen.insert(target.alias.clone()) {
targets.push(target);
}
(seen, targets)
},
)
.1
}
fn ssh_config_paths() -> Vec<PathBuf> {
let mut paths = Vec::new();
if let Some(home) = std::env::var_os("HOME") {
paths.push(PathBuf::from(home).join(".ssh/config"));
}
paths
}
pub fn primary_ssh_config_path() -> Option<PathBuf> {
ssh_config_paths().into_iter().next()
}
pub fn parse_ssh_config(input: &str) -> Vec<RemoteTarget> {
let mut targets = Vec::new();
let mut block = HostBlock::default();
for raw in input.lines() {
let line = strip_comment(raw).trim();
if line.is_empty() {
continue;
}
let mut parts = line.split_whitespace();
let Some(key) = parts.next() else {
continue;
};
let key = key.to_ascii_lowercase();
if key == "host" {
flush_block(&mut targets, &mut block);
block.aliases = parts
.filter(|alias| is_explicit_host_alias(alias))
.map(ToString::to_string)
.collect();
continue;
}
if block.aliases.is_empty() {
continue;
}
match key.as_str() {
"hostname" => block.host_name = parts.next().map(ToString::to_string),
"user" => block.user = parts.next().map(ToString::to_string),
_ => {}
}
}
flush_block(&mut targets, &mut block);
targets
}
fn flush_block(targets: &mut Vec<RemoteTarget>, block: &mut HostBlock) {
for alias in block.aliases.drain(..) {
targets.push(RemoteTarget {
alias,
host_name: block.host_name.clone(),
user: block.user.clone(),
});
}
block.host_name = None;
block.user = None;
}
fn strip_comment(line: &str) -> &str {
line.split_once('#').map(|(head, _)| head).unwrap_or(line)
}
fn is_explicit_host_alias(alias: &str) -> bool {
!alias.starts_with('!') && !alias.contains('*') && !alias.contains('?')
}
pub fn launch_croft(host: &str, path: Option<&str>, solo: bool) -> Result<RemoteOutcome> {
launch_croft_with(host, path, None, solo)
}
pub fn install_only_streaming(
adopted: AdoptedMaster,
log_tx: std::sync::mpsc::Sender<String>,
can_launch_tx: std::sync::mpsc::Sender<()>,
) -> Result<AdoptedMaster> {
let host_label = adopted.host.clone();
let log_tx = spawn_log_tee(install_log_path(), log_tx);
let _ = log_tx.send(format!(
"Install session for {host_label} (croft {})",
env!("CARGO_PKG_VERSION")
));
let _ = log_tx.send(format!("Adopting control socket for {host_label}"));
let ssh = SshControl::adopt(adopted.clone());
let result = install_only_streaming_over(&ssh, &host_label, &log_tx, &can_launch_tx);
std::mem::forget(ssh);
result.map(|_| adopted)
}
fn install_only_streaming_over(
ssh: &SshControl,
host_label: &str,
log_tx: &std::sync::mpsc::Sender<String>,
can_launch_tx: &std::sync::mpsc::Sender<()>,
) -> Result<()> {
let _ = log_tx.send(format!("Checking installed croft on {host_label}"));
let present = remote_croft_present(ssh).unwrap_or(false);
if present {
let _ = can_launch_tx.send(());
}
let _ = log_tx.send("Hashing local source tree".to_string());
let local_stamp = local_source_stamp()?;
let _ = log_tx.send(format!("Local source stamp: {local_stamp}"));
if !remote_install_needed(ssh, &local_stamp)? {
let _ = log_tx.send(format!("Croft on {host_label} is already up to date."));
if !present {
let _ = can_launch_tx.send(());
}
return Ok(());
}
mark_remote_updating(ssh);
let bulk = crate::remote_bulk::establish(&ssh.host, &ssh.socket_path, |msg| {
let _ = log_tx.send(msg);
});
let _ = log_tx.send(format!("Installing/updating Croft on {host_label}"));
if let Err(e) = install_remote_croft_streaming(ssh, &bulk.lane, &local_stamp, log_tx) {
clear_remote_updating(ssh);
return Err(e);
}
let _ = log_tx.send("Install complete.".to_string());
Ok(())
}
pub(crate) fn spawn_log_tee(
path: PathBuf,
downstream: std::sync::mpsc::Sender<String>,
) -> std::sync::mpsc::Sender<String> {
let (tx, rx) = std::sync::mpsc::channel::<String>();
std::thread::spawn(move || {
if let Some(parent) = path.parent() {
let _ = std::fs::create_dir_all(parent);
}
let mut file = std::fs::File::create(&path).ok();
while let Ok(line) = rx.recv() {
if let Some(f) = file.as_mut() {
use std::io::Write as _;
let secs = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
let _ = writeln!(f, "[{secs}] {line}");
}
let _ = downstream.send(line);
}
});
tx
}
fn install_log_path() -> PathBuf {
let home = std::env::var_os("HOME")
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from("."));
home.join(".cache").join("croft").join("install.log")
}
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)]
enum RemoteStatusClass {
ReturnToLocal,
Exited,
NotInstalled,
Failed,
}
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,
}
}
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}"),
}
}
fn remote_has_session_supervisor(ssh: &SshControl) -> bool {
ssh.command()
.arg(&ssh.host)
.arg("command -v dtach >/dev/null 2>&1")
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.map(|s| s.success())
.unwrap_or(false)
}
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
}
fn run_croft_session(
mut ssh: SshControl,
host: &str,
path: Option<&str>,
persistent: bool,
solo: bool,
) -> Result<RemoteOutcome> {
let mut bootstrapped = false;
let relay_id = relay_session_id(path.unwrap_or(""));
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())];
let status = run_remote_croft(&ssh, path, &env, solo)?;
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");
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,
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)
}
fn run_command_streaming(
mut cmd: Command,
log_tx: &std::sync::mpsc::Sender<String>,
) -> Result<std::process::ExitStatus> {
use std::io::{BufRead, BufReader};
cmd.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
let mut child = cmd.spawn().context("spawning streaming subprocess")?;
let stdout = child.stdout.take().expect("stdout pipe");
let stderr = child.stderr.take().expect("stderr pipe");
let tx1 = log_tx.clone();
let h1 = std::thread::spawn(move || {
let r = BufReader::new(stdout);
for line in r.lines().map_while(|l| l.ok()) {
let _ = tx1.send(line);
}
});
let tx2 = log_tx.clone();
let h2 = std::thread::spawn(move || {
let r = BufReader::new(stderr);
for line in r.lines().map_while(|l| l.ok()) {
let _ = tx2.send(line);
}
});
let status = child.wait().context("waiting for subprocess")?;
let _ = h1.join();
let _ = h2.join();
Ok(status)
}
fn install_remote_croft_streaming(
ssh: &SshControl,
lane: &crate::remote_bulk::BulkLane,
source_stamp: &str,
log_tx: &std::sync::mpsc::Sender<String>,
) -> Result<()> {
match try_local_cross_install_streaming(ssh, lane, source_stamp, log_tx) {
Ok(true) => return Ok(()),
Ok(false) => {}
Err(e) => {
let _ = log_tx.send(format!(
"Local cross-build skipped ({e}); falling back to remote cargo install"
));
}
}
let _ = log_tx.send("Syncing source tree to remote".to_string());
sync_local_source_to_remote_streaming(ssh, lane, log_tx)?;
let _ = log_tx
.send("Running cargo install on remote (first time can take several minutes)".to_string());
let mut cmd = lane.ssh_command(&ssh.socket_path);
cmd.arg(&ssh.host).arg(remote_install_command(source_stamp));
let status = run_command_streaming(cmd, log_tx).context("installing croft on remote")?;
if !status.success() {
anyhow::bail!("remote croft install failed with {status}");
}
Ok(())
}
fn try_local_cross_install_streaming(
ssh: &SshControl,
lane: &crate::remote_bulk::BulkLane,
source_stamp: &str,
log_tx: &std::sync::mpsc::Sender<String>,
) -> Result<bool> {
if let Some(reason) = cross_compile_unavailable_reason() {
let _ = log_tx.send(format!("Local cross-build skipped: {reason}"));
return Ok(false);
}
let Some(triple) = remote_target_triple(ssh)? else {
return Ok(false);
};
if !rust_target_installed(triple) {
let _ = log_tx.send(format!(
"Local cross-build skipped: rustup target `{triple}` missing (run `rustup target add {triple}` once to enable the fast path)"
));
return Ok(false);
}
let source = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let jobs = std::thread::available_parallelism()
.map(|n| (n.get() / 2).max(1))
.unwrap_or(1)
.to_string();
sync_workspace_lock(&source, |msg| {
let _ = log_tx.send(msg);
});
let fd_limit = raise_fd_limit();
let _ = log_tx.send(format!(
"Cross-compiling croft locally for {triple} (niced, {jobs} jobs, fd limit {fd_limit})"
));
let zigbuild = cargo_zigbuild_command(&source, triple, &jobs);
let status = run_command_streaming(zigbuild, log_tx).context("running cargo zigbuild")?;
if !status.success() {
anyhow::bail!("cargo zigbuild exited with {status}");
}
let binary = source
.join("target")
.join(triple)
.join("remote-fast")
.join("croft");
if !binary.exists() {
anyhow::bail!(
"cargo zigbuild reported success but {} is missing",
binary.display()
);
}
let mut mkdir = ssh.background_command();
mkdir
.arg(&ssh.host)
.arg("mkdir -p \"$HOME/.cargo/bin\" \"$HOME/.cache/croft\"");
let mkdir_status =
run_command_streaming(mkdir, log_tx).context("creating remote install dirs")?;
if !mkdir_status.success() {
anyhow::bail!("remote mkdir exited with {mkdir_status}");
}
let dest = format!("{}:.cargo/bin/croft.new", ssh.host);
let _ = log_tx.send(format!(
"Rsyncing binary to {dest} (bulk lane, {} KB/s cap)",
lane.bwlimit_kbps()
));
let rsync = ship_binary_rsync_command(lane, &ssh.socket_path, &binary, &dest);
let rsync_status =
run_command_streaming(rsync, log_tx).context("rsyncing croft binary to remote")?;
if !rsync_status.success() {
anyhow::bail!("rsync exited with {rsync_status}");
}
let mut act = ssh.background_command();
act.arg(&ssh.host).arg(activate_command(source_stamp));
let act_status =
run_command_streaming(act, log_tx).context("activating remote croft binary")?;
if !act_status.success() {
anyhow::bail!("remote activation exited with {act_status}");
}
let _ = log_tx.send("Installed croft on remote via local cross-build.".to_string());
Ok(true)
}
fn sync_local_source_to_remote_streaming(
ssh: &SshControl,
lane: &crate::remote_bulk::BulkLane,
log_tx: &std::sync::mpsc::Sender<String>,
) -> Result<()> {
let source = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let mut mkdir = ssh.background_command();
mkdir.arg(&ssh.host).arg(remote_source_dir_prep(&source));
let mkdir_status =
run_command_streaming(mkdir, log_tx).context("creating remote source dir")?;
if !mkdir_status.success() {
anyhow::bail!("remote mkdir exited with {mkdir_status}");
}
let mut source_arg: std::ffi::OsString = source.clone().into_os_string();
source_arg.push("/");
let dest = format!("{}:.cache/croft/source/", ssh.host);
let rsync = source_sync_rsync_command(lane, &ssh.socket_path, &source_arg, &dest);
let status = run_command_streaming(rsync, log_tx).context("running rsync to remote")?;
if !status.success() {
anyhow::bail!("rsync exited with {status}");
}
Ok(())
}
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}");
install_remote_croft(&ssh, &local_stamp)?;
}
let persistent = remote_has_session_supervisor(&ssh);
run_croft_session(ssh, host, path, persistent, solo)
}
fn spawn_background_install(ssh: &SshControl) {
let adopted = AdoptedMaster {
host: ssh.host.clone(),
socket_dir: ssh.socket_dir.clone(),
socket_path: ssh.socket_path.clone(),
};
std::thread::spawn(move || {
let (log_tx, _) = std::sync::mpsc::channel();
let (can_launch_tx, _) = std::sync::mpsc::channel();
let _ = install_only_streaming(adopted, log_tx, can_launch_tx);
});
}
pub struct SshControl {
host: String,
socket_dir: PathBuf,
socket_path: PathBuf,
}
#[derive(Clone)]
pub struct AdoptedMaster {
pub host: String,
pub socket_dir: PathBuf,
pub socket_path: PathBuf,
}
impl SshControl {
pub fn adopt(a: AdoptedMaster) -> Self {
Self {
host: a.host,
socket_dir: a.socket_dir,
socket_path: a.socket_path,
}
}
fn start(host: &str) -> Result<Self> {
let socket_dir = ssh_control_dir()?;
std::fs::create_dir_all(&socket_dir)
.with_context(|| format!("creating {}", socket_dir.display()))?;
let socket_path = socket_dir.join("ctl");
let status = Command::new("ssh")
.arg("-M")
.arg("-S")
.arg(&socket_path)
.arg("-f")
.arg("-N")
.arg("-T")
.arg("-o")
.arg("ConnectTimeout=10")
.arg("-o")
.arg("ServerAliveInterval=10")
.arg("-o")
.arg("ServerAliveCountMax=3")
.arg(host)
.status()
.context("starting SSH control connection")?;
if !status.success() {
anyhow::bail!("ssh control connection exited with {status}");
}
Ok(Self {
host: host.to_string(),
socket_dir,
socket_path,
})
}
fn command(&self) -> Command {
ssh_socket_command(&self.socket_path, false)
}
fn background_command(&self) -> Command {
ssh_socket_command(&self.socket_path, true)
}
}
fn ssh_socket_command(socket_path: &Path, background: bool) -> Command {
let mut command = Command::new("ssh");
command
.arg("-S")
.arg(socket_path)
.arg("-o")
.arg("ControlMaster=no")
.arg("-o")
.arg("ConnectTimeout=10")
.arg("-o")
.arg("ServerAliveInterval=10")
.arg("-o")
.arg("ServerAliveCountMax=3");
if background {
command
.arg("-n")
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null());
}
command
}
impl Drop for SshControl {
fn drop(&mut self) {
let _ = Command::new("ssh")
.arg("-S")
.arg(&self.socket_path)
.arg("-O")
.arg("exit")
.arg(&self.host)
.status();
let _ = std::fs::remove_dir_all(&self.socket_dir);
}
}
struct DropPump {
stop: Arc<AtomicBool>,
tail: Option<Child>,
handle: Option<JoinHandle<()>>,
}
impl DropPump {
fn start(ssh: &SshControl, relay_id: &str) -> Result<Self> {
let id = relay_id;
let resolve = format!(
"set -e; \
RELAY=\"$HOME/.cache/croft/relay-{id}\"; \
INBOX=\"$RELAY/inbox\"; \
LOG=\"$RELAY/requests.log\"; \
mkdir -p \"$INBOX\"; \
: > \"$LOG\"; \
printf '%s\\n%s\\n' \"$INBOX\" \"$LOG\""
);
let output = ssh
.command()
.arg(&ssh.host)
.arg(&resolve)
.stderr(Stdio::inherit())
.output()
.context("preparing remote drop relay")?;
if !output.status.success() {
anyhow::bail!("remote relay setup failed with {}", output.status);
}
let stdout = String::from_utf8_lossy(&output.stdout);
let mut lines = stdout.lines();
let inbox_dir = lines
.next()
.ok_or_else(|| anyhow::anyhow!("remote relay setup returned no inbox path"))?
.trim()
.to_string();
let requests_log = lines
.next()
.ok_or_else(|| anyhow::anyhow!("remote relay setup returned no log path"))?
.trim()
.to_string();
if inbox_dir.is_empty() || requests_log.is_empty() {
anyhow::bail!("remote relay setup returned blank paths");
}
let mut tail = Command::new("ssh")
.arg("-S")
.arg(&ssh.socket_path)
.arg("-o")
.arg("ControlMaster=no")
.arg(&ssh.host)
.arg(format!(
"exec tail -F -n 0 {} 2>/dev/null",
shell_quote(&requests_log)
))
.stdout(Stdio::piped())
.stderr(Stdio::null())
.stdin(Stdio::null())
.spawn()
.context("spawning remote requests tail")?;
let stdout = tail
.stdout
.take()
.context("capturing remote requests tail stdout")?;
let stop = Arc::new(AtomicBool::new(false));
let pump_ssh_host = ssh.host.clone();
let pump_socket = ssh.socket_path.clone();
let pump_inbox = inbox_dir.clone();
let pump_stop = stop.clone();
let handle = thread::spawn(move || {
run_pump(pump_ssh_host, pump_socket, pump_inbox, stdout, pump_stop);
});
Ok(Self {
stop,
tail: Some(tail),
handle: Some(handle),
})
}
}
impl Drop for DropPump {
fn drop(&mut self) {
self.stop.store(true, Ordering::SeqCst);
if let Some(mut tail) = self.tail.take() {
let _ = tail.kill();
let _ = tail.wait();
}
if let Some(handle) = self.handle.take() {
let _ = handle.join();
}
}
}
fn run_pump(
host: String,
socket: PathBuf,
inbox_dir: String,
stdout: std::process::ChildStdout,
stop: Arc<AtomicBool>,
) {
let reader = BufReader::new(stdout);
for line in reader.lines() {
if stop.load(Ordering::SeqCst) {
break;
}
let Ok(line) = line else { break };
match parse_relay_request(&line) {
Some(RelayRequest::Pull { id, src }) => {
handle_pull_request(&host, &socket, &inbox_dir, &id, &src);
}
Some(RelayRequest::Clipboard { id }) => {
handle_clipboard_request(&host, &socket, &inbox_dir, &id);
}
Some(RelayRequest::Open { id, url }) => {
handle_open_request(&host, &socket, &inbox_dir, &id, &url);
}
Some(RelayRequest::Forward { id, port, open }) => {
handle_forward_request(&host, &socket, &inbox_dir, &id, &port, open);
}
Some(RelayRequest::Unforward { local, remote }) => {
handle_unforward_request(&host, &socket, &local, &remote);
}
None => {}
}
}
}
fn handle_clipboard_request(host: &str, socket: &Path, inbox_dir: &str, request_id: &str) {
let dest_dir = format!("{inbox_dir}/{request_id}");
let mkdir = format!("mkdir -p {}", shell_quote(&dest_dir));
let mkdir_ok = Command::new("ssh")
.arg("-S")
.arg(socket)
.arg("-o")
.arg("ControlMaster=no")
.arg(host)
.arg(&mkdir)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.map(|s| s.success())
.unwrap_or(false);
if !mkdir_ok {
write_relay_err(host, socket, inbox_dir, request_id, "remote mkdir failed");
return;
}
let payload = match crate::clipboard::read_string() {
Some(s) => s,
None => {
write_relay_err(
host,
socket,
inbox_dir,
request_id,
"local clipboard unavailable",
);
return;
}
};
let remote_cmd = format!(
"cat > {dst}",
dst = shell_quote(&format!("{dest_dir}/clipboard.txt")),
);
let mut ssh_recv = match Command::new("ssh")
.arg("-S")
.arg(socket)
.arg("-o")
.arg("ControlMaster=no")
.arg(host)
.arg(&remote_cmd)
.stdin(Stdio::piped())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
{
Ok(c) => c,
Err(e) => {
write_relay_err(
host,
socket,
inbox_dir,
request_id,
&format!("clipboard relay spawn failed: {e}"),
);
return;
}
};
if let Some(mut stdin) = ssh_recv.stdin.take() {
use std::io::Write as _;
let _ = stdin.write_all(payload.as_bytes());
}
let status = ssh_recv.wait();
match status {
Ok(s) if s.success() => {
let touch = format!("touch {}/.ok", shell_quote(&dest_dir));
let _ = Command::new("ssh")
.arg("-S")
.arg(socket)
.arg("-o")
.arg("ControlMaster=no")
.arg(host)
.arg(&touch)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status();
}
Ok(s) => write_relay_err(
host,
socket,
inbox_dir,
request_id,
&format!("clipboard relay ssh exited {s}"),
),
Err(e) => write_relay_err(
host,
socket,
inbox_dir,
request_id,
&format!("clipboard relay wait failed: {e}"),
),
}
}
enum RelayRequest {
Pull {
id: String,
src: String,
},
Clipboard {
id: String,
},
Open {
id: String,
url: String,
},
Forward {
id: String,
port: String,
open: bool,
},
Unforward {
local: String,
remote: String,
},
}
fn parse_relay_request(line: &str) -> Option<RelayRequest> {
let line = line.trim();
let mut parts = line.split('\t');
let kind = parts.next()?;
let id = parts.next()?.to_string();
if id.is_empty() {
return None;
}
match kind {
"pull" => {
let src = parts.next()?.to_string();
if src.is_empty() {
return None;
}
Some(RelayRequest::Pull { id, src })
}
"clipboard" => Some(RelayRequest::Clipboard { id }),
"open" => {
let url = parts.next()?.to_string();
if url.is_empty() {
return None;
}
Some(RelayRequest::Open { id, url })
}
"forward" => {
let port = parts.next()?.to_string();
if port.is_empty() {
return None;
}
let open = parts.next() == Some("1");
Some(RelayRequest::Forward { id, port, open })
}
"unforward" => {
let _ = id;
let local = parts.next()?.to_string();
let remote = parts.next()?.to_string();
if local.is_empty() || remote.is_empty() {
return None;
}
Some(RelayRequest::Unforward { local, remote })
}
_ => None,
}
}
fn url_is_safe_to_open(url: &str) -> bool {
let lower: String = url
.chars()
.take(16)
.collect::<String>()
.to_ascii_lowercase();
let scheme_ok = lower.starts_with("https://")
|| lower.starts_with("http://")
|| lower.starts_with("mailto:");
if !scheme_ok {
return false;
}
!url.chars()
.any(|c| c == '\0' || c == '\n' || c == '\r' || c == '\t')
}
fn handle_pull_request(host: &str, socket: &Path, inbox_dir: &str, request_id: &str, src: &str) {
let src_path = PathBuf::from(src);
let dest_dir = format!("{inbox_dir}/{request_id}");
if !src_path.exists() {
write_relay_err(
host,
socket,
inbox_dir,
request_id,
&format!("local file not found: {}", src_path.display()),
);
return;
}
let Some(parent) = src_path.parent() else {
write_relay_err(host, socket, inbox_dir, request_id, "source has no parent");
return;
};
let Some(basename) = src_path.file_name() else {
write_relay_err(
host,
socket,
inbox_dir,
request_id,
"source has no basename",
);
return;
};
let mut tar = match Command::new("tar")
.env("COPYFILE_DISABLE", "1")
.arg("-c")
.arg("-f")
.arg("-")
.arg("-C")
.arg(parent)
.arg(basename)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.stdin(Stdio::null())
.spawn()
{
Ok(c) => c,
Err(e) => {
write_relay_err(
host,
socket,
inbox_dir,
request_id,
&format!("local tar spawn failed: {e}"),
);
return;
}
};
let tar_stdout = match tar.stdout.take() {
Some(s) => s,
None => {
let _ = tar.wait();
write_relay_err(host, socket, inbox_dir, request_id, "tar stdout missing");
return;
}
};
let remote_cmd = format!(
"set -e; mkdir -p {dir} && tar -x -f - -C {dir}",
dir = shell_quote(&dest_dir),
);
let ssh_recv = match Command::new("ssh")
.arg("-S")
.arg(socket)
.arg("-o")
.arg("ControlMaster=no")
.arg(host)
.arg(&remote_cmd)
.stdin(Stdio::from(tar_stdout))
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
{
Ok(c) => c,
Err(e) => {
let _ = tar.wait();
write_relay_err(
host,
socket,
inbox_dir,
request_id,
&format!("ssh recv spawn failed: {e}"),
);
return;
}
};
let ssh_out = ssh_recv.wait_with_output();
let tar_out = tar.wait_with_output();
match (tar_out, ssh_out) {
(Ok(t), Ok(s)) if t.status.success() && s.status.success() => {
let touch = format!("touch {}/.ok", shell_quote(&dest_dir));
let _ = Command::new("ssh")
.arg("-S")
.arg(socket)
.arg("-o")
.arg("ControlMaster=no")
.arg(host)
.arg(&touch)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status();
}
(Ok(t), Ok(s)) => {
let mut detail = format!("tar exited {}, ssh exited {}", t.status, s.status);
let tar_err = String::from_utf8_lossy(&t.stderr);
let ssh_err = String::from_utf8_lossy(&s.stderr);
if !tar_err.trim().is_empty() {
detail.push_str(" | tar: ");
detail.push_str(tar_err.trim());
}
if !ssh_err.trim().is_empty() {
detail.push_str(" | remote: ");
detail.push_str(ssh_err.trim());
}
write_relay_err(host, socket, inbox_dir, request_id, &detail);
}
(Err(e), _) | (_, Err(e)) => write_relay_err(
host,
socket,
inbox_dir,
request_id,
&format!("relay pipe wait failed: {e}"),
),
}
}
fn ssh_exec(host: &str, socket: &Path, cmd: &str) -> bool {
Command::new("ssh")
.arg("-S")
.arg(socket)
.arg("-o")
.arg("ControlMaster=no")
.arg(host)
.arg(cmd)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.map(|s| s.success())
.unwrap_or(false)
}
fn open_local_url(url: &str) -> std::io::Result<std::process::ExitStatus> {
let program = if cfg!(target_os = "linux") {
"xdg-open"
} else {
"open"
};
Command::new(program)
.arg(url)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
}
fn handle_open_request(host: &str, socket: &Path, inbox_dir: &str, request_id: &str, url: &str) {
if !url_is_safe_to_open(url) {
write_relay_err(
host,
socket,
inbox_dir,
request_id,
"rejected: URL scheme must be http/https/mailto and contain no control chars",
);
return;
}
let dest_dir = format!("{inbox_dir}/{request_id}");
if !ssh_exec(
host,
socket,
&format!("mkdir -p {}", shell_quote(&dest_dir)),
) {
write_relay_err(host, socket, inbox_dir, request_id, "remote mkdir failed");
return;
}
match open_local_url(url) {
Ok(s) if s.success() => {
let _ = ssh_exec(
host,
socket,
&format!("touch {}/.ok", shell_quote(&dest_dir)),
);
}
Ok(s) => write_relay_err(
host,
socket,
inbox_dir,
request_id,
&format!("local open(1) exited {s}"),
),
Err(e) => write_relay_err(
host,
socket,
inbox_dir,
request_id,
&format!("local open(1) spawn failed: {e}"),
),
}
}
fn pick_local_port(remote: u16) -> u16 {
use std::net::TcpListener;
if TcpListener::bind(("127.0.0.1", remote)).is_ok() {
return remote;
}
TcpListener::bind(("127.0.0.1", 0))
.ok()
.and_then(|l| l.local_addr().ok())
.map(|a| a.port())
.unwrap_or(remote)
}
fn handle_forward_request(
host: &str,
socket: &Path,
inbox_dir: &str,
request_id: &str,
port: &str,
open: bool,
) {
let Some(remote_port) = port.parse::<u16>().ok().filter(|p| *p >= 1) else {
write_relay_err(
host,
socket,
inbox_dir,
request_id,
"rejected: port must be 1..=65535",
);
return;
};
let dest_dir = format!("{inbox_dir}/{request_id}");
if !ssh_exec(
host,
socket,
&format!("mkdir -p {}", shell_quote(&dest_dir)),
) {
write_relay_err(host, socket, inbox_dir, request_id, "remote mkdir failed");
return;
}
let local_port = pick_local_port(remote_port);
let spec = format!("127.0.0.1:{local_port}:127.0.0.1:{remote_port}");
let forwarded = Command::new("ssh")
.arg("-S")
.arg(socket)
.arg("-O")
.arg("forward")
.arg("-L")
.arg(&spec)
.arg(host)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.map(|s| s.success())
.unwrap_or(false);
if !forwarded {
write_relay_err(host, socket, inbox_dir, request_id, "ssh -O forward failed");
return;
}
if open {
let _ = open_local_url(&format!("http://127.0.0.1:{local_port}/"));
}
let _ = ssh_exec(
host,
socket,
&format!("printf %s {local_port} > {}/.ok", shell_quote(&dest_dir)),
);
}
fn handle_unforward_request(host: &str, socket: &Path, local: &str, remote: &str) {
let (Ok(local), Ok(remote)) = (local.parse::<u16>(), remote.parse::<u16>()) else {
return;
};
let spec = format!("127.0.0.1:{local}:127.0.0.1:{remote}");
let _ = Command::new("ssh")
.arg("-S")
.arg(socket)
.arg("-O")
.arg("cancel")
.arg("-L")
.arg(&spec)
.arg(host)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status();
}
fn write_relay_err(host: &str, socket: &Path, inbox_dir: &str, request_id: &str, message: &str) {
let dest_dir = format!("{inbox_dir}/{request_id}");
let err_path = format!("{dest_dir}/.err");
let cmd = format!(
"mkdir -p {dir} && printf %s {msg} > {err}",
dir = shell_quote(&dest_dir),
msg = shell_quote(message),
err = shell_quote(&err_path),
);
let _ = Command::new("ssh")
.arg("-S")
.arg(socket)
.arg("-o")
.arg("ControlMaster=no")
.arg(host)
.arg(&cmd)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status();
}
pub(crate) fn relay_session_id(launch_arg: &str) -> String {
let mut hasher = std::collections::hash_map::DefaultHasher::new();
hasher.write(launch_arg.as_bytes());
format!("{:016x}", hasher.finish())
}
pub fn ssh_control_dir() -> Result<PathBuf> {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.context("system clock before unix epoch")?
.as_millis();
Ok(std::env::temp_dir().join(format!("croft-ssh-{}-{now}", std::process::id())))
}
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")
}
fn install_remote_croft(ssh: &SshControl, source_stamp: &str) -> Result<()> {
match try_local_cross_install(ssh, source_stamp) {
Ok(true) => return Ok(()),
Ok(false) => {}
Err(e) => {
eprintln!("Local cross-build failed ({e}); falling back to remote `cargo install`");
}
}
sync_local_source_to_remote(ssh)?;
let status = ssh
.command()
.arg(&ssh.host)
.arg(remote_install_command(source_stamp))
.status()
.context("installing croft on remote")?;
if !status.success() {
anyhow::bail!("remote croft install failed with {status}");
}
Ok(())
}
pub(crate) fn raise_fd_limit() -> u64 {
let mut lim = libc::rlimit {
rlim_cur: 0,
rlim_max: 0,
};
if unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &mut lim) } != 0 {
return 0;
}
let ceiling: libc::rlim_t = 1 << 20;
let target = if lim.rlim_max == libc::RLIM_INFINITY {
ceiling
} else {
lim.rlim_max.min(ceiling)
};
for candidate in [target, 65536, 10240] {
if candidate <= lim.rlim_cur {
break;
}
let raised = libc::rlimit {
rlim_cur: candidate,
rlim_max: lim.rlim_max,
};
if unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &raised) } == 0 {
return candidate;
}
}
lim.rlim_cur
}
fn cross_compile_unavailable_reason() -> Option<String> {
for (tool, version_arg, install_hint) in [
("cargo", "--version", "install Rust via https://rustup.rs"),
("cargo-zigbuild", "--version", "run `croft setup-cross`"),
("zig", "version", "run `croft setup-cross`"),
] {
if cross_tool_program(tool).is_none() {
return Some(format!(
"`{tool}` not found on PATH or standard toolchain locations ({install_hint})"
));
}
if !probe_cross_tool(tool, version_arg) {
return Some(format!("`{tool} {version_arg}` failed ({install_hint})"));
}
}
None
}
fn probe_cross_tool(tool: &str, version_arg: &str) -> bool {
cross_tool_command(tool)
.arg(version_arg)
.output()
.map(|o| o.status.success())
.unwrap_or(false)
}
fn cross_tool_search_dirs_from(path: Option<&OsStr>, home: Option<&OsStr>) -> Vec<PathBuf> {
let mut dirs = Vec::new();
if let Some(path) = path {
for dir in std::env::split_paths(path) {
push_unique_path(&mut dirs, dir);
}
}
if let Some(home) = home {
let home = PathBuf::from(home);
push_unique_path(&mut dirs, home.join(".cargo").join("bin"));
push_unique_path(&mut dirs, home.join(".local").join("bin"));
}
push_unique_path(&mut dirs, PathBuf::from("/opt/homebrew/bin"));
push_unique_path(&mut dirs, PathBuf::from("/usr/local/bin"));
dirs
}
fn push_unique_path(paths: &mut Vec<PathBuf>, path: PathBuf) {
if !paths.iter().any(|existing| existing == &path) {
paths.push(path);
}
}
fn cross_tool_search_dirs() -> Vec<PathBuf> {
let path = std::env::var_os("PATH");
let home = std::env::var_os("HOME");
cross_tool_search_dirs_from(path.as_deref(), home.as_deref())
}
fn cross_tool_path() -> OsString {
let path = std::env::var_os("PATH");
let home = std::env::var_os("HOME");
cross_tool_path_from(path.as_deref(), home.as_deref())
}
fn cross_tool_path_from(path: Option<&OsStr>, home: Option<&OsStr>) -> OsString {
std::env::join_paths(cross_tool_search_dirs_from(path, home))
.unwrap_or_else(|_| path.map(OsString::from).unwrap_or_default())
}
fn cross_tool_program(tool: &str) -> Option<PathBuf> {
find_executable_in_dirs(tool, &cross_tool_search_dirs())
}
fn find_executable_in_dirs(tool: &str, dirs: &[PathBuf]) -> Option<PathBuf> {
dirs.iter()
.map(|dir| dir.join(tool))
.find(|candidate| is_executable_file(candidate))
}
fn is_executable_file(path: &Path) -> bool {
if !path.is_file() {
return false;
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::metadata(path)
.map(|m| m.permissions().mode() & 0o111 != 0)
.unwrap_or(false)
}
#[cfg(not(unix))]
{
true
}
}
fn cross_tool_command(tool: &str) -> Command {
let program = cross_tool_program(tool).unwrap_or_else(|| PathBuf::from(tool));
let mut command = Command::new(program);
command.env("PATH", cross_tool_path());
command
}
fn checkout_dir() -> Option<PathBuf> {
let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
dir.is_dir().then_some(dir)
}
fn cross_tool_command_in_checkout(tool: &str) -> Command {
let mut command = cross_tool_command(tool);
if let Some(dir) = checkout_dir() {
command.current_dir(dir);
}
command
}
fn cargo_zigbuild_command(source: &Path, triple: &str, jobs: &str) -> Command {
let cargo = cross_tool_program("cargo").unwrap_or_else(|| PathBuf::from("cargo"));
let mut zigbuild = Command::new("nice");
zigbuild
.args(["-n", "19"])
.arg(cargo)
.args([
"zigbuild",
"--profile",
"remote-fast",
"--locked",
"--jobs",
jobs,
"--bin",
"croft",
"--target",
triple,
])
.env("PATH", cross_tool_path())
.current_dir(source);
zigbuild
}
fn sync_workspace_lock(source: &Path, log: impl Fn(String)) {
match cross_tool_command("cargo")
.args(["update", "-p", "croft-software", "--offline"])
.current_dir(source)
.output()
{
Ok(out) if out.status.success() => {
log(
"Synced Cargo.lock to the bumped croft version before the locked cross-build"
.to_string(),
);
}
Ok(out) => log(format!(
"Cargo.lock sync skipped (cargo update exited {}): {}",
out.status,
String::from_utf8_lossy(&out.stderr).trim()
)),
Err(e) => log(format!("Cargo.lock sync skipped ({e})")),
}
}
fn ship_binary_rsync_command(
lane: &crate::remote_bulk::BulkLane,
interactive_socket: &Path,
binary: &Path,
dest: &str,
) -> Command {
let mut rsync = Command::new("rsync");
rsync.args(["-az", "--checksum"]);
rsync.args(lane.rsync_throttle_args());
rsync.arg("-e").arg(lane.rsync_ssh_arg(interactive_socket));
rsync.arg(binary).arg(dest);
rsync
}
fn remote_source_dir_prep(source: &Path) -> String {
let keeps: String = std::iter::once("target")
.chain(
SOURCE_STAMP_INPUTS
.iter()
.copied()
.filter(|name| source.join(name).exists()),
)
.map(|name| format!("! -name '{name}' "))
.collect();
format!(
"mkdir -p \"$HOME/.cache/croft/source\" && \
find \"$HOME/.cache/croft/source/.\" -mindepth 1 -maxdepth 1 \
{keeps}-exec rm -rf {{}} +"
)
}
fn source_sync_filter_args() -> Vec<String> {
let mut args: Vec<String> = Vec::new();
for name in SOURCE_SKIP_NAMES {
args.push(format!("--exclude={name}"));
}
for name in SOURCE_STAMP_INPUTS {
args.push(format!("--include=/{name}"));
args.push(format!("--include=/{name}/***"));
}
args.push(String::from("--exclude=*"));
args
}
fn source_sync_tar_members(source: &Path) -> Vec<&'static str> {
SOURCE_STAMP_INPUTS
.iter()
.copied()
.filter(|name| source.join(name).exists())
.collect()
}
fn source_sync_rsync_command(
lane: &crate::remote_bulk::BulkLane,
interactive_socket: &Path,
source_arg: &std::ffi::OsStr,
dest: &str,
) -> Command {
let mut rsync = Command::new("rsync");
rsync.args(["-a", "-z", "--delete"]);
rsync.args(source_sync_filter_args());
rsync.args(lane.rsync_throttle_args());
rsync.arg("-e").arg(lane.rsync_ssh_arg(interactive_socket));
rsync.arg(source_arg).arg(dest);
rsync
}
fn remote_target_triple(ssh: &SshControl) -> Result<Option<&'static str>> {
let output = ssh
.command()
.arg(&ssh.host)
.arg("uname -m")
.output()
.context("probing remote architecture")?;
if !output.status.success() {
return Ok(None);
}
let arch = String::from_utf8_lossy(&output.stdout).trim().to_string();
Ok(arch_to_musl_triple(&arch))
}
pub fn arch_to_musl_triple(arch: &str) -> Option<&'static str> {
match arch {
"x86_64" | "amd64" => Some("x86_64-unknown-linux-musl"),
"aarch64" | "arm64" => Some("aarch64-unknown-linux-musl"),
_ => None,
}
}
fn rust_target_installed(triple: &str) -> bool {
let Ok(output) = cross_tool_command_in_checkout("rustup")
.args(["target", "list", "--installed"])
.output()
else {
return false;
};
if !output.status.success() {
return false;
}
String::from_utf8_lossy(&output.stdout)
.lines()
.any(|line| line.trim() == triple)
}
fn try_local_cross_install(ssh: &SshControl, source_stamp: &str) -> Result<bool> {
if let Some(reason) = cross_compile_unavailable_reason() {
eprintln!("Local cross-build skipped: {reason}");
return Ok(false);
}
let Some(triple) = remote_target_triple(ssh)? else {
return Ok(false);
};
if !rust_target_installed(triple) {
eprintln!(
"Local cross-build skipped: rustup target `{triple}` not installed (run `rustup target add {triple}` once to enable the fast path)"
);
return Ok(false);
}
let source = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
sync_workspace_lock(&source, |msg| println!("{msg}"));
raise_fd_limit();
let jobs = std::thread::available_parallelism()
.map(|n| (n.get() / 2).max(1))
.unwrap_or(1)
.to_string();
println!("Cross-compiling croft locally for {triple} (niced, {jobs} jobs)");
let status = cargo_zigbuild_command(&source, triple, &jobs)
.status()
.context("running cargo zigbuild")?;
if !status.success() {
anyhow::bail!("cargo zigbuild exited with {status}");
}
let binary = source
.join("target")
.join(triple)
.join("remote-fast")
.join("croft");
if !binary.exists() {
anyhow::bail!(
"cargo zigbuild reported success but {} is missing",
binary.display()
);
}
let mkdir = ssh
.command()
.arg(&ssh.host)
.arg("mkdir -p \"$HOME/.cargo/bin\" \"$HOME/.cache/croft\"")
.status()
.context("creating remote install dirs")?;
if !mkdir.success() {
anyhow::bail!("remote mkdir exited with {mkdir}");
}
let ssh_e = format!(
"ssh -S {} -o ControlMaster=no",
shell_quote_for_e_arg(&ssh.socket_path),
);
let dest = format!("{}:.cargo/bin/croft.new", ssh.host);
let rsync_status = Command::new("rsync")
.args(["-az", "--checksum", "-e"])
.arg(&ssh_e)
.arg(&binary)
.arg(&dest)
.status()
.context("rsyncing croft binary to remote")?;
if !rsync_status.success() {
anyhow::bail!("rsync exited with {rsync_status}");
}
let activate_status = ssh
.command()
.arg(&ssh.host)
.arg(activate_command(source_stamp))
.status()
.context("activating remote croft binary")?;
if !activate_status.success() {
anyhow::bail!("remote activation exited with {activate_status}");
}
println!("Installed croft on remote via local cross-build.");
Ok(true)
}
pub fn remote_croft_command(path: Option<&str>, env: &[(String, String)], solo: bool) -> String {
remote_croft_command_for_terminal(
path,
std::env::var("TERM_PROGRAM").ok().as_deref(),
std::env::var("TERM").ok().as_deref(),
crate::iterm2_inline::detect_osk_auto(),
env,
solo,
)
}
fn remote_croft_command_for_terminal(
path: Option<&str>,
term_program: Option<&str>,
term: Option<&str>,
osk: bool,
env: &[(String, String)],
solo: bool,
) -> String {
use crate::iterm2_inline::InlineImageProtocol;
let mut prefix = String::from("export CROFT_REMOTE_AUTOUPDATE=1; ");
if osk {
prefix.push_str("export CROFT_FORCE_OSK=1; ");
}
match crate::iterm2_inline::inline_image_protocol_for(term_program, term) {
InlineImageProtocol::ITerm2 => {
let tp = term_program.unwrap_or("iTerm.app");
prefix.push_str("export CROFT_FORCE_INLINE_IMAGES=1 TERM_PROGRAM=");
prefix.push_str(&shell_quote(tp));
prefix.push_str("; ");
}
InlineImageProtocol::Kitty => {
prefix.push_str("export TERM_PROGRAM=ghostty; ");
}
InlineImageProtocol::Sixel => {}
InlineImageProtocol::None => {}
}
for (k, v) in env {
prefix.push_str("export ");
prefix.push_str(k);
prefix.push('=');
prefix.push_str(&shell_quote(v));
prefix.push_str("; ");
}
prefix.push_str("export PATH=\"$HOME/.cargo/bin:$PATH\"; command -v croft >/dev/null 2>&1 || { echo 'croft not found on remote PATH' >&2; exit 127; }; ");
let croft_invocation = match path.filter(|p| !p.is_empty()) {
Some(p) => format!("croft {}", shell_quote(p)),
None => String::from("croft"),
};
if solo {
let collab_socket = collab_socket_path(path);
return format!(
"{prefix}if croft collab-relay --probe >/dev/null 2>&1; then mkdir -p \"$(dirname \"{collab_socket}\")\"; croft collab-relay --ensure --socket \"{collab_socket}\"; export CROFT_COLLAB_SOCKET=\"{collab_socket}\"; export CROFT_COLLAB_ROLE=guest; exec {croft_invocation}; else exec {croft_invocation}; fi"
);
}
let socket = dtach_socket_path(path);
let mux_socket = mux_socket_path(path);
let workspace_flag = match path.filter(|p| !p.is_empty()) {
Some(p) => format!(" --workspace {}", shell_quote(p)),
None => String::new(),
};
format!(
"{prefix}if croft session-host --probe >/dev/null 2>&1; then mkdir -p \"$(dirname \"{mux_socket}\")\"; export CROFT_SESSION_PERSISTENT=1; exec croft session-host --socket \"{mux_socket}\"{workspace_flag} -- {croft_invocation}; elif command -v dtach >/dev/null 2>&1; then mkdir -p \"$(dirname \"{socket}\")\"; export CROFT_SESSION_PERSISTENT=1; exec dtach -A \"{socket}\" -E -z -r winch {croft_invocation}; else exec {croft_invocation}; fi"
)
}
fn dtach_socket_path(path: Option<&str>) -> String {
use std::hash::Hasher;
let mut hasher = std::collections::hash_map::DefaultHasher::new();
hasher.write(path.unwrap_or("").as_bytes());
format!("$HOME/.cache/croft/sessions/{:016x}.sock", hasher.finish())
}
fn mux_socket_path(path: Option<&str>) -> String {
use std::hash::Hasher;
let mut hasher = std::collections::hash_map::DefaultHasher::new();
hasher.write(path.unwrap_or("").as_bytes());
format!(
"$HOME/.cache/croft/sessions/{:016x}.mux.sock",
hasher.finish()
)
}
fn collab_socket_path(path: Option<&str>) -> String {
use std::hash::Hasher;
let mut hasher = std::collections::hash_map::DefaultHasher::new();
hasher.write(path.unwrap_or("").as_bytes());
format!(
"$HOME/.cache/croft/sessions/{:016x}.collab.sock",
hasher.finish()
)
}
fn is_transport_failure(code: Option<i32>) -> bool {
code == Some(255)
}
fn remote_install_needed(ssh: &SshControl, local_stamp: &str) -> Result<bool> {
let output = ssh
.command()
.arg(&ssh.host)
.arg(remote_install_check_command())
.output()
.context("checking remote croft install")?;
if !output.status.success() {
return Ok(true);
}
Ok(String::from_utf8_lossy(&output.stdout).trim() != local_stamp)
}
fn remote_install_check_command() -> &'static str {
r#"if [ -f "$HOME/.cargo/env" ]; then
. "$HOME/.cargo/env"
fi
export PATH="$HOME/.cargo/bin:$PATH"
command -v croft >/dev/null 2>&1 && cat "$HOME/.cache/croft/install-stamp" 2>/dev/null"#
}
fn sync_local_source_to_remote(ssh: &SshControl) -> Result<()> {
match sync_via_rsync(ssh) {
Ok(()) => Ok(()),
Err(e) => {
eprintln!("rsync sync failed ({e}); falling back to tar pipe");
sync_via_tar(ssh)
}
}
}
fn sync_via_rsync(ssh: &SshControl) -> Result<()> {
let source = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let mkdir_status = ssh
.command()
.arg(&ssh.host)
.arg(remote_source_dir_prep(&source))
.status()
.context("creating remote source dir")?;
if !mkdir_status.success() {
anyhow::bail!("remote mkdir exited with {mkdir_status}");
}
let ssh_e = format!(
"ssh -S {} -o ControlMaster=no",
shell_quote_for_e_arg(&ssh.socket_path),
);
let mut source_arg: std::ffi::OsString = source.clone().into_os_string();
source_arg.push("/");
let dest = format!("{}:.cache/croft/source/", ssh.host);
let status = Command::new("rsync")
.args(["-a", "-z", "--delete"])
.args(source_sync_filter_args())
.arg("-e")
.arg(&ssh_e)
.arg(&source_arg)
.arg(&dest)
.status()
.context("running rsync to remote")?;
if !status.success() {
anyhow::bail!("rsync exited with {status}");
}
Ok(())
}
fn sync_via_tar(ssh: &SshControl) -> Result<()> {
let source = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let mut tar = Command::new("tar")
.env("COPYFILE_DISABLE", "1")
.args(["-czf", "-"])
.args(
SOURCE_SKIP_NAMES
.iter()
.map(|name| format!("--exclude={name}")),
)
.arg("-C")
.arg(&source)
.args(source_sync_tar_members(&source))
.stdout(Stdio::piped())
.spawn()
.with_context(|| format!("packing {}", source.display()))?;
let tar_stdout = tar.stdout.take().context("opening tar stdout")?;
let mut remote = ssh
.command()
.arg(&ssh.host)
.arg(format!(
"{} && tar -xzf - -C \"$HOME/.cache/croft/source\"",
remote_source_dir_prep(&source)
))
.stdin(Stdio::from(tar_stdout))
.spawn()
.context("copying croft source to remote")?;
let ssh_status = remote.wait().context("waiting for remote source copy")?;
let tar_status = tar.wait().context("waiting for local source archive")?;
if !tar_status.success() {
anyhow::bail!("local source archive failed with {tar_status}");
}
if !ssh_status.success() {
anyhow::bail!("remote source copy failed with {ssh_status}");
}
Ok(())
}
pub(crate) fn shell_quote_for_e_arg(p: &std::path::Path) -> String {
let s = p.to_string_lossy();
if s.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '/' | '.' | '_' | '-'))
{
s.into_owned()
} else {
format!("'{}'", s.replace('\'', r"'\''"))
}
}
fn remote_install_command(source_stamp: &str) -> String {
format!(
r#"set -e
if [ -f "$HOME/.cargo/env" ]; then
. "$HOME/.cargo/env"
fi
export PATH="$HOME/.cargo/bin:$PATH"
# Package installs need root. Run them directly when already root, otherwise
# via sudo if available. CROFT_SUDO is empty in both the root and the
# no-sudo case so the install commands stay identical.
if [ "$(id -u)" = "0" ]; then
CROFT_SUDO=""
elif command -v sudo >/dev/null 2>&1; then
CROFT_SUDO="sudo"
else
CROFT_SUDO=""
fi
# Install system packages with whatever package manager the box ships.
croft_pkg_install() {{
if command -v apt-get >/dev/null 2>&1; then
export DEBIAN_FRONTEND=noninteractive
$CROFT_SUDO apt-get update
$CROFT_SUDO apt-get install -y "$@"
elif command -v dnf >/dev/null 2>&1; then
$CROFT_SUDO dnf install -y "$@"
elif command -v yum >/dev/null 2>&1; then
$CROFT_SUDO yum install -y "$@"
elif command -v apk >/dev/null 2>&1; then
$CROFT_SUDO apk add "$@"
elif command -v pacman >/dev/null 2>&1; then
$CROFT_SUDO pacman -Sy --noconfirm "$@"
elif command -v zypper >/dev/null 2>&1; then
$CROFT_SUDO zypper install -y "$@"
else
return 1
fi
}}
# croft compiles native crates from source, so the final link step needs a C
# compiler/linker (`cc`) and pkg-config. Stock cloud images (Ubuntu Server,
# minimal Fedora, Alpine, ...) ship without them, which is why a bare
# `cargo install` dies with `linker `cc` not found`. The user opted into a
# from-source install, so install the toolchain rather than fail. This runs
# unconditionally, even when cargo already exists, because cargo can be
# present on a box that still lacks cc. The per-manager package names differ:
# Debian bundles the compiler in build-essential; others name it separately.
croft_ensure_build_toolchain() {{
if command -v cc >/dev/null 2>&1 && command -v pkg-config >/dev/null 2>&1; then
return 0
fi
if command -v apt-get >/dev/null 2>&1; then
export DEBIAN_FRONTEND=noninteractive
$CROFT_SUDO apt-get update
$CROFT_SUDO apt-get install -y build-essential pkg-config
elif command -v dnf >/dev/null 2>&1; then
$CROFT_SUDO dnf install -y gcc make pkgconf-pkg-config
elif command -v yum >/dev/null 2>&1; then
$CROFT_SUDO yum install -y gcc make pkgconfig
elif command -v apk >/dev/null 2>&1; then
$CROFT_SUDO apk add build-base pkgconf
elif command -v pacman >/dev/null 2>&1; then
$CROFT_SUDO pacman -Sy --noconfirm base-devel pkgconf
elif command -v zypper >/dev/null 2>&1; then
$CROFT_SUDO zypper install -y gcc make pkg-config
else
echo 'croft: no supported package manager found to install a C toolchain (need cc + pkg-config)' >&2
return 1
fi
}}
if ! command -v cargo >/dev/null 2>&1; then
if ! command -v curl >/dev/null 2>&1; then
if ! croft_pkg_install curl ca-certificates; then
echo 'cargo and curl are missing and no supported package manager was found to bootstrap them' >&2
exit 127
fi
fi
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal
. "$HOME/.cargo/env"
fi
export PATH="$HOME/.cargo/bin:$PATH"
# Ensure the C toolchain before compiling, regardless of whether cargo was
# already installed: a box can have rustup/cargo but no cc.
croft_ensure_build_toolchain
# dtach lets a remote croft session survive an SSH transport drop (laptop
# sleep, network change): croft launches itself under it for reconnect. Best
# effort and never fatal; a box without dtach just runs without persistence.
command -v dtach >/dev/null 2>&1 || croft_pkg_install dtach || true
# Cap the host build to ~half its cores and run it niced: this fallback
# compiles on the shared remote (often while other workloads run and,
# with launch-now, while a live croft session is using the box), so the
# default `cargo install -j <all cores>` would pin the machine. (nproc+1)/2
# stays >=1 even on a single core; nice is best-effort if present.
CROFT_JOBS=$(( ( $(nproc 2>/dev/null || echo 2) + 1 ) / 2 ))
# A live croft session on this box outranks the build entirely: the user
# is typing into a shell that shares these cores, RAM, and disk. Half the
# cores still wrecks a small VPS, so drop to one compile job and put all
# codegen IO in the idle class; the update simply takes longer.
if pgrep -x croft >/dev/null 2>&1; then
CROFT_JOBS=1
fi
CROFT_NICE=""
if command -v nice >/dev/null 2>&1; then CROFT_NICE="nice -n 19"; fi
CROFT_IONICE=""
if command -v ionice >/dev/null 2>&1; then CROFT_IONICE="ionice -c3"; fi
$CROFT_NICE $CROFT_IONICE cargo install --path "$HOME/.cache/croft/source" --jobs "$CROFT_JOBS" --force --locked
mkdir -p "$HOME/.cache/croft"
printf %s {stamp} > "$HOME/.cache/croft/install-stamp"
rm -f "$HOME/.cache/croft/updating"
"#,
stamp = shell_quote(source_stamp)
)
}
fn activate_command(source_stamp: &str) -> String {
format!(
"chmod 755 \"$HOME/.cargo/bin/croft.new\" && mv \"$HOME/.cargo/bin/croft.new\" \"$HOME/.cargo/bin/croft\" && printf %s {stamp} > \"$HOME/.cache/croft/install-stamp\" && rm -f \"$HOME/.cache/croft/updating\"",
stamp = shell_quote(source_stamp)
)
}
fn mark_remote_updating(ssh: &SshControl) {
let _ = ssh
.background_command()
.arg(&ssh.host)
.arg("mkdir -p \"$HOME/.cache/croft\" && : > \"$HOME/.cache/croft/updating\"")
.status();
}
fn clear_remote_updating(ssh: &SshControl) {
let _ = ssh
.background_command()
.arg(&ssh.host)
.arg("rm -f \"$HOME/.cache/croft/updating\"")
.status();
}
fn remote_croft_present(ssh: &SshControl) -> Result<bool> {
let output = ssh
.command()
.arg(&ssh.host)
.arg(
r#"if [ -f "$HOME/.cargo/env" ]; then . "$HOME/.cargo/env"; fi
export PATH="$HOME/.cargo/bin:$PATH"
command -v croft >/dev/null 2>&1 && echo yes"#,
)
.output()
.context("probing remote croft presence")?;
Ok(String::from_utf8_lossy(&output.stdout).trim() == "yes")
}
fn local_source_stamp() -> Result<String> {
source_stamp_for(&PathBuf::from(env!("CARGO_MANIFEST_DIR")))
}
const SOURCE_SKIP_NAMES: &[&str] = &[".git", "target", ".DS_Store"];
const SOURCE_STAMP_INPUTS: &[&str] = &[
"Cargo.toml",
"Cargo.lock",
"build.rs",
"rust-toolchain.toml",
"src",
"assets",
];
fn source_stamp_for(root: &PathBuf) -> Result<String> {
let mut hasher = std::collections::hash_map::DefaultHasher::new();
for name in SOURCE_STAMP_INPUTS {
let path = root.join(name);
let Ok(meta) = std::fs::metadata(&path) else {
continue;
};
hasher.write(name.as_bytes());
if meta.is_dir() {
hash_source_dir(root, &path, &mut hasher)?;
} else {
hasher.write_u64(meta.len());
hasher.write(
&std::fs::read(&path).with_context(|| format!("reading {}", path.display()))?,
);
}
}
Ok(format!("{:016x}", hasher.finish()))
}
fn hash_source_dir(root: &PathBuf, dir: &PathBuf, hasher: &mut impl Hasher) -> Result<()> {
let mut entries = std::fs::read_dir(dir)
.with_context(|| format!("reading {}", dir.display()))?
.collect::<std::result::Result<Vec<_>, _>>()
.with_context(|| format!("reading entries in {}", dir.display()))?;
entries.sort_by_key(|entry| entry.path());
for entry in entries {
let path = entry.path();
let name = entry.file_name();
let name = name.to_string_lossy();
if SOURCE_SKIP_NAMES.contains(&name.as_ref()) {
continue;
}
let meta = entry
.metadata()
.with_context(|| format!("reading metadata for {}", path.display()))?;
let rel = path.strip_prefix(root).unwrap_or(&path);
hasher.write(rel.to_string_lossy().as_bytes());
if meta.is_dir() {
hasher.write_u8(b'/');
hash_source_dir(root, &path, hasher)?;
} else if meta.is_file() {
hasher.write_u64(meta.len());
hasher.write(
&std::fs::read(&path).with_context(|| format!("reading {}", path.display()))?,
);
}
}
Ok(())
}
fn shell_quote(value: &str) -> String {
format!("'{}'", value.replace('\'', "'\"'\"'"))
}
#[cfg(test)]
fn ssh_control_socket_path_for_test(dir: &Path) -> PathBuf {
dir.join("ctl")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_source_sync_ships_only_build_inputs() {
let tmp = tempfile::tempdir().unwrap();
let src = tmp.path().join("checkout");
let dst = tmp.path().join("staged");
for dir in [
"src",
"assets",
"target.noindex/debug",
"target/debug",
".git",
] {
std::fs::create_dir_all(src.join(dir)).unwrap();
}
std::fs::write(src.join("src/main.rs"), "fn main() {}").unwrap();
std::fs::write(src.join("assets/logo.png"), "png").unwrap();
std::fs::write(src.join("Cargo.toml"), "[package]").unwrap();
std::fs::write(src.join("Cargo.lock"), "lock").unwrap();
std::fs::write(src.join("build.rs"), "fn main() {}").unwrap();
std::fs::write(src.join("rust-toolchain.toml"), "[toolchain]").unwrap();
std::fs::write(src.join("target.noindex/debug/croft"), "HUGE").unwrap();
std::fs::write(src.join("target/debug/croft"), "HUGE").unwrap();
std::fs::write(src.join(".git/config"), "gitdir").unwrap();
std::fs::write(src.join("assets/.DS_Store"), "finder").unwrap();
std::fs::create_dir_all(src.join("src/vendor/target")).unwrap();
std::fs::write(src.join("src/vendor/target/blob"), "HUGE").unwrap();
let mut rsync = Command::new("rsync");
rsync.arg("-a").args(source_sync_filter_args());
rsync
.arg(format!("{}/", src.display()))
.arg(format!("{}/", dst.display()));
let Ok(status) = rsync.status() else {
return; };
assert!(status.success(), "rsync exited with {status}");
for shipped in [
"src/main.rs",
"assets/logo.png",
"Cargo.toml",
"Cargo.lock",
"build.rs",
"rust-toolchain.toml",
] {
assert!(dst.join(shipped).exists(), "{shipped} must be shipped");
}
for withheld in [
"target.noindex",
"target",
".git",
"assets/.DS_Store",
"src/vendor/target",
] {
assert!(
!dst.join(withheld).exists(),
"{withheld} must never be shipped: this is the 176 GB bug"
);
}
}
fn staged_remote_source(home: &std::path::Path) -> std::path::PathBuf {
let source = home.join(".cache/croft/source");
std::fs::create_dir_all(source.join("target/remote-fast")).unwrap();
std::fs::create_dir_all(source.join("target.noindex/debug")).unwrap();
std::fs::create_dir_all(source.join(".cargo")).unwrap();
std::fs::write(source.join(".cargo/config.toml"), "[build]\njobs = 1\n").unwrap();
std::fs::write(source.join("build.rs"), "fn main() {}").unwrap();
std::fs::create_dir_all(source.join("src")).unwrap();
std::fs::write(source.join("src/main.rs"), "fn main() {}").unwrap();
std::fs::write(source.join("Cargo.toml"), "[package]\n").unwrap();
source
}
fn assert_prep_outcome(source: &std::path::Path) {
assert!(
source.join("target/remote-fast").is_dir(),
"removing the remote's own target/ would force a from-scratch rebuild every install"
);
assert!(
source.join("src/main.rs").is_file() && source.join("Cargo.toml").is_file(),
"inputs present in the local checkout must survive: deleting them re-ships \
everything and yanks the tree out from under a concurrent cargo install"
);
assert!(
!source.join("target.noindex").exists(),
"the artifact tree a previous croft shipped must be reclaimed"
);
assert!(
!source.join(".cargo").exists(),
"a stale dotfile like .cargo/config.toml would silently reconfigure every later remote build"
);
assert!(
!source.join("build.rs").exists(),
"an input no longer in the local checkout must not survive on the remote (tar never deletes)"
);
}
#[test]
fn the_remote_dir_prep_evicts_stale_entries_but_keeps_cache_and_inputs() {
let checkout = tempfile::tempdir().unwrap();
std::fs::create_dir_all(checkout.path().join("src")).unwrap();
std::fs::write(checkout.path().join("Cargo.toml"), "[package]\n").unwrap();
let prep = remote_source_dir_prep(checkout.path());
let tmp = tempfile::tempdir().unwrap();
let source = staged_remote_source(tmp.path());
let status = std::process::Command::new("sh")
.arg("-c")
.arg(&prep)
.env("HOME", tmp.path())
.status()
.unwrap();
assert!(status.success(), "the prep command must run under plain sh");
assert_prep_outcome(&source);
let empty = tempfile::tempdir().unwrap();
let status = std::process::Command::new("sh")
.arg("-c")
.arg(&prep)
.env("HOME", empty.path())
.status()
.unwrap();
assert!(status.success(), "a first install has no source dir yet");
}
#[test]
fn the_remote_dir_prep_follows_a_symlinked_source_dir() {
let checkout = tempfile::tempdir().unwrap();
std::fs::create_dir_all(checkout.path().join("src")).unwrap();
std::fs::write(checkout.path().join("Cargo.toml"), "[package]\n").unwrap();
let prep = remote_source_dir_prep(checkout.path());
let tmp = tempfile::tempdir().unwrap();
let real = tempfile::tempdir().unwrap();
let source = staged_remote_source(real.path());
std::fs::create_dir_all(tmp.path().join(".cache/croft")).unwrap();
std::os::unix::fs::symlink(
real.path().join(".cache/croft/source"),
tmp.path().join(".cache/croft/source"),
)
.unwrap();
let status = std::process::Command::new("sh")
.arg("-c")
.arg(&prep)
.env("HOME", tmp.path())
.status()
.unwrap();
assert!(status.success(), "the prep command must run under plain sh");
assert_prep_outcome(&source);
}
#[test]
fn the_tar_fallback_packs_only_build_inputs() {
let tmp = tempfile::tempdir().unwrap();
let src = tmp.path().join("checkout");
std::fs::create_dir_all(src.join("src")).unwrap();
std::fs::create_dir_all(src.join("target.noindex")).unwrap();
std::fs::write(src.join("src/main.rs"), "fn main() {}").unwrap();
std::fs::write(src.join("Cargo.toml"), "[package]").unwrap();
std::fs::write(src.join("target.noindex/blob"), "HUGE").unwrap();
let members = source_sync_tar_members(&src);
assert!(members.contains(&"src"), "src is a build input");
assert!(
members.contains(&"Cargo.toml"),
"Cargo.toml is a build input"
);
assert!(
!members.iter().any(|m| m.starts_with("target")),
"the artifact tree must never be packed"
);
assert!(
!members.contains(&"build.rs"),
"a member that does not exist must not be named, or tar fails"
);
}
#[test]
fn the_pinned_toolchain_has_every_cross_target() {
if let Some(reason) = cross_compile_unavailable_reason() {
eprintln!("SKIP the_pinned_toolchain_has_every_cross_target: {reason}");
return;
}
let Ok(out) = cross_tool_command_in_checkout("rustup")
.args(["target", "list", "--installed"])
.output()
else {
eprintln!("SKIP the_pinned_toolchain_has_every_cross_target: rustup would not run");
return;
};
if !out.status.success() {
eprintln!("SKIP the_pinned_toolchain_has_every_cross_target: rustup errored");
return;
}
let text = String::from_utf8_lossy(&out.stdout);
let installed: Vec<&str> = text.lines().map(str::trim).collect();
let missing: Vec<&str> = crate::cli::CROSS_TARGETS
.iter()
.copied()
.filter(|t| !installed.contains(t))
.collect();
assert!(
missing.is_empty(),
"the pinned toolchain is missing {missing:?}, so every remote \
update will compile croft on the remote box instead of shipping \
a prebuilt binary. Fix from inside this checkout, so the \
rust-toolchain.toml override applies:\n rustup target add {}",
missing.join(" ")
);
}
#[test]
fn only_toolchain_sensitive_calls_run_in_the_checkout() {
let source = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
assert_eq!(
cross_tool_command_in_checkout("rustup").get_current_dir(),
Some(source.as_path()),
"a target query must resolve the pinned toolchain"
);
assert_eq!(
cross_tool_command("cargo").get_current_dir(),
None,
"a presence probe must not trigger a toolchain auto-install"
);
}
#[test]
fn source_stamp_tracks_build_inputs_only() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().to_path_buf();
std::fs::create_dir_all(root.join("src")).unwrap();
std::fs::create_dir_all(root.join("target.noindex")).unwrap();
std::fs::create_dir_all(root.join("docs")).unwrap();
std::fs::write(root.join("Cargo.toml"), "[package]").unwrap();
std::fs::write(root.join("src/main.rs"), "fn main() {}").unwrap();
std::fs::write(root.join("target.noindex/dep.rlib"), "artifact-v1").unwrap();
std::fs::write(root.join("docs/NOTES.md"), "notes-v1").unwrap();
let base = source_stamp_for(&root).unwrap();
std::fs::write(root.join("target.noindex/dep.rlib"), "artifact-v2").unwrap();
std::fs::write(root.join("docs/NOTES.md"), "notes-v2").unwrap();
assert_eq!(
source_stamp_for(&root).unwrap(),
base,
"build artifacts and docs must not change the source stamp"
);
std::fs::write(root.join("src/main.rs"), "fn main() { changed(); }").unwrap();
assert_ne!(
source_stamp_for(&root).unwrap(),
base,
"a source edit must change the stamp"
);
}
#[test]
fn drop_to_local_exit_code_maps_to_return_to_local() {
assert_eq!(
classify_remote_status(Some(DROP_TO_LOCAL_EXIT_CODE)),
RemoteStatusClass::ReturnToLocal
);
assert_eq!(classify_remote_status(Some(0)), RemoteStatusClass::Exited);
assert_eq!(
classify_remote_status(Some(127)),
RemoteStatusClass::NotInstalled
);
assert_eq!(classify_remote_status(Some(1)), RemoteStatusClass::Failed);
assert_eq!(classify_remote_status(None), RemoteStatusClass::Failed);
}
#[test]
fn parse_ssh_config_extracts_explicit_hosts() {
let targets = parse_ssh_config(
r#"
Host *
User nobody
Host genesis-cloud github.com
HostName 10.0.0.2
User ubuntu
Host !blocked *.internal
User root
"#,
);
assert_eq!(
targets,
vec![
RemoteTarget {
alias: String::from("genesis-cloud"),
host_name: Some(String::from("10.0.0.2")),
user: Some(String::from("ubuntu")),
},
RemoteTarget {
alias: String::from("github.com"),
host_name: Some(String::from("10.0.0.2")),
user: Some(String::from("ubuntu")),
},
]
);
}
#[test]
fn remote_croft_command_quotes_paths() {
let command = remote_croft_command_for_terminal(
Some("/tmp/it's here"),
None,
None,
false,
&[],
false,
);
assert!(command.contains("croft '/tmp/it'\"'\"'s here'"));
assert!(command.starts_with("export CROFT_REMOTE_AUTOUPDATE=1;"));
}
#[test]
fn remote_croft_command_forwards_supported_terminal_program() {
let command =
remote_croft_command_for_terminal(None, Some("iTerm.app"), None, false, &[], false);
assert!(command.contains("export CROFT_FORCE_INLINE_IMAGES=1 TERM_PROGRAM='iTerm.app';"));
}
#[test]
fn remote_croft_command_exports_kitty_hint_for_ghostty() {
let command =
remote_croft_command_for_terminal(None, Some("ghostty"), None, false, &[], false);
assert!(command.contains("export TERM_PROGRAM=ghostty;"));
assert!(!command.contains("CROFT_FORCE_INLINE_IMAGES"));
}
#[test]
fn remote_croft_command_exports_kitty_hint_from_term_only() {
let command =
remote_croft_command_for_terminal(None, None, Some("xterm-kitty"), false, &[], false);
assert!(command.contains("export TERM_PROGRAM=ghostty;"));
}
#[test]
fn remote_launch_carries_only_a_deterministic_relay_key() {
let id = relay_session_id("");
let env = vec![(String::from("CROFT_RELAY_KEY"), id.clone())];
let command = remote_croft_command_for_terminal(None, None, None, false, &env, false);
assert!(
command.contains(&format!("export CROFT_RELAY_KEY='{id}'")),
"launch must export the deterministic relay key, got: {command}",
);
assert!(
!command.contains("CROFT_DROP_RELAY"),
"launch must not use the old per-connection relay env, got: {command}",
);
}
#[test]
fn relay_session_id_matches_dtach_socket_and_is_deterministic() {
assert_eq!(relay_session_id(""), relay_session_id(""));
assert_ne!(relay_session_id("/srv/app"), relay_session_id("/srv/other"));
assert!(dtach_socket_path(None).contains(&relay_session_id("")));
assert!(dtach_socket_path(Some("/srv/app")).contains(&relay_session_id("/srv/app")));
}
#[test]
fn cross_tool_search_dirs_cover_gui_launch_tool_locations() {
let launchd_path = OsString::from("/usr/bin:/bin:/usr/sbin:/sbin");
let home = PathBuf::from("/Users/example");
let dirs =
cross_tool_search_dirs_from(Some(launchd_path.as_os_str()), Some(home.as_os_str()));
assert_eq!(dirs.first(), Some(&PathBuf::from("/usr/bin")));
assert!(
dirs.contains(&home.join(".cargo").join("bin")),
"cargo, rustup, and cargo-zigbuild installed by rustup live here, but launchd omits it"
);
assert!(
dirs.contains(&PathBuf::from("/opt/homebrew/bin")),
"Apple Silicon Homebrew's zig lives here, but launchd omits it"
);
assert!(dirs.contains(&PathBuf::from("/usr/local/bin")));
}
#[test]
fn cross_tool_lookup_finds_home_cargo_bin_outside_inherited_path() {
use std::os::unix::fs::PermissionsExt;
let tmp = tempfile::tempdir().unwrap();
let bin_dir = tmp.path().join(".cargo").join("bin");
std::fs::create_dir_all(&bin_dir).unwrap();
let tool = bin_dir.join("cargo-zigbuild");
std::fs::write(&tool, "#!/bin/sh\nexit 0\n").unwrap();
std::fs::set_permissions(&tool, std::fs::Permissions::from_mode(0o755)).unwrap();
let launchd_path = OsString::from("/usr/bin:/bin:/usr/sbin:/sbin");
let dirs = cross_tool_search_dirs_from(
Some(launchd_path.as_os_str()),
Some(tmp.path().as_os_str()),
);
assert_eq!(
find_executable_in_dirs("cargo-zigbuild", &dirs),
Some(tool),
"the remote fast path must work when Croft.app starts with launchd's stripped PATH"
);
}
#[test]
fn remote_croft_command_forwards_osk_flag_when_local_osk_is_armed() {
let command = remote_croft_command_for_terminal(None, None, None, true, &[], false);
assert!(command.contains("export CROFT_FORCE_OSK=1;"));
let command = remote_croft_command_for_terminal(None, None, None, false, &[], false);
assert!(!command.contains("CROFT_FORCE_OSK"));
}
#[test]
fn remote_command_prefers_session_host_and_falls_back_to_dtach() {
let command =
remote_croft_command_for_terminal(Some("/srv/app"), None, None, false, &[], false);
assert!(command.contains("if croft session-host --probe"));
assert!(command.contains("exec croft session-host --socket"));
assert!(command.contains(".mux.sock"));
assert!(command.contains("--workspace '/srv/app' -- croft '/srv/app'"));
assert!(command.contains("elif command -v dtach"));
assert!(command.contains("dtach -A"));
assert!(command.contains("-E"));
assert!(command.contains("-z"));
assert!(command.contains("-r winch"));
assert!(command.contains("export CROFT_SESSION_PERSISTENT=1;"));
assert!(command.contains("else exec croft"));
}
#[test]
fn remote_command_omits_workspace_flag_without_a_path() {
let command = remote_croft_command_for_terminal(None, None, None, false, &[], false);
assert!(command.contains("exec croft session-host --socket"));
assert!(!command.contains("--workspace"));
assert!(command.contains(" -- croft;"));
}
#[test]
fn dtach_socket_is_stable_per_workspace_and_differs_across_paths() {
let a1 = dtach_socket_path(Some("/srv/app"));
let a2 = dtach_socket_path(Some("/srv/app"));
let b = dtach_socket_path(Some("/srv/other"));
assert_eq!(a1, a2, "same workspace must map to the same dtach session");
assert_ne!(a1, b, "different workspaces must not share a session");
assert!(a1.contains("/.cache/croft/sessions/"));
let m = mux_socket_path(Some("/srv/app"));
assert_ne!(m, a1);
assert!(m.ends_with(".mux.sock"));
assert!(m.contains(&relay_session_id("/srv/app")));
let c = collab_socket_path(Some("/srv/app"));
assert_ne!(c, a1);
assert_ne!(c, m);
assert!(c.ends_with(".collab.sock"));
assert!(c.contains(&relay_session_id("/srv/app")));
}
#[test]
fn remote_command_solo_skips_the_mux_and_wires_the_collab_relay() {
let command = remote_croft_command_for_terminal(
Some("/srv/app"),
Some("iTerm.app"),
Some("xterm-256color"),
false,
&[],
true,
);
assert!(!command.contains("session-host --socket"));
assert!(!command.contains("dtach -A"));
assert!(command.contains("if croft collab-relay --probe"));
assert!(command.contains("collab-relay --ensure --socket"));
assert!(command.contains(&collab_socket_path(Some("/srv/app"))));
assert!(command.contains("export CROFT_COLLAB_SOCKET="));
assert!(command.contains("export CROFT_COLLAB_ROLE=guest;"));
assert!(command.contains("exec croft '/srv/app'"));
let shared = remote_croft_command_for_terminal(
Some("/srv/app"),
Some("iTerm.app"),
Some("xterm-256color"),
false,
&[],
false,
);
assert!(shared.contains("if croft session-host --probe"));
assert!(!shared.contains("CROFT_COLLAB_ROLE"));
}
#[test]
fn transport_failure_is_exit_255_only() {
assert!(is_transport_failure(Some(255)));
assert!(!is_transport_failure(Some(0)));
assert!(!is_transport_failure(Some(1)));
assert!(!is_transport_failure(Some(101)));
assert!(!is_transport_failure(None));
}
#[test]
fn parse_relay_request_pulls_have_id_and_path() {
match super::parse_relay_request("pull\tabc-123\t/Users/v/foo.txt") {
Some(super::RelayRequest::Pull { id, src }) => {
assert_eq!(id, "abc-123");
assert_eq!(src, "/Users/v/foo.txt");
}
other => panic!("expected Pull, got {:?}", other.is_some()),
}
}
#[test]
fn activate_command_writes_stamp_then_clears_updating_marker() {
let command = super::activate_command("deadbeef");
assert!(command.contains("mv \"$HOME/.cargo/bin/croft.new\" \"$HOME/.cargo/bin/croft\""));
let stamp_at = command
.find("printf %s 'deadbeef' > \"$HOME/.cache/croft/install-stamp\"")
.expect("stamp write present");
let clear_at = command
.find("rm -f \"$HOME/.cache/croft/updating\"")
.expect("marker clear present");
assert!(
stamp_at < clear_at,
"stamp must be written before marker clear"
);
}
#[test]
fn parse_relay_request_open_extracts_id_and_url() {
match super::parse_relay_request("open\topen-1\thttps://example.com/x") {
Some(super::RelayRequest::Open { id, url }) => {
assert_eq!(id, "open-1");
assert_eq!(url, "https://example.com/x");
}
_ => panic!("expected Open variant"),
}
}
#[test]
fn url_is_safe_to_open_accepts_http_https_mailto() {
assert!(super::url_is_safe_to_open("https://example.com/path"));
assert!(super::url_is_safe_to_open("http://example.com"));
assert!(super::url_is_safe_to_open("HTTPS://Example.COM"));
assert!(super::url_is_safe_to_open("mailto:foo@example.com"));
}
#[test]
fn url_is_safe_to_open_rejects_other_schemes_and_control_chars() {
assert!(!super::url_is_safe_to_open("file:///etc/passwd"));
assert!(!super::url_is_safe_to_open("javascript:alert(1)"));
assert!(!super::url_is_safe_to_open("ssh://attacker"));
assert!(!super::url_is_safe_to_open("https://example.com\nrm -rf /"));
assert!(!super::url_is_safe_to_open("https://example.com\r\nx"));
assert!(!super::url_is_safe_to_open("plaintext"));
}
#[test]
fn parse_relay_request_clipboard_requires_id_only() {
match super::parse_relay_request("clipboard\tclip-7") {
Some(super::RelayRequest::Clipboard { id }) => assert_eq!(id, "clip-7"),
_ => panic!("expected Clipboard variant"),
}
}
#[test]
fn parse_relay_request_rejects_malformed_lines() {
assert!(super::parse_relay_request("ping\tabc\t/x").is_none());
assert!(super::parse_relay_request("pull\t\t/x").is_none());
assert!(super::parse_relay_request("pull\tabc\t").is_none());
assert!(super::parse_relay_request("clipboard\t").is_none());
}
#[test]
fn parse_relay_request_forward_extracts_port_and_open_flag() {
match super::parse_relay_request("forward\tfwd-1\t3000\t1") {
Some(super::RelayRequest::Forward { id, port, open }) => {
assert_eq!(id, "fwd-1");
assert_eq!(port, "3000");
assert!(open);
}
_ => panic!("expected Forward variant"),
}
}
#[test]
fn parse_relay_request_forward_defaults_open_to_false() {
match super::parse_relay_request("forward\tfwd-2\t8080") {
Some(super::RelayRequest::Forward { open, .. }) => assert!(!open),
_ => panic!("expected Forward variant"),
}
assert!(super::parse_relay_request("forward\tfwd-3\t").is_none());
}
#[test]
fn pick_local_port_mirrors_a_free_port() {
let p = super::pick_local_port(54321);
assert!(p == 54321 || p >= 1024, "got {p}");
}
#[test]
fn remote_install_command_installs_from_staged_source() {
let command = remote_install_command("abc123");
assert!(command.contains("cargo install --path \"$HOME/.cache/croft/source\""));
assert!(command.contains("rustup.rs"));
assert!(command.contains("printf %s 'abc123' > \"$HOME/.cache/croft/install-stamp\""));
}
#[test]
fn remote_install_compile_yields_to_a_live_croft_session() {
let command = remote_install_command("abc123");
assert!(
command.contains("pgrep -x croft"),
"must detect a live croft session on the box"
);
assert!(
command.contains("CROFT_JOBS=1"),
"a live session drops the compile to a single job"
);
assert!(
command.contains("ionice") && command.contains("-c3"),
"codegen writes must run in the idle IO class so the session's PTY never waits on them"
);
let gate = command.find("pgrep -x croft").unwrap();
let install = command.find("cargo install --path").unwrap();
assert!(gate < install, "the session check must precede the compile");
}
#[test]
fn install_log_tee_writes_lines_to_file_and_forwards_them_unchanged() {
let dir = std::env::temp_dir().join(format!("croft-log-tee-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("install.log");
let (down_tx, down_rx) = std::sync::mpsc::channel::<String>();
let tee = spawn_log_tee(path.clone(), down_tx);
tee.send(String::from("Cross-compiling croft locally"))
.unwrap();
tee.send(String::from("Local cross-build skipped (zig missing)"))
.unwrap();
let timeout = std::time::Duration::from_secs(2);
assert_eq!(
down_rx.recv_timeout(timeout).unwrap(),
"Cross-compiling croft locally",
"downstream consumers must still receive every line"
);
assert_eq!(
down_rx.recv_timeout(timeout).unwrap(),
"Local cross-build skipped (zig missing)"
);
drop(tee);
let deadline = std::time::Instant::now() + timeout;
let mut contents = String::new();
while std::time::Instant::now() < deadline {
contents = std::fs::read_to_string(&path).unwrap_or_default();
if contents.contains("zig missing") {
break;
}
std::thread::sleep(std::time::Duration::from_millis(50));
}
assert!(contents.contains("Cross-compiling croft locally"));
assert!(
contents.contains("Local cross-build skipped (zig missing)"),
"the skip REASON is the whole point of the persistent log"
);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn remote_install_command_ensures_c_toolchain_unconditionally() {
let command = remote_install_command("abc123");
assert!(command.contains("croft_ensure_build_toolchain"));
assert!(command.contains("build-essential"));
let ensure_call = command
.rfind("\ncroft_ensure_build_toolchain")
.expect("toolchain ensure must be invoked");
let cargo_install = command
.find("cargo install --path")
.expect("cargo install must be present");
assert!(
ensure_call < cargo_install,
"the C toolchain must be ensured before `cargo install` runs"
);
}
#[test]
fn arch_to_musl_triple_maps_every_arch_uname_reports_for_supported_targets() {
assert_eq!(
arch_to_musl_triple("x86_64"),
Some("x86_64-unknown-linux-musl")
);
assert_eq!(
arch_to_musl_triple("amd64"),
Some("x86_64-unknown-linux-musl"),
"BSD-style `uname -m` reports amd64 for the same machine class linux reports as x86_64; the fast-install path must accept both"
);
assert_eq!(
arch_to_musl_triple("aarch64"),
Some("aarch64-unknown-linux-musl")
);
assert_eq!(
arch_to_musl_triple("arm64"),
Some("aarch64-unknown-linux-musl"),
"Apple Silicon Linux VMs report arm64; same triple as aarch64"
);
}
#[test]
fn arch_to_musl_triple_returns_none_for_unsupported_archs_so_caller_falls_back() {
for arch in ["i686", "armv7l", "ppc64le", "riscv64", "mips", ""] {
assert_eq!(
arch_to_musl_triple(arch),
None,
"{arch} has no statically-known musl target in croft's bundled toolchain; caller must fall back to remote cargo install"
);
}
}
#[test]
fn remote_install_check_uses_cargo_path_before_probe() {
let command = remote_install_check_command();
let path_pos = command
.find("export PATH=\"$HOME/.cargo/bin:$PATH\"")
.unwrap();
let probe_pos = command.find("command -v croft").unwrap();
assert!(command.contains(". \"$HOME/.cargo/env\""));
assert!(path_pos < probe_pos);
assert!(command.contains("cat \"$HOME/.cache/croft/install-stamp\""));
}
#[test]
fn shell_quote_for_e_arg_passes_alnum_paths_through() {
assert_eq!(
shell_quote_for_e_arg(Path::new("/tmp/croft-ssh-1234/ctl")),
"/tmp/croft-ssh-1234/ctl",
);
}
#[test]
fn shell_quote_for_e_arg_quotes_paths_with_spaces() {
let q = shell_quote_for_e_arg(Path::new("/Users/v a/croft/ctl"));
assert_eq!(q, "'/Users/v a/croft/ctl'");
}
#[test]
fn shell_quote_for_e_arg_escapes_single_quotes_inside_path() {
let q = shell_quote_for_e_arg(Path::new("/tmp/it's/ctl"));
assert_eq!(q, "'/tmp/it'\\''s/ctl'");
}
#[test]
fn ssh_control_socket_path_is_short_and_inside_temp_dir() {
let dir = std::env::temp_dir().join("croft-ssh-test");
let socket = ssh_control_socket_path_for_test(&dir);
assert!(socket.starts_with(&dir));
assert_eq!(socket.file_name().and_then(|s| s.to_str()), Some("ctl"));
}
fn args_of(cmd: &Command) -> Vec<String> {
cmd.get_args()
.map(|a| a.to_string_lossy().into_owned())
.collect()
}
#[test]
fn background_ssh_never_reads_the_attached_sessions_stdin() {
let socket = PathBuf::from("/tmp/croft-ctl/ctl");
let background = args_of(&ssh_socket_command(&socket, true));
assert!(
background.iter().any(|a| a == "-n"),
"a background command sharing the session's tty steals its keystrokes"
);
let interactive = args_of(&ssh_socket_command(&socket, false));
assert!(
!interactive.iter().any(|a| a == "-n"),
"the interactive session is the one process that must keep the tty"
);
}
#[test]
fn binary_ship_never_rides_the_interactive_master_when_lane_is_dedicated() {
let lane = crate::remote_bulk::BulkLane::new(
crate::remote_bulk::LaneMode::Dedicated {
socket_path: PathBuf::from("/tmp/bulk/ctl"),
},
512,
);
let cmd = ship_binary_rsync_command(
&lane,
Path::new("/tmp/interactive/ctl"),
Path::new("/tmp/target/croft"),
"host:.cargo/bin/croft.new",
);
let args = args_of(&cmd);
let e = args
.iter()
.position(|a| a == "-e")
.map(|i| args[i + 1].clone())
.expect("rsync must use an explicit -e remote shell");
assert!(e.contains("/tmp/bulk/ctl"));
assert!(!e.contains("/tmp/interactive/ctl"));
assert!(
args.iter().any(|a| a == "--bwlimit=512"),
"unpaced bulk saturates the uplink queue and lags the session even on its own connection"
);
}
#[test]
fn binary_ship_throttles_on_the_shared_mux_when_no_lane_is_available() {
let lane = crate::remote_bulk::BulkLane::new(crate::remote_bulk::LaneMode::SharedMux, 300);
let cmd = ship_binary_rsync_command(
&lane,
Path::new("/tmp/interactive/ctl"),
Path::new("/tmp/target/croft"),
"host:.cargo/bin/croft.new",
);
let args = args_of(&cmd);
let e = args
.iter()
.position(|a| a == "-e")
.map(|i| args[i + 1].clone())
.expect("rsync must use an explicit -e remote shell");
assert!(e.contains("/tmp/interactive/ctl"));
assert!(args.iter().any(|a| a == "--bwlimit=300"));
assert!(args.iter().any(|a| a == "--checksum"));
}
#[test]
fn source_sync_honors_the_bulk_lane_and_allow_lists_the_build_inputs() {
let lane = crate::remote_bulk::BulkLane::new(
crate::remote_bulk::LaneMode::Dedicated {
socket_path: PathBuf::from("/tmp/bulk/ctl"),
},
700,
);
let cmd = source_sync_rsync_command(
&lane,
Path::new("/tmp/interactive/ctl"),
std::ffi::OsStr::new("/Users/v/croft/"),
"host:.cache/croft/source/",
);
let args = args_of(&cmd);
let e = args
.iter()
.position(|a| a == "-e")
.map(|i| args[i + 1].clone())
.expect("rsync must use an explicit -e remote shell");
assert!(e.contains("/tmp/bulk/ctl"));
assert!(!e.contains("/tmp/interactive/ctl"));
assert!(args.iter().any(|a| a == "--bwlimit=700"));
for name in SOURCE_STAMP_INPUTS {
assert!(
args.iter().any(|a| a == &format!("--include=/{name}")),
"{name} is a build input and must be shipped"
);
}
assert!(
args.iter().any(|a| a == "--exclude=*"),
"the allow-list is only an allow-list if everything else is denied"
);
for name in SOURCE_SKIP_NAMES {
assert!(
args.iter().any(|a| a == &format!("--exclude={name}")),
"{name} is skipped by the stamp walk, so it must not be shipped"
);
}
assert!(args.iter().any(|a| a == "--delete"));
}
#[test]
fn raise_fd_limit_lifts_the_soft_limit_beyond_the_linkers_needs() {
let soft = raise_fd_limit();
assert!(
soft >= 4096,
"croft's cross-link opens ~250 rlibs plus zig's own files; a {soft}-fd soft limit reproduces ProcessFdQuotaExceeded"
);
}
#[test]
fn cargo_lock_croft_version_matches_cargo_toml_so_locked_cross_build_never_falls_back() {
let root = Path::new(env!("CARGO_MANIFEST_DIR"));
let toml = std::fs::read_to_string(root.join("Cargo.toml")).unwrap();
let toml_version = toml
.lines()
.find_map(|l| {
l.strip_prefix("version = \"")
.and_then(|r| r.strip_suffix('"'))
})
.expect("Cargo.toml has a package version");
let lock = std::fs::read_to_string(root.join("Cargo.lock")).unwrap();
let lock_version = lock
.split("name = \"croft-software\"")
.nth(1)
.and_then(|after| {
after.lines().find_map(|l| {
l.trim()
.strip_prefix("version = \"")
.and_then(|r| r.strip_suffix('"'))
})
})
.expect("Cargo.lock has a croft entry");
assert_eq!(
lock_version, toml_version,
"Cargo.lock croft version {lock_version} drifted from Cargo.toml {toml_version}; run `cargo update -p croft-software`"
);
}
}