use super::*;
pub(super) struct DropPump {
stop: Arc<AtomicBool>,
tail: Option<Child>,
handle: Option<JoinHandle<()>>,
}
pub(super) 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 {
pub(super) 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 = Ssh::bare_client(&ssh.socket_path)
.arg(&ssh.host)
.arg(format!(
"exec tail -F -n 0 {} 2>/dev/null",
shell_quote(&requests_log)
))
.into_command()
.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();
}
}
}
pub(super) const MISSING_PULL_GRACE: std::time::Duration = std::time::Duration::from_secs(2);
pub(super) 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,
remote_ipv6,
}) => {
handle_forward_request(&host, &socket, &inbox_dir, &id, &port, open, remote_ipv6);
}
Some(RelayRequest::Unforward {
local,
remote,
remote_ipv6,
}) => {
handle_unforward_request(&host, &socket, &local, &remote, remote_ipv6);
}
None => {}
}
}
}
pub(super) 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,
remote_ipv6: bool,
},
Unforward {
local: String,
remote: String,
remote_ipv6: bool,
},
}
impl RelayRequest {
pub(super) 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,
}
}
}
pub(super) 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");
let remote_ipv6 = parse_forward_target_ipv6(parts.next())?;
Some(RelayRequest::Forward {
id,
port,
open,
remote_ipv6,
})
}
"unforward" => {
let _ = id;
let local = parts.next()?.to_string();
let remote = parts.next()?.to_string();
if local.is_empty() || remote.is_empty() {
return None;
}
let remote_ipv6 = parse_forward_target_ipv6(parts.next())?;
Some(RelayRequest::Unforward {
local,
remote,
remote_ipv6,
})
}
_ => None,
}
}
fn parse_forward_target_ipv6(field: Option<&str>) -> Option<bool> {
match field {
None | Some("") | Some("127.0.0.1") => Some(false),
Some("[::1]") | Some("::1") => Some(true),
Some(_) => None,
}
}
pub(super) 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}"))
)
}
pub(super) 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} && cat > {err}",
dir = shell_quote(&dest_dir),
err = shell_quote(&err_path),
);
let Ok(mut ssh) = Ssh::bare_client(socket)
.arg(host)
.arg(&cmd)
.into_command()
.stdin(Stdio::piped())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
else {
return;
};
if let Some(mut stdin) = ssh.stdin.take() {
let _ = std::io::Write::write_all(&mut stdin, message.as_bytes());
}
let _ = ssh.wait();
}
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())
}