sail/shell.rs
1//! Interactive terminal session against a `pty` command in a Sailbox.
2//!
3//! [`Sailbox::shell`](crate::Sailbox::shell) is the high-level entry; the CLI
4//! drives [`run_interactive`] directly for its `--tty` flows. It puts the local
5//! terminal in raw mode, forwards keystrokes (so Ctrl-C/Ctrl-D reach the remote
6//! process as signals), renders the merged output, propagates window resizes,
7//! and restores the terminal on exit. Unix-only: on other platforms the calls
8//! return an unsupported error and the build still succeeds.
9
10use std::sync::Arc;
11use std::time::Duration;
12
13use crate::error::{RpcStatus, SailError};
14use crate::exec::ExecOptions;
15use crate::sailbox::object::Sailbox;
16
17/// Options for [`Sailbox::shell`].
18#[derive(Debug, Clone, Default)]
19pub struct ShellOptions {
20 /// Login shell to run when no command is given (default: the guest's
21 /// `$SHELL`, else `/bin/bash`). Ignored when a command is given.
22 pub shell: Option<String>,
23 /// `$TERM` for the remote pty (default: the local `$TERM`).
24 pub term: Option<String>,
25 /// Working directory for the session. `None` starts it in the image's
26 /// working directory, or `/` when the image does not set one.
27 pub cwd: Option<String>,
28 /// Run the session as this Sailbox user, with Docker `USER` semantics
29 /// (see [`ExecOptions::user`]). `None` runs as the image's `USER` when
30 /// the image sets one, root otherwise; pass `"0:0"` to force root.
31 pub user: Option<String>,
32 /// Wall-clock limit for the session; `None` means no limit.
33 pub timeout: Option<Duration>,
34 /// Turn off all local forwarding for the session (on by default): the
35 /// browser opens and localhost servers, plus paste, drag-and-drop, and
36 /// clipboard bridging. Every byte then passes through verbatim.
37 pub no_forward: bool,
38 /// Turn off forwarding the session's browser opens only, keeping everything
39 /// else forwarded. Ignored when `no_forward` is set.
40 pub no_forward_browser: bool,
41}
42
43/// True when stdin and stdout are both TTYs, required for an interactive PTY.
44#[doc(hidden)]
45pub fn stdio_is_tty() -> bool {
46 use std::io::IsTerminal;
47 std::io::stdin().is_terminal() && std::io::stdout().is_terminal()
48}
49
50fn tty_required() -> SailError {
51 SailError::Execution {
52 code: RpcStatus::FailedPrecondition,
53 detail: "shell requires an interactive terminal (stdin and stdout must be TTYs)"
54 .to_string(),
55 }
56}
57
58impl Sailbox {
59 /// Open an interactive pty session on the Sailbox, driving the local
60 /// terminal. With no `command`, runs a login shell; pass a command to run
61 /// that under a pty instead (e.g. a REPL or an editor). Raw-mode
62 /// keystrokes (including Ctrl-C, Ctrl-Z, and Ctrl-D) reach the remote
63 /// process, its output renders locally, and terminal resizes propagate.
64 /// Blocks until the remote process exits and returns its exit code.
65 /// Requires an interactive local terminal (stdin and stdout TTYs). While
66 /// the session is open, browser opens, localhost servers, paste, and
67 /// drag-and-drop are forwarded to the local machine, and Ctrl+V forwards
68 /// your clipboard (a two-way clipboard on devbox images, upload-and-paste
69 /// elsewhere); see [`ShellOptions::no_forward`].
70 ///
71 /// Runs on the local machine, which must be Unix (it needs Unix TTY and
72 /// signal APIs).
73 ///
74 /// This is the one process-global API in the crate: for the session's
75 /// duration it owns stdin/stdout, switches the terminal to raw mode, and
76 /// installs a signal handler, restoring them when the session ends. The
77 /// bridge runs on a blocking thread, so cancelling this future does not
78 /// end the session; stop it by exiting the remote process.
79 pub async fn shell(
80 &self,
81 command: Option<&str>,
82 options: ShellOptions,
83 ) -> Result<i32, SailError> {
84 if !stdio_is_tty() {
85 return Err(tty_required());
86 }
87 let command = match command {
88 Some(command) => command.to_string(),
89 None => login_shell_command(options.shell.as_deref()),
90 };
91 let (cols, rows) = terminal_size();
92 // An interactive shell forwards the session's localhost servers, browser
93 // opens, and clipboard/paste to the user's machine unless opted out.
94 let (forward_ports, forward_browser, forward_clipboard) =
95 crate::exec::forward_flags(options.no_forward, options.no_forward_browser);
96 let proc = self
97 .client()
98 .exec_shell(
99 self.sailbox_id(),
100 &command,
101 ExecOptions {
102 timeout: options.timeout,
103 pty: true,
104 term: options
105 .term
106 .or_else(|| std::env::var("TERM").ok())
107 .unwrap_or_default(),
108 cols,
109 rows,
110 cwd: options.cwd,
111 user: options.user,
112 forward_ports,
113 forward_browser,
114 forward_clipboard,
115 ..Default::default()
116 },
117 )
118 .await?;
119 let proc = Arc::new(proc);
120 tokio::task::spawn_blocking(move || run_interactive(proc))
121 .await
122 .map_err(|err| SailError::Internal {
123 message: format!("shell bridge task failed: {err}"),
124 })?
125 }
126}
127
128/// The command for an interactive login session: `exec` the login shell so
129/// `$0` and login semantics match ssh. An explicit shell is quoted so a path
130/// with spaces runs as a literal program; the default stays unquoted so the
131/// guest shell expands `$SHELL`.
132fn login_shell_command(shell: Option<&str>) -> String {
133 match shell {
134 Some(shell) => format!("exec {} -l", crate::exec::sh_quote(shell)),
135 None => "exec ${SHELL:-/bin/bash} -l".to_string(),
136 }
137}
138
139/// The local terminal size as (cols, rows), defaulting to 80x24.
140#[cfg(unix)]
141#[doc(hidden)]
142pub fn terminal_size() -> (u32, u32) {
143 let mut size = libc::winsize {
144 ws_row: 0,
145 ws_col: 0,
146 ws_xpixel: 0,
147 ws_ypixel: 0,
148 };
149 let ok = unsafe { libc::ioctl(libc::STDOUT_FILENO, libc::TIOCGWINSZ, &raw mut size) } == 0;
150 if ok && size.ws_col > 0 && size.ws_row > 0 {
151 (u32::from(size.ws_col), u32::from(size.ws_row))
152 } else {
153 (80, 24)
154 }
155}
156
157/// The local terminal size as (cols, rows), defaulting to 80x24.
158#[cfg(not(unix))]
159#[doc(hidden)]
160pub fn terminal_size() -> (u32, u32) {
161 (80, 24)
162}
163
164/// Interactive PTY sessions need Unix TTY and signal APIs.
165#[cfg(not(unix))]
166#[doc(hidden)]
167pub fn run_interactive(_proc: Arc<crate::exec::ExecProcess>) -> Result<i32, SailError> {
168 Err(SailError::Execution {
169 code: RpcStatus::Unimplemented,
170 detail: "interactive PTY sessions are not supported on this platform".to_string(),
171 })
172}
173
174#[cfg(unix)]
175#[doc(hidden)]
176pub use unix::run_interactive;
177
178#[cfg(unix)]
179#[doc(hidden)]
180pub use unix::{drive_output_pump, RenderControl};
181
182#[cfg(unix)]
183mod unix {
184 use std::collections::{HashMap, HashSet};
185 use std::io::Write;
186 use std::path::PathBuf;
187 use std::sync::atomic::{AtomicBool, Ordering};
188 use std::sync::Arc;
189 use std::thread;
190 use std::time::{Duration, Instant};
191
192 use super::terminal_size;
193 use crate::error::{RpcStatus, SailError};
194 use crate::exec::{ExecProcess, ForwardEvent, OutputStream, ReadStep};
195 use crate::shell_input::{
196 dropped_local_files, find, partial_suffix_len, sanitize_drop_name, InputEvent,
197 InputScanner, PASTE_END, PASTE_START,
198 };
199
200 /// Drive a future to completion from this bridge's dedicated thread. On
201 /// the shared runtime's blocking pool (the [`Sailbox::shell`] path) an
202 /// ambient handle exists and `Handle::block_on` is the correct, safe
203 /// call; on a plain thread (the CLI's direct `run_interactive` use) fall
204 /// back to the crate's shared-runtime `block_on`.
205 fn block_on<F: std::future::Future>(future: F) -> F::Output {
206 match tokio::runtime::Handle::try_current() {
207 Ok(handle) => handle.block_on(future),
208 Err(_) => crate::runtime::block_on(future),
209 }
210 }
211
212 /// Set by the SIGWINCH handler; drained by the input loop to issue a resize.
213 static RESIZE_PENDING: AtomicBool = AtomicBool::new(false);
214
215 extern "C" fn on_sigwinch(_signum: libc::c_int) {
216 RESIZE_PENDING.store(true, Ordering::Relaxed);
217 }
218
219 /// Drive the local terminal against a PTY exec until the remote process
220 /// exits, returning its exit code. Raw mode and the SIGWINCH handler are
221 /// always restored, even on error. When the session forwards its clipboard
222 /// (`proc.forward_clipboard()`), dragged files and Ctrl+V pastes forward
223 /// into the guest and in-guest copies mirror back to the local clipboard;
224 /// without it every byte passes through verbatim.
225 pub fn run_interactive(proc: Arc<ExecProcess>) -> Result<i32, SailError> {
226 let saved = enter_raw_mode()?;
227 let prev_winch = install_sigwinch();
228 let prev_in_flags = set_stdin_nonblocking();
229 // Non-blocking stdout so the output pump is never parked in a write to a
230 // slow terminal: it must stay free to notice the ring dropped and repaint.
231 let prev_out_flags = set_stdout_nonblocking();
232
233 // Seed the remote PTY with the current size.
234 let (cols, rows) = terminal_size();
235 block_on(proc.resize(cols, rows));
236
237 let stop = Arc::new(AtomicBool::new(false));
238 let render = Arc::new(RenderControl::default());
239 let output = spawn_output_pump(Arc::clone(&proc), Arc::clone(&stop), Arc::clone(&render));
240 // Browser-open and localhost-port forwarding (guest-gated by the launch
241 // flags); idles harmlessly when the session opted out.
242 let forward = spawn_forward_consumer(Arc::clone(&proc));
243 // The clipboard bridge, both directions, rides the same opt-in as the
244 // clipboard launch flag: mirror in-guest copies onto the local
245 // clipboard, and scan stdin for pastes/drags to send the other way.
246 let forward_clipboard = proc.forward_clipboard();
247 let clipboard = forward_clipboard.then(|| spawn_clipboard_consumer(Arc::clone(&proc)));
248
249 if forward_clipboard {
250 drive_input_forwarding(
251 PasteBridge::new(Arc::clone(&proc), Arc::clone(&render)),
252 &stop,
253 );
254 } else {
255 drive_input(&proc, &stop);
256 }
257
258 // Tear down in reverse order so the terminal is always usable afterwards.
259 let _ = output.join();
260 let _ = forward.join();
261 if let Some(consumer) = clipboard {
262 let _ = consumer.join();
263 }
264 restore_stdout_flags(prev_out_flags);
265 restore_stdin_flags(prev_in_flags);
266 restore_sigwinch(prev_winch);
267 restore_terminal(&saved);
268
269 // A witnessed Exit is the command's real result. When the stream ended
270 // without one, the command did not exit; the box was parked (put to
271 // sleep) or otherwise became unreachable mid-session. Report that instead
272 // of calling wait(), which would block forever on an Exit an interactive
273 // shell never emits; the box's session stays intact for a fresh reconnect.
274 match proc.try_wait() {
275 Some(result) => result,
276 None => Err(SailError::Execution {
277 code: RpcStatus::Unavailable,
278 detail: format!(
279 "the box became unavailable and the shell session ended; \
280 reconnect with `sail box shell {}`",
281 proc.sailbox_id(),
282 ),
283 }),
284 }
285 }
286
287 /// Shared switches between the input side and the output pump: `paused`
288 /// stops the pump writing to the terminal while an upload progress line
289 /// owns it, and `bracketed_paste` tracks whether the guest application has
290 /// paste bracketing (DEC mode 2004) on, so injected pastes are framed the
291 /// way the terminal would frame a real one. Public only because the pump
292 /// is driven directly by integration tests.
293 #[doc(hidden)]
294 #[derive(Default)]
295 pub struct RenderControl {
296 paused: AtomicBool,
297 bracketed_paste: AtomicBool,
298 }
299
300 /// Least time between screen-repaint requests while the local terminal is
301 /// too slow to keep up: without a bound a persistently-behind reader would
302 /// ask on every drop and flood the guest with resync RPCs. Capping repaint
303 /// requests to one per 100 ms is plenty to keep the screen current.
304 const RESYNC_MIN_INTERVAL: Duration = Duration::from_millis(100);
305
306 /// Most backlog the pump buffers toward the terminal before it stops draining
307 /// the ring. Holding the cap small means a slow terminal quickly lets the
308 /// ring back up and drop-oldest, which the reader reports as a drop — the
309 /// signal that triggers a repaint. Larger would just make the terminal crawl
310 /// further through stale frames before recovering.
311 const OUTPUT_PENDING_CAP: usize = 256 * 1024;
312
313 /// Spawn the thread that renders merged PTY output to the terminal, then
314 /// signals stop when the stream ends. The terminal fd is already non-blocking
315 /// (set by [`run_interactive`]).
316 fn spawn_output_pump(
317 proc: Arc<ExecProcess>,
318 stop: Arc<AtomicBool>,
319 render: Arc<RenderControl>,
320 ) -> thread::JoinHandle<()> {
321 thread::spawn(move || {
322 let mut reader = proc.reader(OutputStream::Stdout);
323 let mut sink = RawFdWriter(libc::STDOUT_FILENO);
324 drive_output_pump(&mut reader, &mut sink, &proc, &render);
325 stop.store(true, Ordering::Relaxed);
326 })
327 }
328
329 /// Least time between retries of a port that could not be forwarded because
330 /// its local port was busy. The port watcher only re-reports the guest's
331 /// listeners when the set changes, so this retry covers a local port freeing
332 /// up while the guest server keeps running.
333 const FORWARD_RETRY_INTERVAL: Duration = Duration::from_secs(3);
334
335 /// Spawn the thread that acts on the session's local-forwarding events. It
336 /// drains until the stream ends (the accessor then returns `None`). Active
337 /// port forwards are held for the life of the session and dropped on exit.
338 fn spawn_forward_consumer(proc: Arc<ExecProcess>) -> thread::JoinHandle<()> {
339 thread::spawn(move || {
340 let mut forwards: HashMap<u16, crate::forward::PortForward> = HashMap::new();
341 // Ports whose local port was busy, so the forward could not bind. Kept
342 // so the bind is retried on the interval below in case the local port
343 // frees up.
344 let mut conflicts: HashSet<u16> = HashSet::new();
345 loop {
346 // Wait for the next event, but only until the retry interval when
347 // there are conflicts to re-attempt; otherwise wait indefinitely.
348 let next: Result<Option<ForwardEvent>, tokio::time::error::Elapsed> =
349 if conflicts.is_empty() {
350 Ok(block_on(proc.next_forward_event()))
351 } else {
352 block_on(async {
353 tokio::time::timeout(FORWARD_RETRY_INTERVAL, proc.next_forward_event())
354 .await
355 })
356 };
357 match next {
358 Ok(Some(ForwardEvent::OpenUrl(url))) => {
359 let open = if !is_openable_scheme(&url) {
360 // open_local_url only opens http(s); skip building a
361 // forward for a URL it would refuse anyway.
362 false
363 } else if let Some(port) = crate::forward::forwardable_local_port(&url) {
364 // A URL for a server in the box: forward its port, then
365 // open the bound local address (rewritten below). If it
366 // can't be forwarded, don't open it against the user's
367 // own machine. A login's localhost callback is a server
368 // too, so the port watcher forwards it the same way.
369 if ensure_forward(&proc, &mut forwards, &mut conflicts, port) {
370 true
371 } else {
372 notify_local_port_busy(&url, port);
373 false
374 }
375 } else if crate::forward::is_unforwardable_loopback_url(&url) {
376 // A loopback URL the tunnel can't reach: opening it would
377 // hit the user's own machine, not the sandbox.
378 notify_loopback_unreachable(&url);
379 false
380 } else if let Some(callback) = crate::forward::redirect_callback(&url) {
381 // An external login URL whose redirect returns to a
382 // loopback callback. Don't start a login whose redirect,
383 // carrying the auth code, would hit the user's machine
384 // rather than the sandbox.
385 match callback {
386 // Open only once the callback port is actually
387 // forwarded. The snapshot precedes this URL, so a
388 // listening forwardable callback is already in
389 // `forwards`; a port not there is one whose local
390 // port is busy or whose server is not listening on a
391 // reachable address, and an immediate redirect would
392 // hit the user's own machine.
393 crate::forward::RedirectCallback::Forwardable(port)
394 if forwards.contains_key(&port) =>
395 {
396 true
397 }
398 crate::forward::RedirectCallback::Forwardable(port) => {
399 notify_callback_unforwarded(&url, port);
400 false
401 }
402 // A loopback the tunnel cannot dial at all.
403 crate::forward::RedirectCallback::Unreachable => {
404 notify_callback_unreachable(&url);
405 false
406 }
407 }
408 } else {
409 // An external URL with no localhost callback: open it.
410 true
411 };
412 if open {
413 let url = crate::forward::rewrite_loopback_url(&url, |remote| {
414 forwards
415 .get(&remote)
416 .map(crate::forward::PortForward::local_port)
417 });
418 open_local_url(&url);
419 }
420 }
421 Ok(Some(ForwardEvent::PortSnapshot(ports))) => {
422 // Reconcile against the authoritative set: drop forwards and
423 // conflicts for servers that are gone, then forward the rest.
424 let listening: HashSet<u16> = ports.iter().copied().collect();
425 forwards.retain(|port, _| listening.contains(port));
426 conflicts.retain(|port| listening.contains(port));
427 for port in ports {
428 ensure_forward(&proc, &mut forwards, &mut conflicts, port);
429 }
430 }
431 // The stream ended.
432 Ok(None) => break,
433 // No event within the interval: retry any port whose local port
434 // was busy, in case it has since freed up.
435 Err(_) => {
436 for port in conflicts.iter().copied().collect::<Vec<_>>() {
437 ensure_forward(&proc, &mut forwards, &mut conflicts, port);
438 }
439 }
440 }
441 }
442 })
443 }
444
445 /// Forward `port` (guest to the same local port) if it is not already
446 /// forwarded. Returns whether the port is now forwarded. The local port
447 /// always matches the guest port and is never remapped: a login callback
448 /// redirect targets that exact port, so binding elsewhere would send the
449 /// browser to whatever already holds the local port rather than the sandbox.
450 /// A busy local port is recorded in `conflicts` and retried on the interval.
451 fn ensure_forward(
452 proc: &Arc<ExecProcess>,
453 forwards: &mut HashMap<u16, crate::forward::PortForward>,
454 conflicts: &mut HashSet<u16>,
455 port: u16,
456 ) -> bool {
457 if forwards.contains_key(&port) {
458 return true;
459 }
460 if let Ok(forward) = block_on(proc.forward_port(port, port)) {
461 forwards.insert(port, forward);
462 conflicts.remove(&port);
463 true
464 } else {
465 conflicts.insert(port);
466 false
467 }
468 }
469
470 /// Notify that a URL the Sailbox asked to open targets a loopback address the
471 /// sandbox cannot reach, so it was not opened against the user's own machine.
472 fn notify_loopback_unreachable(url: &str) {
473 let notice = format!(
474 "\r\n[sail] not opening {url}: it targets a loopback address the sandbox cannot reach\r\n"
475 );
476 let _ = RawFdWriter(libc::STDERR_FILENO).write_all(notice.as_bytes());
477 }
478
479 /// Notify that a Sailbox server was not opened because its port is already in use
480 /// on the local machine, so the forward could not bind it.
481 fn notify_local_port_busy(url: &str, port: u16) {
482 let notice = format!("\r\n[sail] not opening {url}: local port {port} is in use\r\n");
483 let _ = RawFdWriter(libc::STDERR_FILENO).write_all(notice.as_bytes());
484 }
485
486 /// Whether `open_local_url` would open this URL (it opens only http(s)).
487 fn is_openable_scheme(url: &str) -> bool {
488 url.starts_with("http://") || url.starts_with("https://")
489 }
490
491 /// Notify that a login was not opened because its localhost callback port is
492 /// not forwarded (its local port is busy, or its server is not listening on a
493 /// reachable address), so the provider's redirect could not reach the sandbox.
494 fn notify_callback_unforwarded(url: &str, port: u16) {
495 let notice = format!(
496 "\r\n[sail] not opening {url}: its login callback port {port} is not forwarded\r\n"
497 );
498 let _ = RawFdWriter(libc::STDERR_FILENO).write_all(notice.as_bytes());
499 }
500
501 /// Notify that a login was not opened because its callback is a loopback
502 /// address the sandbox cannot reach, so the redirect would hit the user's
503 /// own machine.
504 fn notify_callback_unreachable(url: &str) {
505 let notice = format!(
506 "\r\n[sail] not opening {url}: its login callback is a loopback address the sandbox cannot reach\r\n"
507 );
508 let _ = RawFdWriter(libc::STDERR_FILENO).write_all(notice.as_bytes());
509 }
510
511 /// Open a URL in the user's local browser, best-effort. Only http(s) URLs
512 /// are opened, so a sandbox process cannot drive arbitrary local handlers.
513 /// The child inherits no terminal, so an opener's own output can't corrupt
514 /// the session. Silent on success: the browser tab appearing is the signal.
515 fn open_local_url(url: &str) {
516 if !is_openable_scheme(url) {
517 return;
518 }
519 let _ = local_browser_command(url)
520 .stdin(std::process::Stdio::null())
521 .stdout(std::process::Stdio::null())
522 .stderr(std::process::Stdio::null())
523 .spawn();
524 }
525
526 /// The platform command that opens a URL in the default browser. This
527 /// module is Unix-only, so the choice is macOS `open` or Linux `xdg-open`.
528 fn local_browser_command(url: &str) -> std::process::Command {
529 let program = if cfg!(target_os = "macos") {
530 "open"
531 } else {
532 "xdg-open"
533 };
534 let mut command = std::process::Command::new(program);
535 command.arg(url);
536 command
537 }
538
539 /// Render one live output stream onto a terminal `sink` until the stream
540 /// ends, favoring a current screen over a faithful replay.
541 ///
542 /// The terminal writer must never block the loop: a slow terminal has to keep
543 /// the pump free to notice the ring dropped and ask the guest to repaint the
544 /// current screen ([`ExecProcess::resync`]). So `sink` is written
545 /// non-blockingly, backlog is held to [`OUTPUT_PENDING_CAP`] so the ring
546 /// backs up and drops-oldest when the terminal falls behind, and a reported
547 /// drop discards the torn backlog and requests a repaint rather than crawling
548 /// the slow terminal through stale frames it will never catch. The command is
549 /// detached on the server, so none of this ever blocks it.
550 ///
551 /// Generic over the sink so the drop-to-repaint behavior is testable against a
552 /// deliberately slow writer without a real terminal.
553 #[doc(hidden)]
554 pub fn drive_output_pump<W: Write>(
555 reader: &mut crate::exec::StreamReader,
556 sink: &mut W,
557 proc: &Arc<ExecProcess>,
558 render: &RenderControl,
559 ) {
560 let mut pending: Vec<u8> = Vec::new();
561 let mut last_resync: Option<Instant> = None;
562 // Hold an observed drop until a repaint is actually requested. resync_due
563 // only fires once per RESYNC_MIN_INTERVAL, so a drop seen during that
564 // cooldown would otherwise be forgotten, leaving the screen showing a
565 // torn, partial frame.
566 let mut resync_pending = false;
567 let mut modes = BracketedPasteTracker::default();
568 loop {
569 // An upload progress line owns the terminal: stop rendering (and
570 // stop draining the ring, which then backs up and drops-oldest just
571 // like a slow terminal — the existing repaint path heals it).
572 if render.paused.load(Ordering::Relaxed) {
573 thread::sleep(Duration::from_millis(5));
574 continue;
575 }
576 // Push as much backlog as the terminal accepts right now, without
577 // blocking on it.
578 let mut flushed = false;
579 if !pending.is_empty() {
580 let written = write_nonblocking(sink, &pending);
581 if written > 0 {
582 pending.drain(..written);
583 flushed = true;
584 }
585 }
586 // Refill from the ring, but only up to the cap: leaving the rest in
587 // the ring lets it back up and drop-oldest when the terminal is slow.
588 let mut progressed = false;
589 if pending.len() < OUTPUT_PENDING_CAP {
590 // Don't wait for new data while there is still backlog to push.
591 let wait = if pending.is_empty() {
592 Duration::from_millis(50)
593 } else {
594 Duration::ZERO
595 };
596 match reader.next(wait) {
597 ReadStep::Chunk(bytes) => {
598 // A Snapshot reset the ring: `bytes` is the repaint, and
599 // it supersedes the stale backlog buffered toward the
600 // terminal. Drop that backlog before queuing the repaint
601 // so the finished screen renders at once instead of stuck
602 // behind bytes the slow terminal will never finish
603 // draining (the bounded end-of-stream flush would give up
604 // before reaching it).
605 if reader.took_reset() {
606 pending.clear();
607 }
608 modes.scan(&bytes, render);
609 pending.extend_from_slice(&bytes);
610 progressed = true;
611 }
612 ReadStep::Eof => {
613 flush_blocking(sink, &pending);
614 return;
615 }
616 ReadStep::Pending => {}
617 }
618 while pending.len() < OUTPUT_PENDING_CAP {
619 match reader.try_next() {
620 // Honor a reset here too: the repaint can land in this
621 // batch drain when the Snapshot arrives after next()
622 // above already returned a stale chunk this iteration.
623 Some(more) => {
624 if reader.took_reset() {
625 pending.clear();
626 }
627 modes.scan(&more, render);
628 pending.extend_from_slice(&more);
629 }
630 None => break,
631 }
632 }
633 }
634 // The ring evicted output we had not shown: the backlog is now a torn
635 // tail, so drop it and repaint the current screen instead.
636 if reader.took_drop() {
637 pending.clear();
638 resync_pending = true;
639 }
640 if resync_pending && resync_due(&mut last_resync) {
641 resync_pending = false;
642 let handle = Arc::clone(proc);
643 crate::runtime::runtime().spawn(async move { handle.resync().await });
644 }
645 // Yield when no new ring data was read and bytes are still queued,
646 // either because the backlog is at the cap (so the ring can back up
647 // and drop-oldest for a slow terminal) or because the terminal is
648 // back-pressured and accepted nothing (so the loop does not spin).
649 // A terminal actively draining a partial backlog is making progress,
650 // so it keeps looping.
651 if !progressed
652 && !pending.is_empty()
653 && (pending.len() >= OUTPUT_PENDING_CAP || !flushed)
654 {
655 thread::sleep(Duration::from_millis(5));
656 }
657 }
658 }
659
660 /// Write what the terminal will take right now, returning the bytes accepted.
661 /// A full terminal (`WouldBlock`), or any transient error, accepts zero and
662 /// the caller keeps the rest rather than propagating a terminal write error.
663 fn write_nonblocking<W: Write>(sink: &mut W, buf: &[u8]) -> usize {
664 sink.write(buf).unwrap_or(0)
665 }
666
667 /// End of stream: land the final bytes even against a non-blocking terminal,
668 /// but bounded so a wedged terminal cannot hang the exit.
669 fn flush_blocking<W: Write>(sink: &mut W, buf: &[u8]) {
670 let mut off = 0;
671 for _ in 0..2000 {
672 if off >= buf.len() {
673 break;
674 }
675 match sink.write(&buf[off..]) {
676 Ok(0) => thread::sleep(Duration::from_millis(1)),
677 Ok(n) => off += n,
678 Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
679 thread::sleep(Duration::from_millis(1));
680 }
681 Err(_) => break,
682 }
683 }
684 let _ = sink.flush();
685 }
686
687 /// A `Write` over a raw fd. On a non-blocking fd a full pipe surfaces as a
688 /// `WouldBlock` error rather than parking the thread.
689 struct RawFdWriter(libc::c_int);
690
691 impl Write for RawFdWriter {
692 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
693 let n = unsafe { libc::write(self.0, buf.as_ptr().cast(), buf.len()) };
694 if n < 0 {
695 Err(std::io::Error::last_os_error())
696 } else {
697 Ok(n as usize)
698 }
699 }
700
701 fn flush(&mut self) -> std::io::Result<()> {
702 Ok(())
703 }
704 }
705
706 /// Whether enough time has passed since the last repaint request to send
707 /// another, stamping the clock when it returns true.
708 fn resync_due(last: &mut Option<Instant>) -> bool {
709 let now = Instant::now();
710 if last.is_none_or(|t| now.duration_since(t) >= RESYNC_MIN_INTERVAL) {
711 *last = Some(now);
712 true
713 } else {
714 false
715 }
716 }
717
718 /// Forward raw stdin bytes to the guest, draining pending resizes, until the
719 /// output stream ends or local stdin closes.
720 fn drive_input(proc: &Arc<ExecProcess>, stop: &AtomicBool) {
721 let mut buf = [0u8; 4096];
722 let mut stdin_open = true;
723 while !stop.load(Ordering::Relaxed) {
724 if RESIZE_PENDING.swap(false, Ordering::Relaxed) {
725 let (cols, rows) = terminal_size();
726 block_on(proc.resize(cols, rows));
727 }
728 if !stdin_open {
729 thread::sleep(Duration::from_millis(20));
730 continue;
731 }
732 let n = unsafe {
733 libc::read(
734 libc::STDIN_FILENO,
735 buf.as_mut_ptr().cast::<libc::c_void>(),
736 buf.len(),
737 )
738 };
739 match n.cmp(&0) {
740 std::cmp::Ordering::Greater => {
741 if block_on(proc.write_stdin(&buf[..n as usize])).is_err() {
742 break; // remote closed stdin or exec ended
743 }
744 }
745 std::cmp::Ordering::Equal => {
746 // Local stdin reached EOF: send EOF and stop reading it, but
747 // keep draining output until the remote process exits.
748 let _ = block_on(proc.close_stdin());
749 stdin_open = false;
750 }
751 std::cmp::Ordering::Less => {
752 // A nonblocking read with no data yet (WouldBlock), or one a
753 // handled signal such as SIGWINCH interrupted (Interrupted),
754 // is transient: back off briefly and retry rather than ending
755 // the input loop, which would wedge stdin until the command
756 // exits.
757 let err = std::io::Error::last_os_error();
758 if matches!(
759 err.kind(),
760 std::io::ErrorKind::WouldBlock | std::io::ErrorKind::Interrupted
761 ) {
762 thread::sleep(Duration::from_millis(10));
763 } else {
764 break;
765 }
766 }
767 }
768 }
769 }
770
771 // --- local paste and drag-and-drop forwarding ---
772
773 /// Parent of the per-session directory where forwarded drops and pastes
774 /// land. Each session gets its own subdirectory (see PasteBridge::new) so
775 /// two shells' drops of the same name never collide, and a cancel/failure
776 /// rollback only ever deletes files this session uploaded.
777 const GUEST_DROPS_ROOT: &str = "/tmp/sail-drops";
778 /// Wait this long before drawing the upload progress line: most drops are
779 /// small images that land invisibly fast, and flashing a progress line for
780 /// them would just flicker the screen.
781 const UPLOAD_UI_DELAY: Duration = Duration::from_millis(400);
782 /// Largest content pushed onto the guest clipboard in one RPC (the message
783 /// must fit the transport's 4 MiB frame). Larger images upload as files
784 /// and paste as a guest path instead.
785 const CLIPBOARD_PUSH_MAX: usize = 3 * 1024 * 1024;
786 /// Longest a clipboard push may hold the input thread. The push must
787 /// complete before the Ctrl+V chord is forwarded (or the guest
788 /// application would paste the clipboard's previous content), and the
789 /// input thread is what sequences both, so a slow guest stalls keystroke
790 /// forwarding for the push's duration. This deadline bounds that stall
791 /// well under the RPC's own; on expiry the caller falls back exactly as
792 /// for any other failed push. It must exceed the guest agent's own 3s
793 /// serve-verification budget (saild's guestClipboardCmdTimeout) with
794 /// round-trip slack, or a push the guest completed near its budget would
795 /// be misclassified as failed.
796 const CLIPBOARD_PUSH_DEADLINE: Duration = Duration::from_secs(5);
797 /// Upload stream granularity: small enough for responsive progress, large
798 /// enough that per-message overhead is noise.
799 const UPLOAD_CHUNK_BYTES: usize = 256 * 1024;
800 /// How long an ambiguous escape-sequence prefix waits for its remaining
801 /// bytes before being forwarded as a real keypress. Terminals send
802 /// sequences in one burst, so only a human typing a lone ESC waits this out.
803 const CARRY_FLUSH_AFTER: Duration = Duration::from_millis(25);
804
805 /// Tracks DEC private mode 2004 (bracketed paste) in the guest's output so
806 /// injected pastes are framed exactly as the terminal would frame a real
807 /// one. Snapshot repaints re-assert tracked modes, so the flag survives
808 /// reattach and heals after any dropped chunk.
809 #[derive(Default)]
810 struct BracketedPasteTracker {
811 tail: Vec<u8>,
812 }
813
814 impl BracketedPasteTracker {
815 fn scan(&mut self, bytes: &[u8], render: &RenderControl) {
816 const INTRO: &[u8] = b"\x1b[?";
817 let mut buf = std::mem::take(&mut self.tail);
818 buf.extend_from_slice(bytes);
819 let mut i = 0;
820 while i < buf.len() {
821 let Some(at) = find(&buf[i..], INTRO) else {
822 break;
823 };
824 let start = i + at;
825 let mut j = start + INTRO.len();
826 while j < buf.len() && (buf[j].is_ascii_digit() || buf[j] == b';') {
827 j += 1;
828 }
829 let Some(&fin) = buf.get(j) else {
830 // Split across chunks: carry the partial sequence, bounded —
831 // a parameter run longer than any real mode list is not one.
832 if buf.len() - start <= 24 {
833 self.tail = buf[start..].to_vec();
834 }
835 return;
836 };
837 if fin == b'h' || fin == b'l' {
838 let in_params = buf[start + INTRO.len()..j]
839 .split(|&b| b == b';')
840 .any(|param| param == b"2004");
841 if in_params {
842 render.bracketed_paste.store(fin == b'h', Ordering::Relaxed);
843 }
844 }
845 i = j;
846 }
847 let keep = partial_suffix_len(&buf, INTRO);
848 if keep > 0 {
849 self.tail = buf[buf.len() - keep..].to_vec();
850 }
851 }
852 }
853
854 /// Applies guest-clipboard updates to the local clipboard, so a copy made
855 /// inside the guest is pasteable locally. Exits when the stream ends. The
856 /// clipboard handle stays alive for the whole session: on X11 the
857 /// selection lives only as long as the handle that set it.
858 fn spawn_clipboard_consumer(proc: Arc<ExecProcess>) -> thread::JoinHandle<()> {
859 thread::spawn(move || {
860 let mut clipboard: Option<arboard::Clipboard> = None;
861 while let Some((mime, data)) = block_on(proc.next_clipboard_update()) {
862 if mime != "text/plain" {
863 continue;
864 }
865 let Ok(text) = String::from_utf8(data) else {
866 continue;
867 };
868 if clipboard.is_none() {
869 clipboard = arboard::Clipboard::new().ok();
870 }
871 if let Some(clipboard) = clipboard.as_mut() {
872 let _ = clipboard.set_text(text);
873 }
874 }
875 })
876 }
877
878 /// The forwarding twin of [`drive_input`]: stdin is scanned for bracketed
879 /// pastes and the Ctrl+V chord (see [`crate::shell_input`]), which the
880 /// [`PasteBridge`] turns into uploads, clipboard pushes, or verbatim
881 /// forwards; every other byte passes through untouched.
882 fn drive_input_forwarding(mut bridge: PasteBridge, stop: &AtomicBool) {
883 let mut scanner = InputScanner::new();
884 let mut buf = [0u8; 4096];
885 let mut stdin_open = true;
886 let mut carry_deadline: Option<Instant> = None;
887 while !stop.load(Ordering::Relaxed) {
888 if RESIZE_PENDING.swap(false, Ordering::Relaxed) {
889 let (cols, rows) = terminal_size();
890 block_on(bridge.proc.resize(cols, rows));
891 }
892 if !stdin_open {
893 thread::sleep(Duration::from_millis(20));
894 continue;
895 }
896 // Keystrokes read while an upload owned stdin replay first, in
897 // order. Refresh the idle deadline like the read path: a replayed
898 // bare ESC lands in the scanner carry and must still flush.
899 if !bridge.stashed_input.is_empty() {
900 let stashed = std::mem::take(&mut bridge.stashed_input);
901 if bridge.handle_events(scanner.scan(&stashed)).is_err() {
902 break;
903 }
904 carry_deadline = scanner
905 .has_idle_carry()
906 .then(|| Instant::now() + CARRY_FLUSH_AFTER);
907 }
908 let n = unsafe {
909 libc::read(
910 libc::STDIN_FILENO,
911 buf.as_mut_ptr().cast::<libc::c_void>(),
912 buf.len(),
913 )
914 };
915 match n.cmp(&0) {
916 std::cmp::Ordering::Greater => {
917 if bridge
918 .handle_events(scanner.scan(&buf[..n as usize]))
919 .is_err()
920 {
921 break;
922 }
923 carry_deadline = scanner
924 .has_idle_carry()
925 .then(|| Instant::now() + CARRY_FLUSH_AFTER);
926 }
927 std::cmp::Ordering::Equal => {
928 // Local stdin reached EOF: flush whatever the scanner
929 // still held verbatim, then send EOF and keep draining
930 // output until the remote process exits.
931 let held = scanner.flush_all();
932 if !held.is_empty() && bridge.forward(&held).is_err() {
933 break;
934 }
935 let _ = block_on(bridge.proc.close_stdin());
936 stdin_open = false;
937 }
938 std::cmp::Ordering::Less => {
939 let err = std::io::Error::last_os_error();
940 if !matches!(
941 err.kind(),
942 std::io::ErrorKind::WouldBlock | std::io::ErrorKind::Interrupted
943 ) {
944 break;
945 }
946 // Idle: a carried escape prefix past its deadline was a
947 // real keypress (e.g. a lone ESC), so forward it now. A
948 // mid-paste hold is exempt (has_idle_carry): the paste's
949 // remaining bytes are still coming.
950 if carry_deadline.is_some_and(|deadline| Instant::now() >= deadline) {
951 carry_deadline = None;
952 if scanner.has_idle_carry() {
953 let carry = scanner.take_carry();
954 if !carry.is_empty() && bridge.forward(&carry).is_err() {
955 break;
956 }
957 }
958 }
959 thread::sleep(Duration::from_millis(10));
960 }
961 }
962 }
963 }
964
965 /// What the local clipboard holds, in the order pasting cares about:
966 /// copied files, then an image (encoded to PNG), then text.
967 enum LocalClipboard {
968 Files(Vec<PathBuf>),
969 Image(Vec<u8>),
970 Text(String),
971 Empty,
972 }
973
974 fn read_local_clipboard() -> LocalClipboard {
975 let Ok(mut clipboard) = arboard::Clipboard::new() else {
976 return LocalClipboard::Empty;
977 };
978 if let Ok(files) = clipboard.get().file_list() {
979 if !files.is_empty() && files.iter().all(|path| path.is_file()) {
980 return LocalClipboard::Files(files);
981 }
982 }
983 if let Ok(image) = clipboard.get_image() {
984 if let Some(png) = encode_png(&image) {
985 return LocalClipboard::Image(png);
986 }
987 }
988 match clipboard.get_text() {
989 Ok(text) if !text.is_empty() => LocalClipboard::Text(text),
990 _ => LocalClipboard::Empty,
991 }
992 }
993
994 /// Encode arboard's raw RGBA image as PNG, the type both the guest
995 /// clipboard and the coding agents (claude, codex) inside it expect. The
996 /// encoder itself rejects a byte buffer that does not match the
997 /// dimensions.
998 fn encode_png(image: &arboard::ImageData) -> Option<Vec<u8>> {
999 let width = u32::try_from(image.width).ok()?;
1000 let height = u32::try_from(image.height).ok()?;
1001 let mut out = Vec::new();
1002 let mut encoder = png::Encoder::new(&mut out, width, height);
1003 encoder.set_color(png::ColorType::Rgba);
1004 encoder.set_depth(png::BitDepth::Eight);
1005 let mut writer = encoder.write_header().ok()?;
1006 writer.write_image_data(&image.bytes).ok()?;
1007 writer.finish().ok()?;
1008 Some(out)
1009 }
1010
1011 /// How an upload ended: the guest paths to paste, a user cancel (paste
1012 /// nothing), or a failure (the caller falls back to forwarding the
1013 /// original bytes where that makes sense).
1014 enum UploadOutcome {
1015 Done(Vec<String>),
1016 Cancelled,
1017 Failed,
1018 }
1019
1020 /// One file (or in-memory blob) headed for the guest drops directory.
1021 struct UploadSource {
1022 guest_path: String,
1023 size: u64,
1024 data: UploadData,
1025 }
1026
1027 enum UploadData {
1028 File(PathBuf),
1029 Memory(Vec<u8>),
1030 }
1031
1032 /// Turns scanned paste events into guest activity: dragged files upload
1033 /// and paste as guest paths, Ctrl+V forwards the local clipboard (guest
1034 /// clipboard when supported, file upload otherwise), everything else
1035 /// forwards verbatim.
1036 struct PasteBridge {
1037 proc: Arc<ExecProcess>,
1038 render: Arc<RenderControl>,
1039 /// This session's private drop directory under GUEST_DROPS_ROOT, keyed
1040 /// by the exec id so concurrent shells never share a path.
1041 drops_dir: String,
1042 /// Guest file names already used this session, so a re-dropped name
1043 /// gets a numbered variant instead of clobbering a different file.
1044 used_names: std::collections::HashSet<String>,
1045 /// Whether this guest accepts clipboard writes. `None` until the first
1046 /// attempt; latches `Some(false)` on Unimplemented (the guest has no
1047 /// clipboard) so later pastes skip straight to the file fallback.
1048 guest_clipboard: Option<bool>,
1049 /// Keystrokes read while an upload owned stdin (watching for cancel),
1050 /// replayed in order afterwards.
1051 stashed_input: Vec<u8>,
1052 }
1053
1054 impl PasteBridge {
1055 fn new(proc: Arc<ExecProcess>, render: Arc<RenderControl>) -> PasteBridge {
1056 // Name the per-session directory by the hash of the exec id, so it
1057 // is always path-safe, never `.`/`..`, and collision-free whatever
1058 // shape the server's id takes: two concurrent sessions never share
1059 // a path.
1060 use sha2::Digest as _;
1061 use std::fmt::Write as _;
1062 let digest = sha2::Sha256::digest(proc.exec_request_id().as_bytes());
1063 let mut session = String::with_capacity(16);
1064 for byte in &digest[..8] {
1065 let _ = write!(session, "{byte:02x}");
1066 }
1067 let drops_dir = format!("{GUEST_DROPS_ROOT}/{session}");
1068 PasteBridge {
1069 proc,
1070 render,
1071 drops_dir,
1072 used_names: std::collections::HashSet::new(),
1073 guest_clipboard: None,
1074 stashed_input: Vec::new(),
1075 }
1076 }
1077
1078 fn handle_events(&mut self, events: Vec<InputEvent>) -> Result<(), ()> {
1079 for event in events {
1080 match event {
1081 InputEvent::Bytes(bytes) => self.forward(&bytes)?,
1082 InputEvent::Paste(body) => self.handle_paste(&body)?,
1083 InputEvent::PasteChord(chord) => self.handle_chord(&chord)?,
1084 }
1085 }
1086 Ok(())
1087 }
1088
1089 /// Forward bytes to the guest pty. Err means the exec ended and the
1090 /// input loop should stop, matching [`drive_input`].
1091 fn forward(&self, bytes: &[u8]) -> Result<(), ()> {
1092 block_on(self.proc.write_stdin(bytes)).map_err(|_| ())
1093 }
1094
1095 /// A completed bracketed paste: a drag-and-drop of local files uploads
1096 /// them and pastes the guest paths; any other paste (or a failed
1097 /// upload) forwards byte-identically.
1098 fn handle_paste(&mut self, body: &[u8]) -> Result<(), ()> {
1099 if let Some(files) = dropped_local_files(body) {
1100 match self.upload_files(&files) {
1101 UploadOutcome::Done(paths) => {
1102 // Keep the trailing separator the drag arrived with,
1103 // so typing right after the drop stays a separate
1104 // argument exactly as it would locally.
1105 let text = format!("{} ", paths.join(" "));
1106 return self.inject_uploaded(&text, &paths);
1107 }
1108 UploadOutcome::Cancelled => return Ok(()),
1109 UploadOutcome::Failed => {} // fall through to the original paste
1110 }
1111 }
1112 let mut raw = Vec::with_capacity(body.len() + PASTE_START.len() + PASTE_END.len());
1113 raw.extend_from_slice(PASTE_START);
1114 raw.extend_from_slice(body);
1115 raw.extend_from_slice(PASTE_END);
1116 self.forward(&raw)
1117 }
1118
1119 /// A Ctrl+V press: make the local clipboard available in the guest,
1120 /// then (except for uploads that paste a path themselves) deliver the
1121 /// keypress so the guest application reacts to it as usual.
1122 fn handle_chord(&mut self, chord: &[u8]) -> Result<(), ()> {
1123 match read_local_clipboard() {
1124 LocalClipboard::Files(files) => {
1125 let outcome = self.upload_files(&files);
1126 self.inject_outcome(outcome)
1127 }
1128 LocalClipboard::Image(png) => {
1129 if png.len() <= CLIPBOARD_PUSH_MAX && self.push_clipboard("image/png", &png) {
1130 return self.forward(chord);
1131 }
1132 // No guest clipboard took the image (a non-devbox guest, or
1133 // one over the push cap): upload it and inject the path, the
1134 // only way a paste-reading agent gets an image here. The
1135 // chord is deliberately not forwarded — doing so would paste
1136 // whatever the guest clipboard last held. Unlike text, which
1137 // is on the clipboard almost always (so the text path never
1138 // injects, to keep vim visual-block / quoted-insert intact),
1139 // an image on the clipboard is almost always an intended
1140 // paste, so injecting wins over preserving a Ctrl+V binding.
1141 let name = self.reserve_name(std::path::Path::new("clipboard.png"));
1142 let outcome = self.upload_bytes(name, png);
1143 self.inject_outcome(outcome)
1144 }
1145 LocalClipboard::Text(text) => {
1146 if text.len() <= CLIPBOARD_PUSH_MAX {
1147 // The chord is forwarded whether or not the push
1148 // lands. Ctrl+V is not only "paste": vim binds it to
1149 // visual-block and readline to quoted-insert, and text
1150 // sits on the clipboard almost always, so replacing a
1151 // failed push with injected text or a file would fire
1152 // inside those apps constantly. On a guest with no
1153 // clipboard the app's paste read finds nothing, which
1154 // is exactly how these sessions behaved before
1155 // clipboard forwarding existed; terminal-level paste
1156 // (Cmd+V) remains the text path there.
1157 self.push_clipboard("text/plain", text.as_bytes());
1158 return self.forward(chord);
1159 }
1160 // Too big for a clipboard push. Forwarding the keypress
1161 // anyway would paste whatever the guest clipboard last
1162 // held, so deliver the text as a file like an oversized
1163 // image.
1164 let name = self.reserve_name(std::path::Path::new("clipboard.txt"));
1165 let outcome = self.upload_bytes(name, text.into_bytes());
1166 self.inject_outcome(outcome)
1167 }
1168 LocalClipboard::Empty => self.forward(chord),
1169 }
1170 }
1171
1172 /// Try to place content on the guest clipboard, reporting success,
1173 /// waiting at most [`CLIPBOARD_PUSH_DEADLINE`]. Unimplemented latches
1174 /// the fallback: this guest has no clipboard (its image ships none,
1175 /// or it predates the feature), and that never changes mid-session.
1176 /// Other failures, the deadline included, just skip the push this
1177 /// time.
1178 fn push_clipboard(&mut self, mime: &str, data: &[u8]) -> bool {
1179 if self.guest_clipboard == Some(false) {
1180 return false;
1181 }
1182 let pushed = block_on(async {
1183 tokio::time::timeout(CLIPBOARD_PUSH_DEADLINE, self.proc.set_clipboard(mime, data))
1184 .await
1185 });
1186 match pushed {
1187 Ok(Ok(())) => {
1188 self.guest_clipboard = Some(true);
1189 true
1190 }
1191 Ok(Err(SailError::Execution {
1192 code: RpcStatus::Unimplemented,
1193 ..
1194 })) => {
1195 self.guest_clipboard = Some(false);
1196 false
1197 }
1198 Ok(Err(_)) | Err(_) => false,
1199 }
1200 }
1201
1202 /// Paste an upload's guest paths, or forward nothing when the upload was
1203 /// cancelled or failed (the original chord/paste was already handled).
1204 fn inject_outcome(&mut self, outcome: UploadOutcome) -> Result<(), ()> {
1205 match outcome {
1206 UploadOutcome::Done(paths) => self.inject_uploaded(&paths.join(" "), &paths),
1207 UploadOutcome::Cancelled | UploadOutcome::Failed => Ok(()),
1208 }
1209 }
1210
1211 /// Paste the uploaded files' guest paths, deleting the uploads if the
1212 /// session ends before the paste can land, so nothing stays
1213 /// unreferenced in the guest.
1214 fn inject_uploaded(&mut self, text: &str, paths: &[String]) -> Result<(), ()> {
1215 if self.inject(text).is_err() {
1216 let _ = block_on(self.proc.remove_guest_files(paths));
1217 return Err(());
1218 }
1219 Ok(())
1220 }
1221
1222 /// Paste text into the guest exactly as the terminal would: bracketed
1223 /// while the application has mode 2004 on, plain keystrokes otherwise.
1224 fn inject(&self, text: &str) -> Result<(), ()> {
1225 let bracketed = self.render.bracketed_paste.load(Ordering::Relaxed);
1226 let mut bytes = Vec::with_capacity(text.len() + 16);
1227 if bracketed {
1228 bytes.extend_from_slice(PASTE_START);
1229 }
1230 bytes.extend_from_slice(text.as_bytes());
1231 if bracketed {
1232 bytes.extend_from_slice(PASTE_END);
1233 }
1234 self.forward(&bytes)
1235 }
1236
1237 /// Reserve a guest-side name for an upload, numbering repeats
1238 /// (photo.png, photo-2.png, ...) within the session.
1239 fn reserve_name(&mut self, path: &std::path::Path) -> String {
1240 let base = sanitize_drop_name(path);
1241 let mut name = base.clone();
1242 let mut n = 1;
1243 while !self.used_names.insert(name.clone()) {
1244 n += 1;
1245 name = match base.rsplit_once('.') {
1246 Some((stem, ext)) if !stem.is_empty() => format!("{stem}-{n}.{ext}"),
1247 _ => format!("{base}-{n}"),
1248 };
1249 }
1250 name
1251 }
1252
1253 fn upload_files(&mut self, files: &[PathBuf]) -> UploadOutcome {
1254 let mut sources = Vec::with_capacity(files.len());
1255 for path in files {
1256 let Ok(meta) = std::fs::metadata(path) else {
1257 return UploadOutcome::Failed;
1258 };
1259 let name = self.reserve_name(path);
1260 sources.push(UploadSource {
1261 guest_path: format!("{}/{name}", self.drops_dir),
1262 size: meta.len(),
1263 data: UploadData::File(path.clone()),
1264 });
1265 }
1266 self.run_upload(sources)
1267 }
1268
1269 /// Upload one in-memory blob under a name already reserved via
1270 /// [`reserve_name`](Self::reserve_name).
1271 fn upload_bytes(&mut self, name: String, bytes: Vec<u8>) -> UploadOutcome {
1272 self.run_upload(vec![UploadSource {
1273 guest_path: format!("{}/{name}", self.drops_dir),
1274 size: bytes.len() as u64,
1275 data: UploadData::Memory(bytes),
1276 }])
1277 }
1278
1279 /// Stream the sources to the guest while this thread keeps the
1280 /// terminal responsive: a progress line appears for slow uploads, Esc
1281 /// or Ctrl+C cancels (aborting the write streams, which the guest
1282 /// discards uncommitted), and other keystrokes are stashed for replay.
1283 /// Guest output rendering is paused throughout; if anything was drawn
1284 /// over the screen, a resync repaints it from the authoritative guest
1285 /// screen state.
1286 fn run_upload(&mut self, sources: Vec<UploadSource>) -> UploadOutcome {
1287 let total: u64 = sources.iter().map(|s| s.size).sum();
1288 let guest_paths: Vec<String> = sources.iter().map(|s| s.guest_path.clone()).collect();
1289 let label = if sources.len() == 1 {
1290 guest_paths[0]
1291 .rsplit('/')
1292 .next()
1293 .unwrap_or_default()
1294 .to_string()
1295 } else {
1296 format!("{} files", sources.len())
1297 };
1298 self.render.paused.store(true, Ordering::Relaxed);
1299 let progress = Arc::new(std::sync::atomic::AtomicU64::new(0));
1300 let committed: Arc<std::sync::Mutex<Vec<String>>> =
1301 Arc::new(std::sync::Mutex::new(Vec::new()));
1302 // Spawn where the exec stream lives (see block_on): an embedding
1303 // runtime's channels must not be redialed on the crate's own
1304 // reactor.
1305 let handle = tokio::runtime::Handle::try_current()
1306 .unwrap_or_else(|_| crate::runtime::runtime().handle().clone());
1307 let mut task = handle.spawn(upload_task(
1308 Arc::clone(&self.proc),
1309 sources,
1310 Arc::clone(&progress),
1311 Arc::clone(&committed),
1312 ));
1313 let started = Instant::now();
1314 let mut ui = ProgressLine::new(label, total);
1315 let mut esc_at: Option<Instant> = None;
1316 let outcome = loop {
1317 if task.is_finished() {
1318 // A bare ESC still inside its disambiguation window was a
1319 // real keypress after all; replay it with the other
1320 // stashed input instead of dropping it.
1321 if esc_at.take().is_some() {
1322 self.stashed_input.push(0x1b);
1323 }
1324 break match block_on(&mut task) {
1325 Ok(Ok(())) => UploadOutcome::Done(guest_paths.clone()),
1326 Ok(Err(err)) => {
1327 self.roll_back_upload(&committed, &guest_paths);
1328 ui.flash(&format!("[sail] upload failed: {err}"));
1329 UploadOutcome::Failed
1330 }
1331 Err(_) => {
1332 self.roll_back_upload(&committed, &guest_paths);
1333 UploadOutcome::Failed
1334 }
1335 };
1336 }
1337 if self.poll_cancel(&mut esc_at) {
1338 // Aborting drops the in-flight writer mid-stream; the
1339 // guest treats the torn stream as uncommitted and discards
1340 // it.
1341 task.abort();
1342 let _ = block_on(&mut task);
1343 self.roll_back_upload(&committed, &guest_paths);
1344 ui.flash("[sail] upload canceled");
1345 break UploadOutcome::Cancelled;
1346 }
1347 ui.tick(started, progress.load(Ordering::Relaxed));
1348 thread::sleep(Duration::from_millis(30));
1349 };
1350 ui.clear();
1351 self.render.paused.store(false, Ordering::Relaxed);
1352 if ui.wrote {
1353 // The progress line scribbled over the guest's screen; repaint
1354 // it from the guest's authoritative screen state.
1355 block_on(self.proc.resync());
1356 }
1357 outcome
1358 }
1359
1360 /// Undo an upload that will paste nothing (cancelled or failed):
1361 /// delete the files that already committed — nothing points at them,
1362 /// and cancel means the user wants none of the dragged content in the
1363 /// guest — and release the reserved names so a retried drag lands on
1364 /// the same paths. Deletion is best effort: if the guest is unreachable
1365 /// the unreferenced files linger in its /tmp until the Sailbox goes away.
1366 fn roll_back_upload(
1367 &mut self,
1368 committed: &Arc<std::sync::Mutex<Vec<String>>>,
1369 guest_paths: &[String],
1370 ) {
1371 let committed = std::mem::take(&mut *committed.lock().unwrap());
1372 if !committed.is_empty() {
1373 let _ = block_on(self.proc.remove_guest_files(&committed));
1374 }
1375 for path in guest_paths {
1376 if let Some(name) = path.rsplit('/').next() {
1377 self.used_names.remove(name);
1378 }
1379 }
1380 }
1381
1382 /// Drain stdin during an upload. Ctrl+C cancels at once; a bare ESC
1383 /// cancels after a short pause — long enough for the rest of an escape
1384 /// sequence (an arrow key) to arrive and be stashed instead. Everything
1385 /// else is stashed and replayed after the upload.
1386 fn poll_cancel(&mut self, esc_at: &mut Option<Instant>) -> bool {
1387 let mut buf = [0u8; 256];
1388 loop {
1389 let n = unsafe {
1390 libc::read(
1391 libc::STDIN_FILENO,
1392 buf.as_mut_ptr().cast::<libc::c_void>(),
1393 buf.len(),
1394 )
1395 };
1396 if n <= 0 {
1397 break;
1398 }
1399 let bytes = &buf[..n as usize];
1400 for (idx, &byte) in bytes.iter().enumerate() {
1401 if byte == 0x03 {
1402 // Keys typed in the same burst as the cancel replay
1403 // after the upload settles.
1404 self.stashed_input.extend_from_slice(&bytes[idx + 1..]);
1405 return true;
1406 }
1407 if esc_at.take().is_some() {
1408 // The pending ESC was the start of a sequence after all.
1409 self.stashed_input.push(0x1b);
1410 }
1411 if byte == 0x1b && idx == bytes.len() - 1 {
1412 *esc_at = Some(Instant::now());
1413 } else {
1414 self.stashed_input.push(byte);
1415 }
1416 }
1417 }
1418 // 60ms: longer than one 30ms poll tick of run_upload, so a split
1419 // escape sequence has a whole further poll to finish arriving.
1420 esc_at.is_some_and(|at| at.elapsed() >= Duration::from_millis(60))
1421 }
1422 }
1423
1424 /// The background half of an upload: stream every source into the guest,
1425 /// publishing progress for the interactive thread's UI and each committed
1426 /// guest path for cancel's rollback.
1427 async fn upload_task(
1428 proc: Arc<ExecProcess>,
1429 sources: Vec<UploadSource>,
1430 progress: Arc<std::sync::atomic::AtomicU64>,
1431 committed: Arc<std::sync::Mutex<Vec<String>>>,
1432 ) -> Result<(), SailError> {
1433 use tokio::io::AsyncReadExt;
1434 for source in sources {
1435 let mut writer = proc.guest_file_writer(&source.guest_path);
1436 match source.data {
1437 UploadData::Memory(bytes) => {
1438 for chunk in bytes.chunks(UPLOAD_CHUNK_BYTES) {
1439 writer.write_chunk(chunk.to_vec()).await?;
1440 progress.fetch_add(chunk.len() as u64, Ordering::Relaxed);
1441 }
1442 }
1443 UploadData::File(path) => {
1444 let mut file =
1445 tokio::fs::File::open(&path)
1446 .await
1447 .map_err(|err| SailError::Internal {
1448 message: format!("read {}: {err}", path.display()),
1449 })?;
1450 let mut chunk = vec![0u8; UPLOAD_CHUNK_BYTES];
1451 loop {
1452 let n = file
1453 .read(&mut chunk)
1454 .await
1455 .map_err(|err| SailError::Internal {
1456 message: format!("read {}: {err}", path.display()),
1457 })?;
1458 if n == 0 {
1459 break;
1460 }
1461 writer.write_chunk(chunk[..n].to_vec()).await?;
1462 progress.fetch_add(n as u64, Ordering::Relaxed);
1463 }
1464 }
1465 }
1466 // Record the path before finish()'s await: finish closes the
1467 // client stream, so a cancel that aborts this task during the
1468 // await can still let the guest commit the file. Recording first
1469 // guarantees rollback has the path — an rm of a file that never
1470 // committed is a harmless no-op.
1471 committed.lock().unwrap().push(source.guest_path);
1472 writer.finish().await?;
1473 }
1474 Ok(())
1475 }
1476
1477 /// The one-line upload status drawn at the cursor. It only ever repaints
1478 /// itself in place; whatever it overwrote is restored by the post-upload
1479 /// resync.
1480 struct ProgressLine {
1481 label: String,
1482 total: u64,
1483 wrote: bool,
1484 last_draw: Option<Instant>,
1485 }
1486
1487 impl ProgressLine {
1488 fn new(label: String, total: u64) -> ProgressLine {
1489 ProgressLine {
1490 label,
1491 total,
1492 wrote: false,
1493 last_draw: None,
1494 }
1495 }
1496
1497 fn tick(&mut self, started: Instant, sent: u64) {
1498 if !self.wrote && started.elapsed() < UPLOAD_UI_DELAY {
1499 return;
1500 }
1501 if self
1502 .last_draw
1503 .is_some_and(|last| last.elapsed() < Duration::from_millis(100))
1504 {
1505 return;
1506 }
1507 self.last_draw = Some(Instant::now());
1508 self.wrote = true;
1509 let percent = (sent.min(self.total) * 100)
1510 .checked_div(self.total)
1511 .unwrap_or(100);
1512 write_terminal_line(&format!(
1513 "[sail] uploading {} {percent}% {} / {} (esc cancels)",
1514 self.label,
1515 format_bytes(sent),
1516 format_bytes(self.total),
1517 ));
1518 }
1519
1520 /// Show a final status long enough to read before the screen repaints.
1521 fn flash(&mut self, message: &str) {
1522 self.wrote = true;
1523 write_terminal_line(message);
1524 thread::sleep(Duration::from_millis(1200));
1525 }
1526
1527 fn clear(&mut self) {
1528 if self.wrote {
1529 write_terminal(ERASE_LINE);
1530 }
1531 }
1532 }
1533
1534 /// Carriage return + erase-line: return to column 0 and clear the row, so
1535 /// the next write overwrites the cursor line in place.
1536 const ERASE_LINE: &[u8] = b"\r\x1b[2K";
1537
1538 /// Overwrite the cursor line with `text`.
1539 fn write_terminal_line(text: &str) {
1540 let mut bytes = Vec::with_capacity(text.len() + ERASE_LINE.len());
1541 bytes.extend_from_slice(ERASE_LINE);
1542 bytes.extend_from_slice(text.as_bytes());
1543 write_terminal(&bytes);
1544 }
1545
1546 fn write_terminal(bytes: &[u8]) {
1547 let mut sink = RawFdWriter(libc::STDOUT_FILENO);
1548 flush_blocking(&mut sink, bytes);
1549 }
1550
1551 /// Sizes for the progress line, in the 1000-based MB/KB a file manager
1552 /// labels the dragged file with.
1553 fn format_bytes(n: u64) -> String {
1554 const MB: u64 = 1_000_000;
1555 if n >= 10 * MB {
1556 format!("{} MB", n / MB)
1557 } else if n >= MB {
1558 format!("{:.1} MB", n as f64 / MB as f64)
1559 } else {
1560 format!("{} KB", n.div_ceil(1000))
1561 }
1562 }
1563
1564 // --- platform terminal plumbing ---
1565
1566 /// Put the local terminal into raw mode, returning the saved settings.
1567 fn enter_raw_mode() -> Result<libc::termios, SailError> {
1568 unsafe {
1569 let mut saved: libc::termios = std::mem::zeroed();
1570 if libc::tcgetattr(libc::STDIN_FILENO, &raw mut saved) != 0 {
1571 return Err(SailError::Internal {
1572 message: format!(
1573 "could not enter raw terminal mode: {}",
1574 std::io::Error::last_os_error()
1575 ),
1576 });
1577 }
1578 let mut raw = saved;
1579 libc::cfmakeraw(&raw mut raw);
1580 if libc::tcsetattr(libc::STDIN_FILENO, libc::TCSADRAIN, &raw const raw) != 0 {
1581 return Err(SailError::Internal {
1582 message: format!(
1583 "could not enter raw terminal mode: {}",
1584 std::io::Error::last_os_error()
1585 ),
1586 });
1587 }
1588 Ok(saved)
1589 }
1590 }
1591
1592 fn restore_terminal(saved: &libc::termios) {
1593 unsafe {
1594 let _ = libc::tcsetattr(
1595 libc::STDIN_FILENO,
1596 libc::TCSADRAIN,
1597 std::ptr::from_ref(saved),
1598 );
1599 }
1600 }
1601
1602 type SigHandler = libc::sighandler_t;
1603
1604 fn install_sigwinch() -> SigHandler {
1605 // `signal` takes the handler as a numeric `sighandler_t`; cast through a
1606 // concrete fn pointer first so this is a pointer-to-int cast, not a
1607 // fn-item-to-int cast.
1608 let handler = on_sigwinch as extern "C" fn(libc::c_int) as usize;
1609 unsafe { libc::signal(libc::SIGWINCH, handler) }
1610 }
1611
1612 fn restore_sigwinch(prev: SigHandler) {
1613 unsafe {
1614 libc::signal(libc::SIGWINCH, prev);
1615 }
1616 }
1617
1618 /// Put stdin into non-blocking mode so the input loop can interleave reads
1619 /// with resize handling and the stop flag. Returns the previous fcntl flags.
1620 fn set_stdin_nonblocking() -> libc::c_int {
1621 unsafe {
1622 let flags = libc::fcntl(libc::STDIN_FILENO, libc::F_GETFL);
1623 if flags >= 0 {
1624 libc::fcntl(libc::STDIN_FILENO, libc::F_SETFL, flags | libc::O_NONBLOCK);
1625 }
1626 flags
1627 }
1628 }
1629
1630 fn restore_stdin_flags(flags: libc::c_int) {
1631 if flags >= 0 {
1632 unsafe {
1633 libc::fcntl(libc::STDIN_FILENO, libc::F_SETFL, flags);
1634 }
1635 }
1636 }
1637
1638 /// Put stdout into non-blocking mode so the output pump is never parked in a
1639 /// write to a slow terminal. Returns the previous fcntl flags.
1640 fn set_stdout_nonblocking() -> libc::c_int {
1641 unsafe {
1642 let flags = libc::fcntl(libc::STDOUT_FILENO, libc::F_GETFL);
1643 if flags >= 0 {
1644 libc::fcntl(libc::STDOUT_FILENO, libc::F_SETFL, flags | libc::O_NONBLOCK);
1645 }
1646 flags
1647 }
1648 }
1649
1650 fn restore_stdout_flags(flags: libc::c_int) {
1651 if flags >= 0 {
1652 unsafe {
1653 libc::fcntl(libc::STDOUT_FILENO, libc::F_SETFL, flags);
1654 }
1655 }
1656 }
1657
1658 #[cfg(test)]
1659 mod tests {
1660 use super::*;
1661
1662 #[test]
1663 fn resync_due_throttles_back_to_back_requests() {
1664 let mut last = None;
1665 // The first request is always due and stamps the clock.
1666 assert!(resync_due(&mut last));
1667 // A second request within RESYNC_MIN_INTERVAL is suppressed, so a
1668 // persistently-behind reader cannot flood the guest with resync RPCs.
1669 assert!(!resync_due(&mut last));
1670 }
1671
1672 #[test]
1673 fn format_bytes_matches_its_thousand_based_labels() {
1674 assert_eq!(format_bytes(0), "0 KB");
1675 assert_eq!(format_bytes(1), "1 KB");
1676 assert_eq!(format_bytes(999_999), "1000 KB");
1677 assert_eq!(format_bytes(1_000_000), "1.0 MB");
1678 assert_eq!(format_bytes(3_200_000), "3.2 MB");
1679 assert_eq!(format_bytes(25_000_000), "25 MB");
1680 }
1681 }
1682}
1683
1684#[cfg(test)]
1685mod tests {
1686 use super::*;
1687
1688 #[test]
1689 fn login_shell_quotes_an_explicit_path() {
1690 // A path with spaces runs as one literal program.
1691 assert_eq!(
1692 login_shell_command(Some("/opt/my tools/zsh")),
1693 "exec '/opt/my tools/zsh' -l"
1694 );
1695 // The default stays unquoted so the guest expands $SHELL.
1696 assert_eq!(
1697 login_shell_command(/* shell */ None),
1698 "exec ${SHELL:-/bin/bash} -l"
1699 );
1700 }
1701
1702 #[tokio::test]
1703 async fn shell_requires_a_tty() {
1704 // Test processes have no TTY on stdin/stdout, so the precondition
1705 // fires before any network or terminal manipulation.
1706 let client = crate::Client::builder("sk_test")
1707 .api_url("http://127.0.0.1:1")
1708 .sailbox_api_url("http://127.0.0.1:1")
1709 .build()
1710 .expect("build");
1711 let err = client
1712 .sailbox("sb_test")
1713 .shell(/* command */ None, ShellOptions::default())
1714 .await
1715 .expect_err("no tty in tests");
1716 assert!(err.to_string().contains("interactive terminal"), "{err}");
1717 }
1718}