1use std::collections::HashSet;
21use std::num::NonZeroUsize;
22use std::path::Path;
23use std::sync::atomic::{AtomicU64, Ordering};
24use std::sync::Arc;
25use std::time::{Duration, Instant};
26
27use base64::Engine;
28use bytes::BytesMut;
29use futures_util::StreamExt;
30use openssh::{KnownHosts, Session, SessionBuilder, Stdio};
31use openssh_sftp_client::file::TokioCompatFile;
32use openssh_sftp_client::{Sftp, SftpOptions};
33use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt};
34use tokio::sync::{Mutex, Semaphore};
35
36use crate::config::{default_shell, Limits, Os, RemoteConfig};
37use crate::error::{Error, Result};
38use crate::guard::StreamGuard;
39use crate::text::shell_quote;
40
41const TIMEOUT_EXIT: i32 = 124;
43const WATCHDOG_GRACE: u64 = 15;
45const CD_FAILED_EXIT: i32 = 97;
47const MAX_CHANNELS: usize = 4;
51const TRANSFER_CHUNK: usize = 1024 * 1024;
55const UPLOAD_WINDOW: usize = 16 * 1024 * 1024;
59const DOWNLOAD_STREAMS: u64 = 32;
62const DOWNLOAD_STEP: u64 = 1024 * 1024;
64const WIN_EXIT_MARKER: &str = "__FARHAND_EXIT__=";
67
68#[derive(Debug, Clone, Copy, PartialEq, Eq)]
70pub enum Platform {
71 Posix,
72 Windows,
73}
74
75impl Platform {
76 pub fn name(self) -> &'static str {
77 match self {
78 Platform::Posix => "posix",
79 Platform::Windows => "windows",
80 }
81 }
82}
83
84#[derive(Debug, Clone, Copy, PartialEq, Eq)]
88enum LoginShell {
89 PowerShell,
90 Cmd,
91}
92
93#[derive(Debug, Clone)]
95pub struct Address {
96 pub hostname: String,
97 pub port: u16,
98 pub alias: String,
100}
101
102#[derive(Debug, Clone)]
103pub struct ExecOutput {
104 pub exit_code: i32,
105 pub stdout: Vec<u8>,
106 pub stderr: Vec<u8>,
107 pub stdout_truncated: bool,
108 pub stderr_truncated: bool,
109 pub timed_out: bool,
110 pub duration: Duration,
111}
112
113struct Conn {
114 session: Arc<Session>,
115 sftp: Sftp,
116 platform: Platform,
117 login_shell: LoginShell,
118 home: String,
120 workdir: String,
122 workdir_created: bool,
125}
126
127pub struct Remote {
128 cfg: RemoteConfig,
129 limits: Limits,
130 conn: Mutex<Option<Arc<Conn>>>,
131 channels: Semaphore,
132 known_dirs: Mutex<HashSet<String>>,
135}
136
137impl Remote {
138 pub fn new(cfg: RemoteConfig, limits: Limits) -> Self {
139 Self {
140 cfg,
141 limits,
142 conn: Mutex::new(None),
143 channels: Semaphore::new(MAX_CHANNELS),
144 known_dirs: Mutex::new(HashSet::new()),
145 }
146 }
147
148 pub fn host(&self) -> &str {
149 &self.cfg.host
150 }
151
152 pub fn address(&self) -> Address {
157 let fallback = Address {
158 hostname: self
159 .cfg
160 .host
161 .rsplit('@')
162 .next()
163 .unwrap_or(&self.cfg.host)
164 .to_string(),
165 port: 22,
166 alias: self.cfg.host.clone(),
167 };
168 let out = match std::process::Command::new("ssh")
169 .arg("-G")
170 .arg(&self.cfg.host)
171 .stdin(std::process::Stdio::null())
172 .stderr(std::process::Stdio::null())
173 .output()
174 {
175 Ok(o) if o.status.success() => o.stdout,
176 _ => return fallback,
177 };
178 let text = String::from_utf8_lossy(&out);
179 let mut addr = fallback;
180 for line in text.lines() {
181 match line.split_once(' ') {
182 Some(("hostname", v)) => addr.hostname = v.trim().to_string(),
183 Some(("port", v)) => addr.port = v.trim().parse().unwrap_or(22),
184 _ => {}
185 }
186 }
187 addr
188 }
189
190 pub fn workdir(&self) -> &str {
192 &self.cfg.workdir
193 }
194
195 pub async fn effective_workdir(&self) -> Result<String> {
197 Ok(self.conn().await?.workdir.clone())
198 }
199
200 pub async fn workdir_created(&self) -> Result<bool> {
203 Ok(self.conn().await?.workdir_created)
204 }
205
206 pub fn limits(&self) -> &Limits {
207 &self.limits
208 }
209
210 pub fn configured_platform(&self) -> Option<Platform> {
213 match self.cfg.os {
214 Os::Auto => None,
215 Os::Posix => Some(Platform::Posix),
216 Os::Windows => Some(Platform::Windows),
217 }
218 }
219
220 pub async fn platform(&self) -> Result<Platform> {
222 Ok(self.conn().await?.platform)
223 }
224
225 pub async fn connect(&self) -> Result<()> {
227 self.conn().await.map(|_| ())
228 }
229
230 pub async fn is_connected(&self) -> bool {
231 match &*self.conn.lock().await {
232 Some(c) => c.session.check().await.is_ok(),
233 None => false,
234 }
235 }
236
237 async fn conn(&self) -> Result<Arc<Conn>> {
238 let mut slot = self.conn.lock().await;
239 if let Some(c) = &*slot {
240 if c.session.check().await.is_ok() {
241 return Ok(c.clone());
242 }
243 tracing::warn!("ssh session to {} dropped; reconnecting", self.cfg.host);
244 *slot = None;
245 self.known_dirs.lock().await.clear();
246 }
247 let wrapper = SshConfigWrapper::create(&[USER_SSH_CONFIG, SYSTEM_SSH_CONFIG])?;
259 let mut builder = SessionBuilder::default();
260 builder
261 .connect_timeout(Duration::from_secs(self.cfg.connect_timeout_secs))
262 .server_alive_interval(Duration::from_secs(self.cfg.server_alive_interval_secs))
263 .known_hosts_check(KnownHosts::Strict)
264 .config_file(&wrapper.path);
265 let session = builder.connect_mux(&self.cfg.host).await.map_err(|e| {
266 Error::Ssh(format!(
267 "cannot connect to `{}`: {e}. Check that `ssh {}` works from a terminal; \
268 FarHand refuses hosts whose key is not yet in known_hosts, so connect once \
269 by hand first.",
270 self.cfg.host, self.cfg.host
271 ))
272 })?;
273 drop(wrapper);
276 let session = Arc::new(session);
277 let sftp_options = SftpOptions::new().tokio_compat_file_write_limit(
278 NonZeroUsize::new(UPLOAD_WINDOW).expect("non-zero window"),
279 );
280 let sftp = Sftp::from_clonable_session(session.clone(), sftp_options)
281 .await
282 .map_err(|e| {
283 Error::Ssh(format!(
284 "sftp subsystem unavailable on `{}`: {e}",
285 self.cfg.host
286 ))
287 })?;
288 let sftp_home = sftp
291 .fs()
292 .canonicalize(".")
293 .await
294 .map_err(|e| Error::Ssh(format!("cannot resolve the remote home: {e}")))?
295 .to_string_lossy()
296 .into_owned();
297 let detected = if is_sftp_drive_path(&sftp_home) {
298 Platform::Windows
299 } else {
300 Platform::Posix
301 };
302 let platform = match (self.cfg.os, detected) {
303 (Os::Auto, d) => d,
304 (Os::Posix, Platform::Posix) | (Os::Windows, Platform::Windows) => detected,
305 (configured, d) => {
306 tracing::warn!(
307 "config says os = {:?} but the remote looks like {}; using {}",
308 configured,
309 d.name(),
310 d.name()
311 );
312 d
313 }
314 };
315 let home = match platform {
316 Platform::Posix => sftp_home,
317 Platform::Windows => from_sftp_path(&sftp_home),
318 };
319 let login_shell = match platform {
320 Platform::Posix => LoginShell::PowerShell, Platform::Windows => {
322 let out = session
324 .raw_command("echo %OS%")
325 .stdin(Stdio::null())
326 .output()
327 .await?;
328 if String::from_utf8_lossy(&out.stdout).contains("Windows_NT") {
329 LoginShell::Cmd
330 } else {
331 LoginShell::PowerShell
332 }
333 }
334 };
335 let workdir = normalize_for(platform, &expand_tilde(&self.cfg.workdir, &home));
336 let workdir_created = self
340 .ensure_dir_on(&sftp, platform, &workdir)
341 .await
342 .map_err(|e| match e {
343 Error::Invalid(m) => Error::Invalid(format!("remote.workdir: {m}")),
344 e => Error::Ssh(format!("cannot create remote.workdir `{workdir}`: {e}")),
345 })?;
346 if workdir_created {
347 tracing::info!(host = %self.cfg.host, "created the working directory {workdir}");
348 }
349 let conn = Arc::new(Conn {
350 session,
351 sftp,
352 platform,
353 login_shell,
354 home,
355 workdir,
356 workdir_created,
357 });
358 *slot = Some(conn.clone());
359 tracing::info!(host = %self.cfg.host, platform = platform.name(), "connected");
360 Ok(conn)
361 }
362
363 pub async fn resolve(&self, raw: &str) -> Result<String> {
367 let raw = raw.trim();
368 let conn = self.conn().await?;
369 if raw.is_empty() {
370 return Ok(conn.workdir.clone());
371 }
372 if is_absolute_for(conn.platform, raw) {
373 return Ok(normalize_for(conn.platform, raw));
374 }
375 if raw == "~" || raw.starts_with("~/") || raw.starts_with("~\\") {
376 return Ok(normalize_for(conn.platform, &expand_tilde(raw, &conn.home)));
377 }
378 Ok(normalize_for(
379 conn.platform,
380 &format!("{}/{raw}", conn.workdir),
381 ))
382 }
383
384 pub async fn exec(
388 &self,
389 command: &str,
390 cwd: Option<&str>,
391 timeout_secs: Option<u64>,
392 ) -> Result<ExecOutput> {
393 let conn = self.conn().await?;
394 let cwd = match cwd {
395 Some(c) => self.resolve(c).await?,
396 None => conn.workdir.clone(),
397 };
398 let timeout = timeout_secs
399 .unwrap_or(self.limits.command_timeout_secs)
400 .clamp(1, self.limits.max_command_timeout_secs);
401
402 let _permit = self.channels.acquire().await.expect("semaphore open");
403 let started = Instant::now();
404 let mut cmd = match conn.platform {
405 Platform::Posix => {
406 let script = format!(
410 "cd {} || exit {CD_FAILED_EXIT}\nexport NO_COLOR=1\n{command}\n",
411 shell_quote(&cwd)
412 );
413 let b64 = base64::engine::general_purpose::STANDARD.encode(script.as_bytes());
414 let shell = self
415 .cfg
416 .shell
417 .iter()
418 .map(|s| format!("\"{}\"", s.replace('"', "\\\"")))
419 .collect::<Vec<_>>()
420 .join(" ");
421 let inner =
426 format!("timeout -k 5 {timeout} {shell} \"$(printf %s {b64} | base64 -d)\"");
427 let mut c = conn.session.raw_command("sh");
428 c.raw_arg("-c").raw_arg(format!("'{inner}'"));
429 c
430 }
431 Platform::Windows => {
432 let (exe, extra) = self.powershell();
433 let outer = windows_wrapper(exe, &extra, &cwd, command, timeout);
434 let mut c = conn.session.raw_command(exe);
435 for a in &extra {
436 c.raw_arg(a);
437 }
438 c.raw_arg("-NoProfile")
439 .raw_arg("-NonInteractive")
440 .raw_arg("-ExecutionPolicy")
441 .raw_arg("Bypass")
442 .raw_arg("-EncodedCommand")
443 .raw_arg(encode_utf16_b64(&outer));
444 if conn.login_shell == LoginShell::PowerShell {
445 c.raw_arg("; exit $LASTEXITCODE");
448 }
449 c
450 }
451 };
452 cmd.stdin(Stdio::null())
453 .stdout(Stdio::piped())
454 .stderr(Stdio::piped());
455 let mut child = cmd.spawn().await?;
456 let stdout = child.stdout().take().expect("piped stdout");
457 let stderr = child.stderr().take().expect("piped stderr");
458 let cap = self.limits.max_output_bytes;
459
460 let collect = async {
461 let (out, err) =
462 tokio::join!(collect_bounded(stdout, cap), collect_bounded(stderr, cap));
463 let status = child.wait().await?;
464 Ok::<_, Error>((out?, err?, status))
465 };
466 let watchdog = Duration::from_secs(timeout + WATCHDOG_GRACE);
467 let (mut out, mut err, status) = match tokio::time::timeout(watchdog, collect).await {
468 Ok(r) => r?,
469 Err(_) => {
470 tracing::warn!("local watchdog fired after {}s", watchdog.as_secs());
471 return Err(Error::Timeout { secs: timeout });
472 }
473 };
474 let mut exit_code = status.code().unwrap_or(-1);
475 if conn.platform == Platform::Windows {
476 if let Some(code) = take_windows_exit_marker(&mut out.data) {
477 exit_code = code;
478 }
479 out.data = crlf_to_lf(&out.data);
480 err.data = crlf_to_lf(&decode_clixml(&err.data));
481 }
482 let timed_out = exit_code == TIMEOUT_EXIT;
483 if exit_code == CD_FAILED_EXIT && out.data.is_empty() {
484 return Err(Error::Invalid(format!(
485 "cannot cd into `{cwd}` on the remote"
486 )));
487 }
488 Ok(ExecOutput {
489 exit_code,
490 stdout: out.data,
491 stderr: err.data,
492 stdout_truncated: out.truncated,
493 stderr_truncated: err.truncated,
494 timed_out,
495 duration: started.elapsed(),
496 })
497 }
498
499 fn powershell(&self) -> (&str, Vec<String>) {
502 if self.cfg.shell == default_shell() || self.cfg.shell.is_empty() {
503 ("powershell.exe", Vec::new())
504 } else {
505 (&self.cfg.shell[0], self.cfg.shell[1..].to_vec())
506 }
507 }
508
509 pub async fn read_file(&self, path: &str, max: usize) -> Result<(Vec<u8>, u64)> {
512 let conn = self.conn().await?;
513 let path = self.resolve(path).await?;
514 let sftp_path = to_sftp_path(conn.platform, &path);
515 let _permit = self.channels.acquire().await.expect("semaphore open");
516 let mut fs = conn.sftp.fs();
517 let meta = fs
518 .metadata(&sftp_path)
519 .await
520 .map_err(|e| not_found(&path, e))?;
521 if meta.file_type().map(|t| t.is_dir()).unwrap_or(false) {
522 return Err(Error::Invalid(format!("`{path}` is a directory")));
523 }
524 let len = meta.len().unwrap_or(0);
525 let mut file = conn
526 .sftp
527 .open(&sftp_path)
528 .await
529 .map_err(|e| not_found(&path, e))?;
530 let want = (len as usize).min(max);
531 let mut buf = BytesMut::with_capacity(want);
532 while buf.len() < want {
533 file.seek(std::io::SeekFrom::Start(buf.len() as u64))
537 .await?;
538 let chunk = (want - buf.len()).min(256 * 1024) as u32;
539 match file.read(chunk, buf.split_off(buf.len())).await? {
540 Some(bytes) => buf.unsplit(bytes),
541 None => break,
542 }
543 }
544 let _ = file.close().await;
545 Ok((buf.to_vec(), len))
546 }
547
548 pub async fn write_file(&self, path: &str, content: &[u8]) -> Result<String> {
550 let conn = self.conn().await?;
551 let path = self.resolve(path).await?;
552 if let Some(parent) = parent_of(conn.platform, &path) {
553 self.ensure_dir(&parent).await?;
554 }
555 let _permit = self.channels.acquire().await.expect("semaphore open");
556 conn.sftp
557 .fs()
558 .write(to_sftp_path(conn.platform, &path), content)
559 .await
560 .map_err(|e| Error::Ssh(format!("cannot write `{path}`: {e}")))?;
561 Ok(path)
562 }
563
564 pub async fn upload_file(
571 &self,
572 src: std::fs::File,
573 dest: &str,
574 mut scan: StreamGuard<'_>,
575 max: u64,
576 ) -> Result<(String, u64)> {
577 let conn = self.conn().await?;
578 let path = self.resolve(dest).await?;
579 if let Some(parent) = parent_of(conn.platform, &path) {
580 self.ensure_dir(&parent).await?;
581 }
582 let sftp_path = to_sftp_path(conn.platform, &path);
583 let _permit = self.channels.acquire().await.expect("semaphore open");
584 let mut src = tokio::fs::File::from_std(src);
585 let file = conn
586 .sftp
587 .create(&sftp_path)
588 .await
589 .map_err(|e| Error::Ssh(format!("cannot create `{path}`: {e}")))?;
590 let mut buf = vec![0u8; TRANSFER_CHUNK];
591 let mut sent: u64 = 0;
592 let copied: Result<()> = async {
593 let mut file = std::pin::pin!(TokioCompatFile::new(file));
597 let mut read: u64 = 0;
598 loop {
599 let n = src.read(&mut buf).await?;
600 if n == 0 {
601 break;
602 }
603 read += n as u64;
604 if read > max {
605 return Err(Error::Invalid(format!(
606 "`{path}`: the local file grew past the {max} bytes the transfer \
607 limit leaves while it was being uploaded"
608 )));
609 }
610 let out = scan.feed(&buf[..n])?;
611 file.write_all(&out).await?;
612 sent += out.len() as u64;
613 }
614 let out = scan.finish();
615 file.write_all(&out).await?;
616 sent += out.len() as u64;
617 file.flush().await?;
618 Ok(())
619 }
620 .await;
621 if let Err(e) = copied {
622 let _ = conn.sftp.fs().remove_file(&sftp_path).await;
623 return Err(match e {
624 Error::Denied(_) | Error::Invalid(_) => e,
625 e => Error::Ssh(format!("upload of `{path}` failed: {e}")),
626 });
627 }
628 Ok((path, sent))
629 }
630
631 pub async fn file_size(&self, path: &str) -> Result<u64> {
633 let conn = self.conn().await?;
634 let path = self.resolve(path).await?;
635 let _permit = self.channels.acquire().await.expect("semaphore open");
636 let meta = conn
637 .sftp
638 .fs()
639 .metadata(to_sftp_path(conn.platform, &path))
640 .await
641 .map_err(|e| not_found(&path, e))?;
642 if meta.file_type().map(|t| t.is_dir()).unwrap_or(false) {
643 return Err(Error::Invalid(format!("`{path}` is a directory")));
644 }
645 Ok(meta.len().unwrap_or(0))
646 }
647
648 pub async fn download_into(
654 &self,
655 path: &str,
656 out: &Arc<std::fs::File>,
657 max: u64,
658 ) -> Result<u64> {
659 let conn = self.conn().await?;
660 let path = self.resolve(path).await?;
661 let sftp_path = to_sftp_path(conn.platform, &path);
662 let _permit = self.channels.acquire().await.expect("semaphore open");
663 let meta = conn
664 .sftp
665 .fs()
666 .metadata(&sftp_path)
667 .await
668 .map_err(|e| not_found(&path, e))?;
669 if meta.file_type().map(|t| t.is_dir()).unwrap_or(false) {
670 return Err(Error::Invalid(format!("`{path}` is a directory")));
671 }
672 let len = meta.len().unwrap_or(0);
673 if len > max {
674 return Err(Error::Invalid(format!(
675 "`{path}` is now {len} bytes, more than the {max} bytes the transfer limit \
676 leaves; it changed while being downloaded"
677 )));
678 }
679 out.set_len(len)?;
680 let next = AtomicU64::new(0);
681 let streams = DOWNLOAD_STREAMS.min(len.div_ceil(DOWNLOAD_STEP)).max(1);
682 let readers = (0..streams).map(|_| async {
683 let mut file = conn
684 .sftp
685 .open(&sftp_path)
686 .await
687 .map_err(|e| not_found(&path, e))?;
688 loop {
689 let offset = next.fetch_add(DOWNLOAD_STEP, Ordering::Relaxed);
690 if offset >= len {
691 break;
692 }
693 let want = DOWNLOAD_STEP.min(len - offset);
694 let mut buf = BytesMut::with_capacity(want as usize);
695 while (buf.len() as u64) < want {
696 file.seek(std::io::SeekFrom::Start(offset + buf.len() as u64))
698 .await?;
699 let n = (want - buf.len() as u64).min(256 * 1024) as u32;
700 match file.read(n, buf.split_off(buf.len())).await? {
701 Some(bytes) => buf.unsplit(bytes),
702 None => {
703 return Err(Error::Ssh(format!(
704 "`{path}` shrank while it was being downloaded"
705 )))
706 }
707 }
708 }
709 let out = out.clone();
710 tokio::task::spawn_blocking(move || write_all_at(&out, &buf, offset))
711 .await
712 .map_err(|e| Error::Ssh(format!("download writer failed: {e}")))??;
713 }
714 let _ = file.close().await;
715 Ok::<(), Error>(())
716 });
717 futures_util::future::try_join_all(readers).await?;
718 Ok(len)
719 }
720
721 pub async fn ensure_dir(&self, dir: &str) -> Result<()> {
724 let conn = self.conn().await?;
725 self.ensure_dir_on(&conn.sftp, conn.platform, dir)
726 .await
727 .map(|_| ())
728 }
729
730 async fn ensure_dir_on(&self, sftp: &Sftp, platform: Platform, dir: &str) -> Result<bool> {
733 if self.known_dirs.lock().await.contains(dir) {
734 return Ok(false);
735 }
736 let mut missing: Vec<String> = Vec::new();
738 let mut cur = dir.to_string();
739 loop {
740 if self.known_dirs.lock().await.contains(&cur) {
741 break;
742 }
743 let _permit = self.channels.acquire().await.expect("semaphore open");
744 match sftp.fs().metadata(to_sftp_path(platform, &cur)).await {
745 Ok(m) => {
746 if !m.file_type().map(|t| t.is_dir()).unwrap_or(false) {
747 return Err(Error::Invalid(format!(
748 "`{cur}` exists on the remote and is not a directory"
749 )));
750 }
751 self.known_dirs.lock().await.insert(cur.clone());
752 break;
753 }
754 Err(_) => {
755 missing.push(cur.clone());
756 match parent_of(platform, &cur) {
757 Some(p) => cur = p,
758 None => break,
759 }
760 }
761 }
762 }
763 let mut created = false;
764 for d in missing.into_iter().rev() {
765 let _permit = self.channels.acquire().await.expect("semaphore open");
766 if let Err(e) = sftp.fs().create_dir(to_sftp_path(platform, &d)).await {
767 let exists = sftp
769 .fs()
770 .metadata(to_sftp_path(platform, &d))
771 .await
772 .map(|m| m.file_type().map(|t| t.is_dir()).unwrap_or(false))
773 .unwrap_or(false);
774 if !exists {
775 return Err(Error::Ssh(format!("cannot create directory `{d}`: {e}")));
776 }
777 }
778 self.known_dirs.lock().await.insert(d);
779 created = true;
780 }
781 Ok(created)
782 }
783
784 pub async fn exists(&self, path: &str) -> Result<Option<bool>> {
785 let conn = self.conn().await?;
786 let path = self.resolve(path).await?;
787 let _permit = self.channels.acquire().await.expect("semaphore open");
788 match conn
789 .sftp
790 .fs()
791 .metadata(to_sftp_path(conn.platform, &path))
792 .await
793 {
794 Ok(m) => Ok(Some(m.file_type().map(|t| t.is_dir()).unwrap_or(false))),
795 Err(_) => Ok(None),
796 }
797 }
798
799 pub async fn walk_files(&self, dir: &str, limit: usize) -> Result<Vec<String>> {
803 let conn = self.conn().await?;
804 let sep = separator(conn.platform);
805 let mut files = Vec::new();
806 let mut stack = vec![dir.to_string()];
807 while let Some(d) = stack.pop() {
808 let _permit = self.channels.acquire().await.expect("semaphore open");
809 let handle = conn
810 .sftp
811 .fs()
812 .open_dir(to_sftp_path(conn.platform, &d))
813 .await
814 .map_err(|e| Error::Ssh(format!("cannot list `{d}`: {e}")))?;
815 let mut entries = std::pin::pin!(handle.read_dir());
816 while let Some(entry) = entries.next().await {
817 let entry = entry.map_err(|e| Error::Ssh(format!("cannot list `{d}`: {e}")))?;
818 let name = entry.filename().to_string_lossy().into_owned();
819 if name == "." || name == ".." {
820 continue;
821 }
822 let full = format!("{d}{sep}{name}");
823 match entry.file_type() {
824 Some(t) if t.is_dir() => stack.push(full),
825 Some(t) if t.is_file() => {
826 files.push(full);
827 if files.len() > limit {
828 return Ok(files);
829 }
830 }
831 _ => {}
832 }
833 }
834 }
835 files.sort();
836 Ok(files)
837 }
838
839 pub async fn has_tool(&self, name: &str) -> Result<bool> {
841 let conn = self.conn().await?;
842 let cmd = match conn.platform {
843 Platform::Posix => format!("command -v {} >/dev/null 2>&1", shell_quote(name)),
844 Platform::Windows => format!(
845 "if (Get-Command {} -ErrorAction SilentlyContinue) {{ 'yes' }} else {{ 'no' }}",
846 ps_quote(name)
847 ),
848 };
849 let out = self.exec(&cmd, None, Some(15)).await?;
850 Ok(match conn.platform {
851 Platform::Posix => out.exit_code == 0,
852 Platform::Windows => String::from_utf8_lossy(&out.stdout).contains("yes"),
853 })
854 }
855}
856
857fn not_found(path: &str, e: openssh_sftp_client::Error) -> Error {
858 Error::Ssh(format!("`{path}`: {e}"))
859}
860
861pub fn ps_quote(s: &str) -> String {
865 format!("'{}'", s.replace('\'', "''"))
866}
867
868fn encode_utf16_b64(script: &str) -> String {
870 let bytes: Vec<u8> = script
871 .encode_utf16()
872 .flat_map(|u| u.to_le_bytes())
873 .collect();
874 base64::engine::general_purpose::STANDARD.encode(bytes)
875}
876
877fn windows_wrapper(exe: &str, extra: &[String], cwd: &str, command: &str, timeout: u64) -> String {
905 let inner = format!(
906 "$ProgressPreference='SilentlyContinue'; $ErrorActionPreference='Continue'\n\
907 [Console]::OutputEncoding=[Text.Encoding]::UTF8; [Console]::InputEncoding=[Text.Encoding]::UTF8; \
908 $OutputEncoding=[Text.Encoding]::UTF8\n\
909 $env:NO_COLOR='1'; $env:PYTHONUTF8='1'; $env:PYTHONIOENCODING='utf-8'\n\
910 try {{ Set-Location -LiteralPath {cwd} -ErrorAction Stop }} \
911 catch {{ [Console]::Error.WriteLine('cannot cd'); exit {CD_FAILED_EXIT} }}\n\
912 $global:LASTEXITCODE=0\n\
913 {command}\n\
914 $__fh_ok=$?\n\
915 Write-Output \"{WIN_EXIT_MARKER}$(if ($__fh_ok) {{0}} elseif ($LASTEXITCODE) {{$LASTEXITCODE}} \
916 elseif ($Error.Count -and $Error[0].FullyQualifiedErrorId -like 'NativeCommandError*') {{0}} else {{1}})\"\n",
917 cwd = ps_quote(cwd),
918 );
919 let mut args: Vec<String> = extra.iter().map(|a| ps_quote(a)).collect();
920 args.extend(
921 [
922 "-NoProfile",
923 "-NonInteractive",
924 "-ExecutionPolicy",
925 "Bypass",
926 "-EncodedCommand",
927 ]
928 .iter()
929 .map(|a| ps_quote(a)),
930 );
931 args.push(ps_quote(&encode_utf16_b64(&inner)));
932 format!(
933 "$ProgressPreference='SilentlyContinue'; $ErrorActionPreference='Continue'\n\
934 $p=Start-Process -FilePath {exe} -ArgumentList {args} -NoNewWindow -PassThru\n\
935 $null=$p.Handle\n\
936 if (-not $p.WaitForExit({ms})) {{ taskkill /T /F /PID $p.Id 2>&1 | Out-Null; \
937 $p.WaitForExit(); exit {TIMEOUT_EXIT} }}\n\
938 exit $p.ExitCode\n",
939 exe = ps_quote(exe),
940 args = args.join(","),
941 ms = timeout.saturating_mul(1000),
942 )
943}
944
945fn take_windows_exit_marker(stdout: &mut Vec<u8>) -> Option<i32> {
948 let text = String::from_utf8_lossy(stdout);
949 let pos = text.rfind(WIN_EXIT_MARKER)?;
950 let rest = &text[pos + WIN_EXIT_MARKER.len()..];
951 let line = rest.lines().next().unwrap_or("").trim();
952 let code: i32 = line.parse().ok()?;
953 let keep = text[..pos].trim_end_matches(['\r', '\n']).to_string();
955 stdout.clear();
956 stdout.extend_from_slice(keep.as_bytes());
957 if !stdout.is_empty() {
958 stdout.push(b'\n');
959 }
960 Some(code)
961}
962
963fn crlf_to_lf(data: &[u8]) -> Vec<u8> {
964 let mut out = Vec::with_capacity(data.len());
965 let mut i = 0;
966 while i < data.len() {
967 if data[i] == b'\r' && data.get(i + 1) == Some(&b'\n') {
968 i += 1;
969 continue;
970 }
971 out.push(data[i]);
972 i += 1;
973 }
974 out
975}
976
977fn decode_clixml(data: &[u8]) -> Vec<u8> {
981 let text = String::from_utf8_lossy(data);
982 if !text.contains("#< CLIXML") {
983 return data.to_vec();
984 }
985 let mut out = String::new();
986 let mut rest: &str = &text;
987 loop {
988 match rest.find("#< CLIXML") {
989 None => {
990 out.push_str(rest);
991 break;
992 }
993 Some(h) => {
994 out.push_str(&rest[..h]);
995 let after = &rest[h + "#< CLIXML".len()..];
996 let after = after
997 .strip_prefix("\r\n")
998 .or_else(|| after.strip_prefix('\n'))
999 .unwrap_or(after);
1000 match after.find("</Objs>") {
1001 Some(end) => {
1002 out.push_str(&clixml_strings(&after[..end]));
1003 rest = &after[end + "</Objs>".len()..];
1004 }
1005 None => {
1006 out.push_str(&clixml_strings(after));
1007 break;
1008 }
1009 }
1010 }
1011 }
1012 }
1013 out.into_bytes()
1014}
1015
1016fn clixml_strings(xml: &str) -> String {
1017 let mut out = String::new();
1018 let mut rest = xml;
1019 while let Some(start) = rest.find("<S S=\"") {
1020 let after = &rest[start + 6..];
1021 let Some(q) = after.find('"') else { break };
1022 let kind = &after[..q];
1023 let after = &after[q + 1..];
1024 let Some(gt) = after.find('>') else { break };
1025 let body_start = &after[gt + 1..];
1026 let Some(end) = body_start.find("</S>") else {
1027 break;
1028 };
1029 if kind == "Error" || kind == "Warning" {
1030 out.push_str(&unescape_clixml(&body_start[..end]));
1031 }
1032 rest = &body_start[end + 4..];
1033 }
1034 out
1035}
1036
1037fn unescape_clixml(s: &str) -> String {
1038 let s = s
1039 .replace("_x000D__x000A_", "\n")
1040 .replace("_x000A_", "\n")
1041 .replace("_x000D_", "")
1042 .replace("_x0009_", "\t");
1043 s.replace("<", "<")
1044 .replace(">", ">")
1045 .replace(""", "\"")
1046 .replace("'", "'")
1047 .replace("&", "&")
1048}
1049
1050fn separator(p: Platform) -> char {
1053 match p {
1054 Platform::Posix => '/',
1055 Platform::Windows => '\\',
1056 }
1057}
1058
1059fn is_sftp_drive_path(s: &str) -> bool {
1061 let b = s.as_bytes();
1062 b.len() >= 3 && b[0] == b'/' && b[1].is_ascii_alphabetic() && b[2] == b':'
1063}
1064
1065fn is_drive_path(s: &str) -> bool {
1066 let b = s.as_bytes();
1067 b.len() >= 2 && b[0].is_ascii_alphabetic() && b[1] == b':'
1068}
1069
1070fn is_absolute_for(p: Platform, raw: &str) -> bool {
1071 match p {
1072 Platform::Posix => raw.starts_with('/'),
1073 Platform::Windows => {
1074 is_drive_path(raw) || is_sftp_drive_path(raw) || raw.starts_with("\\\\")
1075 }
1076 }
1077}
1078
1079fn to_sftp_path(p: Platform, native: &str) -> String {
1082 match p {
1083 Platform::Posix => native.to_string(),
1084 Platform::Windows => format!("/{}", native.replace('\\', "/")),
1085 }
1086}
1087
1088fn from_sftp_path(sftp: &str) -> String {
1090 let s = sftp.strip_prefix('/').unwrap_or(sftp);
1091 let s = s.replace('/', "\\");
1092 if s.len() == 2 && is_drive_path(&s) {
1093 format!("{s}\\")
1094 } else {
1095 s
1096 }
1097}
1098
1099fn parent_of(p: Platform, path: &str) -> Option<String> {
1100 match p {
1101 Platform::Posix => {
1102 if path == "/" {
1103 return None;
1104 }
1105 match path.rfind('/') {
1106 Some(0) => Some("/".to_string()),
1107 Some(i) => Some(path[..i].to_string()),
1108 None => None,
1109 }
1110 }
1111 Platform::Windows => {
1112 if path.len() <= 3 {
1114 return None;
1115 }
1116 let i = path.rfind('\\')?;
1117 if i <= 2 {
1118 Some(path[..3].to_string())
1119 } else {
1120 Some(path[..i].to_string())
1121 }
1122 }
1123 }
1124}
1125
1126fn normalize_for(p: Platform, raw: &str) -> String {
1127 match p {
1128 Platform::Posix => normalize(raw),
1129 Platform::Windows => normalize_windows(raw),
1130 }
1131}
1132
1133fn expand_tilde(p: &str, home: &str) -> String {
1135 if p == "~" {
1136 home.to_string()
1137 } else if let Some(rest) = p.strip_prefix("~/").or_else(|| p.strip_prefix("~\\")) {
1138 format!("{home}/{rest}")
1139 } else {
1140 p.to_string()
1141 }
1142}
1143
1144pub fn normalize(p: &str) -> String {
1146 let mut parts: Vec<&str> = Vec::new();
1147 for seg in p.split('/') {
1148 match seg {
1149 "" | "." => {}
1150 ".." => {
1151 parts.pop();
1152 }
1153 s => parts.push(s),
1154 }
1155 }
1156 format!("/{}", parts.join("/"))
1157}
1158
1159pub fn normalize_windows(p: &str) -> String {
1162 let unc = p.starts_with("\\\\") || p.starts_with("//");
1163 let s = p.replace('/', "\\");
1164 let s = s
1165 .strip_prefix('\\')
1166 .filter(|r| is_drive_path(r))
1167 .unwrap_or(&s);
1168 let mut parts: Vec<&str> = Vec::new();
1169 let mut drive = String::new();
1170 for (i, seg) in s.split('\\').enumerate() {
1171 if i == 0 && is_drive_path(seg) && seg.len() == 2 {
1172 drive = seg.to_uppercase();
1173 continue;
1174 }
1175 match seg {
1176 "" | "." => {}
1177 ".." => {
1178 parts.pop();
1179 }
1180 x => parts.push(x),
1181 }
1182 }
1183 if unc {
1184 return format!("\\\\{}", parts.join("\\"));
1185 }
1186 if drive.is_empty() {
1187 return format!("\\{}", parts.join("\\"));
1190 }
1191 if parts.is_empty() {
1192 format!("{drive}\\")
1193 } else {
1194 format!("{drive}\\{}", parts.join("\\"))
1195 }
1196}
1197
1198struct Collected {
1199 data: Vec<u8>,
1200 truncated: bool,
1201}
1202
1203async fn collect_bounded<R: AsyncReadExt + Unpin>(mut r: R, cap: usize) -> Result<Collected> {
1206 let head_cap = cap * 2 / 3;
1207 let tail_cap = cap - head_cap;
1208 let mut head = Vec::new();
1209 let mut tail = Vec::new();
1210 let mut truncated = false;
1211 let mut buf = vec![0u8; 64 * 1024];
1212 loop {
1213 let n = r.read(&mut buf).await?;
1214 if n == 0 {
1215 break;
1216 }
1217 let mut chunk = &buf[..n];
1218 if head.len() < head_cap {
1219 let take = chunk.len().min(head_cap - head.len());
1220 head.extend_from_slice(&chunk[..take]);
1221 chunk = &chunk[take..];
1222 }
1223 if !chunk.is_empty() {
1224 truncated = true;
1225 tail.extend_from_slice(chunk);
1226 if tail.len() > tail_cap * 2 {
1227 let drop = tail.len() - tail_cap;
1228 tail.drain(..drop);
1229 }
1230 }
1231 }
1232 if truncated {
1233 if tail.len() > tail_cap {
1234 let drop = tail.len() - tail_cap;
1235 tail.drain(..drop);
1236 }
1237 let omitted_note = format!("\n\n[... output truncated; limit is {cap} bytes ...]\n\n");
1238 head.extend_from_slice(omitted_note.as_bytes());
1239 head.extend_from_slice(&tail);
1240 }
1241 Ok(Collected {
1242 data: head,
1243 truncated,
1244 })
1245}
1246
1247const USER_SSH_CONFIG: &str = "~/.ssh/config";
1249const SYSTEM_SSH_CONFIG: &str = "/etc/ssh/ssh_config";
1250
1251const SSH_CONFIG_HEADER: &str = "\
1255# Written by FarHand for one connection and removed once it is up.
1256ClearAllForwardings yes
1257ForwardAgent no
1258ForwardX11 no
1259ForwardX11Trusted no
1260Tunnel no
1261GSSAPIDelegateCredentials no
1262";
1263
1264fn ssh_config_text(includes: &[&str]) -> String {
1265 let mut s = SSH_CONFIG_HEADER.to_string();
1266 for i in includes {
1267 s.push_str(&format!("Include {i}\n"));
1268 }
1269 s
1270}
1271
1272struct SshConfigWrapper {
1275 path: std::path::PathBuf,
1276}
1277
1278impl SshConfigWrapper {
1279 fn create(includes: &[&str]) -> Result<Self> {
1280 use std::io::Write;
1281 let path = std::env::temp_dir().join(format!(
1282 "farhand-ssh-{}-{:016x}.conf",
1283 std::process::id(),
1284 random_u64()
1285 ));
1286 let mut f = create_exclusive(&path)?;
1287 f.write_all(ssh_config_text(includes).as_bytes())?;
1288 Ok(Self { path })
1289 }
1290}
1291
1292impl Drop for SshConfigWrapper {
1293 fn drop(&mut self) {
1294 let _ = std::fs::remove_file(&self.path);
1295 }
1296}
1297
1298pub(crate) fn random_u64() -> u64 {
1301 use std::hash::{BuildHasher, Hasher};
1302 let mut h = std::collections::hash_map::RandomState::new().build_hasher();
1303 h.write_u128(
1304 std::time::SystemTime::now()
1305 .duration_since(std::time::UNIX_EPOCH)
1306 .map(|d| d.as_nanos())
1307 .unwrap_or(0),
1308 );
1309 h.finish()
1310}
1311
1312fn create_exclusive(path: &Path) -> Result<std::fs::File> {
1315 let mut o = std::fs::OpenOptions::new();
1316 o.write(true).create_new(true);
1317 #[cfg(unix)]
1318 {
1319 use std::os::unix::fs::OpenOptionsExt;
1320 o.custom_flags(libc::O_NOFOLLOW).mode(0o600);
1321 }
1322 o.open(path).map_err(|e| {
1323 Error::Io(std::io::Error::new(
1324 e.kind(),
1325 format!("cannot create {}: {e}", path.display()),
1326 ))
1327 })
1328}
1329
1330#[cfg(unix)]
1331fn write_all_at(file: &std::fs::File, buf: &[u8], offset: u64) -> std::io::Result<()> {
1332 std::os::unix::fs::FileExt::write_all_at(file, buf, offset)
1333}
1334
1335#[cfg(windows)]
1336fn write_all_at(file: &std::fs::File, mut buf: &[u8], mut offset: u64) -> std::io::Result<()> {
1337 while !buf.is_empty() {
1338 let n = std::os::windows::fs::FileExt::seek_write(file, buf, offset)?;
1339 buf = &buf[n..];
1340 offset += n as u64;
1341 }
1342 Ok(())
1343}
1344
1345#[cfg(test)]
1346mod tests {
1347 use super::*;
1348
1349 #[cfg(unix)]
1350 #[test]
1351 fn temp_files_never_follow_a_planted_link() {
1352 let d = tempfile::tempdir().unwrap();
1353 let outside = d.path().join("outside");
1354 let link = d.path().join("part");
1355 std::os::unix::fs::symlink(&outside, &link).unwrap();
1356 assert!(create_exclusive(&link).is_err());
1358 assert!(!outside.exists());
1359 std::fs::write(&outside, "keep").unwrap();
1360 assert!(create_exclusive(&link).is_err());
1361 assert_eq!(std::fs::read_to_string(&outside).unwrap(), "keep");
1362 let fresh = d.path().join("fresh");
1363 let f = create_exclusive(&fresh).unwrap();
1364 write_all_at(&f, b"xy", 3).unwrap();
1365 assert_eq!(std::fs::read(&fresh).unwrap(), b"\0\0\0xy");
1366 assert!(create_exclusive(&fresh).is_err());
1367 }
1368
1369 #[test]
1370 fn the_ssh_config_wrapper_closes_every_way_back() {
1371 let d = tempfile::tempdir().unwrap();
1372 let user = d.path().join("config");
1373 std::fs::write(
1374 &user,
1375 "Host fhtest\n HostName 192.0.2.1\n RemoteForward 9000 localhost:22\n \
1376 LocalForward 9001 localhost:22\n DynamicForward 9002\n ForwardAgent yes\n \
1377 ForwardX11 yes\n",
1378 )
1379 .unwrap();
1380 let w = SshConfigWrapper::create(&[user.to_str().unwrap()]).unwrap();
1381 let path = w.path.clone();
1382 let out = std::process::Command::new("ssh")
1384 .arg("-G")
1385 .arg("-F")
1386 .arg(&path)
1387 .arg("fhtest")
1388 .stdin(std::process::Stdio::null())
1389 .output();
1390 drop(w);
1391 assert!(!path.exists());
1392 let Ok(out) = out else {
1393 return; };
1395 let text = String::from_utf8_lossy(&out.stdout).to_lowercase();
1396 assert!(text.lines().any(|l| l == "hostname 192.0.2.1"), "{text}");
1398 for line in [
1400 "clearallforwardings yes",
1401 "forwardagent no",
1402 "forwardx11 no",
1403 ] {
1404 assert!(text.lines().any(|l| l == line), "{line}: {text}");
1405 }
1406 for word in ["remoteforward", "localforward", "dynamicforward"] {
1407 assert!(!text.contains(word), "{word}: {text}");
1408 }
1409 }
1410
1411 #[test]
1412 fn tilde_expansion() {
1413 assert_eq!(expand_tilde("~", "/root"), "/root");
1414 assert_eq!(expand_tilde("~/a/b", "/root"), "/root/a/b");
1415 assert_eq!(expand_tilde("/x", "/root"), "/x");
1416 assert_eq!(expand_tilde("rel", "/root"), "rel");
1417 assert_eq!(
1418 normalize_windows(&expand_tilde("~\\x", "C:\\Users\\me")),
1419 "C:\\Users\\me\\x"
1420 );
1421 }
1422
1423 #[test]
1424 fn normalizes_paths() {
1425 assert_eq!(normalize("/a/b/../c/./d"), "/a/c/d");
1426 assert_eq!(normalize("/../x"), "/x");
1427 assert_eq!(normalize("/"), "/");
1428 }
1429
1430 #[test]
1431 fn windows_paths() {
1432 assert_eq!(normalize_windows("C:/Users/me/../x/./y"), "C:\\Users\\x\\y");
1433 assert_eq!(normalize_windows("/C:/Users/me"), "C:\\Users\\me");
1434 assert_eq!(normalize_windows("c:\\"), "C:\\");
1435 assert_eq!(
1436 normalize_windows("C:\\work/proj\\src"),
1437 "C:\\work\\proj\\src"
1438 );
1439 assert_eq!(
1440 normalize_windows("\\\\server\\share\\x"),
1441 "\\\\server\\share\\x"
1442 );
1443 assert_eq!(to_sftp_path(Platform::Windows, "C:\\a\\b"), "/C:/a/b");
1444 assert_eq!(from_sftp_path("/C:/Users/test"), "C:\\Users\\test");
1445 assert_eq!(from_sftp_path("/C:"), "C:\\");
1446 assert!(is_absolute_for(Platform::Windows, "D:\\x"));
1447 assert!(is_absolute_for(Platform::Windows, "/C:/x"));
1448 assert!(!is_absolute_for(Platform::Windows, "src\\main.rs"));
1449 assert!(!is_absolute_for(Platform::Windows, "/tmp"));
1450 assert_eq!(
1451 parent_of(Platform::Windows, "C:\\a\\b").as_deref(),
1452 Some("C:\\a")
1453 );
1454 assert_eq!(
1455 parent_of(Platform::Windows, "C:\\a").as_deref(),
1456 Some("C:\\")
1457 );
1458 assert_eq!(parent_of(Platform::Windows, "C:\\"), None);
1459 assert_eq!(parent_of(Platform::Posix, "/a/b").as_deref(), Some("/a"));
1460 assert_eq!(parent_of(Platform::Posix, "/a").as_deref(), Some("/"));
1461 assert_eq!(parent_of(Platform::Posix, "/"), None);
1462 }
1463
1464 #[test]
1465 fn exit_marker_and_clixml() {
1466 let mut out = b"table\r\n__FARHAND_EXIT__=3\r\n\r\n".to_vec();
1467 assert_eq!(take_windows_exit_marker(&mut out), Some(3));
1468 assert_eq!(out, b"table\n");
1469 let mut out = b"x\n__FARHAND_EXIT__=1\n".to_vec();
1470 assert_eq!(take_windows_exit_marker(&mut out), Some(1));
1471 let mut out = b"__FARHAND_EXIT__=0\n".to_vec();
1472 assert_eq!(take_windows_exit_marker(&mut out), Some(0));
1473 assert!(out.is_empty());
1474 let mut out = b"no marker".to_vec();
1475 assert_eq!(take_windows_exit_marker(&mut out), None);
1476
1477 let err = b"raw first\r\n#< CLIXML\r\n<Objs Version=\"1.1.0.1\"><Obj S=\"progress\"><TN></TN></Obj>\
1478 <S S=\"Error\">Get-Item : Cannot find path 'C:\\nope'_x000D__x000A_</S>\
1479 <S S=\"Error\">At line:6_x000D__x000A_</S></Objs>";
1480 let text = String::from_utf8(decode_clixml(err)).unwrap();
1481 assert_eq!(
1482 text,
1483 "raw first\r\nGet-Item : Cannot find path 'C:\\nope'\nAt line:6\n"
1484 );
1485 assert_eq!(crlf_to_lf(b"a\r\nb\r\n"), b"a\nb\n");
1486 assert_eq!(ps_quote("it's"), "'it''s'");
1487 }
1488
1489 #[test]
1490 fn wrapper_is_plain_ascii_on_the_command_line() {
1491 let w = windows_wrapper("powershell.exe", &[], "C:\\Users\\me", "Get-ChildItem", 30);
1492 assert!(w.contains("WaitForExit(30000)"));
1493 assert!(w.contains("-EncodedCommand"));
1494 assert!(encode_utf16_b64("x")
1495 .chars()
1496 .all(|c| c.is_ascii_alphanumeric() || "+/=".contains(c)));
1497 }
1498
1499 #[tokio::test]
1500 async fn bounded_collection_keeps_head_and_tail() {
1501 let data: Vec<u8> = (0..10_000u32).map(|i| b'a' + (i % 26) as u8).collect();
1502 let c = collect_bounded(&data[..], 300).await.unwrap();
1503 assert!(c.truncated);
1504 assert!(c.data.starts_with(b"abcdefghij"));
1505 assert!(c.data.ends_with(&data[data.len() - 100..]));
1506 let c = collect_bounded(&b"tiny"[..], 300).await.unwrap();
1507 assert!(!c.truncated);
1508 assert_eq!(c.data, b"tiny");
1509 }
1510}