Repository navigation
Expand file tree
/
Copy pathUIKitSshTerminalView.swift
More file actions
463 lines (403 loc) · 15.4 KB
/
Copy pathUIKitSshTerminalView.swift
File metadata and controls
463 lines (403 loc) · 15.4 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
//
// UIKitSshTerminalView.swift
// iOS
//
// Created by Miguel de Icaza on 4/22/20.
// Copyright © 2020 Miguel de Icaza. All rights reserved.
//
import Foundation
import UIKit
import SwiftTerm
import NIOCore
import NIOPosix
import NIOSSH
struct SSHConnectionInfo: Equatable, Sendable {
let host: String
let port: Int
let username: String
let password: String
let term: String
let environment: [String: String]
init(
host: String = "localhost",
port: Int = 22,
username: String,
password: String,
term: String = "xterm-256color",
environment: [String: String] = ["LANG": "en_US.UTF-8"]
) {
self.host = host
self.port = port
self.username = username
self.password = password
self.term = term
self.environment = environment
}
}
private enum SSHClientError: Error {
case invalidChannelType
}
private final class AcceptAllHostKeysDelegate: NIOSSHClientServerAuthenticationDelegate {
func validateHostKey(hostKey: NIOSSHPublicKey, validationCompletePromise: EventLoopPromise<Void>) {
validationCompletePromise.succeed(())
}
}
private final class SSHErrorHandler: ChannelInboundHandler {
typealias InboundIn = Any
private let onError: @Sendable (Error) -> Void
init(onError: @escaping @Sendable (Error) -> Void) {
self.onError = onError
}
func errorCaught(context: ChannelHandlerContext, error: Error) {
onError(error)
context.close(promise: nil)
}
}
private final class SSHShellChannelHandler: ChannelInboundHandler {
typealias InboundIn = SSHChannelData
private let feedSender: TerminalFeedSender
private let term: String
private let environment: [String: String]
private let initialWindowSize: (cols: Int, rows: Int)
init(
feedSender: TerminalFeedSender,
term: String,
environment: [String: String],
initialWindowSize: (cols: Int, rows: Int)
) {
self.feedSender = feedSender
self.term = term
self.environment = environment
self.initialWindowSize = initialWindowSize
}
func handlerAdded(context: ChannelHandlerContext) {
let pipeline = context.pipeline
context.channel.setOption(ChannelOptions.allowRemoteHalfClosure, value: true).whenFailure { error in
pipeline.fireErrorCaught(error)
}
}
func channelActive(context: ChannelHandlerContext) {
let pty = SSHChannelRequestEvent.PseudoTerminalRequest(
wantReply: false,
term: term,
terminalCharacterWidth: initialWindowSize.cols,
terminalRowHeight: initialWindowSize.rows,
terminalPixelWidth: 0,
terminalPixelHeight: 0,
terminalModes: SSHTerminalModes([:])
)
context.triggerUserOutboundEvent(pty, promise: nil)
for (name, value) in environment {
let env = SSHChannelRequestEvent.EnvironmentRequest(wantReply: false, name: name, value: value)
context.triggerUserOutboundEvent(env, promise: nil)
}
context.triggerUserOutboundEvent(SSHChannelRequestEvent.ShellRequest(wantReply: false), promise: nil)
}
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
let payload = unwrapInboundIn(data)
guard case .byteBuffer(var buffer) = payload.data else {
return
}
guard let bytes = buffer.readBytes(length: buffer.readableBytes), !bytes.isEmpty else {
return
}
let chunkSize = 1024
var next = 0
while next < bytes.count {
let end = min(next + chunkSize, bytes.count)
let chunk = bytes[next..<end]
// feed is thread-safe as of the terminal-lock work; keep parsing on the NIO channel thread.
feedSender.feed(byteArray: chunk)
next = end
}
}
func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {
if let status = event as? SSHChannelRequestEvent.ExitStatus {
feedSender.feed(text: "\n[SSH] Session exited with status \(status.exitStatus)\n")
} else if let signal = event as? SSHChannelRequestEvent.ExitSignal {
feedSender.feed(text: "\n[SSH] Session closed: \(signal.signalName)\n")
} else {
context.fireUserInboundEventTriggered(event)
}
}
}
@MainActor
private final class SSHConnection {
private let feedSender: TerminalFeedSender
private let host: String
private let port: Int
private let username: String
private let password: String
private let term: String
private let environment: [String: String]
private let initialWindowSize: (cols: Int, rows: Int)
private var group: EventLoopGroup?
private var channel: Channel?
private var sessionChannel: Channel?
init(
feedSender: TerminalFeedSender,
host: String,
port: Int,
username: String,
password: String,
term: String,
environment: [String: String],
initialWindowSize: (cols: Int, rows: Int)
) {
self.feedSender = feedSender
self.host = host
self.port = port
self.username = username
self.password = password
self.term = term
self.environment = environment
self.initialWindowSize = initialWindowSize
}
func connect() {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
self.group = group
let username = username
let password = password
let reportError: @Sendable (Error) -> Void = { [weak self] error in
Task { @MainActor [weak self] in
self?.handleError(error)
}
}
let bootstrap = ClientBootstrap(group: group)
.channelInitializer { channel in
channel.eventLoop.makeCompletedFuture {
let sshHandler = NIOSSHHandler(
role: .client(
.init(
userAuthDelegate: SimplePasswordDelegate(
username: username,
password: password
),
serverAuthDelegate: AcceptAllHostKeysDelegate()
)
),
allocator: channel.allocator,
inboundChildChannelInitializer: nil
)
try channel.pipeline.syncOperations.addHandler(sshHandler)
try channel.pipeline.syncOperations.addHandler(
SSHErrorHandler(onError: reportError)
)
}
}
.channelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
.channelOption(ChannelOptions.socket(SocketOptionLevel(IPPROTO_TCP), TCP_NODELAY), value: 1)
bootstrap.connect(host: host, port: port).whenComplete { [weak self] result in
Task { @MainActor [weak self] in
self?.connectionCompleted(result)
}
}
}
func send(_ data: Data) {
guard let sessionChannel else { return }
sessionChannel.eventLoop.execute {
var buffer = sessionChannel.allocator.buffer(capacity: data.count)
buffer.writeBytes(data)
let payload = SSHChannelData(type: .channel, data: .byteBuffer(buffer))
sessionChannel.writeAndFlush(payload, promise: nil)
}
}
func resize(cols: Int, rows: Int) {
guard cols > 0, rows > 0, let sessionChannel else { return }
sessionChannel.eventLoop.execute {
let event = SSHChannelRequestEvent.WindowChangeRequest(
terminalCharacterWidth: cols,
terminalRowHeight: rows,
terminalPixelWidth: 0,
terminalPixelHeight: 0
)
sessionChannel.triggerUserOutboundEvent(event, promise: nil)
}
}
func disconnect() {
let channel = channel
let group = group
self.channel = nil
sessionChannel = nil
self.group = nil
if let channel, let group {
channel.closeFuture.whenComplete { _ in
group.shutdownGracefully { _ in }
}
channel.close(promise: nil)
} else if let group {
group.shutdownGracefully { _ in }
}
}
private func connectionCompleted(_ result: Result<Channel, Error>) {
switch result {
case .failure(let error):
handleError(error)
disconnect()
case .success(let channel):
guard group != nil else {
channel.close(promise: nil)
return
}
self.channel = channel
createSessionChannel(on: channel)
}
}
private func createSessionChannel(on channel: Channel) {
let feedSender = feedSender
let term = term
let environment = environment
let initialWindowSize = initialWindowSize
let reportError: @Sendable (Error) -> Void = { [weak self] error in
Task { @MainActor [weak self] in
self?.handleError(error)
}
}
channel.pipeline.handler(type: NIOSSHHandler.self).flatMap { sshHandler in
let promise = channel.eventLoop.makePromise(of: Channel.self)
sshHandler.createChannel(promise, channelType: .session) { childChannel, channelType in
guard channelType == .session else {
return channel.eventLoop.makeFailedFuture(SSHClientError.invalidChannelType)
}
return childChannel.eventLoop.makeCompletedFuture {
let handler = SSHShellChannelHandler(
feedSender: feedSender,
term: term,
environment: environment,
initialWindowSize: initialWindowSize
)
let sync = childChannel.pipeline.syncOperations
try sync.addHandler(handler)
try sync.addHandler(SSHErrorHandler(onError: reportError))
}
}
return promise.futureResult
}.whenComplete { [weak self] result in
Task { @MainActor [weak self] in
self?.sessionChannelCompleted(result)
}
}
}
private func sessionChannelCompleted(_ result: Result<Channel, Error>) {
switch result {
case .failure(let error):
handleError(error)
case .success(let childChannel):
guard channel != nil else {
childChannel.close(promise: nil)
return
}
sessionChannel = childChannel
resize(cols: initialWindowSize.cols, rows: initialWindowSize.rows)
}
}
private func handleError(_ error: Error) {
feedSender.feed(text: "[ERROR] \(error)\n")
}
}
public class SshTerminalView: TerminalView, TerminalViewDelegate {
private var sshConnection: SSHConnection?
private var configuredInfo: SSHConnectionInfo?
public override init (frame: CGRect)
{
let options = TerminalOptions(
// iTerm2 feature report for OSC 1337 Capabilities. The library
// default is nil, which suppresses the reply, because parts of
// the report depend on the host. See the MacTerminal sample for
// the meaning of each flag.
featureReport: "T3CwLrMSc7UUw17Ts3BFGsSyHSxP",
// The library default is empty. This app serves both clipboard
// directions; see kittyClipboardRequestPermission below.
kittyClipboardPolicy: .all)
super.init (frame: frame, font: nil, options: options)
terminalDelegate = self
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func configure(connectionInfo: SSHConnectionInfo) {
if configuredInfo == connectionInfo {
return
}
configuredInfo = connectionInfo
let previousConnection = sshConnection
sshConnection = nil
previousConnection?.disconnect()
startConnection(connectionInfo: connectionInfo)
DispatchQueue.main.async { [weak self] in
_ = self?.becomeFirstResponder()
}
}
/// Permanently stops the SSH session. The UI owner must call this before
/// it releases the terminal view.
func disconnectSSH() {
configuredInfo = nil
let connection = sshConnection
sshConnection = nil
connection?.disconnect()
}
private func startConnection(connectionInfo: SSHConnectionInfo) {
let dimensions = terminalDimensions
let cols = dimensions.cols > 0 ? dimensions.cols : 80
let rows = dimensions.rows > 0 ? dimensions.rows : 24
let connection = SSHConnection(
feedSender: feedSender,
host: connectionInfo.host,
port: connectionInfo.port,
username: connectionInfo.username,
password: connectionInfo.password,
term: connectionInfo.term,
environment: connectionInfo.environment,
initialWindowSize: (cols: cols, rows: rows)
)
sshConnection = connection
connection.connect()
}
// TerminalViewDelegate conformance
public func scrolled(source: TerminalView, position: Double) {
//
}
public func setTerminalTitle(source: TerminalView, title: String) {
//
}
public func sizeChanged(source: TerminalView, newCols: Int, newRows: Int) {
sshConnection?.resize(cols: newCols, rows: newRows)
}
public func send(source: TerminalView, data: ArraySlice<UInt8>) {
sshConnection?.send(Data(data))
}
public func clipboardCopy(source: TerminalView, content: Data) {
if let str = String (bytes: content, encoding: .utf8) {
UIPasteboard.general.string = str
}
}
public func hostCurrentDirectoryUpdate(source: TerminalView, directory: String?) {
}
// MARK: Kitty clipboard protocol, OSC 5522
//
// The library denies clipboard access by default. Stating the complete
// standard-clipboard service here, with the policy in the options above,
// is what makes DEC private mode 5522 report as supported.
public func kittyClipboardCapabilities(source: TerminalView) -> KittyClipboardCapabilities {
// iOS has no primary selection, so only the standard clipboard.
[.standardRead, .standardWrite]
}
public func kittyClipboardRequestPermission(
source: TerminalView,
request: KittyClipboardPermissionRequest
) -> KittyClipboardPermissionResult {
// This hook is synchronous and UIKit has no modal alert, so this
// sample allows the request. A shipping app should keep the answer
// for a program in its own settings and deny unknown programs.
.allow(rememberPassword: false)
}
public func requestOpenLink (source: TerminalView, link: String, params: [String:String])
{
if let url = URL(string: link) {
UIApplication.shared.open (url)
}
}
public func rangeChanged(source: SwiftTerm.TerminalView, startY: Int, endY: Int) {
// nothing
}
}