Repository navigation
Expand file tree
/
Copy pathssh.rs
More file actions
3936 lines (3612 loc) · 138 KB
/
Copy pathssh.rs
File metadata and controls
3936 lines (3612 loc) · 138 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//! SSH connection and proxy utilities.
mod upload;
use crate::color::Colorize;
use crate::tls::{
GrpcClient, TlsOptions, grpc_client, owner_replica, retry_unrouted, routed_to, with_owner_hint,
};
use miette::{IntoDiagnostic, Report, Result, WrapErr};
#[cfg(unix)]
use nix::sys::signal::Signal;
use openshell_core::driver_mounts;
use openshell_core::forward::{
ForwardSpec, build_proxy_command, format_gateway_url, resolve_ssh_gateway, sandbox_ssh_args,
shell_escape, validate_ssh_session_response, write_forward_pid,
};
use openshell_core::proto::{
CreateSshSessionRequest, GetSandboxRequest, SandboxPhase, SshRelayTarget, TcpForwardFrame,
TcpForwardInit, tcp_forward_init,
};
use openshell_core::upload::{
DestinationKind as UploadDestinationKind, ExpectedDestination, UploadPlan,
};
use std::fs;
use std::future::Future;
use std::io::{IsTerminal, Write};
#[cfg(unix)]
use std::os::unix::process::CommandExt;
use std::path::{Path, PathBuf};
use std::process::{Command, ExitStatus, Stdio};
use std::sync::OnceLock;
use std::time::{Duration, Instant};
use tokio::io::AsyncWriteExt;
use tokio::process::{Child, Command as TokioCommand};
use tokio_stream::wrappers::ReceiverStream;
use tonic::Code;
use tonic::metadata::AsciiMetadataValue;
/// Time budget for the local listener to become reachable after `ssh` starts.
/// This is a user-visible readiness deadline for both foreground and background
/// forwards, not a soft cleanup grace period.
const FORWARD_LISTENER_READINESS_TIMEOUT: Duration = Duration::from_secs(10);
/// Delay between listener/PID probes within the configured timeout.
const FORWARD_LISTENER_PROBE_INTERVAL: Duration = Duration::from_millis(50);
/// Per-attempt connect timeout, so one hung probe cannot consume the whole
/// grace period.
const FORWARD_LISTENER_CONNECT_TIMEOUT: Duration = Duration::from_millis(200);
/// Time budget for the supervisor relay to register after a fast canonical
/// command has already reported its terminal result.
const TERMINAL_RELAY_REGISTRATION_TIMEOUT: Duration = Duration::from_secs(5);
const TERMINAL_RELAY_REGISTRATION_INTERVAL: Duration = Duration::from_millis(50);
/// An SSH client that remained alive for this long was attached successfully,
/// rather than failing during initial authentication or setup.
const CONNECT_ESTABLISHED_DURATION: Duration = Duration::from_secs(2);
/// Briefly wait for the gateway lifecycle projection to catch up with an SSH
/// exit status before treating status 255 as a transport failure.
const CONNECT_TERMINAL_STATUS_TIMEOUT: Duration = Duration::from_millis(500);
const CONNECT_TERMINAL_STATUS_INTERVAL: Duration = Duration::from_millis(50);
/// Time allowed to restore an established canonical-main attachment after its
/// transport is lost.
const CONNECT_RECOVERY_TIMEOUT: Duration = Duration::from_mins(1);
const CONNECT_RETRY_INITIAL_DELAY: Duration = Duration::from_millis(250);
const CONNECT_RETRY_MAX_DELAY: Duration = Duration::from_secs(5);
const CONNECT_CHILD_TERMINATION_TIMEOUT: Duration = Duration::from_secs(5);
const SSH_TRANSPORT_FAILURE_EXIT_CODE: i32 = 255;
const SYNC_RETRY_ATTEMPTS: usize = 4;
const SYNC_RETRY_DELAY: Duration = Duration::from_secs(2);
static DEFAULT_SSH_LOG_LEVEL: OnceLock<&'static str> = OnceLock::new();
/// Set the SSH log level derived from CLI verbosity before starting commands.
pub fn set_default_ssh_log_level(level: &'static str) {
DEFAULT_SSH_LOG_LEVEL
.set(level)
.expect("SSH log level is configured only once");
}
#[derive(Clone, Copy, Debug)]
pub enum Editor {
Vscode,
Cursor,
}
impl Editor {
fn binary(self) -> &'static str {
match self {
Self::Vscode => "code",
Self::Cursor => "cursor",
}
}
fn remote_target(host_alias: &str) -> String {
format!("ssh-remote+{host_alias}")
}
fn label(self) -> &'static str {
match self {
Self::Vscode => "VS Code",
Self::Cursor => "Cursor",
}
}
}
struct SshSessionConfig {
proxy_command: String,
sandbox_id: String,
sandbox_name: String,
gateway_url: String,
token: String,
main_terminal: bool,
ingress_admission: Option<openshell_core::proto::SandboxIngressAdmission>,
replica: Option<AsciiMetadataValue>,
}
async fn ssh_session_config(
server: &str,
name: &str,
tls: &TlsOptions,
workspace: &str,
terminal_relay_registration_timeout: Option<Duration>,
) -> Result<SshSessionConfig> {
let mut client = grpc_client(server, tls).await?;
// Resolve the sandbox and retain its ID for local lifecycle tracking.
let response = client
.get_sandbox(with_owner_hint(GetSandboxRequest {
name: name.to_string(),
workspace_scope: Some(openshell_core::proto::workspace_selector(
(workspace).to_string(),
)),
}))
.await
.into_diagnostic()?;
let replica = owner_replica(&response);
let sandbox = response
.into_inner()
.sandbox
.ok_or_else(|| miette::miette!("sandbox not found"))?;
let relay_registration_deadline =
terminal_relay_registration_timeout.map(|timeout| tokio::time::Instant::now() + timeout);
let response = loop {
match client
.create_ssh_session(CreateSshSessionRequest {
sandbox: name.to_string(),
workspace_scope: Some(openshell_core::proto::workspace_selector(
(workspace).to_string(),
)),
})
.await
{
Ok(response) => break response,
Err(status)
if status.code() == Code::FailedPrecondition
&& relay_registration_deadline
.is_some_and(|deadline| tokio::time::Instant::now() < deadline) =>
{
tokio::time::sleep(TERMINAL_RELAY_REGISTRATION_INTERVAL).await;
}
Err(status) => return Err(status).into_diagnostic(),
}
};
let session = response.into_inner();
validate_ssh_session_response(&session)
.map_err(|err| miette::miette!("gateway returned invalid SSH session response: {err}"))?;
let exe = std::env::current_exe()
.into_diagnostic()
.wrap_err("failed to resolve OpenShell executable")?;
let exe_command = exe.to_string_lossy().into_owned();
// When using Cloudflare bearer auth, the SSH CONNECT must go through the
// external tunnel endpoint (the cluster URL), not the server's internal
// scheme/host/port which may be plaintext HTTP on 127.0.0.1.
let gateway_url = if tls.is_bearer_auth() {
server.trim_end_matches('/').to_string()
} else {
// If the server returned a loopback gateway address, override it with the
// cluster endpoint's host. This handles the case where the server defaults
// to 127.0.0.1 but the cluster is actually running on a remote host.
#[allow(clippy::cast_possible_truncation)]
let gateway_port_u16 = session.gateway_port as u16;
let (gateway_scheme, gateway_host, gateway_port) = resolve_ssh_gateway(
&session.gateway_scheme,
&session.gateway_host,
gateway_port_u16,
server,
);
format_gateway_url(&gateway_scheme, &gateway_host, gateway_port)
};
let gateway_name = tls
.gateway_name()
.ok_or_else(|| miette::miette!("gateway name is required to build SSH proxy command"))?;
let proxy_command = build_proxy_command(
&exe_command,
&gateway_url,
name,
workspace,
&session.token,
gateway_name,
);
Ok(SshSessionConfig {
ingress_admission: sandbox
.status
.as_ref()
.and_then(|status| status.ingress_admission.clone()),
proxy_command,
sandbox_id: session.sandbox_id.clone(),
sandbox_name: name.to_string(),
gateway_url,
token: session.token,
main_terminal: sandbox.spec.as_ref().is_none_or(|spec| spec.tty),
replica,
})
}
fn ssh_base_command(proxy_command: &str) -> Command {
// An explicit environment override wins over the CLI verbosity default.
let ssh_log_level = std::env::var("OPENSHELL_SSH_LOG_LEVEL").unwrap_or_else(|_| {
DEFAULT_SSH_LOG_LEVEL
.get()
.copied()
.unwrap_or("ERROR")
.to_string()
});
let mut command = Command::new("ssh");
// Nested ProxyCommand processes inherit the effective verbosity too.
command.env("OPENSHELL_SSH_LOG_LEVEL", &ssh_log_level);
command
.args(sandbox_ssh_args(proxy_command, &ssh_log_level))
// Detect a dead relay within ~45s. The relay rides on a TCP connection
// that the client has no way to observe silently dropping (gateway
// restart, supervisor restart, cluster failover), so fall back to
// SSH-level keepalives instead of hanging forever.
.arg("-o")
.arg("ServerAliveInterval=15")
.arg("-o")
.arg("ServerAliveCountMax=3");
command
}
async fn exec_or_wait(command: Command, replace_process: bool) -> Result<i32> {
if replace_process && std::io::stdin().is_terminal() {
#[cfg(unix)]
{
let mut command = command;
let err = command.exec();
return Err(miette::miette!("failed to exec ssh: {err}"));
}
}
// Catch terminal signals in the parent while SSH receives the same signals
// from the foreground process group. Unlike SIG_IGN, caught dispositions
// reset to their defaults when the child execs, so SSH stays interruptible.
#[cfg(unix)]
let mut signals = if !replace_process && std::io::stdin().is_terminal() {
Some(TerminationSignals::new()?)
} else {
None
};
let mut child = TokioCommand::from(command)
.kill_on_drop(true)
.spawn()
.into_diagnostic()?;
#[cfg(unix)]
if let Some(signals) = signals.as_mut() {
loop {
tokio::select! {
status = child.wait() => return Ok(process_exit_code(status.into_diagnostic()?)),
_ = signals.recv() => {}
}
}
}
Ok(process_exit_code(child.wait().await.into_diagnostic()?))
}
fn main_attach_command(session: &SshSessionConfig) -> Command {
let mut command = ssh_base_command(&session.proxy_command);
if session.main_terminal {
command.arg("-tt").arg("-o").arg("RequestTTY=force");
} else {
command.arg("-T");
}
command
.arg("-o")
.arg("SetEnv=TERM=xterm-256color")
.arg("-s")
.arg("sandbox")
.arg("openshell-main")
.stdin(Stdio::inherit())
.stdout(Stdio::inherit())
.stderr(Stdio::inherit());
command
}
async fn run_main_attach(session: &SshSessionConfig, replace_process: bool) -> Result<i32> {
let command = main_attach_command(session);
exec_or_wait(command, replace_process).await
}
fn process_exit_code(status: ExitStatus) -> i32 {
status.code().unwrap_or(1)
}
#[cfg(unix)]
struct TerminationSignals {
interrupt: tokio::signal::unix::Signal,
quit: tokio::signal::unix::Signal,
terminate: tokio::signal::unix::Signal,
}
#[cfg(unix)]
impl TerminationSignals {
fn new() -> Result<Self> {
use tokio::signal::unix::{SignalKind, signal};
Ok(Self {
interrupt: signal(SignalKind::interrupt()).into_diagnostic()?,
quit: signal(SignalKind::quit()).into_diagnostic()?,
terminate: signal(SignalKind::terminate()).into_diagnostic()?,
})
}
async fn recv(&mut self) -> Signal {
tokio::select! {
_ = self.interrupt.recv() => Signal::SIGINT,
_ = self.quit.recv() => Signal::SIGQUIT,
_ = self.terminate.recv() => Signal::SIGTERM,
}
}
}
struct ConnectCancellation {
#[cfg(unix)]
signals: TerminationSignals,
}
impl ConnectCancellation {
// Unix signal registration is fallible; retain the shared API on Windows.
#[cfg_attr(not(unix), allow(clippy::unnecessary_wraps))]
fn new() -> Result<Self> {
Ok(Self {
#[cfg(unix)]
signals: TerminationSignals::new()?,
})
}
// Waiting consumes mutable signal state only on Unix.
#[cfg_attr(not(unix), allow(clippy::needless_pass_by_ref_mut))]
async fn wait<F, T>(&mut self, future: F) -> std::result::Result<T, i32>
where
F: Future<Output = T>,
{
#[cfg(unix)]
{
tokio::select! {
biased;
result = future => Ok(result),
signal = self.signals.recv() => Err(128 + signal as i32),
}
}
#[cfg(not(unix))]
{
Ok(future.await)
}
}
}
#[cfg(unix)]
fn forward_signal_to_child(child: &Child, signal: Signal) -> Result<()> {
let Some(pid) = child.id() else {
return Ok(());
};
let pid = i32::try_from(pid).into_diagnostic()?;
match nix::sys::signal::kill(nix::unistd::Pid::from_raw(pid), signal) {
Ok(()) | Err(nix::errno::Errno::ESRCH) => Ok(()),
Err(error) => Err(error).into_diagnostic(),
}
}
#[cfg(unix)]
async fn terminate_and_reap_child(child: &mut Child, signal: Signal) -> Result<i32> {
forward_signal_to_child(child, signal)?;
if let Ok(status) = tokio::time::timeout(CONNECT_CHILD_TERMINATION_TIMEOUT, child.wait()).await
{
status.into_diagnostic()?;
} else {
child.kill().await.into_diagnostic()?;
child.wait().await.into_diagnostic()?;
}
Ok(128 + signal as i32)
}
// The shared cancellation state is mutated by the Unix signal receiver.
#[cfg_attr(not(unix), allow(clippy::needless_pass_by_ref_mut))]
async fn run_main_attach_supervised(
session: &SshSessionConfig,
cancellation: &mut ConnectCancellation,
) -> Result<i32> {
#[cfg(not(unix))]
let _ = cancellation;
let mut command = TokioCommand::from(main_attach_command(session));
command.kill_on_drop(true);
let mut child = command.spawn().into_diagnostic()?;
#[cfg(unix)]
{
tokio::select! {
biased;
status = child.wait() => Ok(process_exit_code(status.into_diagnostic()?)),
signal = cancellation.signals.recv() => terminate_and_reap_child(&mut child, signal).await,
}
}
#[cfg(not(unix))]
{
Ok(process_exit_code(child.wait().await.into_diagnostic()?))
}
}
async fn await_before_recovery_deadline<F, T>(
deadline: Option<Instant>,
future: F,
) -> std::result::Result<T, ()>
where
F: Future<Output = T>,
{
let Some(deadline) = deadline else {
return Ok(future.await);
};
tokio::time::timeout_at(tokio::time::Instant::from_std(deadline), future)
.await
.map_err(|_| ())
}
fn print_connect_recovery_timeout() {
eprintln!(
"Unable to restore the sandbox connection within {} seconds.",
CONNECT_RECOVERY_TIMEOUT.as_secs()
);
}
fn should_recover_connect(
exit_code: i32,
attached_for: Duration,
recovery_active: bool,
main_has_terminal_result: bool,
) -> bool {
!main_has_terminal_result
&& exit_code == SSH_TRANSPORT_FAILURE_EXIT_CODE
&& (recovery_active || attached_for >= CONNECT_ESTABLISHED_DURATION)
}
async fn canonical_main_has_terminal_result(
server: &str,
name: &str,
tls: &TlsOptions,
workspace: &str,
) -> bool {
let probe = async {
let Ok(mut client) = grpc_client(server, tls).await else {
return false;
};
loop {
let Ok(response) = client
.get_sandbox(GetSandboxRequest {
name: name.to_string(),
workspace_scope: Some(openshell_core::proto::workspace_selector(
workspace.to_string(),
)),
})
.await
else {
return false;
};
let Some(sandbox) = response.into_inner().sandbox else {
return false;
};
let phase = SandboxPhase::try_from(sandbox.phase()).unwrap_or(SandboxPhase::Unknown);
if sandbox
.status
.as_ref()
.is_some_and(|status| status.exit_code.is_some())
|| matches!(
phase,
SandboxPhase::Completed
| SandboxPhase::Error
| SandboxPhase::Stopping
| SandboxPhase::Stopped
| SandboxPhase::Suspending
| SandboxPhase::Suspended
| SandboxPhase::Deleting
)
{
return true;
}
tokio::time::sleep(CONNECT_TERMINAL_STATUS_INTERVAL).await;
}
};
tokio::time::timeout(CONNECT_TERMINAL_STATUS_TIMEOUT, probe)
.await
.unwrap_or(false)
}
fn should_start_connect_recovery_window(attached_for: Duration, recovery_active: bool) -> bool {
!recovery_active || attached_for >= CONNECT_RECOVERY_TIMEOUT
}
fn next_connect_retry_delay(delay: Duration) -> Duration {
std::cmp::min(delay.saturating_mul(2), CONNECT_RETRY_MAX_DELAY)
}
fn connect_error_is_retryable(error: &Report) -> bool {
let message = format!("{error:?}").to_ascii_lowercase();
[
"broken pipe",
"connection aborted",
"connection closed",
"connection refused",
"connection reset",
"deadline exceeded",
"h2 protocol",
"http2",
"reset before headers",
"service is currently unavailable",
"timed out",
"timeout",
"transport error",
"unexpected eof",
"unavailable",
"upstream connect error",
]
.iter()
.any(|needle| message.contains(needle))
}
async fn sandbox_connect_supervised(
server: &str,
name: &str,
tls: &TlsOptions,
workspace: &str,
) -> Result<i32> {
let mut recovery_deadline = None;
let mut retry_delay = CONNECT_RETRY_INITIAL_DELAY;
let mut cancellation = ConnectCancellation::new()?;
loop {
if recovery_deadline.is_some_and(|deadline| Instant::now() >= deadline) {
print_connect_recovery_timeout();
return Ok(SSH_TRANSPORT_FAILURE_EXIT_CODE);
}
let session_attempt = match Box::pin(cancellation.wait(await_before_recovery_deadline(
recovery_deadline,
ssh_session_config(server, name, tls, workspace, None),
)))
.await
{
Ok(attempt) => attempt,
Err(exit_code) => return Ok(exit_code),
};
let session = match session_attempt {
Err(()) => {
print_connect_recovery_timeout();
return Ok(SSH_TRANSPORT_FAILURE_EXIT_CODE);
}
Ok(Ok(session)) => session,
Ok(Err(error))
if recovery_deadline.is_some_and(|deadline| Instant::now() < deadline)
&& connect_error_is_retryable(&error) =>
{
tracing::warn!(
sandbox = name,
error = %error,
"failed to create replacement SSH session; retrying"
);
let now = Instant::now();
let delay = recovery_deadline
.map_or(retry_delay, |deadline| retry_delay.min(deadline - now));
if let Err(exit_code) = cancellation.wait(tokio::time::sleep(delay)).await {
return Ok(exit_code);
}
retry_delay = next_connect_retry_delay(retry_delay);
continue;
}
Ok(Err(error)) => return Err(error),
};
let attach_started = Instant::now();
let exit_code = run_main_attach_supervised(&session, &mut cancellation).await?;
let attached_for = attach_started.elapsed();
let recovery_active = recovery_deadline.is_some();
let main_has_terminal_result = if exit_code == SSH_TRANSPORT_FAILURE_EXIT_CODE {
match cancellation
.wait(canonical_main_has_terminal_result(
server, name, tls, workspace,
))
.await
{
Ok(has_result) => has_result,
Err(exit_code) => return Ok(exit_code),
}
} else {
false
};
if !should_recover_connect(
exit_code,
attached_for,
recovery_active,
main_has_terminal_result,
) {
return Ok(exit_code);
}
// Once a replacement attachment survives the full recovery interval,
// treat a later failure as a new interruption. Keeping the existing
// deadline for shorter attempts prevents SSH connect timeouts from
// extending recovery forever.
if should_start_connect_recovery_window(attached_for, recovery_active) {
recovery_deadline = Some(Instant::now() + CONNECT_RECOVERY_TIMEOUT);
retry_delay = CONNECT_RETRY_INITIAL_DELAY;
eprintln!(
"Connection to sandbox lost; reconnecting. To disconnect, press Ctrl-D or Ctrl-P then Ctrl-Q after reattachment; press Ctrl-C while retrying to cancel."
);
}
let Some(deadline) = recovery_deadline else {
return Ok(exit_code);
};
let now = Instant::now();
if now >= deadline {
print_connect_recovery_timeout();
return Ok(exit_code);
}
if let Err(exit_code) = cancellation
.wait(tokio::time::sleep(std::cmp::min(
retry_delay,
deadline - now,
)))
.await
{
return Ok(exit_code);
}
retry_delay = next_connect_retry_delay(retry_delay);
}
}
async fn sandbox_connect_with_mode(
server: &str,
name: &str,
tls: &TlsOptions,
replace_process: bool,
workspace: &str,
terminal_relay_registration_timeout: Option<Duration>,
) -> Result<i32> {
let session = ssh_session_config(
server,
name,
tls,
workspace,
terminal_relay_registration_timeout,
)
.await?;
run_main_attach(&session, replace_process).await
}
/// Connect to a sandbox via SSH.
pub async fn sandbox_connect(
server: &str,
name: &str,
tls: &TlsOptions,
workspace: &str,
) -> Result<i32> {
sandbox_connect_supervised(server, name, tls, workspace).await
}
pub(crate) async fn sandbox_connect_without_exec(
server: &str,
name: &str,
tls: &TlsOptions,
workspace: &str,
) -> Result<i32> {
sandbox_connect_with_mode(server, name, tls, false, workspace, None).await
}
pub(crate) async fn sandbox_connect_terminal_main(
server: &str,
name: &str,
tls: &TlsOptions,
workspace: &str,
) -> Result<i32> {
sandbox_connect_with_mode(
server,
name,
tls,
false,
workspace,
Some(TERMINAL_RELAY_REGISTRATION_TIMEOUT),
)
.await
}
pub async fn sandbox_connect_editor(
server: &str,
gateway: &str,
name: &str,
editor: Editor,
tls: &TlsOptions,
workspace: &str,
) -> Result<()> {
let session = ssh_session_config(server, name, tls, workspace, None).await?;
let workspace_root = discover_workspace_root(&session).await?;
let host_alias = host_alias(name, workspace);
install_ssh_config(gateway, name, workspace)?;
launch_editor(editor, &host_alias, &workspace_root)?;
eprintln!(
"{} Opened {} for sandbox {}",
"✓".green().bold(),
editor.label(),
name
);
Ok(())
}
/// Forward a local port to a sandbox via SSH.
///
/// Background mode keeps the spawned `ssh -N` child alive and records that PID
/// for later management via [`stop_forward`] or [`list_forwards`].
pub async fn sandbox_forward(
server: &str,
name: &str,
spec: &ForwardSpec,
background: bool,
tls: &TlsOptions,
workspace: &str,
) -> Result<()> {
let session = ssh_session_config(server, name, tls, workspace, None).await?;
let scope = openshell_core::ingress::admit_port(
session.ingress_admission.as_ref(),
u32::from(spec.port),
false,
)
.map_err(|error| miette::miette!("{error}"))?;
if scope == openshell_core::proto::IngressScope::SharedHostLoopback {
eprintln!("Target is an admitted shared-host loopback service.");
}
openshell_core::forward::check_port_available(spec)?;
let mut command = TokioCommand::from(ssh_forward_command(
&session.proxy_command,
&session.sandbox_id,
spec,
));
if background {
command
.kill_on_drop(false)
.stdin(Stdio::null())
.stdout(Stdio::inherit())
.stderr(Stdio::inherit());
} else {
command
.stdin(Stdio::inherit())
.stdout(Stdio::inherit())
.stderr(Stdio::inherit());
}
let port = spec.port;
if background {
let mut child = command.spawn().into_diagnostic()?;
let Some(pid) = child.id() else {
terminate_owned_forward_child(&mut child).await;
return Err(miette::miette!(
"ssh process did not expose a PID for background tracking"
));
};
if let Err(err) = wait_for_forward_start(&mut child, spec)
.await
.wrap_err("ssh process started but local forward listener was not reachable")
{
terminate_owned_forward_child(&mut child).await;
return Err(err);
}
let tracked = track_background_forward_or_cleanup(
workspace,
name,
port,
pid,
&session.sandbox_id,
&spec.bind_addr,
|| {
let _ = child.start_kill();
},
);
if tracked.is_err() {
let _ = child.wait().await;
}
tracked?;
return Ok(());
}
let status = {
let mut child = command.spawn().into_diagnostic()?;
if let Err(err) = wait_for_forward_start(&mut child, spec).await {
terminate_owned_forward_child(&mut child).await;
return Err(err);
}
eprintln!("{}", foreground_forward_started_message(name, spec));
child.wait().await.into_diagnostic()?
};
if !status.success() {
return Err(miette::miette!("ssh exited with status {status}"));
}
Ok(())
}
/// A forward must stay owned by the process we spawn so it can be reaped or
/// tracked by PID. User SSH config may otherwise fork it into the background.
fn ssh_forward_command(proxy_command: &str, sandbox_id: &str, spec: &ForwardSpec) -> Command {
let mut command = ssh_base_command(proxy_command);
command
.arg("-o")
.arg("ForkAfterAuthentication=no")
.arg("-N")
.arg("-o")
.arg("ExitOnForwardFailure=yes")
.arg("-o")
.arg(format!("SetEnv=OPENSHELL_FORWARD_SANDBOX_ID={sandbox_id}"))
.arg("-L")
.arg(spec.ssh_forward_arg())
.arg("sandbox");
command
}
/// Wait for the local listener, racing the probe against the `ssh` child
/// exiting. An early exit (e.g. `ExitOnForwardFailure=yes` tearing down the
/// session) means forwarding never came up, so it errors instead of waiting
/// out the grace period.
async fn wait_for_forward_start(child: &mut Child, spec: &ForwardSpec) -> Result<()> {
let listener = wait_for_forward_listener(spec, FORWARD_LISTENER_READINESS_TIMEOUT);
tokio::pin!(listener);
tokio::select! {
result = &mut listener => result,
status = child.wait() => {
let status = status.into_diagnostic()?;
if status.success() {
Err(miette::miette!(
"ssh exited before local forward listener opened on {}:{}",
forward_probe_host(spec),
spec.port,
))
} else {
Err(miette::miette!(
"ssh exited with status {status} before local forward listener opened on {}:{}",
forward_probe_host(spec),
spec.port,
))
}
}
}?;
if let Some(status) = child.try_wait().into_diagnostic()? {
return Err(miette::miette!(
"ssh exited with status {status} after local forward listener opened on {}:{}",
forward_probe_host(spec),
spec.port,
));
}
Ok(())
}
/// Poll the local endpoint until a connect succeeds or `wait_for` elapses. The
/// last probe error is folded into the timeout diagnostic, so a failure reports
/// why the listener never opened, not just that it timed out.
async fn wait_for_forward_listener(spec: &ForwardSpec, wait_for: Duration) -> Result<()> {
wait_for_forward_listener_with_probe(spec, wait_for, |spec| async move {
probe_forward_listener(&spec).await
})
.await
}
async fn wait_for_forward_listener_with_probe<F, Fut>(
spec: &ForwardSpec,
wait_for: Duration,
mut probe: F,
) -> Result<()>
where
F: FnMut(ForwardSpec) -> Fut,
Fut: Future<Output = std::result::Result<(), String>>,
{
let deadline = tokio::time::Instant::now() + wait_for;
loop {
let probe_error = match probe(spec.clone()).await {
Ok(()) => return Ok(()),
Err(err) => err,
};
if tokio::time::Instant::now() >= deadline {
return Err(miette::miette!(
"local forward listener did not open on {}:{} within {}ms: last probe failed with {probe_error}",
forward_probe_host(spec),
spec.port,
wait_for.as_millis(),
));
}
tokio::time::sleep(FORWARD_LISTENER_PROBE_INTERVAL).await;
}
}
/// One bounded TCP connect to the forward endpoint. Returns a `String` error
/// rather than a `miette` diagnostic to stay cheap in the poll loop. The
/// connection only proves reachability and is dropped at once; SSH forwards
/// this throwaway connect to the sandbox-side target.
async fn probe_forward_listener(spec: &ForwardSpec) -> std::result::Result<(), String> {
match tokio::time::timeout(
FORWARD_LISTENER_CONNECT_TIMEOUT,
openshell_core::net::connect_tcp_nodelay_best_effort((forward_probe_host(spec), spec.port)),
)
.await
{
Ok(Ok(stream)) => {
drop(stream);
Ok(())
}
Ok(Err(err)) => Err(err.to_string()),
Err(_) => Err(format!(
"connect timed out after {}ms",
FORWARD_LISTENER_CONNECT_TIMEOUT.as_millis()
)),
}
}
/// Resolve the bind address to a connectable host. Wildcard binds (`0.0.0.0`,
/// `::`, empty) are "any-address" listeners, not valid connect targets, so they
/// map to the matching loopback. Specific addresses are probed as-is.
fn forward_probe_host(spec: &ForwardSpec) -> &str {
match spec.bind_addr.as_str() {
"" | "0.0.0.0" => "127.0.0.1",
"::" => "::1",
host => host,
}
}
/// Best-effort cleanup for the SSH child this process spawned. `kill` waits for
/// the child to exit, so failed startup cannot leave an unreaped process.
async fn terminate_owned_forward_child(child: &mut Child) {
let _ = child.kill().await;
}
/// Track a verified background forward, cleaning it up if PID-file persistence fails.
fn track_background_forward_or_cleanup(
workspace: &str,
name: &str,
port: u16,
pid: u32,
sandbox_id: &str,
bind_addr: &str,
cleanup: impl FnOnce(),
) -> Result<()> {
if let Err(err) = write_forward_pid(workspace, name, port, pid, sandbox_id, bind_addr) {
cleanup();
return Err(err)
.wrap_err("local forward listener was reachable but tracking the SSH process failed");
}
Ok(())
}
fn foreground_forward_started_message(name: &str, spec: &ForwardSpec) -> String {
format!(
"{} Forwarding port {} to sandbox {name}\n Access at: {}\n Press Ctrl+C to stop\n {}",
"✓".green().bold(),
spec.port,
spec.access_url(),
"Hint: pass --background to start forwarding without blocking your terminal".dimmed(),
)
}
async fn sandbox_exec_with_mode(
server: &str,
name: &str,
command: &[String],