forked from holzschu/ios_system
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathios_system.m
2001 lines (1876 loc) · 91.6 KB
/
ios_system.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
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
//
// ios_system.m
//
// Created by Nicolas Holzschuch on 17/11/2017.
// Copyright © 2017 N. Holzschuch. All rights reserved.
//
#import <Foundation/Foundation.h>
#include "ios_system.h"
// ios_system(cmd): Executes the command in "cmd". The goal is to be a drop-in replacement for system(), as much as possible.
// We assume cmd is the command. If vim has prepared '/bin/sh -c "(command -arguments) < inputfile > outputfile",
// it is easier to remove the "/bin/sh -c" part before calling ios_system than inside ios_system.
// See example in (iVim) os_unix.c
//
// ios_executable(cmd): returns true if the command is one of the commands defined in ios_system, and can be executed.
// This is because mch_can_exe (called by executable()) checks for the existence of binaries with the same name in the
// path. Our commands don't exist in the path.
//
// ios_popen(cmd, type): returns a FILE*, executes cmd, and thread_output into input of cmd (if type=="w") or
// the reverse (if type == "r").
#include <pthread.h>
#include <sys/stat.h>
#include <libgen.h> // for basename()
#include <dlfcn.h> // for dlopen()/dlsym()/dlclose()
#include <glob.h> // for wildcard expansion
// Sideloading: when you compile yourself, as opposed to uploading on the app store
// If true, all commands are enabled + debug messages if dylib not found.
// If false, you get a smaller set, but compliance with AppStore rules.
// *Must* be false in the main branch releases.
// Commands that can be enabled only if sideLoading: ctags, readtags, chgrp, chown, chmod, df, id, w.
bool sideLoading = false;
// Should the main thread be joined (which means it takes priority over other tasks)?
// Default value is true, which makes sense for shell-like applications.
// Should be set to false if significant user interaction is carried by the app and
// the app takes responsibility for waiting for the command to terminate.
bool joinMainThread = true;
// Include file for getrlimit/setrlimit:
#include <sys/resource.h>
static struct rlimit limitFilesOpen;
extern __thread int __db_getopt_reset;
__thread FILE* thread_stdin;
__thread FILE* thread_stdout;
__thread FILE* thread_stderr;
__thread void* thread_context;
// Parameters for each session. We can have multiple sessions running in parallel.
typedef struct _sessionParameters {
bool isMainThread; // are we on the first command?
char currentDir[MAXPATHLEN];
char previousDirectory[MAXPATHLEN];
char localMiniRoot[MAXPATHLEN];
pthread_t current_command_root_thread; // thread ID of first command
pthread_t lastThreadId; // thread ID of last command
FILE* stdin;
FILE* stdout;
FILE* stderr;
FILE* tty;
void* context;
int global_errno;
char commandName[NAME_MAX];
char columns[4];
char lines[4];
} sessionParameters;
static void initSessionParameters(sessionParameters* sp) {
NSFileManager *fileManager = [[NSFileManager alloc] init];
sp->isMainThread = TRUE;
sp->current_command_root_thread = 0;
sp->lastThreadId = 0;
NSString* currentDirectory = [fileManager currentDirectoryPath];
strcpy(sp->currentDir, [currentDirectory UTF8String]);
strcpy(sp->previousDirectory, [currentDirectory UTF8String]);
sp->localMiniRoot[0] = 0;
sp->global_errno = 0;
sp->stdin = stdin;
sp->stdout = stdout;
sp->stderr = stderr;
sp->tty = stdin;
sp->context = nil;
sp->commandName[0] = 0;
strcpy(sp->columns, "80");
strcpy(sp->lines, "80");
}
static NSMutableDictionary* sessionList;
// pointer to sessionParameters. thread-local variable so the entire system is thread-safe.
// The sessionParameters pointer is shared by all threads in the same session.
static __thread sessionParameters* currentSession;
// Python3 multiple interpreters:
// limit to 6 = 1 kernel, 4 notebooks, one extra.
// App Store limit is 200 MB
static const int MaxPythonInterpreters = 6; // const so we can allocate an array
int numPythonInterpreters = MaxPythonInterpreters; // Apps can overwrite this
static bool PythonIsRunning[MaxPythonInterpreters];
static int currentPythonInterpreter = 0;
// pointers for sh sessions:
char* sh_session = "sh_session";
// replace system-provided exit() by our own:
// Make sure we call pthread_cancel(currentSession->current_command_root_thread)
// as much as possible, because ios_exit can be called from a signal handler now.
void ios_exit(int n) {
if (currentSession != NULL) {
currentSession->global_errno = n;
}
pthread_exit(NULL);
}
void ios_signal(int signal) {
// Signals the threads of the current session:
if (currentSession != NULL) {
if (currentSession->current_command_root_thread != NULL) {
pthread_kill(currentSession->current_command_root_thread, signal);
}
if (currentSession->lastThreadId != NULL) {
pthread_kill(currentSession->lastThreadId, signal);
}
}
}
#undef getenv
void ios_setWindowSize(int width, int height, const void* sessionId) {
// You can set the window size for a session that is not currently running (e.g. because "sh_session" is running).
// So we set it without calling ios_switchSession:
sessionParameters* resizedSession;
id sessionKey = @((NSUInteger)sessionId);
if (sessionList == nil) {
return;
}
resizedSession = (sessionParameters*)[[sessionList objectForKey: sessionKey] pointerValue];
if (resizedSession == nil) {
return;
}
sprintf(resizedSession->columns, "%d", width);
sprintf(resizedSession->lines, "%d",height);
}
char * ios_getenv(const char *name) {
// intercept calls to getenv("COLUMNS") / getenv("LINES")
if (strcmp(name, "COLUMNS") == 0) {
return currentSession->columns;
}
if (strcmp(name, "LINES") == 0) {
return currentSession->lines;
}
if (strcmp(name, "ROWS") == 0) {
return currentSession->lines;
}
return getenv(name);
}
int ios_getCommandStatus() {
if (currentSession != NULL) return currentSession->global_errno;
else return 0;
}
extern const char* ios_progname(void) {
if (currentSession != NULL) return currentSession->commandName;
else return getprogname();
}
typedef struct _functionParameters {
int argc;
char** argv;
char** argv_ref;
int (*function)(int ac, char** av);
FILE *stdin, *stdout, *stderr;
void* context;
void* dlHandle;
bool isPipeOut;
bool isPipeErr;
sessionParameters* session;
} functionParameters;
static void cleanup_function(void* parameters) {
// This function is called when pthread_exit() or ios_kill() is called
functionParameters *p = (functionParameters *) parameters;
char* commandName = p->argv[0];
if ((strcmp(commandName, "less") == 0) || (strcmp(commandName, "more") == 0)) {
if ((currentSession->current_command_root_thread != 0) && (currentSession->current_command_root_thread != pthread_self())) {
// Command was "root_command | sthg | less". We need to kill root command:
pthread_kill(currentSession->current_command_root_thread, SIGINT);
while (fgetc(thread_stdin) != EOF) { } // flush input, otherwise previous command gets blocked.
}
}
if ((!joinMainThread) && p->isPipeOut) {
if (currentSession->current_command_root_thread != 0) {
if (currentSession->current_command_root_thread != pthread_self()) {
// NSLog(@"Thread %x is waiting for root_thread of currentSession: %x \n", pthread_self(), currentSession->current_command_root_thread);
while (currentSession->current_command_root_thread != 0) { }
} else {
// NSLog(@"Terminating root_thread of currentSession %x \n", pthread_self());
currentSession->current_command_root_thread = 0;
}
}
}
fflush(thread_stdin);
fflush(thread_stdout);
fflush(thread_stderr);
// release parameters:
NSLog(@"Terminating command: %s thread_id %x stdin %d stdout %d stderr %d isPipeOut %d", commandName, pthread_self(), fileno(p->stdin), fileno(p->stdout), fileno(p->stderr), p->isPipeOut);
// Specific to run multiple python3 interpreters:
if ((strncmp(commandName, "python", 6) == 0) && (strlen(commandName) == strlen("python") + 1)) {
// It's one of the multiple python3 interpreters
char commandNumber = commandName[6];
if (commandNumber == '3') PythonIsRunning[0] = false;
else {
commandNumber -= 'A' - 1;
if ((commandNumber > 0) && (commandNumber < MaxPythonInterpreters))
PythonIsRunning[commandNumber] = false;
}
}
bool isSh = strcmp(p->argv[0], "sh") == 0;
for (int i = 0; i < p->argc; i++) free(p->argv_ref[i]);
free(p->argv_ref);
free(p->argv);
bool isLastThread = (currentSession->lastThreadId == pthread_self());
// Required for Jupyter. Must check for Blink/LibTerm/iVim:
// Is that the issue in iVim?
bool mustCloseStderr = (fileno(p->stderr) != fileno(stderr)) && (fileno(p->stderr) != fileno(p->stdout));
if (!isSh) {
mustCloseStderr &= p->isPipeErr;
if (currentSession != nil) {
mustCloseStderr &= fileno(p->stderr) != fileno(currentSession->stderr);
mustCloseStderr &= fileno(p->stderr) != fileno(currentSession->stdout);
}
}
if (mustCloseStderr) {
// NSLog(@"Closing stderr (mustCloseStderr): %d \n", fileno(p->stderr));
fclose(p->stderr);
}
bool mustCloseStdout = fileno(p->stdout) != fileno(stdout);
if (!isSh) {
mustCloseStdout &= p->isPipeOut;
if (currentSession != nil) {
mustCloseStdout &= fileno(p->stdout) != fileno(currentSession->stdout);
}
}
if (mustCloseStdout) {
// NSLog(@"Closing stdout (mustCloseStdout): %d \n", fileno(p->stdout));
fclose(p->stdout);
}
if ((p->dlHandle != RTLD_SELF) && (p->dlHandle != RTLD_MAIN_ONLY)
&& (p->dlHandle != RTLD_DEFAULT) && (p->dlHandle != RTLD_NEXT))
dlclose(p->dlHandle);
free(parameters); // This was malloc'ed in ios_system
if (isLastThread) {
// NSLog(@"Terminating lastthread of currentSession %x lastThreadId %x\n", pthread_self(), currentSession->lastThreadId);
currentSession->lastThreadId = 0;
} else {
// NSLog(@"Current thread %x lastthread %x \n", pthread_self(), currentSession->lastThreadId);
}
ios_releaseThread(pthread_self());
if (currentSession->current_command_root_thread == pthread_self()) {
currentSession->current_command_root_thread = 0;
}
}
void crash_handler(int sig) {
if (sig == SIGSEGV) {
fputs("segmentation fault\n", thread_stderr);
} else if (sig == SIGBUS) {
fputs("bus error\n", thread_stderr);
}
ios_exit(1);
}
static void* run_function(void* parameters) {
functionParameters *p = (functionParameters *) parameters;
ios_storeThreadId(pthread_self());
// NSLog(@"Storing thread_id: %x isPipeOut: %x isPipeErr: %x stdin %d stdout %d stderr %d command= %s\n", pthread_self(), p->isPipeOut, p->isPipeErr, fileno(p->stdin), fileno(p->stdout), fileno(p->stderr), p->argv[0]);
NSLog(@"Starting command: %s thread_id %x", p->argv[0], pthread_self());
// re-initialize for getopt:
// TODO: move to __thread variable for optind too
optind = 1;
opterr = 1;
optreset = 1;
__db_getopt_reset = 1;
thread_stdin = p->stdin;
thread_stdout = p->stdout;
thread_stderr = p->stderr;
thread_context = p->context;
currentSession = p->session;
signal(SIGSEGV, crash_handler);
signal(SIGBUS, crash_handler);
// Because some commands change argv, keep a local copy for release.
p->argv_ref = (char **)malloc(sizeof(char*) * (p->argc + 1));
for (int i = 0; i < p->argc; i++) p->argv_ref[i] = p->argv[i];
pthread_cleanup_push(cleanup_function, parameters);
@try
{
int retval = p->function(p->argc, p->argv);
if (currentSession != nil) currentSession->global_errno = retval;
}
@catch (NSException *exception)
{
// Print exception information
NSLog( @"NSException caught" );
NSLog( @"Name: %@", exception.name);
NSLog( @"Reason: %@", exception.reason );
return NULL;
}
@finally
{
// Cleanup, in both success and fail cases
pthread_cleanup_pop(1);
return NULL;
}
}
static NSString* miniRoot = nil; // limit operations to below a certain directory (~, usually).
static NSArray<NSString*> *allowedPaths = nil;
static NSDictionary *commandList = nil;
// do recompute directoriesInPath only if $PATH has changed
static NSString* fullCommandPath = @"";
static NSArray *directoriesInPath;
void initializeEnvironment() {
// setup a few useful environment variables
// Initialize paths for application files, including history.txt and keys
NSString *docsPath;
if (miniRoot == nil) docsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
else docsPath = miniRoot;
// Where the executables are stored: $PATH + ~/Library/bin + ~/Documents/bin
// Add content of old PATH to this. PATH *is* defined in iOS, surprising as it may be.
// I'm not going to erase it, so we just add ourselves.
// Sometimes, we go through main several times, so make sure we only append to PATH once
NSString* checkingPath = [NSString stringWithCString:getenv("PATH") encoding:NSUTF8StringEncoding];
if (! [fullCommandPath isEqualToString:checkingPath]) {
fullCommandPath = checkingPath;
}
if (![fullCommandPath containsString:@"Documents/bin"]) {
NSString *binPath = [docsPath stringByAppendingPathComponent:@"bin"];
fullCommandPath = [[binPath stringByAppendingString:@":"] stringByAppendingString:fullCommandPath];
setenv("PATH", fullCommandPath.UTF8String, 1); // 1 = override existing value
}
setenv("APPDIR", [[NSBundle mainBundle] resourcePath].UTF8String, 1);
setenv("PATH_LOCALE", docsPath.UTF8String, 0); // CURL config in ~/Documents/ or [Cloud Drive]/
setenv("TERM", "xterm", 1); // 1 = override existing value
setenv("TMPDIR", NSTemporaryDirectory().UTF8String, 0); // tmp directory
setenv("CLICOLOR", "1", 1);
setenv("LSCOLORS", "ExFxBxDxCxegedabagacad", 0); // colors for ls on black background
// We can't write in $HOME so we need to set the position of config files:
setenv("SSH_HOME", docsPath.UTF8String, 0); // SSH keys in ~/Documents/.ssh/ or [Cloud Drive]/.ssh
setenv("DIG_HOME", docsPath.UTF8String, 0); // .digrc is in ~/Documents/.digrc or [Cloud Drive]/.digrc
setenv("CURL_HOME", docsPath.UTF8String, 0); // CURL config in ~/Documents/ or [Cloud Drive]/
setenv("SSL_CERT_FILE", [docsPath stringByAppendingPathComponent:@"cacert.pem"].UTF8String, 0); // SLL cacert.pem in ~/Documents/cacert.pem or [Cloud Drive]/cacert.pem
// iOS already defines "HOME" as the home dir of the application
for (int i = 0; i < MaxPythonInterpreters; i++) PythonIsRunning[i] = false;
NSString *libPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
// environment variables for Python:
setenv("PYTHONHOME", libPath.UTF8String, 0); // Python files are in ~/Library/lib/python[23].x/
// XDG setup directories (~/Library/Caches, ~/Library/Preferences):
setenv("XDG_CACHE_HOME", [libPath stringByAppendingPathComponent:@"Caches"].UTF8String, 0);
setenv("XDG_CONFIG_HOME", [libPath stringByAppendingPathComponent:@"Preferences"].UTF8String, 0);
setenv("XDG_DATA_HOME", libPath.UTF8String, 0);
// if we use Python, we define a few more environment variables:
setenv("PYTHONEXECUTABLE", "python3", 0); // Python executable name for python3
setenv("PYZMQ_BACKEND", "cffi", 0);
// Configuration files are in $HOME (and hidden)
setenv("JUPYTER_CONFIG_DIR", [docsPath stringByAppendingPathComponent:@".jupyter"].UTF8String, 0);
setenv("IPYTHONDIR", [docsPath stringByAppendingPathComponent:@".ipython"].UTF8String, 0);
setenv("MPLCONFIGDIR", [docsPath stringByAppendingPathComponent:@".config/matplotlib"].UTF8String, 0);
// hg config file in ~/Documents/.hgrc
setenv("HGRCPATH", [docsPath stringByAppendingPathComponent:@".hgrc"].UTF8String, 0);
if (![fullCommandPath containsString:@"Library/bin"]) {
NSString *binPath = [libPath stringByAppendingPathComponent:@"bin"];
fullCommandPath = [[binPath stringByAppendingString:@":"] stringByAppendingString:fullCommandPath];
}
if (!sideLoading) {
// If we're not sideloading, executeables will also be in the Application directory
NSString *mainBundlePath = [[NSBundle mainBundle] resourcePath];
NSString *mainBundleLibPath = [mainBundlePath stringByAppendingPathComponent:@"Library"];
// if we're not sideloading, all "executable" files are in the AppDir:
// $APPDIR/Library/bin3
NSString *binPath = [mainBundleLibPath stringByAppendingPathComponent:@"bin3"];
fullCommandPath = [[binPath stringByAppendingString:@":"] stringByAppendingString:fullCommandPath];
// $APPDIR/Library/bin
binPath = [mainBundleLibPath stringByAppendingPathComponent:@"bin"];
fullCommandPath = [[binPath stringByAppendingString:@":"] stringByAppendingString:fullCommandPath];
// $APPDIR/bin
binPath = [mainBundlePath stringByAppendingPathComponent:@"bin"];
fullCommandPath = [[binPath stringByAppendingString:@":"] stringByAppendingString:fullCommandPath];
}
directoriesInPath = [fullCommandPath componentsSeparatedByString:@":"];
setenv("PATH", fullCommandPath.UTF8String, 1); // 1 = override existing value
// Store the maximum number of file descriptors allowed:
getrlimit(RLIMIT_NOFILE, &limitFilesOpen);
}
static char* parseArgument(char* argument, char* command) {
// expand all environment variables, convert "~" to $HOME (only if localFile)
// we also pass the shell command for some specific behaviour (don't do this for that command)
NSString* argumentString = [NSString stringWithCString:argument encoding:NSUTF8StringEncoding];
// 1) expand environment variables, + "~" (not wildcards ? and *)
bool cannotExpand = false;
while ([argumentString containsString:@"$"] && !cannotExpand) {
// It has environment variables inside. Work on them one by one.
// position of first "$" sign:
NSRange r1 = [argumentString rangeOfString:@"$"];
// position of first "/" after this $ sign:
NSRange r2 = [argumentString rangeOfString:@"/" options:NULL range:NSMakeRange(r1.location + r1.length, [argumentString length] - r1.location - r1.length)];
// position of first ":" after this $ sign:
NSRange r3 = [argumentString rangeOfString:@":" options:NULL range:NSMakeRange(r1.location + r1.length, [argumentString length] - r1.location - r1.length)];
if ((r2.location == NSNotFound) && (r3.location == NSNotFound)) r2.location = [argumentString length];
else if ((r2.location == NSNotFound) || (r3.location < r2.location)) r2.location = r3.location;
NSRange rSub = NSMakeRange(r1.location + r1.length, r2.location - r1.location - r1.length);
NSString *variable_string = [argumentString substringWithRange:rSub];
const char* variable = getenv([variable_string UTF8String]);
if (variable) {
// Okay, so this one exists.
NSString* replacement_string = [NSString stringWithCString:variable encoding:NSUTF8StringEncoding];
variable_string = [[NSString stringWithCString:"$" encoding:NSUTF8StringEncoding] stringByAppendingString:variable_string];
argumentString = [argumentString stringByReplacingOccurrencesOfString:variable_string withString:replacement_string];
} else cannotExpand = true; // found a variable we can't expand. stop trying for this argument
}
// 2) Tilde conversion: replace "~" with $HOME
// If there are multiple users on iOS, this code will need to be changed.
if([argumentString hasPrefix:@"~"]) {
// So it begins with "~". We can't use stringByExpandingTildeInPath because apps redefine HOME
NSString* replacement_string;
if (miniRoot == nil)
replacement_string = [NSString stringWithCString:(getenv("HOME")) encoding:NSUTF8StringEncoding];
else replacement_string = miniRoot;
if (([argumentString hasPrefix:@"~/"]) || ([argumentString hasPrefix:@"~:"]) || ([argumentString length] == 1)) {
NSString* test_string = @"~";
argumentString = [argumentString stringByReplacingOccurrencesOfString:test_string withString:replacement_string options:NULL range:NSMakeRange(0, 1)];
}
}
// Also convert ":~something" in PATH style variables
// We don't use these yet, but we could.
// We do this expansion only for setenv
if (strcmp(command, "setenv") == 0) {
// This is something we need to avoid if the command is "scp" or "sftp"
if ([argumentString containsString:@":~"]) {
NSString* homeDir;
if (miniRoot == nil) homeDir = [NSString stringWithCString:(getenv("HOME")) encoding:NSUTF8StringEncoding];
else homeDir = miniRoot;
// Only 1 possibility: ":~" (same as $HOME)
if (homeDir.length > 0) {
if ([argumentString containsString:@":~/"]) {
NSString* test_string = @":~/";
NSString* replacement_string = [[NSString stringWithCString:":" encoding:NSUTF8StringEncoding] stringByAppendingString:homeDir];
replacement_string = [replacement_string stringByAppendingString:[NSString stringWithCString:"/" encoding:NSUTF8StringEncoding]];
argumentString = [argumentString stringByReplacingOccurrencesOfString:test_string withString:replacement_string];
} else if ([argumentString hasSuffix:@":~"]) {
NSString* test_string = @":~";
NSString* replacement_string = [[NSString stringWithCString:":" encoding:NSUTF8StringEncoding] stringByAppendingString:homeDir];
argumentString = [argumentString stringByReplacingOccurrencesOfString:test_string withString:replacement_string options:NULL range:NSMakeRange([argumentString length] - 2, 2)];
} else if ([argumentString hasSuffix:@":"]) {
NSString* test_string = @":";
NSString* replacement_string = [[NSString stringWithCString:":" encoding:NSUTF8StringEncoding] stringByAppendingString:homeDir];
argumentString = [argumentString stringByReplacingOccurrencesOfString:test_string withString:replacement_string options:NULL range:NSMakeRange([argumentString length] - 2, 2)];
}
}
}
}
const char* newArgument = [argumentString UTF8String];
if (strcmp(argument, newArgument) == 0) return argument; // nothing changed
// Make sure the argument is reallocated, so it can be free-ed
char* returnValue = realloc(argument, strlen(newArgument) + 1);
strcpy(returnValue, newArgument);
return returnValue;
}
static void initializeCommandList()
{
// Loads command names and where to find them (digital library, function name) from plist dictionaries:
//
// Syntax for the dictionaris:
// key = command name, followed by an array of 4 components:
// 1st component: name of digital library (will be passed to dlopen(), can be SELF for RTLD_SELF or MAIN for RTLD_MAIN_ONLY)
// 2nd component: name of function to be called
// 3rd component: chain sent to getopt (for arguments in autocomplete)
// 4th component: takes a file/directory as argument
//
// Example:
// <key>rlogin</key>
// <array>
// <string>libnetwork_ios.dylib</string>
// <string>rlogin_main</string>
// <string>468EKLNS:X:acde:fFk:l:n:rs:uxy</string>
// <string>no</string>
// </array>
if (commandList != nil) return;
NSError *error;
NSString* applicationDirectory = [[NSBundle mainBundle] resourcePath];
NSString* commandDictionary = [applicationDirectory stringByAppendingPathComponent:@"commandDictionary.plist"];
NSURL *locationURL = [NSURL fileURLWithPath:commandDictionary isDirectory:NO];
if ([locationURL checkResourceIsReachableAndReturnError:&error] == NO) { NSLog(@"%@", [error localizedDescription]); return; }
NSData* loadedFromFile = [NSData dataWithContentsOfFile:commandDictionary options:0 error:&error];
if (!loadedFromFile) { NSLog(@"%@", [error localizedDescription]); return; }
commandList = [NSPropertyListSerialization propertyListWithData:loadedFromFile options:NSPropertyListImmutable format:NULL error:&error];
if (!commandList) { NSLog(@"%@", [error localizedDescription]); return; }
// replaces the following command, marked as deprecated in the doc:
// commandList = [NSDictionary dictionaryWithContentsOfFile:commandDictionary];
if (sideLoading) {
// more commands, for sideloaders (commands that won't pass AppStore rules, or with licensing issues):
NSString* extraCommandsDictionary = [applicationDirectory stringByAppendingPathComponent:@"extraCommandsDictionary.plist"];
locationURL = [NSURL fileURLWithPath:extraCommandsDictionary isDirectory:NO];
if ([locationURL checkResourceIsReachableAndReturnError:&error] == NO) { NSLog(@"%@", [error localizedDescription]); return; }
NSData* extraLoadedFromFile = [NSData dataWithContentsOfFile:extraCommandsDictionary options:0 error:&error];
if (!extraLoadedFromFile) { NSLog(@"%@", [error localizedDescription]); return; }
NSDictionary* extraCommandList = [NSPropertyListSerialization propertyListWithData:extraLoadedFromFile options:NSPropertyListImmutable format:NULL error:&error];
if (!extraCommandList) { NSLog(@"%@", [error localizedDescription]); return; }
// merge the two dictionaries:
NSMutableDictionary *mutableDict = [commandList mutableCopy];
[mutableDict addEntriesFromDictionary:extraCommandList];
commandList = [mutableDict copy];
}
}
int ios_setMiniRoot(NSString* mRoot) {
BOOL isDir;
NSFileManager *fileManager = [[NSFileManager alloc] init];
if (![fileManager fileExistsAtPath:mRoot isDirectory:&isDir]) {
return 0;
}
if (!isDir) {
return 0;
}
// fileManager has different ways of expressing the same directory.
// We need to actually change to the directory to get its "real name".
NSString* currentDir = [fileManager currentDirectoryPath];
if (![fileManager changeCurrentDirectoryPath:mRoot]) {
return 0;
}
// also don't set the miniRoot if we can't go in there
// get the real name for miniRoot:
miniRoot = [fileManager currentDirectoryPath];
// Back to where we we before:
[fileManager changeCurrentDirectoryPath:currentDir];
if (currentSession != nil) {
strcpy(currentSession->currentDir, [miniRoot UTF8String]);
strcpy(currentSession->previousDirectory, [miniRoot UTF8String]);
}
return 1; // mission accomplished
}
// Called when
int ios_setMiniRootURL(NSURL* mRoot) {
NSFileManager *fileManager = [[NSFileManager alloc] init];
if (currentSession == NULL) {
currentSession = malloc(sizeof(sessionParameters));
initSessionParameters(currentSession);
}
strcpy(currentSession->localMiniRoot, [mRoot.path UTF8String]);
strcpy(currentSession->previousDirectory, currentSession->currentDir);
strcpy(currentSession->currentDir, [[mRoot path] UTF8String]);
[fileManager changeCurrentDirectoryPath:[mRoot path]];
return 1; // mission accomplished
}
int ios_setAllowedPaths(NSArray<NSString *> *paths) {
allowedPaths = paths;
return 1;
}
BOOL __allowed_cd_to_path(NSString *path) {
if (miniRoot == nil || [path hasPrefix:miniRoot]) {
return YES;
}
if (strlen(currentSession->localMiniRoot) != 0) {
NSString *localMiniRootPath = [NSString stringWithCString:currentSession->localMiniRoot encoding:NSUTF8StringEncoding];
if (localMiniRootPath && [path hasPrefix:localMiniRootPath]) {
return YES;
}
}
for (NSString *dir in allowedPaths) {
if ([path hasPrefix:dir]) {
return YES;
}
}
return NO;
}
void __cd_to_dir(NSString *newDir, NSFileManager *fileManager) {
BOOL isDir;
// Check for permission and existence:
if (![fileManager fileExistsAtPath:newDir isDirectory:&isDir]) {
fprintf(thread_stderr, "cd: %s: no such file or directory\n", [newDir UTF8String]);
return;
}
if (!isDir) {
fprintf(thread_stderr, "cd: %s: not a directory\n", [newDir UTF8String]);
return;
}
if (![fileManager isReadableFileAtPath:newDir] ||
![fileManager changeCurrentDirectoryPath:newDir]) {
fprintf(thread_stderr, "cd: %s: permission denied\n", [newDir UTF8String]);
return;
}
// We managed to change the directory.
// Was that allowed?
// Allowed "cd" = below miniRoot *or* below localMiniRoot
NSString* resultDir = [fileManager currentDirectoryPath];
if (__allowed_cd_to_path(resultDir)) {
strcpy(currentSession->previousDirectory, currentSession->currentDir);
return;
}
fprintf(thread_stderr, "cd: %s: permission denied\n", [newDir UTF8String]);
// If the user tried to go above the miniRoot, set it to miniRoot
if ([miniRoot hasPrefix:resultDir]) {
[fileManager changeCurrentDirectoryPath:miniRoot];
strcpy(currentSession->currentDir, [miniRoot UTF8String]);
strcpy(currentSession->previousDirectory, currentSession->currentDir);
} else {
// go back to where we were before:
[fileManager changeCurrentDirectoryPath:[NSString stringWithCString:currentSession->currentDir encoding:NSUTF8StringEncoding]];
}
}
int cd_main(int argc, char** argv) {
if (currentSession == NULL) {
return 1;
}
NSFileManager *fileManager = [[NSFileManager alloc] init];
if (argc > 1) {
NSString* newDir = @(argv[1]);
if (strcmp(argv[1], "-") == 0) {
// "cd -" option to pop back to previous directory
newDir = [NSString stringWithCString:currentSession->previousDirectory encoding:NSUTF8StringEncoding];
}
__cd_to_dir(newDir, fileManager);
} else { // [cd] Help, I'm lost, bring me back home
strcpy(currentSession->previousDirectory, [[fileManager currentDirectoryPath] UTF8String]);
if (miniRoot != nil) {
[fileManager changeCurrentDirectoryPath:miniRoot];
} else {
[fileManager changeCurrentDirectoryPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]];
}
}
strcpy(currentSession->currentDir, [[fileManager currentDirectoryPath] UTF8String]);
return 0;
}
NSString* getoptString(NSString* commandName) {
if (commandList == nil) initializeCommandList();
NSArray* commandStructure = [commandList objectForKey: commandName];
if (commandStructure != nil) return commandStructure[2];
else return @"";
}
NSString* operatesOn(NSString* commandName) {
if (commandList == nil) initializeCommandList();
NSArray* commandStructure = [commandList objectForKey: commandName];
if (commandStructure != nil) return commandStructure[3];
else return @"";
}
int ios_executable(const char* inputCmd) {
// returns 1 if this is one of the commands we define in ios_system, 0 otherwise
if (commandList == nil) initializeCommandList();
// Take basename in case someone put a path before:
NSArray* valuesFromDict = [commandList objectForKey: [NSString stringWithCString:basename(inputCmd) encoding:NSUTF8StringEncoding]];
// we could dlopen() here, but that would defeat the purpose
if (valuesFromDict == nil) return 0;
else return 1;
}
// Where to direct input/output of the next thread:
static __thread FILE* child_stdin = NULL;
static __thread FILE* child_stdout = NULL;
static __thread FILE* child_stderr = NULL;
FILE* ios_popen(const char* inputCmd, const char* type) {
// Save existing streams:
int fd[2] = {0};
const char* command = inputCmd;
// skip past all spaces
while ((command[0] == ' ') && strlen(command) > 0) command++;
if (pipe(fd) < 0) { return NULL; } // Nothing we can do if pipe fails
// NOTES: fd[0] is set up for reading, fd[1] is set up for writing
// fpout = fdopen(fd[1], "w");
// fpin = fdopen(fd[0], "r");
if (type[0] == 'w') {
// open pipe for reading
child_stdin = fdopen(fd[0], "r");
// launch command: if the command fails, return NULL.
int returnValue = ios_system(command);
if (returnValue == 0)
return fdopen(fd[1], "w");
} else if (type[0] == 'r') {
// open pipe for writing
// set up streams for thread
child_stdout = fdopen(fd[1], "w");
// launch command: if the command fails, return NULL.
int returnValue = ios_system(command);
if (returnValue == 0)
return fdopen(fd[0], "r");
}
// pipe creation failed, command starting failed:
return NULL;
}
// small function, behaves like strstr but skips quotes (Yury Korolev)
char *strstrquoted(char* str1, char* str2) {
if (str1 == NULL || str2 == NULL) {
return NULL;
}
size_t len1 = strlen(str1);
size_t len2 = strlen(str2);
if (len1 < len2) {
return NULL;
}
if (strcmp(str1, str2) == 0) {
return str1;
}
char quotechar = 0;
int esclen = 0;
int matchlen = 0;
for (int i = 0; i < len1; i++) {
char ch = str1[i];
if (quotechar) {
if (ch == '\\') {
esclen++;
continue;
}
if (ch == quotechar) {
if (esclen % 2 == 1) {
esclen = 0;
continue;
}
quotechar = 0;
esclen = 0;
continue;
}
esclen = 0;
continue;
}
if (ch == '"' || ch == '\'') {
if (esclen % 2 == 0) {
quotechar = ch;
}
matchlen = 0;
esclen = 0;
continue;
}
if (ch == '\\') {
esclen++;
}
if (str2[matchlen] == ch) {
matchlen++;
if (matchlen == len2) {
return str1 + i - matchlen + 1;
}
continue;
}
matchlen = 0;
}
return NULL;
}
static char* concatenateArgv(char* const argv[]) {
int argc = 0;
int cmdLength = 0;
// concatenate all arguments into a big command.
// We need this because some programs call execv() with a single string: "ssh [email protected] 'hg -R ... --stdio'"
// So we rely on ios_system to break them into chunks.
while(argv[argc] != NULL) { cmdLength += strlen(argv[argc]) + 1; argc++;}
if (argc == 0) return NULL; // safeguard check
char* cmd = malloc((cmdLength + 3 * argc) * sizeof(char)); // space for quotes
strcpy(cmd, argv[0]);
argc = 1;
while (argv[argc] != NULL) {
if (strstrquoted(argv[argc], " ")) {
// argument contains spaces. Enclose it into quotes:
if (strstrquoted(argv[argc], "\"") == NULL) {
// argument does not contain ". Enclose with "
strcat(cmd, " \"");
strcat(cmd, argv[argc]);
strcat(cmd, "\"");
argc++;
continue;
}
if (strstrquoted(argv[argc], "'") == NULL) {
// argument does not contain '. Enclose with '
strcat(cmd, " '");
strcat(cmd, argv[argc]);
strcat(cmd, "'");
argc++;
continue;
}
fprintf(thread_stderr, "Don't know what to do with this argument, sorry: %s\n", argv[argc]);
}
strcat(cmd, " ");
strcat(cmd, argv[argc]);
argc++;
}
return cmd;
}
int pbpaste(int argc, char** argv) {
// We can paste strings and URLs.
if ([UIPasteboard generalPasteboard].hasStrings) {
fprintf(thread_stdout, "%s", [[UIPasteboard generalPasteboard].string UTF8String]);
if (![[UIPasteboard generalPasteboard].string hasSuffix:@"\n"]) fprintf(thread_stdout, "\n");
return 0;
}
if ([UIPasteboard generalPasteboard].hasURLs) {
fprintf(thread_stdout, "%s\n", [[[UIPasteboard generalPasteboard].URL absoluteString] UTF8String]);
return 0;
}
return 1;
}
int pbcopy(int argc, char** argv) {
if (argc == 1) {
// no arguments, listen to stdin
const int bufsize = 1024;
char buffer[bufsize];
NSMutableData* data = [[NSMutableData alloc] init];
ssize_t count = 0;
while ((count = read(fileno(thread_stdin), buffer, bufsize-1))) {
[data appendBytes:buffer length:count];
}
NSString* result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if (!result) {
return 1;
}
[UIPasteboard generalPasteboard].string = result;
} else {
// threre are arguments, concatenate and paste:
char* cmd = concatenateArgv(argv + 1);
[UIPasteboard generalPasteboard].string = @(cmd);
free(cmd);
}
return 0;
}
// Auxiliary function for sh_main. Given a string of characters (command1 && command2),
// split it into the sub commands and execute each of them in sequence:
static int splitCommandAndExecute(char* command) {
// Remember to use fork / waitpid to wait for the commands to finish
if (command == NULL) return 0;
char* maxPointer = command + strlen(command);
int returnValue = 0;
while (command[0] != 0) {
// NSLog(@"stdout %x \n", fileno(thread_stdout));
// NSLog(@"stderr %x \n", fileno(thread_stderr));
char* nextAnd = strstrquoted(command, "&&");
char* nextOr = strstrquoted(command, "||");
if ((nextAnd == NULL) && (nextOr == NULL)) {
// Only one command left
pid_t pid = ios_fork();
returnValue = ios_system(command);
// NSLog(@"Started command, stored last_thread= %x", currentSession->lastThreadId);
ios_waitpid(pid);
break;
}
int nextCommandPosition = 0;
bool andNextCommand = false;
if (nextAnd != NULL) {
nextCommandPosition = nextAnd - command;
andNextCommand = true;
}
if (nextOr != NULL) {
if (nextOr - command < nextCommandPosition) {
nextCommandPosition = nextOr - command;
andNextCommand = false;
}
}
command[nextCommandPosition] = NULL; // terminate string
pid_t pid = ios_fork();
returnValue = ios_system(command);
// NSLog(@"Started command (2), stored last_thread= %x", currentSession->lastThreadId);
ios_waitpid(pid);
if (andNextCommand && (returnValue != 0)) {
// && + the command returned error, we return:
break;
} else if (!andNextCommand && (returnValue == 0)) {
// || + the command worked, we return:
break;
}
command += (nextCommandPosition + 2); // char after "&&" or "||"
while ((command[0] == ' ') && (command < maxPointer)) command++; // skip spaces
if (command > maxPointer) return 0; // happens if the command ends with && or ||
}
return returnValue;
}
sessionParameters* parentSession = NULL;
NSString* parentDir;
int sh_main(int argc, char** argv) {
// NOT an actual shell.
// for commands that call other commands as "sh -c command" or "sh -c command1 && command2"
// NSLog(@"sh_main, stdout %d \n", fileno(thread_stdout));
// NSLog(@"sh_main, stderr %d \n", fileno(thread_stderr));
if ((argc < 2) || (strncmp(argv[1], "-h", 2) == 0)) {
fprintf(thread_stderr, "Not an actual shell. sh is provided for compatibility with commands that call other commands.\n");
fprintf(thread_stderr, "Usage: sh [-flags] command: executes command (all flags are ignored).\n");
fprintf(thread_stderr, " sh [-flags] command1 && command2 [&& command3 && ...]: executes the commands, in order, until one returns error.\n");
fprintf(thread_stderr, " sh [-flags] command1 || command2 [|| command3 || ...]: executes the commands, in order, until one returns OK.\n");
return 0;
}
char** command = argv + 1; // skip past "sh"
while ((command[0][0] == '-') && (command[0] != NULL)) { command++; } // skip past all flags
if (command[0] == NULL) {
argv[0][0] = 'h'; // prevent termination in cleanup_function
return 0;
}
// If we reach this point, we have commands to execute.
// Store current sesssion, create a new session specific for this, execute commands
id sessionKey = @((NSUInteger)&sh_session);
if (sessionList != nil) {
sessionParameters* runningShellSession = (sessionParameters*)[[sessionList objectForKey: sessionKey] pointerValue];
if (runningShellSession != NULL) {
if ((runningShellSession->lastThreadId != 0) && (runningShellSession->lastThreadId != pthread_self())){
// NSLog(@"There is another sh session running: last_thread= %x", runningShellSession->lastThreadId);
argv[0][0] = 'h'; // prevent termination in cleanup_function
return 1;
} else {
// NSLog(@"There is another sh session running: last_thread= %x us= %x. Continuing.", runningShellSession->lastThreadId, pthread_self());
}
}
}
NSFileManager *fileManager = [[NSFileManager alloc] init];
// NSLog(@"parentSession = %x currentSession = %x currentDir = %s\n", parentSession, currentSession, [fileManager currentDirectoryPath].UTF8String);
if (currentSession->context == sh_session) {
return 1; // We cannot have a sh command starting a sh command.
}
if (parentSession == NULL) {
parentSession = currentSession;
parentDir = [fileManager currentDirectoryPath];
}
ios_switchSession(&sh_session); // create a new session
// NSLog(@"after switchSession, currentDir = %s\n", [fileManager currentDirectoryPath].UTF8String);
currentSession->isMainThread = false;
currentSession->context = sh_session;
currentSession->stdin = thread_stdin;
currentSession->stdout = thread_stdout;
currentSession->stderr = thread_stderr;
currentSession->current_command_root_thread = NULL;
currentSession->lastThreadId = NULL;
// Need to loop twice: over each argument, and inside each argument.
// &&: keep computing until one command is in error
// ||: keep computing until one command is not in error
// Remember to use fork / waitpid to wait for the commands to finish
int returnValue = 0;
while (command[0] != NULL) {
int i = 0;
while ((command[i] != NULL) && (strcmp(command[i], "&&") != 0) && (strcmp(command[i], "||") != 0)) i++;
if (command[i] == NULL) {
char* lastCommand = concatenateArgv(command);
returnValue = splitCommandAndExecute(lastCommand);
free(lastCommand);
break;
}
bool andNextCommand = (strcmp(command[i], "&&") == 0); // should we continue?
command[i] = NULL;
char* newCommand = concatenateArgv(command);