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};
use std::time::Duration;
#[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>,
}
const SSH_PROGRAMS: [&str; 1] = ["ssh"];
const SSH_FLAGS_WITH_ARG: [char; 22] = [
'B', 'b', 'c', 'D', 'E', 'e', 'F', 'I', 'i', 'J', 'L', 'l', 'm', 'O', 'o', 'P', 'p', 'Q', 'R',
'S', 'W', 'w',
];
pub fn ssh_destination(cmd: &[&str]) -> Option<String> {
let program = cmd.first()?.rsplit('/').next()?;
if !SSH_PROGRAMS.contains(&program) {
return None;
}
let takes_arg = |c: char| SSH_FLAGS_WITH_ARG.contains(&c);
let mut rest = cmd[1..].iter();
while let Some(word) = rest.next() {
if *word == "--" {
return rest
.next()
.and_then(|w| (!w.is_empty()).then(|| (*w).to_string()));
}
let Some(flags) = word.strip_prefix('-') else {
return (!word.is_empty()).then(|| (*word).to_string());
};
if flags.is_empty() {
continue;
}
for (i, c) in flags.char_indices() {
if takes_arg(c) {
if i + c.len_utf8() == flags.len() {
rest.next();
}
break;
}
}
}
None
}
pub fn resolve_offer_host<'a>(dest: &str, targets: &'a [RemoteTarget]) -> Option<&'a RemoteTarget> {
let host = dest.rsplit('@').next().unwrap_or(dest).trim();
if host.is_empty() {
return None;
}
targets
.iter()
.find(|t| t.alias.eq_ignore_ascii_case(host))
.or_else(|| {
targets.iter().find(|t| {
t.host_name
.as_deref()
.is_some_and(|h| h.eq_ignore_ascii_case(host))
})
})
}
pub fn ssh_reroot_decision<'a>(
argv: &[&str],
targets: &'a [RemoteTarget],
) -> Result<&'a RemoteTarget, String> {
match ssh_destination(argv) {
Some(dest) => resolve_offer_host(&dest, targets).ok_or_else(|| {
format!("{dest} is not in your ~/.ssh/config, so croft cannot open a workspace on it")
}),
None => Err(String::from("This pane is not an SSH session")),
}
}
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<()>,
confirm_fallback: &mut dyn FnMut(&str) -> bool,
) -> 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, confirm_fallback);
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<()>,
confirm_fallback: &mut dyn FnMut(&str) -> bool,
) -> 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} (source: {})",
env!("CARGO_MANIFEST_DIR")
));
if let Some(warning) = source_snapshot_warning() {
let _ = log_tx.send(warning);
}
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}"));
let mut gate = |reason: &str| {
if present {
let _ = log_tx.send(format!(
"Update NOT installed: cross-build unavailable ({reason}). Run `croft setup-cross` on this machine, then reconnect — updates then ship a prebuilt binary in seconds."
));
false
} else {
confirm_fallback(reason)
}
};
if let Err(e) = install_remote_croft_streaming(ssh, &bulk.lane, &local_stamp, log_tx, &mut gate)
{
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(session_supervisor_check_command())
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.map(|s| s.success())
.unwrap_or(false)
}
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"
}
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
}
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);
}
}
}
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 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)
}
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>,
confirm_fallback: &mut dyn FnMut(&str) -> bool,
) -> Result<()> {
let mut ship = |binary: &Path| -> Result<()> {
let dest = format!("{}:.cargo/bin/croft.new", ssh.host);
let status = ship_file_rsync_command(lane, &ssh.socket_path, binary, &dest)
.status()
.context("rsyncing the prebuilt croft to the remote")?;
anyhow::ensure!(status.success(), "rsync exited with {status}");
Ok(())
};
let mut log = |m: String| {
let _ = log_tx.send(m);
};
match try_prebuilt_install(ssh, source_stamp, &mut ship, &mut log) {
Ok(true) => return Ok(()),
Ok(false) => {}
Err(e) => log(format!("Prebuilt install failed ({e:#}); building instead")),
}
let reason = match try_local_cross_install_streaming(ssh, lane, source_stamp, log_tx) {
Ok(None) => return Ok(()),
Ok(Some(reason)) => reason,
Err(e) => format!("local cross-build failed: {e:#}"),
};
if !confirm_fallback(&reason) {
anyhow::bail!(
"cross-build unavailable ({reason}); remote compile declined — run `croft setup-cross`, then reconnect for the fast install"
);
}
let _ = log_tx.send(format!("Falling back to remote cargo install ({reason})"));
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(())
}
pub(crate) fn cross_build_unavailable(triple: &str) -> Option<String> {
if let Some(reason) = cross_compile_unavailable_reason() {
return Some(reason);
}
if !rust_target_installed(triple) {
return Some(format!(
"rustup target `{triple}` missing (run `rustup target add {triple}` once to enable the fast path)"
));
}
None
}
pub(crate) fn cross_build_static(
triple: &str,
log_tx: &std::sync::mpsc::Sender<String>,
) -> Result<PathBuf> {
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()
);
}
Ok(binary)
}
fn try_local_cross_install_streaming(
ssh: &SshControl,
lane: &crate::remote_bulk::BulkLane,
source_stamp: &str,
log_tx: &std::sync::mpsc::Sender<String>,
) -> Result<Option<String>> {
if let Some(reason) = cross_compile_unavailable_reason() {
let _ = log_tx.send(format!("Local cross-build skipped: {reason}"));
return Ok(Some(reason));
}
let Some(triple) = remote_target_triple(ssh)? else {
let reason = String::from("could not detect the remote architecture");
let _ = log_tx.send(format!("Local cross-build skipped: {reason}"));
return Ok(Some(reason));
};
if !rust_target_installed(triple) {
let reason = format!(
"rustup target `{triple}` missing (run `rustup target add {triple}` once to enable the fast path)"
);
let _ = log_tx.send(format!("Local cross-build skipped: {reason}"));
return Ok(Some(reason));
}
let binary = cross_build_static(triple, log_tx)?;
let mkdir = ssh.background_shell("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_file_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 act = ssh.background_shell(&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(None)
}
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 mkdir = ssh.background_shell(&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}");
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)
}
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, &mut |_| false);
});
}
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()?;
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 background_shell(&self, script: &str) -> Command {
let mut command = self.background_command();
command.arg(&self.host).arg(script);
command
}
}
#[cfg(test)]
thread_local! {
static TEST_SSH: std::cell::RefCell<Option<PathBuf>> = const { std::cell::RefCell::new(None) };
}
fn ssh_program() -> OsString {
#[cfg(test)]
if let Some(p) = TEST_SSH.with(|p| p.borrow().clone()) {
return p.into_os_string();
}
OsString::from("ssh")
}
fn ssh_socket_read(socket_path: &Path, host: &str, script: &str) -> Command {
let mut command = ssh_socket_command(socket_path, true);
command.arg(host).arg(script).stdout(Stdio::piped());
command
}
fn read_remote_hashes(mut command: Command) -> Option<std::collections::BTreeMap<String, String>> {
let out = crate::review_ops::spawn_retrying_busy(&mut command)
.and_then(std::process::Child::wait_with_output)
.ok()?;
if !out.status.success() {
return None;
}
crate::config_sync::parse_remote_listing(&String::from_utf8_lossy(&out.stdout))
}
fn ssh_socket_command(socket_path: &Path, background: bool) -> Command {
let mut command = Command::new(ssh_program());
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<()>>,
}
fn relay_setup_error(status: ExitStatus, stderr: &[u8]) -> String {
let err = String::from_utf8_lossy(stderr);
let err = err.trim();
if err.is_empty() {
format!("remote relay setup failed with {status}")
} else {
format!("remote relay setup failed with {status}: {err}")
}
}
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::piped())
.output()
.context("preparing remote drop relay")?;
if !output.status.success() {
anyhow::bail!("{}", relay_setup_error(output.status, &output.stderr));
}
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();
}
}
}
const MISSING_PULL_GRACE: std::time::Duration = std::time::Duration::from_secs(2);
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 };
let request = parse_relay_request(&line);
if let Some(RelayRequest::Pull { id, src }) = &request
&& !Path::new(src).exists()
{
let (host, socket, inbox_dir) = (host.clone(), socket.clone(), inbox_dir.clone());
let (id, src) = (id.clone(), src.clone());
thread::spawn(move || {
thread::sleep(MISSING_PULL_GRACE);
if ssh_exec(&host, &socket, &claim_command(&inbox_dir, &id)) {
handle_pull_request(&host, &socket, &inbox_dir, &id, &src);
}
});
continue;
}
if let Some(id) = request.as_ref().and_then(RelayRequest::id)
&& !ssh_exec(&host, &socket, &claim_command(&inbox_dir, id))
{
continue;
}
match request {
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::Copy { id }) => {
handle_copy_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}"),
),
}
}
fn handle_copy_request(host: &str, socket: &Path, inbox_dir: &str, request_id: &str) {
if !copy_request_id_is_safe(request_id) {
return;
}
let quoted = shell_quote(&format!("{inbox_dir}/{request_id}.txt"));
let limit = MAX_COPY_PAYLOAD_BYTES + 1;
let remote_cmd = format!("head -c {limit} {quoted}; rm -f {quoted}");
let Ok(mut child) = Command::new("ssh")
.arg("-S")
.arg(socket)
.arg("-o")
.arg("ControlMaster=no")
.arg(host)
.arg(&remote_cmd)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
else {
return;
};
let Some(mut out) = child.stdout.take() else {
let _ = child.kill();
let _ = child.wait();
return;
};
let (tx, rx) = std::sync::mpsc::channel();
thread::spawn(move || {
use std::io::Read as _;
let mut buf = Vec::new();
let _ = out.by_ref().take(limit as u64).read_to_end(&mut buf);
let _ = tx.send(buf);
});
let payload = match rx.recv_timeout(COPY_READ_TIMEOUT) {
Ok(bytes) => {
let _ = child.wait();
bytes
}
Err(_) => {
let _ = child.kill();
let _ = child.wait();
return;
}
};
if payload.is_empty() || payload.len() > MAX_COPY_PAYLOAD_BYTES {
return;
}
let _ = crate::clipboard::write_string(&String::from_utf8_lossy(&payload));
}
pub(crate) const MAX_COPY_PAYLOAD_BYTES: usize = 4 * 1024 * 1024;
const COPY_READ_TIMEOUT: Duration = Duration::from_secs(15);
fn copy_request_id_is_safe(id: &str) -> bool {
!id.is_empty()
&& id.len() <= 128
&& id
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
}
enum RelayRequest {
Pull {
id: String,
src: String,
},
Clipboard {
id: String,
},
Copy {
id: String,
},
Open {
id: String,
url: String,
},
Forward {
id: String,
port: String,
open: bool,
},
Unforward {
local: String,
remote: String,
},
}
impl RelayRequest {
fn id(&self) -> Option<&str> {
match self {
Self::Pull { id, .. }
| Self::Clipboard { id }
| Self::Copy { id }
| Self::Open { id, .. }
| Self::Forward { id, .. } => Some(id),
Self::Unforward { .. } => None,
}
}
}
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 }),
"copy" => Some(RelayRequest::Copy { 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 pull_source_allowed(src: &Path) -> bool {
use std::path::Component;
let hidden = |p: &Path| {
p.components().any(|c| match c {
Component::Normal(name) => name.to_string_lossy().starts_with('.'),
Component::ParentDir => true,
_ => false,
})
};
if !src.is_absolute() || hidden(src) {
return false;
}
std::fs::canonicalize(src).is_ok_and(|real| !hidden(&real))
}
fn pull_tar_args(parent: &Path, basename: &std::ffi::OsStr) -> Vec<std::ffi::OsString> {
let mut args: Vec<std::ffi::OsString> = ["-c", "-f", "-", "--exclude", ".*", "-C"]
.iter()
.map(Into::into)
.collect();
args.push(parent.into());
args.push("--".into());
args.push(basename.into());
args
}
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() && !pull_source_allowed(&src_path) {
write_relay_err(
host,
socket,
inbox_dir,
request_id,
&format!("refusing to send a hidden path: {}", src_path.display()),
);
return;
}
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")
.args(pull_tar_args(parent, 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 claim_command(inbox_dir: &str, id: &str) -> String {
let claims = format!("{inbox_dir}/.claims");
format!(
"mkdir -p {} && mkdir {}",
shell_quote(&claims),
shell_quote(&format!("{claims}/{id}"))
)
}
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(crate) fn client_process_nonce() -> String {
use std::hash::{Hash, Hasher};
let mut hasher = std::collections::hash_map::DefaultHasher::new();
std::process::id().hash(&mut hasher);
if let Ok(since_epoch) = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH) {
since_epoch.as_nanos().hash(&mut hasher);
}
let here = Box::new(0u8);
(Box::as_ref(&here) as *const u8 as usize).hash(&mut hasher);
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();
static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let dir = std::env::temp_dir().join(format!("croft-ssh-{}-{now}-{seq}", std::process::id()));
let mut builder = std::fs::DirBuilder::new();
#[cfg(unix)]
{
use std::os::unix::fs::DirBuilderExt;
builder.mode(0o700);
}
builder
.create(&dir)
.with_context(|| format!("creating {}", dir.display()))?;
Ok(dir)
}
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<()> {
let mut ship = |binary: &Path| -> Result<()> {
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 status = Command::new("rsync")
.args(["-az", "--checksum", "-e"])
.arg(&ssh_e)
.arg(binary)
.arg(&dest)
.status()
.context("rsyncing the prebuilt croft to the remote")?;
anyhow::ensure!(status.success(), "rsync exited with {status}");
Ok(())
};
match try_prebuilt_install(ssh, source_stamp, &mut ship, &mut |m| println!("{m}")) {
Ok(true) => return Ok(()),
Ok(false) => {}
Err(e) => eprintln!("Prebuilt install failed ({e:#}); building instead"),
}
let reason = match try_local_cross_install(ssh, source_stamp) {
Ok(None) => return Ok(()),
Ok(Some(reason)) => reason,
Err(e) => {
eprintln!("Local cross-build failed ({e:#})");
format!("local cross-build failed: {e:#}")
}
};
if !confirm_remote_compile_on_tty(&ssh.host, &reason) {
anyhow::bail!(
"cross-build unavailable ({reason}); remote compile declined — run `croft setup-cross`, then `croft remote {}` again for the fast install",
ssh.host
);
}
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 push_config_files(ssh: &SshControl, resolution: &SyncResolution, log: &mut dyn FnMut(String)) {
let prefs = crate::config_layers::load_merged(None).prefs;
if crate::config_sync::host_excluded(&ssh.host, &prefs.config_sync_excluded_hosts) {
log(format!(
"Config sync: off for {} (config_sync_excluded_hosts)",
ssh.host
));
return;
}
let (files, skipped) = crate::config_sync::apply_exclusions(
crate::config_sync::local_files(),
&prefs.config_sync_excluded_files,
);
if !skipped.is_empty() {
log(format!(
"Config sync: not pushing {} (config_sync_excluded_files)",
skipped.join(", ")
));
}
if files.is_empty() {
return;
}
let mut mk = ssh.background_shell("mkdir -p ~/.config/croft");
if !matches!(mk.status(), Ok(st) if st.success()) {
log(String::from(
"Config sync: could not create ~/.config/croft on the remote; skipping",
));
return;
}
let Some(remote) = read_remote_hashes(ssh_socket_read(
&ssh.socket_path,
&ssh.host,
&crate::config_sync::remote_hash_script(),
)) else {
log(String::from(
"Config sync: could not read the remote's copies; pushing nothing rather than risk overwriting them",
));
return;
};
let state_path = crate::config_sync::SyncState::path();
let mut state = crate::config_sync::SyncState::load(&state_path);
let bulk = crate::remote_bulk::establish(&ssh.host, &ssh.socket_path, |_| {});
let mut pushed = Vec::new();
let mut failed = Vec::new();
let mut kept = Vec::new();
let mut conflicts = Vec::new();
for (syncable, local) in &files {
let Ok(bytes) = std::fs::read(local) else {
failed.push(syncable.name);
continue;
};
let local_hash = crate::config_sync::content_hash(&bytes);
let there = remote.get(syncable.name).map(String::as_str);
let chosen = |list: &[String]| list.iter().any(|n| n == syncable.name);
let plan = if chosen(&resolution.take_local) {
crate::config_sync::Plan::Push
} else if chosen(&resolution.keep_remote) && there.is_some_and(|r| r != local_hash) {
let entry = state.file_mut(&ssh.host, syncable.name);
entry.kept = there.map(|r| (r.to_string(), local_hash.clone()));
crate::config_sync::Plan::Kept
} else {
crate::config_sync::plan(&local_hash, there, state.file(&ssh.host, syncable.name))
};
match plan {
crate::config_sync::Plan::Push => {
let dest = crate::config_sync::remote_dest(&ssh.host, syncable.name);
let mut rsync = ship_file_rsync_command(&bulk.lane, &ssh.socket_path, local, &dest);
match rsync.status() {
Ok(st) if st.success() => {
let entry = state.file_mut(&ssh.host, syncable.name);
entry.pushed = Some(local_hash);
entry.kept = None;
pushed.push(syncable);
}
_ => failed.push(syncable.name),
}
}
crate::config_sync::Plan::UpToDate => {
let entry = state.file_mut(&ssh.host, syncable.name);
entry.pushed = Some(local_hash);
entry.kept = None;
}
crate::config_sync::Plan::Kept => kept.push(syncable.name),
crate::config_sync::Plan::Conflict => conflicts.push(syncable.name),
}
}
if let Err(e) = state.save(&state_path) {
log(format!(
"Config sync: could not record what was pushed ({e})"
));
}
if !kept.is_empty() {
log(format!(
"Config sync: keeping the remote's own {} (as you chose)",
kept.join(", ")
));
}
for name in &conflicts {
log(format!(
"Config sync: {name} was changed on {host} since croft last pushed it, so it was left alone. \
`croft sync-config {host} --diff {name}` compares the two; `--take-local {name}` pushes yours, \
`--keep-remote {name}` keeps theirs",
host = ssh.host
));
}
if !pushed.is_empty() {
let names: Vec<&str> = pushed.iter().map(|s| s.name).collect();
log(format!("Config sync: pushed {}", names.join(", ")));
log(format!(
"Config sync: {} applies on the remote within a few seconds",
names.join(", ")
));
}
if !failed.is_empty() {
log(format!(
"Config sync: could not push {} (the remote keeps its own copy)",
failed.join(", ")
));
}
}
#[derive(Debug, Default, Clone)]
pub struct SyncResolution {
pub take_local: Vec<String>,
pub keep_remote: Vec<String>,
}
pub fn sync_config_now(host: &str, resolution: &SyncResolution, diff: Option<&str>) -> Result<()> {
for name in resolution
.take_local
.iter()
.chain(&resolution.keep_remote)
.map(String::as_str)
.chain(diff)
{
if !crate::config_sync::SYNCABLE.iter().any(|s| s.name == name) {
let names: Vec<&str> = crate::config_sync::SYNCABLE
.iter()
.map(|s| s.name)
.collect();
anyhow::bail!("{name} is not a synced file ({})", names.join(", "));
}
}
let ssh = SshControl::start(host)?;
match diff {
Some(name) => print_config_diff(&ssh, name),
None => {
push_config_files(&ssh, resolution, &mut |msg| println!("{msg}"));
Ok(())
}
}
}
struct ConfigRepush {
target: std::sync::Arc<std::sync::Mutex<(String, PathBuf)>>,
stop: std::sync::Arc<std::sync::atomic::AtomicBool>,
worker: Option<std::thread::JoinHandle<()>>,
}
impl ConfigRepush {
fn start(ssh: &SshControl, watch: crate::config_sync::ConfigWatch) -> Self {
let target = std::sync::Arc::new(std::sync::Mutex::new((
ssh.host.clone(),
ssh.socket_path.clone(),
)));
let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let (t, s) = (target.clone(), stop.clone());
let worker = std::thread::spawn(move || {
let dir = crate::prefs::config_dir();
let mut state = RepushState::new(watch);
let mut exclusions = SyncExclusions::load();
let mut log = config_sync_log();
loop {
std::thread::sleep(std::time::Duration::from_millis(500));
if s.load(std::sync::atomic::Ordering::Relaxed) {
return;
}
let (host, socket) = match t.lock() {
Ok(g) => g.clone(),
Err(_) => return,
};
repush_tick(
&mut state,
&dir,
std::time::Instant::now(),
&mut || match exclusions.current() {
None => RepushGate::Unknown,
Some((hosts, _)) if crate::config_sync::host_excluded(&host, &hosts) => {
RepushGate::HostExcluded
}
Some((_, files)) => RepushGate::Push(files),
},
&mut |files| push_over_bulk_lane(&host, &socket, files),
&mut log,
);
}
});
ConfigRepush {
target,
stop,
worker: Some(worker),
}
}
fn retarget(&self, ssh: &SshControl) {
if let Ok(mut g) = self.target.lock() {
*g = (ssh.host.clone(), ssh.socket_path.clone());
}
}
}
fn print_config_diff(ssh: &SshControl, name: &str) -> Result<()> {
let local = crate::prefs::config_dir().join(name);
let out = ssh_socket_read(
&ssh.socket_path,
&ssh.host,
&format!("cat ~/.config/croft/{name} 2>/dev/null"),
)
.output()?;
let tmp = std::env::temp_dir().join(format!("croft-sync-{}-{name}", std::process::id()));
std::fs::write(&tmp, &out.stdout)?;
let local_arg = if local.is_file() {
local
} else {
PathBuf::from("/dev/null")
};
let status = Command::new("diff")
.args(["-u", "--label"])
.arg(format!("{}:{name}", ssh.host))
.arg("--label")
.arg(format!("local:{name}"))
.arg(&tmp)
.arg(&local_arg)
.status();
let _ = std::fs::remove_file(&tmp);
let status = status?;
if status.code() == Some(0) {
println!("{name} is the same on {} and here", ssh.host);
}
Ok(())
}
impl Drop for ConfigRepush {
fn drop(&mut self) {
self.stop.store(true, std::sync::atomic::Ordering::Relaxed);
if let Some(worker) = self.worker.take() {
let _ = worker.join();
}
}
}
struct SyncExclusions {
known: Option<(Vec<String>, Vec<String>)>,
}
impl SyncExclusions {
fn load() -> Self {
let mut ex = SyncExclusions { known: None };
ex.update(crate::config_layers::load_merged(None));
ex
}
fn current(&mut self) -> Option<(Vec<String>, Vec<String>)> {
self.update(crate::config_layers::load_merged(None));
self.known.clone()
}
fn update(&mut self, merged: crate::config_layers::MergedConfig) {
if merged.warnings.is_empty() {
self.known = Some((
merged.prefs.config_sync_excluded_hosts,
merged.prefs.config_sync_excluded_files,
));
}
}
}
enum RepushGate {
Push(Vec<String>),
HostExcluded,
Unknown,
}
const REPUSH_RETRY: std::time::Duration = std::time::Duration::from_secs(10);
struct RepushState {
watch: crate::config_sync::ConfigWatch,
pending: std::collections::BTreeSet<PathBuf>,
retry_at: Option<std::time::Instant>,
}
impl RepushState {
fn new(watch: crate::config_sync::ConfigWatch) -> Self {
RepushState {
watch,
pending: std::collections::BTreeSet::new(),
retry_at: None,
}
}
}
type Pushes = [(crate::config_sync::Syncable, PathBuf)];
#[derive(Debug, Default, Clone, PartialEq, Eq)]
struct PushResult {
failed: Vec<&'static str>,
held: Vec<&'static str>,
}
fn repush_tick(
state: &mut RepushState,
dir: &Path,
now: std::time::Instant,
exclusions: &mut dyn FnMut() -> RepushGate,
push: &mut dyn FnMut(&Pushes) -> PushResult,
log: &mut dyn FnMut(String),
) {
let changed = state.watch.poll(now);
let retry_due = state.retry_at.is_some_and(|t| now >= t);
if changed.is_empty() && !retry_due {
return;
}
state.pending.extend(changed);
let pending: Vec<PathBuf> = state.pending.iter().cloned().collect();
let files = crate::config_sync::repush_targets(&pending, dir);
state.pending = files.iter().map(|(_, p)| p.clone()).collect();
state.retry_at = None;
if files.is_empty() {
return;
}
let excluded = match exclusions() {
RepushGate::Push(excluded) => excluded,
RepushGate::HostExcluded => {
state.pending.clear();
return;
}
RepushGate::Unknown => {
state.retry_at = Some(now + REPUSH_RETRY);
log(String::from(
"Config sync: holding changes until the config-sync exclusions read cleanly",
));
return;
}
};
let (files, _) = crate::config_sync::apply_exclusions(files, &excluded);
if files.is_empty() {
state.pending.clear();
return;
}
let PushResult { failed, held } = push(&files);
state.pending = files
.iter()
.filter(|(s, _)| failed.contains(&s.name))
.map(|(_, p)| p.clone())
.collect();
if !state.pending.is_empty() {
state.retry_at = Some(now + REPUSH_RETRY);
}
let pushed: Vec<&str> = files
.iter()
.map(|(s, _)| s.name)
.filter(|n| !failed.contains(n) && !held.contains(n))
.collect();
if !pushed.is_empty() {
log(format!("Config sync: re-pushed {}", pushed.join(", ")));
}
for name in &held {
log(format!(
"Config sync: left {name} alone: it was changed on the remote since croft last pushed it \
(`croft sync-config <host> --diff {name}`)"
));
}
if !failed.is_empty() {
log(format!(
"Config sync: could not re-push {} (the remote keeps its copy)",
failed.join(", ")
));
}
}
fn push_over_bulk_lane(
host: &str,
socket: &Path,
files: &[(crate::config_sync::Syncable, PathBuf)],
) -> PushResult {
let mut mk = ssh_socket_command(socket, true);
mk.arg(host).arg("mkdir -p ~/.config/croft");
let all_failed = || PushResult {
failed: files.iter().map(|(s, _)| s.name).collect(),
held: Vec::new(),
};
if !matches!(mk.status(), Ok(st) if st.success()) {
return all_failed();
}
let Some(remote) = read_remote_hashes(ssh_socket_read(
socket,
host,
&crate::config_sync::remote_hash_script(),
)) else {
return all_failed();
};
let state_path = crate::config_sync::SyncState::path();
let mut state = crate::config_sync::SyncState::load(&state_path);
let bulk = crate::remote_bulk::establish(host, socket, |_| {});
let mut result = PushResult::default();
for (syncable, local) in files {
let Ok(bytes) = std::fs::read(local) else {
result.failed.push(syncable.name);
continue;
};
let hash = crate::config_sync::content_hash(&bytes);
let there = remote.get(syncable.name).map(String::as_str);
match crate::config_sync::plan(&hash, there, state.file(host, syncable.name)) {
crate::config_sync::Plan::Push => {
let dest = crate::config_sync::remote_dest(host, syncable.name);
let ok = matches!(
ship_file_rsync_command(&bulk.lane, socket, local, &dest).status(),
Ok(st) if st.success()
);
if ok {
let entry = state.file_mut(host, syncable.name);
entry.pushed = Some(hash);
entry.kept = None;
} else {
result.failed.push(syncable.name);
}
}
crate::config_sync::Plan::UpToDate => {
let entry = state.file_mut(host, syncable.name);
entry.pushed = Some(hash);
entry.kept = None;
}
crate::config_sync::Plan::Kept | crate::config_sync::Plan::Conflict => {
result.held.push(syncable.name)
}
}
}
let _ = state.save(&state_path);
result
}
fn config_sync_log() -> impl FnMut(String) {
let path = install_log_path().with_file_name("config-sync.log");
move |line: String| {
use std::io::Write as _;
if let Some(parent) = path.parent() {
let _ = std::fs::create_dir_all(parent);
}
if let Ok(mut f) = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(&path)
{
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}");
}
}
}
fn ship_file_rsync_command(
lane: &crate::remote_bulk::BulkLane,
interactive_socket: &Path,
local: &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(local).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
}
pub(crate) static FORCE_SOURCE_BUILD: std::sync::atomic::AtomicBool =
std::sync::atomic::AtomicBool::new(false);
fn try_prebuilt_install(
ssh: &SshControl,
source_stamp: &str,
ship: &mut dyn FnMut(&Path) -> Result<()>,
log: &mut dyn FnMut(String),
) -> Result<bool> {
if FORCE_SOURCE_BUILD.load(std::sync::atomic::Ordering::Relaxed) {
log(String::from(
"Prebuilt install skipped: --build asked for a source build",
));
return Ok(false);
}
if !crate::remote_prebuilt::eligible(env!("CARGO_MANIFEST_DIR")) {
log(String::from(
"Prebuilt install skipped: this croft is a source build, so the remote gets the same source",
));
return Ok(false);
}
let Some(triple) = remote_target_triple(ssh)? else {
log(String::from(
"Prebuilt install skipped: no release for the remote's architecture",
));
return Ok(false);
};
let version = env!("CARGO_PKG_VERSION");
let cache = crate::session_state::dirs_cache_croft().join("prebuilt");
let binary = match crate::remote_prebuilt::prepare(
version,
triple,
&cache,
&crate::remote_prebuilt::http_get,
&crate::remote_prebuilt::cosign_verify,
) {
Ok((b, crate::remote_prebuilt::Signature::Verified)) => {
log(format!(
"Release signature verified: v{version}'s SHA256SUMS was signed by its release workflow"
));
b
}
Ok((b, crate::remote_prebuilt::Signature::Unchecked)) => {
log(format!(
"Release signature NOT checked: cosign is not installed here, so v{version}'s SHA256SUMS rests on HTTPS to GitHub; install cosign to verify it"
));
b
}
Err(e) if crate::remote_prebuilt::is_not_published(&e) => {
log(format!(
"Prebuilt install skipped: v{version} has no release binary for {triple}"
));
return Ok(false);
}
Err(e) => return Err(e),
};
let size_mb = std::fs::metadata(&binary).map(|m| m.len()).unwrap_or(0) as f64 / 1e6;
log(format!(
"Installing prebuilt croft v{version} for {triple} ({size_mb:.0} MB) over SSH"
));
let mkdir = ssh
.command()
.arg(&ssh.host)
.arg("mkdir -p \"$HOME/.cargo/bin\" \"$HOME/.cache/croft\"")
.status()
.context("creating remote install dirs")?;
anyhow::ensure!(mkdir.success(), "remote mkdir exited with {mkdir}");
ship(&binary)?;
let activate = ssh
.command()
.arg(&ssh.host)
.arg(activate_command(source_stamp))
.status()
.context("activating the prebuilt croft on the remote")?;
anyhow::ensure!(
activate.success(),
"remote activation exited with {activate}"
);
log(format!("Installed prebuilt croft v{version} on the remote"));
Ok(true)
}
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<Option<String>> {
if let Some(reason) = cross_compile_unavailable_reason() {
eprintln!("Local cross-build skipped: {reason}");
return Ok(Some(reason));
}
let Some(triple) = remote_target_triple(ssh)? else {
let reason = String::from("could not detect the remote architecture");
eprintln!("Local cross-build skipped: {reason}");
return Ok(Some(reason));
};
if !rust_target_installed(triple) {
let reason = format!(
"rustup target `{triple}` not installed (run `rustup target add {triple}` once to enable the fast path)"
);
eprintln!("Local cross-build skipped: {reason}");
return Ok(Some(reason));
}
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(None)
}
fn confirm_remote_compile_on_tty(host: &str, reason: &str) -> bool {
use std::io::{IsTerminal as _, Write as _};
eprintln!("Fast install unavailable: {reason}");
eprintln!(
"Croft can compile itself on {host} instead; the first build can take several minutes and loads the box."
);
if !std::io::stdin().is_terminal() {
eprintln!(
"stdin is not a terminal; declining the remote compile. Run `croft setup-cross`, then retry."
);
return false;
}
eprint!(
"Compile on {host} anyway? [y/N] (N quits; run `croft setup-cross` once and reconnect — much faster) "
);
let _ = std::io::stderr().flush();
let mut line = String::new();
if std::io::stdin().read_line(&mut line).is_err() {
return false;
}
matches!(line.trim().to_ascii_lowercase().as_str(), "y" | "yes")
}
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(),
std::env::var(crate::iterm2_inline::CROFT_INLINE_IMAGES_ENV)
.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>,
croft_inline_images: 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_in(term_program, term, croft_inline_images) {
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"'\''"))
}
}
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()
}
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.
CROFT_LIVE=""
if pgrep -x croft >/dev/null 2>&1; then
CROFT_JOBS=1
CROFT_LIVE=1
fi
# nice and ionice ration CPU and IO, not memory (#694). Each rustc job on
# croft costs well over a GB, so on a host under 16 GB two of them next to
# rust-analyzer were enough to wake the OOM killer, which then took croft or
# a terminal pane. Below that, compile one crate at a time.
CROFT_MEM_KB=$(awk '/^MemTotal:/ {{ print $2 }}' /proc/meminfo 2>/dev/null || true)
CROFT_AVAIL_KB=$(awk '/^MemAvailable:/ {{ print $2 }}' /proc/meminfo 2>/dev/null || true)
if [ -n "$CROFT_MEM_KB" ] && [ "$CROFT_MEM_KB" -lt 16777216 ]; then
CROFT_JOBS=1
fi
# Little memory free right now counts too, whatever the total: a big host
# can still be mostly spoken for by the time the update runs.
if [ -n "$CROFT_AVAIL_KB" ] && [ "$CROFT_AVAIL_KB" -lt 2097152 ]; then
CROFT_JOBS=1
echo "croft: only $(( CROFT_AVAIL_KB / 1024 )) MB of memory available; building with one job" >&2
fi
# And cap the build's memory outright where systemd can: the compile runs
# in its own scope limited to 60% of RAM with no swap, so if it outgrows
# that it is the BUILD the kernel kills, inside its scope, and never croft
# or a shell. Probed first, because a user manager or a delegated memory
# controller is not a given on a server; without one the build runs uncapped
# but still single-job on a small host.
CROFT_MEMCAP=""
# The probe reads the limit back from inside a test scope: systemd accepts
# MemoryMax without complaint where the memory controller is not delegated
# to the user manager (cgroup v1 and hybrid hosts), and enforces nothing.
if [ -n "$CROFT_MEM_KB" ] && command -v systemd-run >/dev/null 2>&1 \
&& [ "$(systemd-run --user --scope --quiet -p MemoryMax=64M -p MemorySwapMax=0 \
sh -c 'cat "/sys/fs/cgroup$(sed -n "s/^0:://p" /proc/self/cgroup)/memory.max"' 2>/dev/null)" = 67108864 ]; then
CROFT_MEMCAP="systemd-run --user --scope --quiet -p MemoryMax=$(( CROFT_MEM_KB * 6 / 10 ))K -p MemorySwapMax=0"
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
# Tell a croft running on this box that a compile is under way, so it stops
# its own language servers (rust-analyzer alone held 2.4 GB in the OOM that
# prompted #694) and restarts them once no marker names a live build.
#
# One marker per build (`building.<this shell's pid>`), so a second install
# finishing first cannot clear the first's. It holds the pid of the COMPILE
# once it starts (systemd-run --scope, nice and ionice all exec, so `$!` is
# cargo itself): a shell killed mid-build leaves cargo running as an orphan,
# and the marker must keep naming it. Markers whose pid is gone are stale;
# they are swept here, and croft ignores them and any from before a reboot.
#
# Which boot a marker belongs to is `building.<pid>.boot`, the kernel's
# boot_id (#736): unlike boot time it does not move when the wall clock is
# stepped. A sidecar rather than a second field, so a croft from before it,
# which reads the marker as one pid, still pauses for this build.
mkdir -p "$HOME/.cache/croft"
# The script runs under the login shell, and zsh aborts on a glob that
# matches nothing (NOMATCH), which an empty cache always is (#734).
# null_glob makes it expand to nothing, as the `[ -f ]` below expects of
# every other shell. Not `emulate sh`: that also clears ERR_EXIT, and a
# failed compile would then write the install stamp.
[ -z "${{ZSH_VERSION:-}}" ] || setopt null_glob
CROFT_BOOT=$(cat /proc/sys/kernel/random/boot_id 2>/dev/null || true)
for CROFT_OLD in "$HOME/.cache/croft"/building.*; do
[ -f "$CROFT_OLD" ] || continue
case "$CROFT_OLD" in
# Its marker sorts first, so a sidecar whose marker is gone is orphaned.
*.boot) [ -e "${{CROFT_OLD%.boot}}" ] || rm -f "$CROFT_OLD"; continue ;;
esac
CROFT_OLD_PID=$(cat "$CROFT_OLD" 2>/dev/null || true)
CROFT_OLD_BOOT=$(cat "$CROFT_OLD.boot" 2>/dev/null || true)
if [ -z "$CROFT_OLD_PID" ] || ! kill -0 "$CROFT_OLD_PID" 2>/dev/null \
|| {{ [ -n "$CROFT_OLD_BOOT" ] && [ -n "$CROFT_BOOT" ] && [ "$CROFT_OLD_BOOT" != "$CROFT_BOOT" ]; }}; then
rm -f "$CROFT_OLD" "$CROFT_OLD.boot"
fi
done
CROFT_MARK="$HOME/.cache/croft/building.$$"
CROFT_BUILD_PID=""
if [ -n "$CROFT_BOOT" ]; then printf %s "$CROFT_BOOT" > "$CROFT_MARK.boot"; fi
printf %s "$$" > "$CROFT_MARK"
# Keep the marker while the compile outlives this shell; croft sees it go
# stale the moment the compile ends.
trap 'if [ -z "$CROFT_BUILD_PID" ] || ! kill -0 "$CROFT_BUILD_PID" 2>/dev/null; then rm -f "$CROFT_MARK" "$CROFT_MARK.boot"; fi' EXIT
if [ -n "$CROFT_LIVE" ]; then
# croft polls the marker once a second, and a server gets up to three
# seconds to shut down cleanly: let both finish before the first rustc.
sleep 5
fi
# eval, because this script runs under the remote user's login shell and
# zsh does not word-split unquoted parameters: bare `$CROFT_NICE ...` would
# try to run a command literally named "nice -n 19". eval re-parses the
# assembled line, which splits correctly under both sh/bash and zsh.
# The subshell marks the build (and every rustc under it) as the kernel's
# first choice when memory runs out, without touching this shell (#694),
# then `exec`s it, so `$!` below is still the compile's own pid.
(
echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true
eval "exec $CROFT_MEMCAP $CROFT_NICE $CROFT_IONICE"' cargo install --path "$HOME/.cache/croft/source" --jobs "$CROFT_JOBS" --force --locked'
) &
CROFT_BUILD_PID=$!
printf %s "$CROFT_BUILD_PID" > "$CROFT_MARK"
wait "$CROFT_BUILD_PID"
rm -f "$CROFT_MARK" "$CROFT_MARK.boot"
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> {
build_stamp_for(
&PathBuf::from(env!("CARGO_MANIFEST_DIR")),
env!("CARGO_PKG_VERSION"),
)
}
fn build_stamp_for(root: &PathBuf, version: &str) -> Result<String> {
if !root.exists() {
return Ok(format!("release-v{version}"));
}
source_stamp_for(root)
}
fn source_snapshot_warning() -> Option<String> {
let dir = env!("CARGO_MANIFEST_DIR");
source_dir_is_snapshot(dir).then(|| {
format!(
"WARNING: this croft was installed from an immutable snapshot ({dir}); remote installs can never ship local changes. Reinstall with `cargo install --path <your repo>` to make installs track your tree."
)
})
}
fn source_dir_is_snapshot(dir: &str) -> bool {
dir.contains("/registry/src/") || dir.contains("/git/checkouts/")
}
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 {
#[cfg(unix)]
fn fake_ssh(dir: &Path, home: &Path) {
use std::os::unix::fs::PermissionsExt;
let shim = dir.join("ssh");
std::fs::write(
&shim,
format!(
"#!/bin/sh\nwhile [ $# -gt 0 ]; do case \"$1\" in -S|-o) shift 2;; -*) shift;; *) break;; esac; done\nshift\nHOME='{}' exec sh -c \"$*\"\n",
home.display()
),
)
.unwrap();
std::fs::set_permissions(&shim, std::fs::Permissions::from_mode(0o755)).unwrap();
TEST_SSH.with(|p| *p.borrow_mut() = Some(shim));
}
#[cfg(unix)]
#[test]
fn the_config_hash_read_sees_the_remotes_files() {
let bin = tempfile::tempdir().unwrap();
let home = tempfile::tempdir().unwrap();
let dir = home.path().join(".config/croft");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("triggers.json"), "{\"c\": \"#123456\"}\n").unwrap();
fake_ssh(bin.path(), home.path());
let got = read_remote_hashes(ssh_socket_read(
&bin.path().join("ctl"),
"box",
&crate::config_sync::remote_hash_script(),
))
.expect("the listing reads");
assert_eq!(
got.get("triggers.json"),
Some(&crate::config_sync::content_hash(b"{\"c\": \"#123456\"}\n")),
"{got:?}"
);
}
#[cfg(unix)]
#[test]
fn the_config_diff_read_returns_the_remote_copy() {
let bin = tempfile::tempdir().unwrap();
let home = tempfile::tempdir().unwrap();
let dir = home.path().join(".config/croft");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("triggers.json"), "remote copy\n").unwrap();
fake_ssh(bin.path(), home.path());
let out = ssh_socket_read(
&bin.path().join("ctl"),
"box",
"cat ~/.config/croft/triggers.json 2>/dev/null",
)
.output()
.unwrap();
assert_eq!(String::from_utf8_lossy(&out.stdout), "remote copy\n");
}
#[cfg(unix)]
#[test]
fn a_read_still_keeps_ssh_off_the_terminal() {
let bin = tempfile::tempdir().unwrap();
let home = tempfile::tempdir().unwrap();
fake_ssh(bin.path(), home.path());
let mut cmd = ssh_socket_read(&bin.path().join("ctl"), "box", "cat && echo done >&2");
assert!(cmd.get_args().any(|a| a == "-n"));
let out = cmd.output().unwrap();
assert!(out.stdout.is_empty());
assert!(out.stderr.is_empty(), "stderr stays off the terminal");
}
#[cfg(unix)]
#[test]
fn an_unreadable_listing_pushes_nothing() {
let bin = tempfile::tempdir().unwrap();
let home = tempfile::tempdir().unwrap();
fake_ssh(bin.path(), home.path());
assert_eq!(
read_remote_hashes(ssh_socket_read(&bin.path().join("ctl"), "box", "exit 255")),
None
);
}
#[cfg(unix)]
#[test]
fn a_session_host_or_dtach_on_the_remote_makes_the_session_persistent() {
use std::os::unix::fs::PermissionsExt;
let exe = |path: &Path, body: &str| {
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, format!("#!/bin/sh\n{body}\n")).unwrap();
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap();
};
let check = |home: &Path, extra_path: &Path| {
std::process::Command::new("/bin/sh")
.arg("-c")
.arg(session_supervisor_check_command())
.env("HOME", home)
.env("PATH", format!("{}:/usr/bin:/bin", extra_path.display()))
.status()
.unwrap()
.success()
};
let home = tempfile::tempdir().unwrap();
let bin = tempfile::tempdir().unwrap();
assert!(!check(home.path(), bin.path()), "neither supervisor");
let croft = home.path().join(".cargo/bin/croft");
exe(&croft, "[ \"$1 $2\" = 'session-host --probe' ]");
assert!(check(home.path(), bin.path()), "croft's session host");
exe(&croft, "exit 2");
assert!(!check(home.path(), bin.path()));
exe(&bin.path().join("dtach"), "exit 0");
assert!(check(home.path(), bin.path()), "dtach");
let launch = remote_croft_command_for_terminal(None, None, None, None, false, &[], false);
assert!(launch.contains("croft session-host --probe >/dev/null 2>&1"));
assert!(launch.contains("command -v dtach >/dev/null 2>&1"));
}
fn report(path: &str, host: Option<&str>) -> CwdReport {
(std::path::PathBuf::from(path), host.map(str::to_string))
}
#[test]
fn a_new_remote_report_is_the_workspace_path() {
let before = report("/Users/me/code", Some("localhost"));
let now = report("/srv/app", Some("db-1.internal"));
assert_eq!(
remote_workspace_path("db-1", Some(&before), Some(&now)).as_deref(),
Some("/srv/app")
);
assert_eq!(
remote_workspace_path("db-1", None, Some(&now)).as_deref(),
Some("/srv/app")
);
}
#[test]
fn an_unchanged_report_counts_only_when_it_names_the_host() {
let same = report("/srv/app", Some("db-1"));
assert_eq!(
remote_workspace_path("db-1", Some(&same), Some(&same)).as_deref(),
Some("/srv/app"),
"the remote prompt reported before the offer sampled"
);
let fqdn = report("/srv/app", Some("DB-1.internal"));
assert_eq!(
remote_workspace_path("db-1", Some(&fqdn), Some(&fqdn)).as_deref(),
Some("/srv/app"),
"a domain-qualified name for the same host, any case"
);
let stale = report("/home/old", Some("web-7"));
assert_eq!(
remote_workspace_path("db-1", Some(&stale), Some(&stale)),
None,
"left over from an earlier session on another host"
);
let prefix = report("/x", Some("db-10"));
assert_eq!(
remote_workspace_path("db-1", Some(&prefix), Some(&prefix)),
None,
"db-10 is not db-1"
);
}
#[test]
fn a_local_or_hostless_report_is_never_remote() {
let local = report("/Users/me", Some("localhost"));
assert_eq!(remote_workspace_path("db-1", None, Some(&local)), None);
let hostless = report("/Users/me", None);
assert_eq!(remote_workspace_path("db-1", None, Some(&hostless)), None);
assert_eq!(remote_workspace_path("db-1", None, None), None);
}
#[test]
fn an_ssh_command_line_yields_its_destination() {
let d = |cmd: &[&str]| ssh_destination(cmd);
assert_eq!(d(&["ssh", "box"]).as_deref(), Some("box"));
assert_eq!(d(&["ssh", "user@box"]).as_deref(), Some("user@box"));
assert_eq!(d(&["ssh", "-p", "2222", "box"]).as_deref(), Some("box"));
assert_eq!(
d(&["ssh", "-i", "~/.ssh/id", "box"]).as_deref(),
Some("box")
);
assert_eq!(
d(&["ssh", "-o", "StrictHostKeyChecking=no", "box"]).as_deref(),
Some("box")
);
assert_eq!(d(&["ssh", "-4qt", "box"]).as_deref(), Some("box"));
assert_eq!(d(&["ssh", "-p2222", "box"]).as_deref(), Some("box"));
for f in [
"B", "b", "c", "D", "E", "e", "F", "I", "i", "J", "L", "l", "m", "O", "o", "P", "p",
"Q", "R", "S", "W", "w",
] {
let flag = format!("-{f}");
assert_eq!(
d(&["ssh", &flag, "decoy", "box"]).as_deref(),
Some("box"),
"-{f} swallowed its argument's place"
);
}
assert_eq!(
d(&["ssh", "box", "tail", "-f", "log"]).as_deref(),
Some("box")
);
assert_eq!(d(&["ssh", "--", "box"]).as_deref(), Some("box"));
assert_eq!(d(&["ssh", "-4", "--", "box"]).as_deref(), Some("box"));
assert_eq!(d(&["/usr/bin/ssh", "box"]).as_deref(), Some("box"));
assert_eq!(d(&["ssh", "--", "-4"]).as_deref(), Some("-4"));
}
#[test]
fn the_offer_appears_only_for_a_known_host_in_an_ssh_pane() {
let targets = parse_ssh_config("Host db-1\n HostName 10.0.0.4\n");
let o = |cmd: &[&str]| {
ssh_reroot_decision(cmd, &targets)
.ok()
.map(|h| h.alias.clone())
};
assert_eq!(o(&["ssh", "db-1"]).as_deref(), Some("db-1"));
assert_eq!(
o(&["ssh", "-p", "2222", "deploy@10.0.0.4"]).as_deref(),
Some("db-1")
);
assert_eq!(o(&["zsh"]), None);
assert_eq!(o(&["ssh", "unknown-box"]), None);
assert_eq!(o(&["ssh"]), None);
assert_eq!(o(&["sshfs", "db-1:/srv", "/mnt"]), None);
}
#[test]
fn a_destination_resolves_against_the_configured_hosts() {
let targets = parse_ssh_config(
"Host db-1\n HostName 10.0.0.4\n User deploy\n\nHost web\n HostName web.example\n",
);
let m = |dest: &str| resolve_offer_host(dest, &targets).map(|t| t.alias.clone());
assert_eq!(m("db-1").as_deref(), Some("db-1"));
assert_eq!(m("deploy@db-1").as_deref(), Some("db-1"));
assert_eq!(m("root@db-1").as_deref(), Some("db-1"));
assert_eq!(m("10.0.0.4").as_deref(), Some("db-1"));
assert_eq!(m("web.example").as_deref(), Some("web"));
assert_eq!(m("DB-1").as_deref(), Some("db-1"));
assert_eq!(m("some-random-box"), None);
assert_eq!(m(""), None);
assert_eq!(m("db-1:22"), None);
let shadowed =
parse_ssh_config("Host jump\n HostName db-1\n\nHost db-1\n HostName 10.0.0.4\n");
assert_eq!(
resolve_offer_host("db-1", &shadowed)
.map(|t| t.alias.clone())
.as_deref(),
Some("db-1"),
"an alias must beat another entry's HostName"
);
assert_eq!(
resolve_offer_host("10.0.0.4", &shadowed)
.map(|t| t.alias.clone())
.as_deref(),
Some("db-1")
);
}
#[test]
fn the_decision_names_the_host_or_says_why_not() {
let targets = parse_ssh_config("Host db-1\n HostName 10.0.0.4\n");
let d = |argv: &[&str]| ssh_reroot_decision(argv, &targets).map(|t| t.alias.clone());
assert_eq!(d(&["ssh", "db-1"]), Ok(String::from("db-1")));
let err = d(&["ssh", "other-box"]).unwrap_err();
assert!(err.contains("other-box"), "unhelpful: {err}");
assert!(err.contains("ssh/config"), "unhelpful: {err}");
let err = d(&["zsh"]).unwrap_err();
assert_eq!(err, "This pane is not an SSH session");
assert!(!err.contains("ssh/config"));
}
#[test]
fn a_long_option_program_is_refused_rather_than_misparsed() {
let d = |cmd: &[&str]| ssh_destination(cmd);
for cmd in [
vec!["mosh", "box"],
vec!["mosh", "--port", "60000", "box"],
vec!["mosh", "--ssh", "ssh -p 2222", "box"],
vec!["et", "box"],
vec!["et", "--port", "2022", "box"],
] {
assert_eq!(
d(&cmd),
None,
"{cmd:?} must be refused while the grammar cannot parse it"
);
}
}
#[test]
fn a_non_ssh_command_line_yields_nothing() {
let d = |cmd: &[&str]| ssh_destination(cmd);
for cmd in [
vec!["zsh"],
vec!["ssh"], vec!["ssh", "-p", "2222"], vec!["ssh-agent"], vec!["ssh-keygen", "-t", "ed25519"],
vec!["sshfs", "box:/srv", "/mnt"], vec!["git", "push", "ssh://box/repo"],
vec![],
] {
assert_eq!(d(&cmd), None, "must not match: {cmd:?}");
}
}
#[test]
fn a_background_shell_puts_the_host_before_the_script() {
let ssh = SshControl {
host: String::from("somebox"),
socket_dir: PathBuf::from("/tmp/x"),
socket_path: PathBuf::from("/tmp/x/ctl"),
};
let cmd = ssh.background_shell("mkdir -p ~/.config/croft");
let args: Vec<String> = cmd
.get_args()
.map(|a| a.to_string_lossy().into_owned())
.collect();
let host_at = args.iter().position(|a| a == "somebox");
let script_at = args.iter().position(|a| a == "mkdir -p ~/.config/croft");
assert!(
host_at.is_some(),
"the destination host must be passed: {args:?}"
);
assert!(script_at.is_some(), "the script must be passed: {args:?}");
assert!(
host_at < script_at,
"ssh takes the destination BEFORE the command, or it reads the \
command as the hostname: {args:?}"
);
assert!(
args.iter().any(|a| a == "-n"),
"a background command must not inherit stdin: {args:?}"
);
}
use super::*;
#[test]
#[cfg(unix)]
fn relay_setup_error_appends_stderr_only_when_present() {
use std::os::unix::process::ExitStatusExt as _;
let status = ExitStatus::from_raw(256); assert_eq!(
relay_setup_error(status, b" ssh: connect refused \n"),
format!("remote relay setup failed with {status}: ssh: connect refused")
);
assert_eq!(
relay_setup_error(status, b" \n"),
format!("remote relay setup failed with {status}")
);
assert!(!relay_setup_error(status, b"").ends_with(": "));
}
#[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 a_release_binary_is_stamped_by_its_version_not_a_missing_tree() {
let tmp = tempfile::tempdir().unwrap();
let gone = tmp.path().join("home/runner/work/croft/croft");
assert_eq!(build_stamp_for(&gone, "0.1.9").unwrap(), "release-v0.1.9");
assert_ne!(
build_stamp_for(&gone, "0.1.9").unwrap(),
build_stamp_for(&gone, "0.1.10").unwrap(),
"a new release is a new stamp, so the remote updates"
);
std::fs::write(tmp.path().join("Cargo.toml"), "[package]").unwrap();
let root = tmp.path().to_path_buf();
assert_eq!(
build_stamp_for(&root, "0.1.9").unwrap(),
source_stamp_for(&root).unwrap(),
"a source tree is still hashed"
);
}
#[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,
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,
None,
false,
&[],
false,
);
assert!(command.contains("export CROFT_FORCE_INLINE_IMAGES=1 TERM_PROGRAM='iTerm.app';"));
}
#[test]
fn remote_croft_command_honors_croft_pane_image_gate() {
let blocked = remote_croft_command_for_terminal(
None,
Some("croft"),
None,
Some("0"),
false,
&[],
false,
);
assert!(!blocked.contains("CROFT_FORCE_INLINE_IMAGES"));
let allowed = remote_croft_command_for_terminal(
None,
Some("croft"),
None,
Some("1"),
false,
&[],
false,
);
assert!(allowed.contains("export CROFT_FORCE_INLINE_IMAGES=1 TERM_PROGRAM='croft';"));
}
#[test]
fn remote_croft_command_exports_kitty_hint_for_ghostty() {
let command =
remote_croft_command_for_terminal(None, Some("ghostty"), None, 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"),
None,
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, 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, None, true, &[], false);
assert!(command.contains("export CROFT_FORCE_OSK=1;"));
let command = remote_croft_command_for_terminal(None, 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,
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, 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"),
None,
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"),
None,
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 a_lost_session_turns_off_every_mode_croft_turned_on() {
let release = lost_session_release_seq();
let takeover = String::from_utf8(crate::app::takeover_mode_seq()).unwrap();
let mut modes = 0;
for set in takeover.split("\x1b[?").skip(1) {
let Some(mode) = set.split('h').next().filter(|m| set.len() > m.len()) else {
continue;
};
for mode in mode.split(';') {
modes += 1;
assert!(
release.contains(&format!("\x1b[?{mode}l")),
"mode {mode} is left on: {release:?}"
);
}
}
assert!(
modes >= 4,
"the takeover's modes were all read: {takeover:?}"
);
assert!(
release.contains("\x1b[0 q"),
"the terminal's own cursor shape"
);
assert!(release.contains("\x1b[?25h"), "a visible cursor");
let rest = release.replace("\x1b[?25h", "");
assert!(
!rest.contains("h\x1b") && !rest.ends_with('h'),
"nothing else is turned on: {release:?}"
);
}
#[test]
fn a_lost_session_leaves_the_alt_screen_last_and_its_colours_come_back_on_resume() {
let release = lost_session_release_seq();
let kitty = release.find("\x1b[=0;1u").expect("the kitty flags cleared");
assert!(release.find("\x1b[<u").is_some_and(|pop| pop < kitty));
assert!(release.ends_with("\x1b7\x1b[?1049l"), "{release:?}");
assert!(kitty < release.len() - "\x1b7\x1b[?1049l".len());
assert!(
release.contains(crate::app::reset_host_colors_seq()),
"{release:?}"
);
let theme = crate::theme::Theme::BLACK;
let reattach = String::from_utf8(crate::app::reattach_reassert_seq(theme)).unwrap();
let takeover = String::from_utf8(crate::app::takeover_mode_seq()).unwrap();
assert!(reattach.starts_with(&takeover), "{reattach:?}");
let (r, g, b) = theme.editor_bg_rgb();
assert!(
reattach.contains(&format!("\x1b]11;rgb:{r:02x}/{g:02x}/{b:02x}\x07")),
"the theme's background: {reattach:?}"
);
assert!(
reattach.contains("\x1b]10;rgb:"),
"and foreground: {reattach:?}"
);
}
#[test]
fn the_ssh_control_dir_is_fresh_and_owner_only() {
use std::os::unix::fs::PermissionsExt;
let dir = super::ssh_control_dir().unwrap();
let mode = std::fs::metadata(&dir).unwrap().permissions().mode();
assert_eq!(mode & 0o777, 0o700);
assert!(std::fs::DirBuilder::new().create(&dir).is_err());
std::fs::remove_dir(&dir).unwrap();
}
#[test]
fn a_pulled_folder_leaves_its_hidden_entries_behind() {
let dir = tempfile::Builder::new()
.prefix("croft-pull")
.tempdir()
.unwrap();
let home = dir.path().join("home");
std::fs::create_dir_all(home.join(".ssh")).unwrap();
std::fs::create_dir_all(home.join("docs/.git")).unwrap();
std::fs::write(home.join(".ssh/id"), "key").unwrap();
std::fs::write(home.join("docs/.git/cfg"), "x").unwrap();
std::fs::write(home.join("docs/a.txt"), "a").unwrap();
std::fs::write(home.join("-dash"), "d").unwrap();
let list = |parent: &Path, name: &str| {
let packed = Command::new("tar")
.args(super::pull_tar_args(parent, std::ffi::OsStr::new(name)))
.output()
.unwrap();
assert!(
packed.status.success(),
"{}",
String::from_utf8_lossy(&packed.stderr)
);
let mut listing = Command::new("tar")
.args(["-t", "-f", "-"])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
.unwrap();
use std::io::Write;
listing
.stdin
.take()
.unwrap()
.write_all(&packed.stdout)
.unwrap();
String::from_utf8(listing.wait_with_output().unwrap().stdout).unwrap()
};
let names = list(dir.path(), "home");
assert!(
names.contains("home/docs/a.txt") && names.contains("home/-dash"),
"{names}"
);
assert!(
!names.contains(".ssh") && !names.contains(".git"),
"{names}"
);
assert_eq!(list(&home, "-dash").trim(), "-dash");
}
#[test]
fn a_pull_refuses_hidden_paths_and_links_into_them() {
let dir = tempfile::Builder::new()
.prefix("croft-pull")
.tempdir()
.unwrap();
let root = std::fs::canonicalize(dir.path()).unwrap();
std::fs::create_dir(root.join(".ssh")).unwrap();
std::fs::write(root.join(".ssh/id_ed25519"), "key").unwrap();
std::fs::write(root.join("-notes.txt"), "hi").unwrap();
std::os::unix::fs::symlink(root.join(".ssh/id_ed25519"), root.join("key")).unwrap();
assert!(super::pull_source_allowed(&root.join("-notes.txt")));
assert!(!super::pull_source_allowed(&root.join(".ssh/id_ed25519")));
assert!(
!super::pull_source_allowed(&root.join("key")),
"a link into .ssh"
);
assert!(!super::pull_source_allowed(
&root.join("x/../.ssh/id_ed25519")
));
assert!(!super::pull_source_allowed(Path::new("relative.txt")));
}
#[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_copy_carries_only_an_id() {
match super::parse_relay_request("copy\tcopy-7") {
Some(super::RelayRequest::Copy { id }) => assert_eq!(id, "copy-7"),
_ => panic!("expected Copy variant"),
}
assert!(super::parse_relay_request("copy\t").is_none());
}
#[test]
fn a_copy_id_that_leaves_the_inbox_is_refused() {
for id in [
"../../../../etc/passwd",
"../outside",
"copy/7",
"copy 7",
"copy;rm -rf /",
"copy$(id)",
"",
] {
assert!(
!super::copy_request_id_is_safe(id),
"{id:?} must not be accepted as a copy id"
);
}
assert!(super::copy_request_id_is_safe("copy-12345-0"));
}
#[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 a_broken_config_read_keeps_the_last_good_sync_exclusions() {
let mut ex = SyncExclusions { known: None };
let broken = crate::config_layers::MergedConfig {
prefs: crate::prefs::Prefs::default(),
provenance: Default::default(),
chain: Vec::new(),
warnings: vec![String::from("config.json: expected value at line 1")],
user_config_error: Some(String::from("config.json: expected value at line 1")),
};
ex.update(broken.clone());
assert_eq!(ex.known, None);
let prefs = crate::prefs::Prefs {
config_sync_excluded_hosts: vec![String::from("shared-box")],
config_sync_excluded_files: vec![String::from("macros.json")],
..Default::default()
};
let clean = crate::config_layers::MergedConfig {
prefs,
provenance: Default::default(),
chain: Vec::new(),
warnings: Vec::new(),
user_config_error: None,
};
ex.update(clean);
let good = Some((
vec![String::from("shared-box")],
vec![String::from("macros.json")],
));
assert_eq!(ex.known, good);
ex.update(broken);
assert_eq!(ex.known, good);
}
#[test]
fn a_live_repush_ships_each_edit_once_and_retries_a_failed_one() {
use crate::config_sync::ConfigWatch;
let dir = tempfile::tempdir().unwrap();
let keys = dir.path().join("keybindings.json");
let snips = dir.path().join("snippets.json");
let macros = dir.path().join("macros.json");
std::fs::write(&keys, "[]").unwrap();
let mut state = RepushState::new(ConfigWatch::new(vec![
keys.clone(),
snips.clone(),
macros.clone(),
]));
let t0 = std::time::Instant::now();
let mut sent: Vec<Vec<&'static str>> = Vec::new();
let mut lines: Vec<String> = Vec::new();
let tick = |state: &mut RepushState,
now: std::time::Instant,
excluded: Option<Vec<String>>,
fail: &'static [&'static str],
sent: &mut Vec<Vec<&'static str>>,
lines: &mut Vec<String>| {
repush_tick(
state,
dir.path(),
now,
&mut || match excluded.clone() {
Some(files) => RepushGate::Push(files),
None => RepushGate::HostExcluded,
},
&mut |files| {
sent.push(files.iter().map(|(s, _)| s.name).collect());
PushResult {
failed: fail.to_vec(),
held: Vec::new(),
}
},
&mut |l| lines.push(l),
);
};
let step = ConfigWatch::INTERVAL;
tick(
&mut state,
t0 + step,
Some(vec![]),
&[],
&mut sent,
&mut lines,
);
assert!(sent.is_empty(), "nothing edited yet");
std::fs::write(&keys, r#"[{"key": "ctrl+k"}]"#).unwrap();
std::fs::write(&snips, "{}").unwrap();
std::fs::write(¯os, "{}").unwrap();
let failed_at = t0 + step * 2;
tick(
&mut state,
failed_at,
Some(vec![String::from("macros.json")]),
&["snippets.json"],
&mut sent,
&mut lines,
);
assert_eq!(sent, vec![vec!["keybindings.json", "snippets.json"]]);
assert_eq!(
lines,
vec![
"Config sync: re-pushed keybindings.json".to_string(),
"Config sync: could not re-push snippets.json (the remote keeps its copy)"
.to_string(),
]
);
tick(
&mut state,
t0 + step * 3,
Some(vec![]),
&[],
&mut sent,
&mut lines,
);
assert_eq!(sent.len(), 1, "no retry before REPUSH_RETRY");
tick(
&mut state,
failed_at + REPUSH_RETRY,
Some(vec![]),
&[],
&mut sent,
&mut lines,
);
assert_eq!(sent.last().unwrap(), &vec!["snippets.json"]);
assert!(state.pending.is_empty());
assert_eq!(
lines.last().unwrap(),
"Config sync: re-pushed snippets.json"
);
std::fs::write(&keys, "[ ]").unwrap();
let later = failed_at + REPUSH_RETRY + step;
tick(&mut state, later, None, &[], &mut sent, &mut lines);
assert_eq!(sent.len(), 2, "an excluded host is never pushed to");
assert!(state.pending.is_empty());
}
#[test]
fn a_live_repush_holds_changes_until_the_exclusions_read_cleanly() {
use crate::config_sync::ConfigWatch;
let dir = tempfile::tempdir().unwrap();
let keys = dir.path().join("keybindings.json");
std::fs::write(&keys, "[]").unwrap();
let mut state = RepushState::new(ConfigWatch::new(vec![keys.clone()]));
let t0 = std::time::Instant::now();
std::fs::write(&keys, r#"[{"key": "ctrl+k"}]"#).unwrap();
let mut sent = 0;
let mut lines = Vec::new();
let first = t0 + ConfigWatch::INTERVAL * 2;
repush_tick(
&mut state,
dir.path(),
first,
&mut || RepushGate::Unknown,
&mut |_| {
sent += 1;
PushResult::default()
},
&mut |l| lines.push(l),
);
assert_eq!(sent, 0, "nothing leaves while the exclusions are unknown");
assert_eq!(state.pending.len(), 1, "the edit is held");
assert!(lines[0].contains("holding changes"), "{lines:?}");
repush_tick(
&mut state,
dir.path(),
first + REPUSH_RETRY,
&mut || RepushGate::Push(Vec::new()),
&mut |_| {
sent += 1;
PushResult::default()
},
&mut |l| lines.push(l),
);
assert_eq!(sent, 1, "it goes once they read cleanly");
assert!(state.pending.is_empty());
}
#[test]
fn a_live_repush_holds_a_file_edited_on_the_remote() {
use crate::config_sync::ConfigWatch;
let dir = tempfile::tempdir().unwrap();
let keys = dir.path().join("keybindings.json");
std::fs::write(&keys, "[]").unwrap();
let mut state = RepushState::new(ConfigWatch::new(vec![keys.clone()]));
let t0 = std::time::Instant::now();
std::fs::write(&keys, r#"[{"key": "ctrl+k"}]"#).unwrap();
let mut lines = Vec::new();
repush_tick(
&mut state,
dir.path(),
t0 + ConfigWatch::INTERVAL * 2,
&mut || RepushGate::Push(Vec::new()),
&mut |_| PushResult {
failed: Vec::new(),
held: vec!["keybindings.json"],
},
&mut |l| lines.push(l),
);
assert!(state.pending.is_empty(), "a held file is not retried");
assert!(state.retry_at.is_none());
assert!(!lines.iter().any(|l| l.contains("re-pushed")), "{lines:?}");
assert!(
lines
.iter()
.any(|l| l.contains("left keybindings.json alone") && l.contains("--diff")),
"{lines:?}"
);
}
#[test]
fn remote_install_marks_the_build_for_the_oom_killer_first() {
let command = remote_install_command("abc123");
let adj = command
.find("echo 1000 > /proc/self/oom_score_adj")
.unwrap();
let install = command.find("cargo install --path").unwrap();
assert!(adj < install, "the score must be set before the compile");
let out = Command::new("sh")
.args(["-n", "-c", &command])
.output()
.unwrap();
assert!(
out.status.success(),
"{}",
String::from_utf8_lossy(&out.stderr)
);
}
#[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 remote_install_compile_is_memory_bounded() {
let command = remote_install_command("abc123");
let install = command.find("cargo install --path").unwrap();
let before = |needle: &str| {
let at = command
.find(needle)
.unwrap_or_else(|| panic!("missing {needle:?}"));
assert!(at < install, "{needle:?} must come before the compile");
};
before("/proc/meminfo");
before("-lt 16777216");
before("systemd-run --user --scope");
before("MemoryMax=");
before("MemorySwapMax=0");
before("CROFT_MARK=\"$HOME/.cache/croft/building.$$\"");
before("trap '");
assert!(
command.contains(r#"eval "exec $CROFT_MEMCAP $CROFT_NICE $CROFT_IONICE""#),
"the memory cap must wrap the compile itself"
);
let avail = command.find("-lt 2097152").unwrap();
let avail_branch = &command[avail..command[avail..].find("fi\n").unwrap() + avail];
assert!(
avail_branch.contains("CROFT_JOBS=1"),
"low available memory must drop to one job: {avail_branch}"
);
let cleared = command
.rfind("rm -f \"$CROFT_MARK\" \"$CROFT_MARK.boot\"")
.unwrap();
assert!(cleared > install);
}
#[cfg(unix)]
fn install_command(
dir: &std::path::Path,
cargo_exit: u8,
systemd_run: &str,
seen: &std::path::Path,
hold: Option<&std::path::Path>,
) -> std::process::Command {
install_command_under("sh", dir, cargo_exit, systemd_run, seen, hold)
}
#[cfg(unix)]
fn install_command_under(
shell: &str,
dir: &std::path::Path,
cargo_exit: u8,
systemd_run: &str,
seen: &std::path::Path,
hold: Option<&std::path::Path>,
) -> std::process::Command {
use std::os::unix::fs::PermissionsExt;
let bin = dir.join("bin");
let home = dir.join("home");
std::fs::create_dir_all(&bin).unwrap();
std::fs::create_dir_all(home.join(".cache/croft")).unwrap();
let stub = |name: &str, body: &str| {
let path = bin.join(name);
std::fs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
};
for ok in ["cc", "pkg-config", "dtach"] {
stub(ok, "exit 0");
}
stub("pgrep", "exit 1");
stub("systemd-run", systemd_run);
let tries =
crate::test_budget::spawn_budget(std::time::Duration::from_secs(5)).as_millis() / 50;
stub(
"cargo",
&format!(
r#"i=0
while [ "$i" -lt {tries} ]; do
for f in "$HOME"/.cache/croft/building.*; do
case "$f" in
*.boot) ;;
*) if [ "$(cat "$f" 2>/dev/null)" = "$$" ]; then m=$$; b=$(cat "$f.boot" 2>/dev/null); break 2; fi ;;
esac
done
sleep 0.05; i=$((i+1))
done
printf '%s %s %s' "$$" "$m" "$b" > "$CROFT_TEST_SEEN"
if [ -n "$CROFT_TEST_HOLD" ]; then
: > "$CROFT_TEST_HOLD.ready"
j=0
while [ ! -e "$CROFT_TEST_HOLD" ] && [ "$j" -lt {tries} ]; do sleep 0.05; j=$((j+1)); done
fi
exit {cargo_exit}"#
),
);
let path = format!("{}:/usr/bin:/bin", bin.display());
let mut cmd = std::process::Command::new(shell);
cmd.arg("-c")
.arg(remote_install_command("abc123"))
.env_clear()
.env("HOME", &home)
.env("PATH", path)
.env("CROFT_TEST_SEEN", seen)
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null());
if let Some(hold) = hold {
cmd.env("CROFT_TEST_HOLD", hold);
}
cmd
}
#[cfg(unix)]
fn run_install_script(dir: &std::path::Path, cargo_exit: u8) -> (bool, String) {
let seen = dir.join("seen");
let status = install_command(dir, cargo_exit, "exit 1", &seen, None)
.status()
.unwrap();
let seen = std::fs::read_to_string(seen).unwrap_or_default();
(status.success(), seen)
}
#[cfg(target_os = "linux")]
fn running(pid: u32) -> bool {
std::fs::read_to_string(format!("/proc/{pid}/stat"))
.ok()
.and_then(|s| s.rsplit_once(") ").map(|(_, rest)| !rest.starts_with('Z')))
.unwrap_or(false)
}
#[cfg(target_os = "linux")]
fn build_seen(dir: &std::path::Path) -> bool {
crate::update_watch::source_build_running(
&dir.join("home/.cache/croft"),
crate::update_watch::boot_id,
crate::update_watch::boot_time,
running,
)
}
#[cfg(target_os = "linux")]
#[test]
fn a_killed_install_shell_leaves_the_marker_naming_the_live_compile() {
let tmp = tempfile::tempdir().unwrap();
let hold = tmp.path().join("hold");
let seen = tmp.path().join("seen");
let mut shell = install_command(tmp.path(), 0, "exit 1", &seen, Some(&hold))
.spawn()
.unwrap();
let ready = tmp.path().join("hold.ready");
crate::test_budget::await_spawned(
std::time::Duration::from_secs(10),
"the stub compile to start",
|| ready.exists(),
);
let seen = std::fs::read_to_string(&seen).unwrap();
let cargo: u32 = seen.split(' ').next().unwrap().parse().unwrap();
assert!(seen.starts_with(&format!("{cargo} {cargo}")), "{seen}");
unsafe {
libc::kill(shell.id() as libc::pid_t, libc::SIGTERM);
}
let _ = shell.wait();
assert!(running(cargo), "the compile must outlive its shell");
assert_eq!(
leftover_markers(tmp.path())
.iter()
.filter(|n| !n.ends_with(".boot"))
.map(
|n| std::fs::read_to_string(tmp.path().join("home/.cache/croft").join(n))
.unwrap()
)
.collect::<Vec<_>>(),
vec![cargo.to_string()],
"the marker must keep naming the compile"
);
assert!(build_seen(tmp.path()), "croft must still see the build");
std::fs::write(&hold, "").unwrap();
crate::test_budget::await_spawned(
std::time::Duration::from_secs(10),
"the build to read as over once the compile exits",
|| !build_seen(tmp.path()),
);
}
#[cfg(target_os = "linux")]
#[test]
fn a_second_install_finishing_first_leaves_the_first_ones_marker() {
let tmp = tempfile::tempdir().unwrap();
let hold = tmp.path().join("hold");
let mut long = install_command(
tmp.path(),
0,
"exit 1",
&tmp.path().join("seen-long"),
Some(&hold),
)
.spawn()
.unwrap();
let ready = tmp.path().join("hold.ready");
crate::test_budget::await_spawned(
std::time::Duration::from_secs(10),
"the long build's compile to start",
|| ready.exists(),
);
let short = install_command(
tmp.path(),
0,
"exit 1",
&tmp.path().join("seen-short"),
None,
)
.status()
.unwrap();
assert!(short.success());
assert!(
build_seen(tmp.path()),
"the short build's end hid the long one: {:?}",
leftover_markers(tmp.path())
);
std::fs::write(&hold, "").unwrap();
assert!(long.wait().unwrap().success());
assert!(leftover_markers(tmp.path()).is_empty());
}
#[cfg(target_os = "linux")]
#[test]
fn the_install_script_caps_the_compile_only_when_the_limit_reads_back() {
for (probe, capped) in [("67108864", true), ("max", false)] {
let tmp = tempfile::tempdir().unwrap();
let log = tmp.path().join("capped");
let systemd_run = format!(
r#"while [ $# -gt 0 ]; do case "$1" in -p) shift 2 ;; --*) shift ;; *) break ;; esac; done
if [ "$1" = sh ]; then echo {probe}; exit 0; fi
: > "{}"
exec "$@""#,
log.display()
);
let seen = tmp.path().join("seen");
let status = install_command(tmp.path(), 0, &systemd_run, &seen, None)
.status()
.unwrap();
assert!(status.success(), "probe {probe}");
assert_eq!(log.exists(), capped, "probe {probe}");
let seen = std::fs::read_to_string(&seen).unwrap();
let mut f = seen.split(' ');
assert_eq!(f.next(), f.next(), "probe {probe}: {seen}");
}
}
#[cfg(unix)]
fn leftover_markers(dir: &std::path::Path) -> Vec<String> {
std::fs::read_dir(dir.join("home/.cache/croft"))
.unwrap()
.flatten()
.map(|e| e.file_name().to_string_lossy().into_owned())
.filter(|n| n.starts_with("building."))
.collect()
}
#[cfg(unix)]
#[test]
fn the_install_script_marks_the_compile_and_clears_the_mark() {
let tmp = tempfile::tempdir().unwrap();
let (ok, seen) = run_install_script(tmp.path(), 0);
assert!(ok, "the stubbed install must succeed");
let mut fields = seen.splitn(3, ' ');
let (own, marked, boot) = (
fields.next().unwrap(),
fields.next().expect("cargo ran and reported"),
fields.next().unwrap_or_default(),
);
let host_boot = std::fs::read_to_string("/proc/sys/kernel/random/boot_id")
.map(|b| b.trim().to_string())
.unwrap_or_default();
assert_eq!(boot.trim(), host_boot, "the marker's boot sidecar");
assert_eq!(
own, marked,
"while cargo runs the marker must name cargo itself, so a killed \
script shell cannot make the build look finished"
);
assert!(leftover_markers(tmp.path()).is_empty());
assert_eq!(
std::fs::read_to_string(tmp.path().join("home/.cache/croft/install-stamp")).unwrap(),
"abc123"
);
let tmp = tempfile::tempdir().unwrap();
let (ok, _) = run_install_script(tmp.path(), 3);
assert!(!ok, "a failing compile must fail the install");
assert!(
leftover_markers(tmp.path()).is_empty(),
"a failed build left its marker behind"
);
}
#[cfg(unix)]
#[test]
fn the_install_script_reaches_cargo_under_zsh() {
if !crate::lsp::manager::is_on_path("zsh") {
eprintln!("SKIPPED: zsh not on PATH");
return;
}
let under_zsh = |dir: &std::path::Path, cargo_exit| {
let seen = dir.join("seen");
let status = install_command_under("zsh", dir, cargo_exit, "exit 1", &seen, None)
.status()
.unwrap();
(
status.success(),
std::fs::read_to_string(seen).unwrap_or_default(),
)
};
let tmp = tempfile::tempdir().unwrap();
let (ok, seen) = under_zsh(tmp.path(), 0);
assert!(ok, "an empty cache must not stop the install under zsh");
let mut fields = seen.splitn(3, ' ');
let own = fields.next().unwrap();
let marked = fields.next().expect("cargo ran under zsh");
assert_eq!(own, marked);
assert!(leftover_markers(tmp.path()).is_empty());
assert_eq!(
std::fs::read_to_string(tmp.path().join("home/.cache/croft/install-stamp")).unwrap(),
"abc123"
);
let tmp = tempfile::tempdir().unwrap();
let (ok, _) = under_zsh(tmp.path(), 3);
assert!(!ok, "a failing compile must fail the install under zsh");
assert!(
!tmp.path().join("home/.cache/croft/install-stamp").exists(),
"a failed compile must not write the install stamp"
);
}
#[cfg(unix)]
#[test]
fn the_install_script_sweeps_only_dead_markers() {
let tmp = tempfile::tempdir().unwrap();
let cache = tmp.path().join("home/.cache/croft");
std::fs::create_dir_all(&cache).unwrap();
std::fs::write(cache.join("building.1"), std::process::id().to_string()).unwrap();
std::fs::write(cache.join("building.2"), "2147483646").unwrap();
let this_boot = std::fs::read_to_string("/proc/sys/kernel/random/boot_id").ok();
if let Some(boot) = &this_boot {
std::fs::write(cache.join("building.1.boot"), boot.trim()).unwrap();
std::fs::write(cache.join("building.3"), std::process::id().to_string()).unwrap();
std::fs::write(cache.join("building.3.boot"), "another-boot").unwrap();
}
std::fs::write(cache.join("building.4.boot"), "orphan").unwrap();
let (ok, _) = run_install_script(tmp.path(), 0);
assert!(ok);
let mut left = leftover_markers(tmp.path());
left.sort();
let expect: Vec<String> = if this_boot.is_some() {
vec!["building.1".into(), "building.1.boot".into()]
} else {
vec!["building.1".into()]
};
assert_eq!(
left, expect,
"only the live build of this boot, and its sidecar, may survive another build"
);
}
#[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 a_relay_request_is_claimed_by_exactly_one_pump() {
let tmp = tempfile::tempdir().unwrap();
let inbox = tmp.path().join("inbox").display().to_string();
let run = |cmd: String| {
std::process::Command::new("sh")
.arg("-c")
.arg(cmd)
.status()
.unwrap()
.success()
};
assert!(run(claim_command(&inbox, "open-1-2")));
assert!(
!run(claim_command(&inbox, "open-1-2")),
"a second claim loses"
);
assert!(run(claim_command(&inbox, "open-1-3")));
assert_eq!(
super::parse_relay_request("open\topen-1\thttps://x/")
.and_then(|r| r.id().map(str::to_string)),
Some(String::from("open-1"))
);
}
#[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_file_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 a_config_push_rides_the_bulk_lane_like_the_binary_does() {
let lane = crate::remote_bulk::BulkLane::new(
crate::remote_bulk::LaneMode::Dedicated {
socket_path: PathBuf::from("/tmp/bulk/ctl"),
},
512,
);
let cmd = ship_file_rsync_command(
&lane,
Path::new("/tmp/interactive/ctl"),
Path::new("/home/u/.config/croft/keybindings.json"),
&crate::config_sync::remote_dest("host", "keybindings.json"),
);
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"));
assert!(
args.iter().any(|a| a == "--checksum"),
"content comparison is what makes the push a no-op when nothing changed"
);
assert!(
args.iter()
.any(|a| a == "host:.config/croft/keybindings.json"),
"the file must land in the remote's config dir, got {args:?}"
);
}
#[test]
fn a_config_push_never_carries_the_trust_bearing_config_json() {
let lane = crate::remote_bulk::BulkLane::new(crate::remote_bulk::LaneMode::SharedMux, 300);
for s in crate::config_sync::SYNCABLE {
let cmd = ship_file_rsync_command(
&lane,
Path::new("/tmp/ctl"),
Path::new("/home/u/.config/croft").join(s.name).as_path(),
&crate::config_sync::remote_dest("host", s.name),
);
let args = args_of(&cmd);
assert!(
!args.iter().any(|a| a.ends_with("config.json")),
"config.json carries MCP consent and must never be in a push argv, got {args:?}"
);
}
}
#[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_file_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`"
);
}
#[test]
fn snapshot_dirs_are_detected_and_real_repos_are_not() {
assert!(source_dir_is_snapshot(
"/Users/u/.cargo/registry/src/index.crates.io-6f17d22bba15001f/croft-software-0.1.757"
));
assert!(source_dir_is_snapshot(
"/home/u/.cargo/git/checkouts/croft-9a1f/de1a7ab"
));
assert!(source_dir_is_snapshot(
"/custom/cargo-home/.cargo/git/checkouts/croft-9a1f/de1a7ab"
));
assert!(source_dir_is_snapshot(
"/custom/cargo-home/registry/src/index.crates.io-6f17d22bba15001f/croft-software-0.1.757"
));
assert!(source_dir_is_snapshot(
"/custom/cargo-home/git/checkouts/croft-9a1f/de1a7ab"
));
assert!(!source_dir_is_snapshot("/Users/u/Documents/croft"));
assert!(!source_dir_is_snapshot("/home/u/work/croft"));
assert!(
source_snapshot_warning().is_none(),
"the test build itself must come from a working tree, not a snapshot"
);
}
}
pub type RefusedHosts = std::collections::BTreeMap<String, std::time::SystemTime>;
pub fn refusal_live(at: std::time::SystemTime, now: std::time::SystemTime) -> bool {
now.duration_since(at)
.is_ok_and(|age| age <= REFUSED_HOST_TTL)
}
pub fn offer_allowed(
host: &str,
disabled: bool,
excluded: &[String],
refused: &RefusedHosts,
now: std::time::SystemTime,
) -> bool {
if disabled {
return false;
}
if excluded.iter().any(|h| h.eq_ignore_ascii_case(host)) {
return false;
}
!refused
.get(&host.to_ascii_lowercase())
.is_some_and(|at| refusal_live(*at, now))
}
pub type CwdReport = (std::path::PathBuf, Option<String>);
pub fn remote_workspace_path(
host: &str,
at_offer: Option<&CwdReport>,
now: Option<&CwdReport>,
) -> Option<String> {
let (path, reporter) = now?;
let reporter = reporter.as_deref().filter(|h| !h.is_empty())?;
if crate::command_history::is_local_host(reporter) {
return None;
}
let fresh = at_offer != now;
if !fresh && !same_host(host, reporter) {
return None;
}
Some(path.to_string_lossy().into_owned())
}
fn same_host(alias: &str, reported: &str) -> bool {
let (a, r) = (alias.to_ascii_lowercase(), reported.to_ascii_lowercase());
a == r
|| r.strip_prefix(&a).is_some_and(|rest| rest.starts_with('.'))
|| a.strip_prefix(&r).is_some_and(|rest| rest.starts_with('.'))
}
pub fn ssh_pane_samples(
named: &[(i32, i32, String)],
targets: impl FnOnce() -> Vec<RemoteTarget>,
cmdline: impl Fn(i32) -> Option<Vec<String>>,
) -> Vec<(i32, Option<String>)> {
let mut targets = Some(targets);
let mut config: Vec<RemoteTarget> = Vec::new();
let mut out = Vec::with_capacity(named.len());
for (shell, fg, name) in named {
if shell == fg || !is_ssh_program(name) {
out.push((*shell, None));
continue;
}
let Some(argv) = cmdline(*fg) else {
continue;
};
if let Some(parse) = targets.take() {
config = parse();
}
let argv: Vec<&str> = argv.iter().map(String::as_str).collect();
out.push((*shell, ssh_offer_host(&argv, &config)));
}
out
}
pub fn is_ssh_program(name: &str) -> bool {
let base = name.rsplit('/').next().unwrap_or(name);
SSH_PROGRAMS.contains(&base)
}
pub fn ssh_offer_host(argv: &[&str], targets: &[RemoteTarget]) -> Option<String> {
ssh_reroot_decision(argv, targets)
.ok()
.map(|t| t.alias.clone())
}
pub const REFUSED_HOST_TTL: std::time::Duration = std::time::Duration::from_secs(7 * 24 * 3600);
pub fn refused_hosts_path(cache_dir: &Path) -> PathBuf {
cache_dir.join("remote-offer-refused.json")
}
pub fn load_refused_hosts(path: &Path, now: std::time::SystemTime) -> RefusedHosts {
let Ok(raw) = std::fs::read_to_string(path) else {
return Default::default();
};
let Ok(map) = serde_json::from_str::<std::collections::BTreeMap<String, u64>>(&raw) else {
return Default::default();
};
map.into_iter()
.map(|(h, at)| {
(
h.to_ascii_lowercase(),
std::time::UNIX_EPOCH + std::time::Duration::from_secs(at),
)
})
.filter(|(_, at)| refusal_live(*at, now))
.collect()
}
pub fn forget_refused_host(path: &Path, host: &str) -> std::io::Result<()> {
let Ok(raw) = std::fs::read_to_string(path) else {
return Ok(());
};
let mut map: std::collections::BTreeMap<String, u64> =
serde_json::from_str(&raw).unwrap_or_default();
if map.remove(&host.to_ascii_lowercase()).is_none() {
return Ok(());
}
let body = serde_json::to_string_pretty(&map).map_err(std::io::Error::other)?;
std::fs::write(path, body)
}
pub fn remember_refused_host(
path: &Path,
host: &str,
now: std::time::SystemTime,
) -> std::io::Result<()> {
let mut map: std::collections::BTreeMap<String, u64> = std::fs::read_to_string(path)
.ok()
.and_then(|raw| serde_json::from_str(&raw).ok())
.unwrap_or_default();
let now_secs = now
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
map.insert(host.to_ascii_lowercase(), now_secs);
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir)?;
}
let body = serde_json::to_string_pretty(&map).map_err(std::io::Error::other)?;
std::fs::write(path, body)
}
#[cfg(test)]
mod offer_tests {
use super::*;
use std::time::{Duration, SystemTime};
#[test]
fn the_offer_policy_respects_every_opt_out() {
let now = SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000);
let none = RefusedHosts::new();
assert!(offer_allowed("db-1", false, &[], &none, now));
assert!(
!offer_allowed("db-1", true, &[], &none, now),
"the global switch"
);
assert!(
!offer_allowed("db-1", false, &[String::from("DB-1")], &none, now),
"the per-host list, case-insensitively"
);
let refused: RefusedHosts = [(String::from("db-1"), now)].into_iter().collect();
assert!(
!offer_allowed("DB-1", false, &[], &refused, now),
"a learned refusal"
);
assert!(offer_allowed(
"web-2",
false,
&[String::from("db-1")],
&refused,
now
));
assert!(
offer_allowed(
"db-1",
false,
&[],
&refused,
now + REFUSED_HOST_TTL + Duration::from_secs(1)
),
"an in-memory refusal past the TTL no longer blocks"
);
}
#[test]
fn a_refusal_is_live_inside_its_window_and_never_from_the_future() {
let now = SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000);
assert!(refusal_live(now, now));
assert!(
refusal_live(now - REFUSED_HOST_TTL, now),
"the edge is inclusive"
);
assert!(!refusal_live(
now - REFUSED_HOST_TTL - Duration::from_secs(1),
now
));
assert!(
!refusal_live(now + Duration::from_secs(1), now),
"a clock corrected backward must not pin the entry"
);
}
#[test]
fn pane_samples_give_a_verdict_only_where_there_is_one() {
let named = vec![
(10, 10, String::from("zsh")),
(20, 21, String::from("vim")),
(30, 31, String::from("ssh")),
(40, 41, String::from("ssh")),
(50, 51, String::from("ssh")),
];
let parses = std::cell::Cell::new(0);
let targets = || {
parses.set(parses.get() + 1);
vec![RemoteTarget {
alias: String::from("db-1"),
host_name: Some(String::from("10.0.0.5")),
user: None,
}]
};
let cmdline = |pid: i32| match pid {
41 => Some(vec![String::from("ssh"), String::from("db-1")]),
51 => Some(vec![String::from("ssh"), String::from("elsewhere")]),
_ => None,
};
let samples = ssh_pane_samples(&named, targets, cmdline);
assert_eq!(
samples,
vec![
(10, None),
(20, None),
(40, Some(String::from("db-1"))),
(50, None),
],
"the unreadable ssh (pane 3) gets no verdict at all"
);
assert_eq!(parses.get(), 1, "the config is parsed once per pass");
let parses = std::cell::Cell::new(0);
let quiet = vec![(10, 10, String::from("zsh")), (20, 21, String::from("vim"))];
let samples = ssh_pane_samples(
&quiet,
|| {
parses.set(parses.get() + 1);
Vec::new()
},
|_| None,
);
assert_eq!(samples, vec![(10, None), (20, None)]);
assert_eq!(parses.get(), 0, "and not at all when no pane is ssh");
}
#[test]
fn refused_hosts_round_trip_and_expire() {
let dir = tempfile::tempdir().unwrap();
let path = refused_hosts_path(dir.path());
let now = SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000);
assert!(
load_refused_hosts(&path, now).is_empty(),
"no file, no memory"
);
remember_refused_host(&path, "Jump", now).unwrap();
remember_refused_host(
&path,
"old-box",
now - REFUSED_HOST_TTL - Duration::from_secs(1),
)
.unwrap();
remember_refused_host(&path, "ahead", now + Duration::from_secs(60)).unwrap();
let loaded = load_refused_hosts(&path, now);
assert!(
loaded.contains_key("jump"),
"stored lower-cased: {loaded:?}"
);
assert_eq!(loaded["jump"], now, "and its time comes back with it");
assert!(
!loaded.contains_key("old-box"),
"an entry past the TTL is forgotten"
);
assert!(
!loaded.contains_key("ahead"),
"an entry from the future (clock moved back) is forgotten too"
);
std::fs::write(&path, "not json").unwrap();
assert!(
load_refused_hosts(&path, now).is_empty(),
"garbage reads as empty"
);
}
#[test]
fn only_ssh_itself_is_an_ssh_program() {
assert!(is_ssh_program("ssh"));
assert!(is_ssh_program("/usr/bin/ssh"), "a path is tolerated");
assert!(
!is_ssh_program("ssh-agent"),
"whole-name match, as SSH_PROGRAMS promises"
);
assert!(!is_ssh_program("sshfs"));
assert!(
!is_ssh_program("mosh"),
"long-option programs are refused (see #445)"
);
assert!(!is_ssh_program(""));
}
#[test]
fn a_success_forgets_a_remembered_refusal() {
let dir = tempfile::tempdir().unwrap();
let path = refused_hosts_path(dir.path());
let now = SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000);
forget_refused_host(&path, "nobody").unwrap();
assert!(!path.exists(), "forgetting with no file creates nothing");
remember_refused_host(&path, "db-1", now).unwrap();
remember_refused_host(&path, "jump", now).unwrap();
forget_refused_host(&path, "DB-1").unwrap();
let left = load_refused_hosts(&path, now);
assert!(
!left.contains_key("db-1") && left.contains_key("jump"),
"{left:?}"
);
}
#[test]
fn the_offer_host_is_the_config_alias_or_nothing() {
let targets = vec![RemoteTarget {
alias: String::from("db-1"),
host_name: Some(String::from("10.0.0.5")),
user: None,
}];
assert_eq!(
ssh_offer_host(&["ssh", "-p", "2222", "db-1"], &targets).as_deref(),
Some("db-1")
);
assert_eq!(ssh_offer_host(&["ssh", "unknown-box"], &targets), None);
assert_eq!(ssh_offer_host(&["vim", "db-1"], &targets), None);
}
}