forked from blinksh/blink
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMCPSession.m
419 lines (357 loc) · 12.6 KB
/
MCPSession.m
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
////////////////////////////////////////////////////////////////////////////////
//
// B L I N K
//
// Copyright (C) 2016-2018 Blink Mobile Shell Project
//
// This file is part of Blink.
//
// Blink is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Blink is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Blink. If not, see <http://www.gnu.org/licenses/>.
//
// In addition, Blink is also subject to certain additional terms under
// GNU GPL version 3 section 7.
//
// You should have received a copy of these additional terms immediately
// following the terms and conditions of the GNU General Public License
// which accompanied the Blink Source Code. If not, see
// <http://www.github.com/blinksh/blink>.
//
////////////////////////////////////////////////////////////////////////////////
#include <stdio.h>
#include <string.h>
#include <libgen.h>
#include <sys/stat.h>
#include <dispatch/dispatch.h>
#import "MCPSession.h"
#import "MoshSession.h"
#import "BKPubKey.h"
#import "SSHCopyIDSession.h"
#import "SSHSession.h"
#import "BKUserConfigurationManager.h"
#import "BlinkPaths.h"
#include <ios_system/ios_system.h>
#include "ios_error.h"
#include "Blink-Swift.h"
@implementation MCPSession {
NSString * _sessionUUID;
Session *_childSession;
NSString *_currentCmd;
NSMutableArray *_sshClients;
// dispatch_queue_t _cmdQueue;
dispatch_queue_t _sshQueue;
TermStream *_cmdStream;
NSString *_currentCmdLine;
}
@dynamic sessionParams;
- (id)initWithDevice:(TermDevice *)device andParams:(MCPParams *)params {
if (self = [super initWithDevice:device andParams:params]) {
_sshClients = [[NSMutableArray alloc] init];
_sessionUUID = [[NSProcessInfo processInfo] globallyUniqueString];
_cmdQueue = dispatch_queue_create("mcp.command.queue", DISPATCH_QUEUE_SERIAL);
_sshQueue = dispatch_queue_create("mcp.sshclients.queue", DISPATCH_QUEUE_SERIAL);
[self setActiveSession];
}
return self;
}
- (void)executeWithArgs:(NSString *)args {
dispatch_async(_cmdQueue, ^{
[self setActiveSession];
ios_setStreams(_stream.in, _stream.out, _stream.out);
NSString *homePath = [BlinkPaths homePath];
ios_setMiniRoot(homePath);
[[NSFileManager defaultManager] changeCurrentDirectoryPath:homePath];
[self updateAllowedPaths];
// We are restoring mosh session if possible first.
if ([@"mosh" isEqualToString:self.sessionParams.childSessionType] && self.sessionParams.hasEncodedState) {
BlinkMosh *mosh = [[BlinkMosh alloc] initWithMcpSession: self device:_device andParams:self.sessionParams.childSessionParams];
_childSession = mosh;
[_childSession executeAttachedWithArgs:@""];
_childSession = nil;
if (self.sessionParams.hasEncodedState) {
return;
}
}
if ([@"mosh1" isEqualToString:self.sessionParams.childSessionType] && self.sessionParams.hasEncodedState) {
MoshSession *mosh = [[MoshSession alloc] initWithDevice:_device andParams:self.sessionParams.childSessionParams];
mosh.mcpSession = self;
_childSession = mosh;
[_childSession executeAttachedWithArgs:@""];
_childSession = nil;
if (self.sessionParams.hasEncodedState) {
return;
}
}
#if TARGET_OS_MACCATALYST
BKHosts *localhost = [BKHosts withHost:@"localhost"];
if (localhost) {
NSString *sshcmd = [NSString stringWithFormat: @"ssh -A %@", localhost.host];
[self enqueueCommand:sshcmd];
} else {
[_device prompt:@"blink> " secure:NO shell:YES];
}
#else
[_device prompt:@"blink> " secure:NO shell:YES];
#endif
});
}
/*!
@brief Enqueue a new command coming from a x-callback-url. After completing successfully return to the
@discussion Accepts the x-callback-url and the x-success URL to call after a successful command completion
@param cmd Command to be executed
@param xCallbackSuccessUrl Success URL of the original application (like Shortcuts) to return to after reunning the command
*/
- (void)enqueueXCallbackCommand:(NSString *)cmd xCallbackSuccessUrl:(NSURL *)xCallbackSuccessUrl {
[self enqueueCommand:cmd];
dispatch_async(_cmdQueue, ^{
blink_openurl(xCallbackSuccessUrl);
});
}
- (void)enqueueCommand:(NSString *)cmd {
[self enqueueCommand:cmd skipHistoryRecord:NO];
}
- (void)enqueueCommand:(NSString *)cmd skipHistoryRecord: (BOOL) skipHistoryRecord {
// NOTE This shouldn't be done this way. The MCP should read from, but not write to the input.
// The terminal device in this case is acting like a shell, which is not fully wrong, but I don't like it.
// The terminal view is also receiving requests for "what's being typed" in order to then do Completion, etc...
if (_cmdStream) {
[_device writeInDirectly:[NSString stringWithFormat: @"%@\n", cmd]];
return;
}
dispatch_async(_cmdQueue, ^{
self->_currentCmdLine = cmd;
[self _runCommand:cmd skipHistoryRecord:skipHistoryRecord];
self->_currentCmdLine = nil;
});
}
- (BOOL)_runCommand:(NSString *)cmdline skipHistoryRecord: (BOOL) skipHistoryRecord {
cmdline = [cmdline stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
if (!skipHistoryRecord) {
[HistoryObj appendIfNeededWithCommand:cmdline];
}
NSString *mayBeURLString = [cmdline stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSURL *mayBeHttpURL = [NSURL URLWithString:mayBeURLString];
NSString *scheme = mayBeHttpURL.scheme.lowercaseString;
if ([@"http" isEqual: scheme] || [@"https" isEqual:scheme]) {
cmdline = [NSString stringWithFormat:@"browse %@", mayBeURLString];
}
NSArray *arr = [cmdline componentsSeparatedByString:@" "];
NSString *cmd = arr[0];
if ([cmd isEqualToString:@"exit"]) {
dispatch_async(dispatch_get_main_queue(), ^{
[self.delegate sessionFinished];
});
return NO;
}
if ([cmd isEqualToString:@"mosh"]) {
[self _runMoshWithArgs:cmdline];
if (self.sessionParams.hasEncodedState) {
return NO;
}
} else if ([cmd isEqualToString:@"mosh1"]) {
[self _runMosh1WithArgs:cmdline];
if (self.sessionParams.hasEncodedState) {
return NO;
}
} else if ([cmd isEqualToString:@"ssh2"]) {
[self _runSSHWithArgs:cmdline];
} else if ([cmd isEqualToString:@"ssh-copy-id"]) {
[self _runSSHCopyIDWithArgs:cmdline];
} else if (![cmd isEqualToString:@""]) {
// Manually set raw mode for some commands, as we cannot receive control any other way.
[_device closeReadline];
if ([cmd isEqualToString:@"less"] || [cmd isEqualToString:@"vim"]) {
self.device.rawMode = true;
self.device.autoCR = TRUE;
}
[self setActiveSession];
_currentCmd = cmdline;
_cmdStream = [_device.stream duplicate];
ios_setStreams(_cmdStream.in, _cmdStream.out, _cmdStream.out);
// ios_system provides a get command that returns a "tty" instead of an open. We can control it here.
FILE* tty = [_cmdStream openTTY];
ios_settty(tty);
ios_setWindowSize((int)self.device.cols, (int)self.device.rows, _sessionUUID.UTF8String);
pid_t _pid = ios_fork();
ios_system(cmdline.UTF8String);
_currentCmd = nil;
ios_waitpid(_pid);
ios_releaseThreadId(_pid);
self.device.autoCR = FALSE;
fclose(tty);
tty = nil;
[_cmdStream close];
_cmdStream = nil;
_sshClients = [[NSMutableArray alloc] init];
}
[_device prompt:@"blink> " secure:NO shell:YES];
return YES;
}
- (int)main:(int)argc argv:(char **)argv
{
return 0;
}
- (void)registerSSHClient:(id __weak)sshClient {
dispatch_sync(_sshQueue, ^(void){
[_sshClients addObject:sshClient];
});
}
- (void)unregisterSSHClient:(id __weak)sshClient {
dispatch_sync(_sshQueue, ^(void){
[_sshClients removeObject:sshClient];
});
}
- (bool)isRunningCmd {
return _childSession != nil || _currentCmd != nil || _currentCmdLine != nil;
}
- (void)updateAllowedPaths
{
NSArray<NSString *>* allowedPaths = [BlinkPaths cleanedSymlinksInHomeDirectory];
ios_setAllowedPaths(allowedPaths);
}
- (void)_runSSHCopyIDWithArgs:(NSString *)args
{
self.sessionParams.childSessionParams = nil;
_childSession = [[SSHCopyIDSession alloc] initWithDevice:_device andParams:self.sessionParams.childSessionParams];
self.sessionParams.childSessionType = @"sshcopyid";
// duplicate args
NSString *str = [NSString stringWithFormat:@"%@", args];
[_childSession executeAttachedWithArgs:str];
_childSession = nil;
}
- (void)_runMoshWithArgs:(NSString *)args
{
self.sessionParams.childSessionParams = [[MoshParams alloc] init];
self.sessionParams.childSessionType = @"mosh";
BlinkMosh *mosh = [[BlinkMosh alloc] initWithMcpSession: self device:_device andParams:self.sessionParams.childSessionParams];
//MoshSession *mosh = [[MoshSession alloc] initWithDevice:_device andParams:self.sessionParams.childSessionParams];
//mosh.mcpSession = self;
_childSession = mosh;
// duplicate args
NSString *str = [NSString stringWithFormat:@"%@", args];
[_childSession executeAttachedWithArgs:str];
_childSession = nil;
}
- (void)_runMosh1WithArgs:(NSString *)args
{
self.sessionParams.childSessionParams = [[MoshParams alloc] init];
self.sessionParams.childSessionType = @"mosh1";
//BlinkMosh *mosh = [[BlinkMosh alloc] initWithMcpSession: self device:_device andParams:self.sessionParams.childSessionParams];
MoshSession *mosh = [[MoshSession alloc] initWithDevice:_device andParams:self.sessionParams.childSessionParams];
mosh.mcpSession = self;
_childSession = mosh;
// duplicate args
NSString *str = [NSString stringWithFormat:@"%@", args];
[_childSession executeAttachedWithArgs:str];
_childSession = nil;
}
- (void)_runSSHWithArgs:(NSString *)args
{
self.sessionParams.childSessionParams = nil;
_childSession = [[SSHSession alloc] initWithDevice:_device andParams:self.sessionParams.childSessionParams];
self.sessionParams.childSessionType = @"ssh";
[_childSession executeAttachedWithArgs:args];
_childSession = nil;
}
- (void)sigwinch
{
[self setActiveSession];
ios_setWindowSize((int)self.device.cols, (int)self.device.rows, _sessionUUID.UTF8String);
[_childSession sigwinch];
dispatch_sync(_sshQueue, ^{
for (id client in _sshClients) {
[client sigwinch];
}
});
}
// TODO It would be nice if this could be re-used (interrupt children, interrupt yourself).
- (void)kill
{
if (_sshClients.count > 0) {
dispatch_sync(_sshQueue, ^{
for (id client in _sshClients) {
[client kill];
}
});
return;
} else if (_childSession) {
[_childSession kill];
} else if (_cmdStream) {
[self setActiveSession];
ios_kill();
}
ios_closeSession(_sessionUUID.UTF8String);
[_device close];
}
- (void)suspend
{
[self setActiveSession];
[_childSession suspend];
}
- (void)handleControl:(NSString *)control
{
NSString *ctrlC = @"\x03";
NSString *ctrlD = @"\x04";
if (_childSession) {
if (_sshClients.count > 0) {
dispatch_sync(_sshQueue, ^{
for (id client in _sshClients) {
[client kill];
}
});
}
return;
} else if (_currentCmd) {
if ([control isEqualToString:ctrlD]) {
// We give a chance to the session to capture the new stdin, as it may have changed.
[self setActiveSession];
if (_cmdStream != NULL) {
[_cmdStream close];
_cmdStream = NULL;
_cmdStream = [_device.stream duplicate];
}
ios_setStreams(_cmdStream.in, _cmdStream.out, _cmdStream.out);
return;
}
if ([control isEqualToString:ctrlC]) {
if (_sshClients.count > 0) {
dispatch_sync(_sshQueue, ^{
for (id client in _sshClients) {
[client kill];
}
});
} else {
if (_tokioSignals) {
[_tokioSignals signalCtrlC];
_tokioSignals = nil;
} else {
[self setActiveSession];
ios_kill();
}
}
return;
}
}
return;
}
- (void)setActiveSession {
// Need to reset all thread variables, including context!
// This fixes "segmentation faults" after a few subsequent session - new command cycles.
thread_context = NULL;
ios_switchSession(_sessionUUID.UTF8String);
ios_setContext((__bridge void*)self);
thread_stdout = NULL;
thread_stdin = NULL;
thread_stderr = NULL;
}
@end