/
TTY.swift
256 lines (218 loc) · 9.38 KB
/
TTY.swift
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
import Foundation
import Logging
import NIO
import NIOSSH
public struct TTYSTDError: Error {
public let message: ByteBuffer
}
public struct ExecCommandStream {
public let stdout: AsyncThrowingStream<ByteBuffer, Error>
public let stderr: AsyncThrowingStream<ByteBuffer, Error>
struct Continuation {
let stdout: AsyncThrowingStream<ByteBuffer, Error>.Continuation
let stderr: AsyncThrowingStream<ByteBuffer, Error>.Continuation
func onOutput(_ output: ExecCommandHandler.Output) {
switch output {
case .stdout(let buffer):
stdout.yield(buffer)
case .stderr(let buffer):
stderr.yield(buffer)
case .eof(let error):
stdout.finish(throwing: error)
stderr.finish(throwing: error)
case .channelSuccess:
()
case .exit(0):
stdout.finish()
stderr.finish()
case .exit(let status):
stdout.finish(throwing: SSHClient.CommandFailed(exitCode: status))
stderr.finish(throwing: SSHClient.CommandFailed(exitCode: status))
}
}
}
}
public enum ExecCommandOutput {
case stdout(ByteBuffer)
case stderr(ByteBuffer)
}
final class ExecCommandHandler: ChannelDuplexHandler {
enum Output {
case channelSuccess
case stdout(ByteBuffer)
case stderr(ByteBuffer)
case eof(Error?)
case exit(Int)
}
typealias InboundIn = SSHChannelData
typealias InboundOut = ByteBuffer
typealias OutboundIn = ByteBuffer
typealias OutboundOut = SSHChannelData
let logger: Logger
let onOutput: (Channel, Output) -> ()
init(logger: Logger, onOutput: @escaping (Channel, Output) -> ()) {
self.logger = logger
self.onOutput = onOutput
}
func handlerAdded(context: ChannelHandlerContext) {
context.channel.setOption(ChannelOptions.allowRemoteHalfClosure, value: true).whenFailure { error in
context.fireErrorCaught(error)
}
}
func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {
switch event {
case is NIOSSH.ChannelSuccessEvent:
onOutput(context.channel, .channelSuccess)
case is NIOSSH.ChannelFailureEvent:
onOutput(context.channel, .eof(CitadelError.channelFailure))
case let status as SSHChannelRequestEvent.ExitStatus:
onOutput(context.channel, .exit(status.exitStatus))
default:
context.fireUserInboundEventTriggered(event)
}
}
func handlerRemoved(context: ChannelHandlerContext) {
onOutput(context.channel, .eof(nil))
}
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
let data = self.unwrapInboundIn(data)
guard case .byteBuffer(let buffer) = data.data else {
logger.error("Unable to process channelData for executed command. Data was not a ByteBuffer")
return onOutput(context.channel, .eof(SSHExecError.invalidData))
}
switch data.type {
case .channel:
onOutput(context.channel, .stdout(buffer))
case .stdErr:
onOutput(context.channel, .stderr(buffer))
default:
// We don't know this std channel
()
}
}
func errorCaught(context: ChannelHandlerContext, error: Error) {
onOutput(context.channel, .eof(error))
}
}
extension SSHClient {
public struct CommandFailed: Error {
public let exitCode: Int
}
/// Executes a command on the remote server. This will return the output of the command (stdout). If the command fails, the error will be thrown. If the output is too large, the command will fail.
/// - Parameters:
/// - command: The command to execute.
/// - maxResponseSize: The maximum size of the response. If the response is larger, the command will fail.
/// - mergeStreams: If the answer should also include stderr.
/// - inShell: Whether to request the remote server to start a shell before executing the command.
public func executeCommand(_ command: String, maxResponseSize: Int = .max, mergeStreams: Bool = false, inShell: Bool = false) async throws -> ByteBuffer {
var result = ByteBuffer()
let stream = try await executeCommandStream(command, inShell: inShell)
for try await chunk in stream {
switch chunk {
case .stderr(let chunk):
guard mergeStreams else {
continue
}
fallthrough
case .stdout(let chunk):
let newResponseSize = chunk.readableBytes + result.readableBytes
if newResponseSize > maxResponseSize {
throw CitadelError.commandOutputTooLarge
}
result.writeImmutableBuffer(chunk)
}
}
return result
}
/// Executes a command on the remote server. This will return the output stream of the command. If the command fails, the error will be thrown.
/// - Parameters:
/// - command: The command to execute.
/// - inShell: Whether to request the remote server to start a shell before executing the command.
public func executeCommandStream(_ command: String, inShell: Bool = false) async throws -> AsyncThrowingStream<ExecCommandOutput, Error> {
var streamContinuation: AsyncThrowingStream<ExecCommandOutput, Error>.Continuation!
let stream = AsyncThrowingStream<ExecCommandOutput, Error>(bufferingPolicy: .unbounded) { continuation in
streamContinuation = continuation
}
var hasReceivedChannelSuccess = false
let handler = ExecCommandHandler(logger: logger) { channel, output in
switch output {
case .stdout(let stdout):
streamContinuation.yield(.stdout(stdout))
case .stderr(let stderr):
streamContinuation.yield(.stderr(stderr))
case .eof(let error):
streamContinuation.finish(throwing: error)
case .channelSuccess:
if inShell, !hasReceivedChannelSuccess {
let commandData = SSHChannelData(type: .channel,
data: .byteBuffer(ByteBuffer(string: command + ";exit\n")))
channel.writeAndFlush(commandData, promise: nil)
hasReceivedChannelSuccess = true
}
case .exit(let status):
if status == 0 {
streamContinuation.finish()
} else {
streamContinuation.finish(throwing: CommandFailed(exitCode: status))
}
}
}
let channel = try await eventLoop.flatSubmit {
let createChannel = self.eventLoop.makePromise(of: Channel.self)
self.session.sshHandler.createChannel(createChannel) { channel, _ in
channel.pipeline.addHandlers(handler)
}
self.eventLoop.scheduleTask(in: .seconds(15)) {
createChannel.fail(CitadelError.channelCreationFailed)
}
return createChannel.futureResult
}.get()
if inShell {
try await channel.triggerUserOutboundEvent(SSHChannelRequestEvent.ShellRequest(
wantReply: true
))
} else {
try await channel.triggerUserOutboundEvent(SSHChannelRequestEvent.ExecRequest(
command: command,
wantReply: true
))
}
return stream
}
/// Executes a command on the remote server. This will return the pair of streams stdout and stderr of the command. If the command fails, the error will be thrown.
/// - Parameters:
/// - command: The command to execute.
public func executeCommandPair(_ command: String, inShell: Bool = false) async throws -> ExecCommandStream {
var stdoutContinuation: AsyncThrowingStream<ByteBuffer, Error>.Continuation!
var stderrContinuation: AsyncThrowingStream<ByteBuffer, Error>.Continuation!
let stdout = AsyncThrowingStream<ByteBuffer, Error>(bufferingPolicy: .unbounded) { continuation in
stdoutContinuation = continuation
}
let stderr = AsyncThrowingStream<ByteBuffer, Error>(bufferingPolicy: .unbounded) { continuation in
stderrContinuation = continuation
}
let handler = ExecCommandStream.Continuation(
stdout: stdoutContinuation,
stderr: stderrContinuation
)
Task {
do {
let stream = try await executeCommandStream(command, inShell: inShell)
for try await chunk in stream {
switch chunk {
case .stdout(let buffer):
handler.stdout.yield(buffer)
case .stderr(let buffer):
handler.stderr.yield(buffer)
}
}
handler.stdout.finish()
handler.stderr.finish()
} catch {
handler.stdout.finish(throwing: error)
handler.stderr.finish(throwing: error)
}
}
return ExecCommandStream(stdout: stdout, stderr: stderr)
}
}