1use std::collections::HashSet;
21use std::sync::Arc;
22use std::time::{Duration, Instant};
23
24use base64::Engine;
25use bytes::BytesMut;
26use futures_util::StreamExt;
27use openssh::{KnownHosts, Session, SessionBuilder, Stdio};
28use openssh_sftp_client::{Sftp, SftpOptions};
29use tokio::io::AsyncReadExt;
30use tokio::sync::{Mutex, Semaphore};
31
32use crate::config::{default_shell, Limits, Os, RemoteConfig};
33use crate::error::{Error, Result};
34use crate::text::shell_quote;
35
36const TIMEOUT_EXIT: i32 = 124;
38const WATCHDOG_GRACE: u64 = 15;
40const CD_FAILED_EXIT: i32 = 97;
42const MAX_CHANNELS: usize = 4;
46const WIN_EXIT_MARKER: &str = "__FARHAND_EXIT__=";
49
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub enum Platform {
53 Posix,
54 Windows,
55}
56
57impl Platform {
58 pub fn name(self) -> &'static str {
59 match self {
60 Platform::Posix => "posix",
61 Platform::Windows => "windows",
62 }
63 }
64}
65
66#[derive(Debug, Clone, Copy, PartialEq, Eq)]
70enum LoginShell {
71 PowerShell,
72 Cmd,
73}
74
75#[derive(Debug, Clone)]
77pub struct Address {
78 pub hostname: String,
79 pub port: u16,
80 pub alias: String,
82}
83
84#[derive(Debug, Clone)]
85pub struct ExecOutput {
86 pub exit_code: i32,
87 pub stdout: Vec<u8>,
88 pub stderr: Vec<u8>,
89 pub stdout_truncated: bool,
90 pub stderr_truncated: bool,
91 pub timed_out: bool,
92 pub duration: Duration,
93}
94
95struct Conn {
96 session: Arc<Session>,
97 sftp: Sftp,
98 platform: Platform,
99 login_shell: LoginShell,
100 home: String,
102 workdir: String,
104}
105
106pub struct Remote {
107 cfg: RemoteConfig,
108 limits: Limits,
109 conn: Mutex<Option<Arc<Conn>>>,
110 channels: Semaphore,
111 known_dirs: Mutex<HashSet<String>>,
114}
115
116impl Remote {
117 pub fn new(cfg: RemoteConfig, limits: Limits) -> Self {
118 Self {
119 cfg,
120 limits,
121 conn: Mutex::new(None),
122 channels: Semaphore::new(MAX_CHANNELS),
123 known_dirs: Mutex::new(HashSet::new()),
124 }
125 }
126
127 pub fn host(&self) -> &str {
128 &self.cfg.host
129 }
130
131 pub fn address(&self) -> Address {
136 let fallback = Address {
137 hostname: self
138 .cfg
139 .host
140 .rsplit('@')
141 .next()
142 .unwrap_or(&self.cfg.host)
143 .to_string(),
144 port: 22,
145 alias: self.cfg.host.clone(),
146 };
147 let out = match std::process::Command::new("ssh")
148 .arg("-G")
149 .arg(&self.cfg.host)
150 .stdin(std::process::Stdio::null())
151 .stderr(std::process::Stdio::null())
152 .output()
153 {
154 Ok(o) if o.status.success() => o.stdout,
155 _ => return fallback,
156 };
157 let text = String::from_utf8_lossy(&out);
158 let mut addr = fallback;
159 for line in text.lines() {
160 match line.split_once(' ') {
161 Some(("hostname", v)) => addr.hostname = v.trim().to_string(),
162 Some(("port", v)) => addr.port = v.trim().parse().unwrap_or(22),
163 _ => {}
164 }
165 }
166 addr
167 }
168
169 pub fn workdir(&self) -> &str {
171 &self.cfg.workdir
172 }
173
174 pub async fn effective_workdir(&self) -> Result<String> {
176 Ok(self.conn().await?.workdir.clone())
177 }
178
179 pub fn limits(&self) -> &Limits {
180 &self.limits
181 }
182
183 pub fn configured_platform(&self) -> Option<Platform> {
186 match self.cfg.os {
187 Os::Auto => None,
188 Os::Posix => Some(Platform::Posix),
189 Os::Windows => Some(Platform::Windows),
190 }
191 }
192
193 pub async fn platform(&self) -> Result<Platform> {
195 Ok(self.conn().await?.platform)
196 }
197
198 pub async fn connect(&self) -> Result<()> {
200 self.conn().await.map(|_| ())
201 }
202
203 pub async fn is_connected(&self) -> bool {
204 match &*self.conn.lock().await {
205 Some(c) => c.session.check().await.is_ok(),
206 None => false,
207 }
208 }
209
210 async fn conn(&self) -> Result<Arc<Conn>> {
211 let mut slot = self.conn.lock().await;
212 if let Some(c) = &*slot {
213 if c.session.check().await.is_ok() {
214 return Ok(c.clone());
215 }
216 tracing::warn!("ssh session to {} dropped; reconnecting", self.cfg.host);
217 *slot = None;
218 self.known_dirs.lock().await.clear();
219 }
220 let mut builder = SessionBuilder::default();
225 builder
226 .connect_timeout(Duration::from_secs(self.cfg.connect_timeout_secs))
227 .server_alive_interval(Duration::from_secs(self.cfg.server_alive_interval_secs))
228 .known_hosts_check(KnownHosts::Strict);
229 let session = builder.connect_mux(&self.cfg.host).await.map_err(|e| {
230 Error::Ssh(format!(
231 "cannot connect to `{}`: {e}. Check that `ssh {}` works from a terminal; \
232 FarHand refuses hosts whose key is not yet in known_hosts, so connect once \
233 by hand first.",
234 self.cfg.host, self.cfg.host
235 ))
236 })?;
237 let session = Arc::new(session);
238 let sftp = Sftp::from_clonable_session(session.clone(), SftpOptions::default())
239 .await
240 .map_err(|e| {
241 Error::Ssh(format!(
242 "sftp subsystem unavailable on `{}`: {e}",
243 self.cfg.host
244 ))
245 })?;
246 let sftp_home = sftp
249 .fs()
250 .canonicalize(".")
251 .await
252 .map_err(|e| Error::Ssh(format!("cannot resolve the remote home: {e}")))?
253 .to_string_lossy()
254 .into_owned();
255 let detected = if is_sftp_drive_path(&sftp_home) {
256 Platform::Windows
257 } else {
258 Platform::Posix
259 };
260 let platform = match (self.cfg.os, detected) {
261 (Os::Auto, d) => d,
262 (Os::Posix, Platform::Posix) | (Os::Windows, Platform::Windows) => detected,
263 (configured, d) => {
264 tracing::warn!(
265 "config says os = {:?} but the remote looks like {}; using {}",
266 configured,
267 d.name(),
268 d.name()
269 );
270 d
271 }
272 };
273 let home = match platform {
274 Platform::Posix => sftp_home,
275 Platform::Windows => from_sftp_path(&sftp_home),
276 };
277 let login_shell = match platform {
278 Platform::Posix => LoginShell::PowerShell, Platform::Windows => {
280 let out = session
282 .raw_command("echo %OS%")
283 .stdin(Stdio::null())
284 .output()
285 .await?;
286 if String::from_utf8_lossy(&out.stdout).contains("Windows_NT") {
287 LoginShell::Cmd
288 } else {
289 LoginShell::PowerShell
290 }
291 }
292 };
293 let workdir = normalize_for(platform, &expand_tilde(&self.cfg.workdir, &home));
294 let conn = Arc::new(Conn {
295 session,
296 sftp,
297 platform,
298 login_shell,
299 home,
300 workdir,
301 });
302 *slot = Some(conn.clone());
303 tracing::info!(host = %self.cfg.host, platform = platform.name(), "connected");
304 Ok(conn)
305 }
306
307 pub async fn resolve(&self, raw: &str) -> Result<String> {
311 let raw = raw.trim();
312 let conn = self.conn().await?;
313 if raw.is_empty() {
314 return Ok(conn.workdir.clone());
315 }
316 if is_absolute_for(conn.platform, raw) {
317 return Ok(normalize_for(conn.platform, raw));
318 }
319 if raw == "~" || raw.starts_with("~/") || raw.starts_with("~\\") {
320 return Ok(normalize_for(conn.platform, &expand_tilde(raw, &conn.home)));
321 }
322 Ok(normalize_for(
323 conn.platform,
324 &format!("{}/{raw}", conn.workdir),
325 ))
326 }
327
328 pub async fn exec(
332 &self,
333 command: &str,
334 cwd: Option<&str>,
335 timeout_secs: Option<u64>,
336 ) -> Result<ExecOutput> {
337 let conn = self.conn().await?;
338 let cwd = match cwd {
339 Some(c) => self.resolve(c).await?,
340 None => conn.workdir.clone(),
341 };
342 let timeout = timeout_secs
343 .unwrap_or(self.limits.command_timeout_secs)
344 .clamp(1, self.limits.max_command_timeout_secs);
345
346 let _permit = self.channels.acquire().await.expect("semaphore open");
347 let started = Instant::now();
348 let mut cmd = match conn.platform {
349 Platform::Posix => {
350 let script = format!(
354 "cd {} || exit {CD_FAILED_EXIT}\nexport NO_COLOR=1\n{command}\n",
355 shell_quote(&cwd)
356 );
357 let b64 = base64::engine::general_purpose::STANDARD.encode(script.as_bytes());
358 let shell = self
359 .cfg
360 .shell
361 .iter()
362 .map(|s| format!("\"{}\"", s.replace('"', "\\\"")))
363 .collect::<Vec<_>>()
364 .join(" ");
365 let inner =
370 format!("timeout -k 5 {timeout} {shell} \"$(printf %s {b64} | base64 -d)\"");
371 let mut c = conn.session.raw_command("sh");
372 c.raw_arg("-c").raw_arg(format!("'{inner}'"));
373 c
374 }
375 Platform::Windows => {
376 let (exe, extra) = self.powershell();
377 let outer = windows_wrapper(exe, &extra, &cwd, command, timeout);
378 let mut c = conn.session.raw_command(exe);
379 for a in &extra {
380 c.raw_arg(a);
381 }
382 c.raw_arg("-NoProfile")
383 .raw_arg("-NonInteractive")
384 .raw_arg("-ExecutionPolicy")
385 .raw_arg("Bypass")
386 .raw_arg("-EncodedCommand")
387 .raw_arg(encode_utf16_b64(&outer));
388 if conn.login_shell == LoginShell::PowerShell {
389 c.raw_arg("; exit $LASTEXITCODE");
392 }
393 c
394 }
395 };
396 cmd.stdin(Stdio::null())
397 .stdout(Stdio::piped())
398 .stderr(Stdio::piped());
399 let mut child = cmd.spawn().await?;
400 let stdout = child.stdout().take().expect("piped stdout");
401 let stderr = child.stderr().take().expect("piped stderr");
402 let cap = self.limits.max_output_bytes;
403
404 let collect = async {
405 let (out, err) =
406 tokio::join!(collect_bounded(stdout, cap), collect_bounded(stderr, cap));
407 let status = child.wait().await?;
408 Ok::<_, Error>((out?, err?, status))
409 };
410 let watchdog = Duration::from_secs(timeout + WATCHDOG_GRACE);
411 let (mut out, mut err, status) = match tokio::time::timeout(watchdog, collect).await {
412 Ok(r) => r?,
413 Err(_) => {
414 tracing::warn!("local watchdog fired after {}s", watchdog.as_secs());
415 return Err(Error::Timeout { secs: timeout });
416 }
417 };
418 let mut exit_code = status.code().unwrap_or(-1);
419 if conn.platform == Platform::Windows {
420 if let Some(code) = take_windows_exit_marker(&mut out.data) {
421 exit_code = code;
422 }
423 out.data = crlf_to_lf(&out.data);
424 err.data = crlf_to_lf(&decode_clixml(&err.data));
425 }
426 let timed_out = exit_code == TIMEOUT_EXIT;
427 if exit_code == CD_FAILED_EXIT && out.data.is_empty() {
428 return Err(Error::Invalid(format!(
429 "cannot cd into `{cwd}` on the remote"
430 )));
431 }
432 Ok(ExecOutput {
433 exit_code,
434 stdout: out.data,
435 stderr: err.data,
436 stdout_truncated: out.truncated,
437 stderr_truncated: err.truncated,
438 timed_out,
439 duration: started.elapsed(),
440 })
441 }
442
443 fn powershell(&self) -> (&str, Vec<String>) {
446 if self.cfg.shell == default_shell() || self.cfg.shell.is_empty() {
447 ("powershell.exe", Vec::new())
448 } else {
449 (&self.cfg.shell[0], self.cfg.shell[1..].to_vec())
450 }
451 }
452
453 pub async fn read_file(&self, path: &str, max: usize) -> Result<(Vec<u8>, u64)> {
456 let conn = self.conn().await?;
457 let path = self.resolve(path).await?;
458 let sftp_path = to_sftp_path(conn.platform, &path);
459 let _permit = self.channels.acquire().await.expect("semaphore open");
460 let mut fs = conn.sftp.fs();
461 let meta = fs
462 .metadata(&sftp_path)
463 .await
464 .map_err(|e| not_found(&path, e))?;
465 if meta.file_type().map(|t| t.is_dir()).unwrap_or(false) {
466 return Err(Error::Invalid(format!("`{path}` is a directory")));
467 }
468 let len = meta.len().unwrap_or(0);
469 let mut file = conn
470 .sftp
471 .open(&sftp_path)
472 .await
473 .map_err(|e| not_found(&path, e))?;
474 let want = (len as usize).min(max);
475 let mut buf = BytesMut::with_capacity(want);
476 let mut remaining = want;
477 while remaining > 0 {
478 let chunk = remaining.min(256 * 1024) as u32;
479 match file.read(chunk, buf.split_off(buf.len())).await? {
480 Some(bytes) => {
481 remaining -= bytes.len();
482 buf.unsplit(bytes);
483 }
484 None => break,
485 }
486 }
487 let _ = file.close().await;
488 Ok((buf.to_vec(), len))
489 }
490
491 pub async fn write_file(&self, path: &str, content: &[u8]) -> Result<String> {
493 let conn = self.conn().await?;
494 let path = self.resolve(path).await?;
495 if let Some(parent) = parent_of(conn.platform, &path) {
496 self.ensure_dir(&parent).await?;
497 }
498 let _permit = self.channels.acquire().await.expect("semaphore open");
499 conn.sftp
500 .fs()
501 .write(to_sftp_path(conn.platform, &path), content)
502 .await
503 .map_err(|e| Error::Ssh(format!("cannot write `{path}`: {e}")))?;
504 Ok(path)
505 }
506
507 pub async fn ensure_dir(&self, dir: &str) -> Result<()> {
510 let conn = self.conn().await?;
511 if self.known_dirs.lock().await.contains(dir) {
512 return Ok(());
513 }
514 let mut missing: Vec<String> = Vec::new();
516 let mut cur = dir.to_string();
517 loop {
518 if self.known_dirs.lock().await.contains(&cur) {
519 break;
520 }
521 let _permit = self.channels.acquire().await.expect("semaphore open");
522 match conn
523 .sftp
524 .fs()
525 .metadata(to_sftp_path(conn.platform, &cur))
526 .await
527 {
528 Ok(m) => {
529 if !m.file_type().map(|t| t.is_dir()).unwrap_or(false) {
530 return Err(Error::Invalid(format!(
531 "`{cur}` exists on the remote and is not a directory"
532 )));
533 }
534 self.known_dirs.lock().await.insert(cur.clone());
535 break;
536 }
537 Err(_) => {
538 missing.push(cur.clone());
539 match parent_of(conn.platform, &cur) {
540 Some(p) => cur = p,
541 None => break,
542 }
543 }
544 }
545 }
546 for d in missing.into_iter().rev() {
547 let _permit = self.channels.acquire().await.expect("semaphore open");
548 if let Err(e) = conn
549 .sftp
550 .fs()
551 .create_dir(to_sftp_path(conn.platform, &d))
552 .await
553 {
554 let exists = conn
556 .sftp
557 .fs()
558 .metadata(to_sftp_path(conn.platform, &d))
559 .await
560 .map(|m| m.file_type().map(|t| t.is_dir()).unwrap_or(false))
561 .unwrap_or(false);
562 if !exists {
563 return Err(Error::Ssh(format!("cannot create directory `{d}`: {e}")));
564 }
565 }
566 self.known_dirs.lock().await.insert(d);
567 }
568 Ok(())
569 }
570
571 pub async fn exists(&self, path: &str) -> Result<Option<bool>> {
572 let conn = self.conn().await?;
573 let path = self.resolve(path).await?;
574 let _permit = self.channels.acquire().await.expect("semaphore open");
575 match conn
576 .sftp
577 .fs()
578 .metadata(to_sftp_path(conn.platform, &path))
579 .await
580 {
581 Ok(m) => Ok(Some(m.file_type().map(|t| t.is_dir()).unwrap_or(false))),
582 Err(_) => Ok(None),
583 }
584 }
585
586 pub async fn walk_files(&self, dir: &str, limit: usize) -> Result<Vec<String>> {
590 let conn = self.conn().await?;
591 let sep = separator(conn.platform);
592 let mut files = Vec::new();
593 let mut stack = vec![dir.to_string()];
594 while let Some(d) = stack.pop() {
595 let _permit = self.channels.acquire().await.expect("semaphore open");
596 let handle = conn
597 .sftp
598 .fs()
599 .open_dir(to_sftp_path(conn.platform, &d))
600 .await
601 .map_err(|e| Error::Ssh(format!("cannot list `{d}`: {e}")))?;
602 let mut entries = std::pin::pin!(handle.read_dir());
603 while let Some(entry) = entries.next().await {
604 let entry = entry.map_err(|e| Error::Ssh(format!("cannot list `{d}`: {e}")))?;
605 let name = entry.filename().to_string_lossy().into_owned();
606 if name == "." || name == ".." {
607 continue;
608 }
609 let full = format!("{d}{sep}{name}");
610 match entry.file_type() {
611 Some(t) if t.is_dir() => stack.push(full),
612 Some(t) if t.is_file() => {
613 files.push(full);
614 if files.len() > limit {
615 return Ok(files);
616 }
617 }
618 _ => {}
619 }
620 }
621 }
622 files.sort();
623 Ok(files)
624 }
625
626 pub async fn has_tool(&self, name: &str) -> Result<bool> {
628 let conn = self.conn().await?;
629 let cmd = match conn.platform {
630 Platform::Posix => format!("command -v {} >/dev/null 2>&1", shell_quote(name)),
631 Platform::Windows => format!(
632 "if (Get-Command {} -ErrorAction SilentlyContinue) {{ 'yes' }} else {{ 'no' }}",
633 ps_quote(name)
634 ),
635 };
636 let out = self.exec(&cmd, None, Some(15)).await?;
637 Ok(match conn.platform {
638 Platform::Posix => out.exit_code == 0,
639 Platform::Windows => String::from_utf8_lossy(&out.stdout).contains("yes"),
640 })
641 }
642}
643
644fn not_found(path: &str, e: openssh_sftp_client::Error) -> Error {
645 Error::Ssh(format!("`{path}`: {e}"))
646}
647
648pub fn ps_quote(s: &str) -> String {
652 format!("'{}'", s.replace('\'', "''"))
653}
654
655fn encode_utf16_b64(script: &str) -> String {
657 let bytes: Vec<u8> = script
658 .encode_utf16()
659 .flat_map(|u| u.to_le_bytes())
660 .collect();
661 base64::engine::general_purpose::STANDARD.encode(bytes)
662}
663
664fn windows_wrapper(exe: &str, extra: &[String], cwd: &str, command: &str, timeout: u64) -> String {
681 let inner = format!(
682 "$ProgressPreference='SilentlyContinue'; $ErrorActionPreference='Continue'\n\
683 [Console]::OutputEncoding=[Text.Encoding]::UTF8; $OutputEncoding=[Text.Encoding]::UTF8\n\
684 $env:NO_COLOR='1'\n\
685 try {{ Set-Location -LiteralPath {cwd} -ErrorAction Stop }} \
686 catch {{ [Console]::Error.WriteLine('cannot cd'); exit {CD_FAILED_EXIT} }}\n\
687 $global:LASTEXITCODE=0\n\
688 {command}\n\
689 $__fh_ok=$?\n\
690 Write-Output \"{WIN_EXIT_MARKER}$(if ($__fh_ok) {{0}} elseif ($LASTEXITCODE) {{$LASTEXITCODE}} else {{1}})\"\n",
691 cwd = ps_quote(cwd),
692 );
693 let mut args: Vec<String> = extra.iter().map(|a| ps_quote(a)).collect();
694 args.extend(
695 [
696 "-NoProfile",
697 "-NonInteractive",
698 "-ExecutionPolicy",
699 "Bypass",
700 "-EncodedCommand",
701 ]
702 .iter()
703 .map(|a| ps_quote(a)),
704 );
705 args.push(ps_quote(&encode_utf16_b64(&inner)));
706 format!(
707 "$ProgressPreference='SilentlyContinue'; $ErrorActionPreference='Continue'\n\
708 $p=Start-Process -FilePath {exe} -ArgumentList {args} -NoNewWindow -PassThru\n\
709 $null=$p.Handle\n\
710 if (-not $p.WaitForExit({ms})) {{ taskkill /T /F /PID $p.Id 2>&1 | Out-Null; \
711 $p.WaitForExit(); exit {TIMEOUT_EXIT} }}\n\
712 exit $p.ExitCode\n",
713 exe = ps_quote(exe),
714 args = args.join(","),
715 ms = timeout.saturating_mul(1000),
716 )
717}
718
719fn take_windows_exit_marker(stdout: &mut Vec<u8>) -> Option<i32> {
722 let text = String::from_utf8_lossy(stdout);
723 let pos = text.rfind(WIN_EXIT_MARKER)?;
724 let rest = &text[pos + WIN_EXIT_MARKER.len()..];
725 let line = rest.lines().next().unwrap_or("").trim();
726 let code: i32 = line.parse().ok()?;
727 let keep = text[..pos].trim_end_matches(['\r', '\n']).to_string();
729 stdout.clear();
730 stdout.extend_from_slice(keep.as_bytes());
731 if !stdout.is_empty() {
732 stdout.push(b'\n');
733 }
734 Some(code)
735}
736
737fn crlf_to_lf(data: &[u8]) -> Vec<u8> {
738 let mut out = Vec::with_capacity(data.len());
739 let mut i = 0;
740 while i < data.len() {
741 if data[i] == b'\r' && data.get(i + 1) == Some(&b'\n') {
742 i += 1;
743 continue;
744 }
745 out.push(data[i]);
746 i += 1;
747 }
748 out
749}
750
751fn decode_clixml(data: &[u8]) -> Vec<u8> {
755 let text = String::from_utf8_lossy(data);
756 if !text.contains("#< CLIXML") {
757 return data.to_vec();
758 }
759 let mut out = String::new();
760 let mut rest: &str = &text;
761 loop {
762 match rest.find("#< CLIXML") {
763 None => {
764 out.push_str(rest);
765 break;
766 }
767 Some(h) => {
768 out.push_str(&rest[..h]);
769 let after = &rest[h + "#< CLIXML".len()..];
770 let after = after
771 .strip_prefix("\r\n")
772 .or_else(|| after.strip_prefix('\n'))
773 .unwrap_or(after);
774 match after.find("</Objs>") {
775 Some(end) => {
776 out.push_str(&clixml_strings(&after[..end]));
777 rest = &after[end + "</Objs>".len()..];
778 }
779 None => {
780 out.push_str(&clixml_strings(after));
781 break;
782 }
783 }
784 }
785 }
786 }
787 out.into_bytes()
788}
789
790fn clixml_strings(xml: &str) -> String {
791 let mut out = String::new();
792 let mut rest = xml;
793 while let Some(start) = rest.find("<S S=\"") {
794 let after = &rest[start + 6..];
795 let Some(q) = after.find('"') else { break };
796 let kind = &after[..q];
797 let after = &after[q + 1..];
798 let Some(gt) = after.find('>') else { break };
799 let body_start = &after[gt + 1..];
800 let Some(end) = body_start.find("</S>") else {
801 break;
802 };
803 if kind == "Error" || kind == "Warning" {
804 out.push_str(&unescape_clixml(&body_start[..end]));
805 }
806 rest = &body_start[end + 4..];
807 }
808 out
809}
810
811fn unescape_clixml(s: &str) -> String {
812 let s = s
813 .replace("_x000D__x000A_", "\n")
814 .replace("_x000A_", "\n")
815 .replace("_x000D_", "")
816 .replace("_x0009_", "\t");
817 s.replace("<", "<")
818 .replace(">", ">")
819 .replace(""", "\"")
820 .replace("'", "'")
821 .replace("&", "&")
822}
823
824fn separator(p: Platform) -> char {
827 match p {
828 Platform::Posix => '/',
829 Platform::Windows => '\\',
830 }
831}
832
833fn is_sftp_drive_path(s: &str) -> bool {
835 let b = s.as_bytes();
836 b.len() >= 3 && b[0] == b'/' && b[1].is_ascii_alphabetic() && b[2] == b':'
837}
838
839fn is_drive_path(s: &str) -> bool {
840 let b = s.as_bytes();
841 b.len() >= 2 && b[0].is_ascii_alphabetic() && b[1] == b':'
842}
843
844fn is_absolute_for(p: Platform, raw: &str) -> bool {
845 match p {
846 Platform::Posix => raw.starts_with('/'),
847 Platform::Windows => {
848 is_drive_path(raw) || is_sftp_drive_path(raw) || raw.starts_with("\\\\")
849 }
850 }
851}
852
853fn to_sftp_path(p: Platform, native: &str) -> String {
856 match p {
857 Platform::Posix => native.to_string(),
858 Platform::Windows => format!("/{}", native.replace('\\', "/")),
859 }
860}
861
862fn from_sftp_path(sftp: &str) -> String {
864 let s = sftp.strip_prefix('/').unwrap_or(sftp);
865 let s = s.replace('/', "\\");
866 if s.len() == 2 && is_drive_path(&s) {
867 format!("{s}\\")
868 } else {
869 s
870 }
871}
872
873fn parent_of(p: Platform, path: &str) -> Option<String> {
874 match p {
875 Platform::Posix => {
876 if path == "/" {
877 return None;
878 }
879 match path.rfind('/') {
880 Some(0) => Some("/".to_string()),
881 Some(i) => Some(path[..i].to_string()),
882 None => None,
883 }
884 }
885 Platform::Windows => {
886 if path.len() <= 3 {
888 return None;
889 }
890 let i = path.rfind('\\')?;
891 if i <= 2 {
892 Some(path[..3].to_string())
893 } else {
894 Some(path[..i].to_string())
895 }
896 }
897 }
898}
899
900fn normalize_for(p: Platform, raw: &str) -> String {
901 match p {
902 Platform::Posix => normalize(raw),
903 Platform::Windows => normalize_windows(raw),
904 }
905}
906
907fn expand_tilde(p: &str, home: &str) -> String {
909 if p == "~" {
910 home.to_string()
911 } else if let Some(rest) = p.strip_prefix("~/").or_else(|| p.strip_prefix("~\\")) {
912 format!("{home}/{rest}")
913 } else {
914 p.to_string()
915 }
916}
917
918pub fn normalize(p: &str) -> String {
920 let mut parts: Vec<&str> = Vec::new();
921 for seg in p.split('/') {
922 match seg {
923 "" | "." => {}
924 ".." => {
925 parts.pop();
926 }
927 s => parts.push(s),
928 }
929 }
930 format!("/{}", parts.join("/"))
931}
932
933pub fn normalize_windows(p: &str) -> String {
936 let unc = p.starts_with("\\\\") || p.starts_with("//");
937 let s = p.replace('/', "\\");
938 let s = s
939 .strip_prefix('\\')
940 .filter(|r| is_drive_path(r))
941 .unwrap_or(&s);
942 let mut parts: Vec<&str> = Vec::new();
943 let mut drive = String::new();
944 for (i, seg) in s.split('\\').enumerate() {
945 if i == 0 && is_drive_path(seg) && seg.len() == 2 {
946 drive = seg.to_uppercase();
947 continue;
948 }
949 match seg {
950 "" | "." => {}
951 ".." => {
952 parts.pop();
953 }
954 x => parts.push(x),
955 }
956 }
957 if unc {
958 return format!("\\\\{}", parts.join("\\"));
959 }
960 if drive.is_empty() {
961 return format!("\\{}", parts.join("\\"));
964 }
965 if parts.is_empty() {
966 format!("{drive}\\")
967 } else {
968 format!("{drive}\\{}", parts.join("\\"))
969 }
970}
971
972struct Collected {
973 data: Vec<u8>,
974 truncated: bool,
975}
976
977async fn collect_bounded<R: AsyncReadExt + Unpin>(mut r: R, cap: usize) -> Result<Collected> {
980 let head_cap = cap * 2 / 3;
981 let tail_cap = cap - head_cap;
982 let mut head = Vec::new();
983 let mut tail = Vec::new();
984 let mut truncated = false;
985 let mut buf = vec![0u8; 64 * 1024];
986 loop {
987 let n = r.read(&mut buf).await?;
988 if n == 0 {
989 break;
990 }
991 let mut chunk = &buf[..n];
992 if head.len() < head_cap {
993 let take = chunk.len().min(head_cap - head.len());
994 head.extend_from_slice(&chunk[..take]);
995 chunk = &chunk[take..];
996 }
997 if !chunk.is_empty() {
998 truncated = true;
999 tail.extend_from_slice(chunk);
1000 if tail.len() > tail_cap * 2 {
1001 let drop = tail.len() - tail_cap;
1002 tail.drain(..drop);
1003 }
1004 }
1005 }
1006 if truncated {
1007 if tail.len() > tail_cap {
1008 let drop = tail.len() - tail_cap;
1009 tail.drain(..drop);
1010 }
1011 let omitted_note = format!("\n\n[... output truncated; limit is {cap} bytes ...]\n\n");
1012 head.extend_from_slice(omitted_note.as_bytes());
1013 head.extend_from_slice(&tail);
1014 }
1015 Ok(Collected {
1016 data: head,
1017 truncated,
1018 })
1019}
1020
1021#[cfg(test)]
1022mod tests {
1023 use super::*;
1024
1025 #[test]
1026 fn tilde_expansion() {
1027 assert_eq!(expand_tilde("~", "/root"), "/root");
1028 assert_eq!(expand_tilde("~/a/b", "/root"), "/root/a/b");
1029 assert_eq!(expand_tilde("/x", "/root"), "/x");
1030 assert_eq!(expand_tilde("rel", "/root"), "rel");
1031 assert_eq!(
1032 normalize_windows(&expand_tilde("~\\x", "C:\\Users\\me")),
1033 "C:\\Users\\me\\x"
1034 );
1035 }
1036
1037 #[test]
1038 fn normalizes_paths() {
1039 assert_eq!(normalize("/a/b/../c/./d"), "/a/c/d");
1040 assert_eq!(normalize("/../x"), "/x");
1041 assert_eq!(normalize("/"), "/");
1042 }
1043
1044 #[test]
1045 fn windows_paths() {
1046 assert_eq!(normalize_windows("C:/Users/me/../x/./y"), "C:\\Users\\x\\y");
1047 assert_eq!(normalize_windows("/C:/Users/me"), "C:\\Users\\me");
1048 assert_eq!(normalize_windows("c:\\"), "C:\\");
1049 assert_eq!(
1050 normalize_windows("C:\\work/proj\\src"),
1051 "C:\\work\\proj\\src"
1052 );
1053 assert_eq!(
1054 normalize_windows("\\\\server\\share\\x"),
1055 "\\\\server\\share\\x"
1056 );
1057 assert_eq!(to_sftp_path(Platform::Windows, "C:\\a\\b"), "/C:/a/b");
1058 assert_eq!(from_sftp_path("/C:/Users/test"), "C:\\Users\\test");
1059 assert_eq!(from_sftp_path("/C:"), "C:\\");
1060 assert!(is_absolute_for(Platform::Windows, "D:\\x"));
1061 assert!(is_absolute_for(Platform::Windows, "/C:/x"));
1062 assert!(!is_absolute_for(Platform::Windows, "src\\main.rs"));
1063 assert!(!is_absolute_for(Platform::Windows, "/tmp"));
1064 assert_eq!(
1065 parent_of(Platform::Windows, "C:\\a\\b").as_deref(),
1066 Some("C:\\a")
1067 );
1068 assert_eq!(
1069 parent_of(Platform::Windows, "C:\\a").as_deref(),
1070 Some("C:\\")
1071 );
1072 assert_eq!(parent_of(Platform::Windows, "C:\\"), None);
1073 assert_eq!(parent_of(Platform::Posix, "/a/b").as_deref(), Some("/a"));
1074 assert_eq!(parent_of(Platform::Posix, "/a").as_deref(), Some("/"));
1075 assert_eq!(parent_of(Platform::Posix, "/"), None);
1076 }
1077
1078 #[test]
1079 fn exit_marker_and_clixml() {
1080 let mut out = b"table\r\n__FARHAND_EXIT__=3\r\n\r\n".to_vec();
1081 assert_eq!(take_windows_exit_marker(&mut out), Some(3));
1082 assert_eq!(out, b"table\n");
1083 let mut out = b"x\n__FARHAND_EXIT__=1\n".to_vec();
1084 assert_eq!(take_windows_exit_marker(&mut out), Some(1));
1085 let mut out = b"__FARHAND_EXIT__=0\n".to_vec();
1086 assert_eq!(take_windows_exit_marker(&mut out), Some(0));
1087 assert!(out.is_empty());
1088 let mut out = b"no marker".to_vec();
1089 assert_eq!(take_windows_exit_marker(&mut out), None);
1090
1091 let err = b"raw first\r\n#< CLIXML\r\n<Objs Version=\"1.1.0.1\"><Obj S=\"progress\"><TN></TN></Obj>\
1092 <S S=\"Error\">Get-Item : Cannot find path 'C:\\nope'_x000D__x000A_</S>\
1093 <S S=\"Error\">At line:6_x000D__x000A_</S></Objs>";
1094 let text = String::from_utf8(decode_clixml(err)).unwrap();
1095 assert_eq!(
1096 text,
1097 "raw first\r\nGet-Item : Cannot find path 'C:\\nope'\nAt line:6\n"
1098 );
1099 assert_eq!(crlf_to_lf(b"a\r\nb\r\n"), b"a\nb\n");
1100 assert_eq!(ps_quote("it's"), "'it''s'");
1101 }
1102
1103 #[test]
1104 fn wrapper_is_plain_ascii_on_the_command_line() {
1105 let w = windows_wrapper("powershell.exe", &[], "C:\\Users\\me", "Get-ChildItem", 30);
1106 assert!(w.contains("WaitForExit(30000)"));
1107 assert!(w.contains("-EncodedCommand"));
1108 assert!(encode_utf16_b64("x")
1109 .chars()
1110 .all(|c| c.is_ascii_alphanumeric() || "+/=".contains(c)));
1111 }
1112
1113 #[tokio::test]
1114 async fn bounded_collection_keeps_head_and_tail() {
1115 let data: Vec<u8> = (0..10_000u32).map(|i| b'a' + (i % 26) as u8).collect();
1116 let c = collect_bounded(&data[..], 300).await.unwrap();
1117 assert!(c.truncated);
1118 assert!(c.data.starts_with(b"abcdefghij"));
1119 assert!(c.data.ends_with(&data[data.len() - 100..]));
1120 let c = collect_bounded(&b"tiny"[..], 300).await.unwrap();
1121 assert!(!c.truncated);
1122 assert_eq!(c.data, b"tiny");
1123 }
1124}