Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,22 @@ public struct SSHTuiConnection: Sendable {
public var session: String { "cmux" }

public var authenticationArguments: [String] {
var arguments = ["/usr/bin/ssh", "-T", "-o", "BatchMode=no", "-o", "RemoteCommand=none", "-o", "RequestTTY=no"]
routeCheckArguments(batchMode: false) + [configuration.destination, "true"]
}

/// A prompt-free `ssh … true` over the carrier's route.
public var preflightArguments: [String] {
// OpenSSH keeps the first value it reads, so a caller's ConnectTimeout still wins.
routeCheckArguments(batchMode: true) + ["-o", "ConnectTimeout=15", configuration.destination, "true"]
}

private func routeCheckArguments(batchMode: Bool) -> [String] {
var arguments = ["/usr/bin/ssh", "-T", "-o", batchMode ? "BatchMode=yes" : "BatchMode=no",
"-o", "RemoteCommand=none", "-o", "RequestTTY=no"]
if let port = configuration.port { arguments += ["-p", String(port)] }
if let identity = configuration.identityFile { arguments += ["-i", identity] }
for option in configuration.sshOptions { arguments += ["-o", option] }
return arguments + [configuration.destination, "true"]
return arguments
}

/// The daemon owns the login shell and therefore keeps it alive when SSH disconnects.
Expand All @@ -56,12 +67,14 @@ public struct SSHTuiConnection: Sendable {
var arguments = ["remote", "ssh", configuration.destination, "--headless", "--json",
"--exit-with-parent", "--lanes", "single", "--carrier",
"--session", session, "--state-dir", stateDirectory]
var sshArguments = ["-o", "RequestTTY=no", "-o", "RemoteCommand=none"]
var sshArguments = ["-o", "BatchMode=yes", "-o", "RequestTTY=no", "-o", "RemoteCommand=none"]
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
if let port = configuration.port { sshArguments += ["-p", String(port)] }
if let identity = configuration.identityFile { sshArguments += ["-i", identity] }
for option in configuration.sshOptions { sshArguments += ["-o", option] }
// The carrier is an exec channel. Interactive authentication precedes this
// launch, and host verification must remain OpenSSH's responsibility.
// The carrier is a headless exec channel that reconnects for its whole
// lifetime. Batch mode turns a prompt it cannot answer into OpenSSH's
// own failure. Interactive authentication and host-key prompts precede
// this launch (SSHTuiPreflight), and verification stays OpenSSH's.
for argument in sshArguments { arguments += ["--ssh-arg", argument] }
arguments += ["--device-name", deviceName]
return arguments
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import CmuxFoundation
import Foundation

/// Proves an SSH route authenticates without a prompt before the headless carrier starts.
///
/// The carrier cannot answer a password, keyboard-interactive or host-key prompt,
/// and it retries OpenSSH's own failures until its startup deadline. A batch-mode
/// `ssh … true` returns OpenSSH's diagnostic in seconds instead. With connection
/// sharing configured it also opens the master the carrier then multiplexes over.
public struct SSHTuiPreflight: Sendable {
public init(connection: SSHTuiConnection, commands: any CommandRunning = CommandRunner(), timeout: TimeInterval = 30) {
self.connection = connection
self.commands = commands
self.timeout = timeout
}

public let connection: SSHTuiConnection
private let commands: any CommandRunning
private let timeout: TimeInterval

public func run() async throws {
var arguments = connection.preflightArguments
var executable = arguments.removeFirst()
// The child inherits the app environment, so the caller's agent is
// passed the same way the carrier receives it.
if let agent = connection.configuration.agentSocketPath {
arguments = ["SSH_AUTH_SOCK=" + agent, executable] + arguments
executable = "/usr/bin/env"
}
let result = await commands.run(
directory: NSHomeDirectory(), executable: executable, arguments: arguments, timeout: timeout
)
if let failure = result.executionError {
try Task.checkCancellation()
throw SSHTuiPreflightError.launchFailed(failure)
}
if result.timedOut { throw SSHTuiPreflightError.timedOut }
// 255 is OpenSSH's own failure. Any other status came from the remote
// `true`, so the route works and the carrier owns what follows.
if result.exitStatus == 255 { throw SSHTuiPreflightError.sshFailed(result.stderr ?? "") }
}
}

public enum SSHTuiPreflightError: LocalizedError, Equatable, Sendable {
/// OpenSSH failed its own connection; carries its standard error.
case sshFailed(String)
case timedOut
case launchFailed(String)

/// OpenSSH's whole standard error, or the empty string. Classify this, not
/// `diagnostic`, so chatty ProxyCommand output cannot push a marker out.
public var standardError: String {
guard case .sshFailed(let output) = self else { return "" }
return output
}

/// OpenSSH's diagnostic without blank lines, or the empty string.
public var diagnostic: String {
standardError.split(whereSeparator: \.isNewline)
.map { $0.trimmingCharacters(in: .whitespaces) }
.filter { !$0.isEmpty }
.suffix(8)
.joined(separator: "\n")
}

/// Whether the route stopped before OpenSSH could authenticate. A
/// ProxyCommand waiting on a login it cannot show stalls here, and an
/// interactive run lets that prompt reach the user.
public var stalledBeforeAuthentication: Bool {
switch self {
case .timedOut: return true
case .sshFailed: return standardError.localizedCaseInsensitiveContains("timed out during banner exchange")
case .launchFailed: return false
}
}

public var errorDescription: String? {
switch self {
case .sshFailed:
let diagnostic = diagnostic
return diagnostic.isEmpty
? String(localized: "cloud.link.sshPreflight.failed", defaultValue: "SSH could not connect to the host.")
: diagnostic
case .timedOut:
return String(localized: "cloud.link.sshPreflight.timedOut", defaultValue: "SSH did not finish connecting in time.")
case .launchFailed(let detail):
return String(
format: String(localized: "cloud.link.sshPreflight.launchFailed", defaultValue: "SSH could not be started: %@"),
detail
)
}
}
}
177 changes: 177 additions & 0 deletions Resources/Localizable.xcstrings
Original file line number Diff line number Diff line change
Expand Up @@ -519648,6 +519648,183 @@
}
}
},
"cloud.link.sshPreflight.failed": {
"extractionState": "manual",
"localizations": {
Comment thread
austinywang marked this conversation as resolved.
Resolved
"en": {
"stringUnit": {
"state": "translated",
"value": "SSH could not connect to the host."
}
},
"de": {
"stringUnit": {
"state": "translated",
"value": "SSH konnte keine Verbindung zum Host herstellen."
}
},
"fr": {
"stringUnit": {
"state": "translated",
"value": "SSH n'a pas pu se connecter à l'hôte."
}
},
"ar": {
"stringUnit": {
"state": "translated",
"value": "تعذّر على SSH الاتصال بالمضيف."
}
},
"es": {
"stringUnit": {
"state": "translated",
"value": "SSH no pudo conectarse al host."
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "SSH 無法連線到主機。"
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "SSH 无法连接到主机。"
}
},
"ko": {
"stringUnit": {
"state": "translated",
"value": "SSH가 호스트에 연결할 수 없습니다."
}
},
"ja": {
"stringUnit": {
"state": "translated",
"value": "SSH でホストに接続できませんでした。"
}
}
}
},
"cloud.link.sshPreflight.timedOut": {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "SSH did not finish connecting in time."
}
},
"de": {
"stringUnit": {
"state": "translated",
"value": "SSH hat den Verbindungsaufbau nicht rechtzeitig abgeschlossen."
}
},
"fr": {
"stringUnit": {
"state": "translated",
"value": "SSH n'a pas terminé la connexion à temps."
}
},
"ar": {
"stringUnit": {
"state": "translated",
"value": "لم يُكمل SSH الاتصال في الوقت المحدد."
}
},
"es": {
"stringUnit": {
"state": "translated",
"value": "SSH no terminó de conectarse a tiempo."
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "SSH 未能及時完成連線。"
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "SSH 未能及时完成连接。"
}
},
"ko": {
"stringUnit": {
"state": "translated",
"value": "SSH가 제시간에 연결을 완료하지 못했습니다."
}
},
"ja": {
"stringUnit": {
"state": "translated",
"value": "SSH の接続が時間内に完了しませんでした。"
}
}
}
},
"cloud.link.sshPreflight.launchFailed": {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "SSH could not be started: %@"
}
},
"de": {
"stringUnit": {
"state": "translated",
"value": "SSH konnte nicht gestartet werden: %@"
}
},
"fr": {
"stringUnit": {
"state": "translated",
"value": "Impossible de démarrer SSH : %@"
}
},
"ar": {
"stringUnit": {
"state": "translated",
"value": "تعذّر بدء SSH: %@"
}
},
"es": {
"stringUnit": {
"state": "translated",
"value": "No se pudo iniciar SSH: %@"
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "無法啟動 SSH:%@"
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "无法启动 SSH:%@"
}
},
"ko": {
"stringUnit": {
"state": "translated",
"value": "SSH를 시작할 수 없습니다: %@"
}
},
"ja": {
"stringUnit": {
"state": "translated",
"value": "SSH を起動できませんでした: %@"
}
}
}
},
"cloud.workspace.ambiguousName": {
"extractionState": "manual",
"localizations": {
Expand Down
34 changes: 33 additions & 1 deletion Sources/RemoteTui/SSHTuiLinkManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ actor SSHTuiLinkManager: RemoteTuiLinkManaging {
private let isEnabled: @Sendable () -> Bool
private var current: CloudMachineLink?
private var connecting: Task<CloudMachineLink.Connected, Error>?
private var checking: Task<Void, Error>?
private var browser: CloudBrowserProxyProcess?
private var browserStarting: Task<CloudBrowserProxyEndpoint, Error>?

Expand All @@ -23,16 +24,45 @@ actor SSHTuiLinkManager: RemoteTuiLinkManaging {
}

func connected(machineID: String) async throws -> CloudMachineLink.Connected {
try await connected(machineID: machineID, preflight: false)
}

/// With `preflight`, a prompt-free `ssh … true` runs before the carrier
/// starts, so an explicit open reports OpenSSH's failure in seconds like
/// `ssh`. Restores and reconnects skip it: the carrier's own retries wait
/// for a host or an agent that comes back, with one login per link.
func connected(machineID: String, preflight: Bool) async throws -> CloudMachineLink.Connected {
guard machineID == connection.id else { throw CancellationError() }
guard isEnabled() else { await disconnect(); throw CancellationError() }
if let current, await current.isConnected, let ready = await current.connected { return ready }
// The preflight spends from a new carrier's startup budget, which the
// socket call's own deadline was sized around. A carrier a restore
// started during the check keeps its own budget.
let deadline = ContinuousClock.now + .seconds(180)
if preflight {
// Opens share one check, so a route asks for one login at a time.
// Only opens wait on it: a restore arriving meanwhile starts or
// joins the carrier on its own, and an open behind a restore's
// retrying carrier still fails in seconds.
let check = checking ?? Task { try await SSHTuiPreflight(connection: connection).run() }
checking = check
defer { if checking == check { checking = nil } }
let failure: Error?
do { try await check.value; failure = nil } catch { failure = error }
try Task.checkCancellation()
guard isEnabled() else { await disconnect(); throw CancellationError() }
// A carrier that logged in meanwhile answers the open, whatever
// the check reported before it.
if let current, await current.isConnected, let ready = await current.connected { return ready }
if let failure { throw failure }
}
if let connecting { return try await connecting.value }
let link = CloudMachineLink(machineID: machineID, clientURL: clientURL, paths: paths)
current = link
let attempt = Task {
try await link.connect(route: "ssh://" + connection.configuration.destination,
session: connection.session, carrier: true,
timeout: .seconds(180), ssh: connection)
timeout: deadline - ContinuousClock.now, ssh: connection)
}
connecting = attempt
defer { if connecting == attempt { connecting = nil } }
Expand Down Expand Up @@ -83,6 +113,8 @@ actor SSHTuiLinkManager: RemoteTuiLinkManaging {
let attempt = connecting
connecting = nil
attempt?.cancel()
checking?.cancel()
checking = nil
browserStarting?.cancel()
browserStarting = nil
let proxy = browser
Expand Down
Loading
Loading