-
Notifications
You must be signed in to change notification settings - Fork 119
/
ios_system.m
1437 lines (1331 loc) · 64.4 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
// is executable, looking at "x" bit. Other methods fails on iOS:
#define S_ISXXX(m) ((m) & (S_IXUSR | S_IXGRP | S_IXOTH))
// Sideloading: when you compile yourself, as opposed to uploading on the app store
// If true, all functions are enabled + debug messages if dylib not found.
// If false, you get a smaller set, but more compliance with AppStore rules.
// *Must* be false in the main branch releases.
bool sideLoading = false;
extern __thread int __db_getopt_reset;
__thread FILE* thread_stdin;
__thread FILE* thread_stdout;
__thread FILE* thread_stderr;
__thread void* thread_context;
#import "sessionParameters.h"
NSMutableDictionary* sessionList;
sessionParameters* currentSession;
// replace system-provided exit() by our own:
void ios_exit(int n) {
if (currentSession != NULL) currentSession.global_errno = n;
pthread_exit(NULL);
}
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 UTF8String];
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;
} functionParameters;
static void cleanup_function(void* parameters) {
// This function is called when pthread_exit() or ios_kill() is called
functionParameters *p = (functionParameters *) parameters;
fflush(thread_stdin);
fflush(thread_stdout);
fflush(thread_stderr);
// release parameters:
for (int i = 0; i < p->argc; i++) free(p->argv_ref[i]);
free(p->argv_ref);
free(p->argv);
if (p->isPipeOut) {
// Close stdout if it won't be closed by another thread
// (i.e. if it's different from the parent thread stdout)
fclose(thread_stdout);
thread_stdout = NULL;
}
if (p->isPipeErr) {
fclose(thread_stderr);
thread_stderr = NULL;
}
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
}
void crash_handler(int sig) {
if (sig == SIGSEGV) {
fputs("segmentation fault\n", thread_stderr);
} else if (sig == SIGABRT) {
fputs("sigabrt signal\n", thread_stderr);
} else if (sig == SIGBUS) {
fputs("bus error\n", thread_stderr);
}
ios_exit(1);
}
static void* run_function(void* parameters) {
// re-initialize for getopt:
// TODO: move to __thread variable for optind too
optind = 1;
opterr = 1;
optreset = 1;
__db_getopt_reset = 1;
functionParameters *p = (functionParameters *) parameters;
thread_stdin = p->stdin;
thread_stdout = p->stdout;
thread_stderr = p->stderr;
thread_context = p->context;
signal(SIGSEGV, crash_handler);
signal(SIGBUS, crash_handler);
signal(SIGABRT, 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);
p->function(p->argc, p->argv);
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
if (sideLoading) {
NSString *libPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
if (![fullCommandPath containsString:@"Library/bin"]) {
NSString *binPath = [libPath stringByAppendingPathComponent:@"bin"];
fullCommandPath = [[binPath stringByAppendingString:@":"] stringByAppendingString:fullCommandPath];
}
// if we use Python, we define a few more environment variables:
setenv("PYTHONHOME", libPath.UTF8String, 0); // Python scripts in ~/Library/lib/python3.6/
setenv("PYZMQ_BACKEND", "cffi", 0);
setenv("JUPYTER_CONFIG_DIR", [docsPath stringByAppendingPathComponent:@".jupyter"].UTF8String, 0);
// hg config file in ~/Documents/.hgrc
setenv("HGRCPATH", [docsPath stringByAppendingPathComponent:@".hgrc"].UTF8String, 0);
}
directoriesInPath = [fullCommandPath componentsSeparatedByString:@":"];
setenv("PATH", fullCommandPath.UTF8String, 1); // 1 = override existing value
}
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));
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) {
currentSession.currentDir = miniRoot;
currentSession.previousDirectory = miniRoot;
}
return 1; // mission accomplished
}
// Called when
int ios_setMiniRootURL(NSURL* mRoot) {
NSFileManager *fileManager = [[NSFileManager alloc] init];
if (currentSession == NULL) {
currentSession = [[sessionParameters alloc] init];
}
currentSession.localMiniRoot = mRoot;
currentSession.previousDirectory = currentSession.currentDir;
currentSession.currentDir = [mRoot path];
[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;
}
NSString *localMiniRootPath = currentSession.localMiniRoot.path;
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)) {
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];
currentSession.currentDir = miniRoot;
currentSession.previousDirectory = currentSession.currentDir;
} else {
// go back to where we were before:
[fileManager changeCurrentDirectoryPath:currentSession.currentDir];
}
}
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 = currentSession.previousDirectory;
}
__cd_to_dir(newDir, fileManager);
} else { // [cd] Help, I'm lost, bring me back home
currentSession.previousDirectory = [fileManager currentDirectoryPath];
if (miniRoot != nil) {
[fileManager changeCurrentDirectoryPath:miniRoot];
} else {
[fileManager changeCurrentDirectoryPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]];
}
}
currentSession.currentDir = [fileManager currentDirectoryPath];
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();
NSArray* valuesFromDict = [commandList objectForKey: [NSString stringWithCString: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++;
// TODO: skip past "/bin/sh -c" and "sh -c"
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:
ios_system(command);
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:
ios_system(command);
return fdopen(fd[0], "r");
}
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 hg@bitbucket.org 'hg -R ... --stdio'"
// So we rely on ios_system to break them into chunks.
while(argv[argc] != NULL) { cmdLength += strlen(argv[argc]) + 1; argc++;}
char* cmd = malloc((cmdLength + 2 * 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) {
if (currentSession == NULL) {
currentSession = [[sessionParameters alloc] init];
}
// We can paste strings and URLs.
if ([UIPasteboard generalPasteboard].hasStrings) {
fprintf(currentSession.stdout, "%s", [[UIPasteboard generalPasteboard].string UTF8String]);
if (![[UIPasteboard generalPasteboard].string hasSuffix:@"\n"]) fprintf(currentSession.stdout, "\n");
return 0;
}
if ([UIPasteboard generalPasteboard].hasURLs) {
fprintf(currentSession.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
if (currentSession == NULL) {
currentSession = [[sessionParameters alloc] init];
}
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;
}
int ios_execv(const char *path, char* const argv[]) {
// path and argv[0] are the same (not in theory, but in practice, since Python wrote the command)
// start "child" with the child streams:
char* cmd = concatenateArgv(argv);
int returnValue = ios_system(cmd);
free(cmd);
return returnValue;
}
int ios_execve(const char *path, char* const argv[], char* envp[]) {
// TODO: save the environment (HOW?) and current dir
// TODO: replace environment with envp. envp looks a lot like current environment, though.
int returnValue = ios_execv(path, argv);
// TODO: restore the environment (HOW?)
return returnValue;
}
const pthread_t ios_getLastThreadId() {
if (!currentSession) return nil;
return (currentSession.lastThreadId);
}
/*
* Public domain dup2() lookalike
* by Curtis Jackson @ AT&T Technologies, Burlington, NC
* electronic address: burl!rcj
* Edited for iOS by N. Holzschuch.
* The idea is that dup2(fd, [012]) is usually called between fork and exec.
*
* dup2 performs the following functions:
*
* Check to make sure that fd1 is a valid open file descriptor.
* Check to see if fd2 is already open; if so, close it.
* Duplicate fd1 onto fd2; checking to make sure fd2 is a valid fd.
* Return fd2 if all went well; return BADEXIT otherwise.
*/
int ios_dup2(int fd1, int fd2)
{
// iOS specifics: trying to access stdin/stdout/stderr?
if (fd1 < 3) {
// specific cases like dup2(STDOUT_FILENO, STDERR_FILENO)
FILE* stream1 = NULL;
switch (fd1) {
case 0: stream1 = child_stdin; break;
case 1: stream1 = child_stdout; break;
case 2: stream1 = child_stderr; break;
}
switch (fd2) {
case 0: child_stdin = stream1; return fd2;
case 1: child_stdout = stream1; return fd2;
case 2: child_stderr = stream1; return fd2;
}
}
if (fd2 == 0) { child_stdin = fdopen(fd1, "rb"); }
else if (fd2 == 1) { child_stdout = fdopen(fd1, "wb"); }
else if (fd2 == 2) {
if (fileno(child_stdout) == fd1) child_stderr = child_stdout;
else child_stderr = fdopen(fd1, "wb"); }
else if (fd1 != fd2) {
if (fcntl(fd1, F_GETFL) < 0)
return -1;
if (fcntl(fd2, F_GETFL) >= 0)
close(fd2);
if (fcntl(fd1, F_DUPFD, fd2) < 0)
return -1;
}
return fd2;
}
int ios_kill()
{
if (currentSession == NULL) return ESRCH;
if (currentSession.current_command_root_thread > 0) {
// Send pthread_cancel with the given signal to the current main thread, if there is one.
return pthread_cancel(currentSession.current_command_root_thread);
}
// No process running
return ESRCH;
}
void ios_switchSession(void* sessionId) {
NSFileManager *fileManager = [[NSFileManager alloc] init];
id sessionKey = [NSNumber numberWithInt:((int)sessionId)];
if (sessionList == nil) {
sessionList = [NSMutableDictionary new];
if (currentSession != NULL) [sessionList setObject: currentSession forKey: sessionKey];
}
currentSession = [sessionList objectForKey: sessionKey];
if (currentSession == NULL) {
currentSession = [[sessionParameters alloc] init];
[sessionList setObject: currentSession forKey: sessionKey];
} else {
if (![currentSession.currentDir isEqualToString:[fileManager currentDirectoryPath]])
[fileManager changeCurrentDirectoryPath:currentSession.currentDir];
currentSession.stdin = stdin;
currentSession.stdout = stdout;
currentSession.stderr = stderr;
}
}
void ios_setDirectoryURL(NSURL* workingDirectoryURL) {
NSFileManager *fileManager = [[NSFileManager alloc] init];
[fileManager changeCurrentDirectoryPath:[workingDirectoryURL path]];
if (currentSession != NULL) {
if ([currentSession.currentDir isEqualToString:[fileManager currentDirectoryPath]]) return;
currentSession.previousDirectory = currentSession.currentDir;
currentSession.currentDir = [workingDirectoryURL path];
}
}
void ios_closeSession(void* sessionId) {
// delete information associated with current session:
if (sessionList == nil) return;
id sessionKey = [NSNumber numberWithInt:((int)sessionId)];
[sessionList removeObjectForKey: sessionKey];
currentSession = NULL;
}
int ios_isatty(int fd) {
if (currentSession == NULL) return 0;
// 2 possibilities: 0, 1, 2 (classical) or fileno(thread_stdout)
if ((fd == STDIN_FILENO) || (fd == fileno(currentSession.stdin)) || (fd == fileno(thread_stdin)))
return (fileno(thread_stdin) == fileno(currentSession.stdin));
if ((fd == STDOUT_FILENO) || (fd == fileno(currentSession.stdout)) || (fd == fileno(thread_stdout)))
return (fileno(thread_stdout) == fileno(currentSession.stdout));
if ((fd == STDERR_FILENO) || (fd == fileno(currentSession.stderr)) || (fd == fileno(thread_stderr)))
return (fileno(thread_stderr) == fileno(currentSession.stderr));
return 0;
}
void ios_setStreams(FILE* _stdin, FILE* _stdout, FILE* _stderr) {
if (currentSession == NULL) return;
currentSession.stdin = _stdin;
currentSession.stdout = _stdout;
currentSession.stderr = _stderr;
}
void ios_setContext(void *context) {
if (currentSession == NULL) return;
currentSession.context = context;
}
// For customization:
// replaces a function (e.g. ls_main) with another one, provided by the user (ls_mine_main)
// if the function does not exist, add it to the list
// if "allOccurences" is true, search for all commands that share the same function, replace them too.
// ("compress" and "uncompress" both point to compress_main. You probably want to replace both, but maybe
// you just happen to have a very fast uncompress, different from compress).
// We work with function names, not function pointers.
void replaceCommand(NSString* commandName, NSString* functionName, bool allOccurences) {
// Does that function exist / is reachable? We've had problems with stripping.
int (*function)(int ac, char** av) = NULL;
function = dlsym(RTLD_MAIN_ONLY, functionName.UTF8String);
if (!function) return; // if not, we don't replace.
if (commandList == nil) initializeCommandList();
NSArray* oldValues = [commandList objectForKey: commandName];
NSString* oldFunctionName = nil;
if (oldValues != nil) oldFunctionName = oldValues[1];
NSMutableDictionary *mutableDict = [commandList mutableCopy];
mutableDict[commandName] = [NSArray arrayWithObjects: @"MAIN", functionName, @"", @"file", nil];
if ((oldFunctionName != nil) && allOccurences) {
// scan through all dictionary entries
for (NSString* existingCommand in mutableDict.allKeys) {
NSArray* currentPosition = [mutableDict objectForKey: existingCommand];
if ([currentPosition[1] isEqualToString:oldFunctionName])
[mutableDict setValue: [NSArray arrayWithObjects: @"MAIN", functionName, @"", @"file", nil] forKey: existingCommand];
}
}
commandList = [mutableDict copy]; // back to non-mutable version
}
// For customization:
// Add an entire plist file defining multiple commands. Commands follow the same syntax as initializeCommandList:
//
// key = command name, followed by an array of 4 components:
// 1st component: name of digital library (can be "MAIN" if command is defined inside program)
// 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>
NSError* addCommandList(NSString* fileLocation) {
if (commandList == nil) initializeCommandList();
NSError* error;
NSURL *locationURL = [NSURL fileURLWithPath:fileLocation isDirectory:NO];
if ([locationURL checkResourceIsReachableAndReturnError:&error] == NO) return error;
NSData* dataLoadedFromFile = [NSData dataWithContentsOfFile:fileLocation options:0 error:&error];
if (!dataLoadedFromFile) return error;
NSDictionary* newCommandList = [NSPropertyListSerialization propertyListWithData:dataLoadedFromFile options:NSPropertyListImmutable format:NULL error:&error];
if (!newCommandList) return error;
// merge the two dictionaries:
NSMutableDictionary *mutableDict = [commandList mutableCopy];
[mutableDict addEntriesFromDictionary:newCommandList];
commandList = [mutableDict copy];
return NULL;
}
NSString* commandsAsString() {
if (commandList == nil) initializeCommandList();
NSError * err;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:commandList.allKeys options:0 error:&err];
NSString * myString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
return myString;
}
NSArray* commandsAsArray() {
if (commandList == nil) initializeCommandList();
return commandList.allKeys;
}
// for output file names, arguments: returns a pointer to
// immediately after the end of the argument, or NULL.
// Method:
// - if argument begins with ", go to next unescaped "
// - if argument begins with ', go to next unescaped '
// - otherwise, move to next unescaped space
//
// Must be combined with another function to remove backslash.
// Aux function:
static void* nextUnescapedCharacter(const char* str, const char c) {
char* nextOccurence = strchr(str, c);
while (nextOccurence != NULL) {
if ((nextOccurence > str + 1) && (*(nextOccurence - 1) == '\\')) {
// There is a backlash before the character.
int numBackslash = 0;
char* countBack = nextOccurence - 1;
while ((countBack > str) && (*countBack == '\\')) { numBackslash++; countBack--; }
if (numBackslash % 2 == 0) return nextOccurence; // even number of backslash
} else return nextOccurence;
nextOccurence = strchr(nextOccurence + 1, c);
}
return nextOccurence;
}
static char* getLastCharacterOfArgument(const char* argument) {
if (strlen(argument) == 0) return NULL; // be safe
if (argument[0] == '"') {
char* endquote = nextUnescapedCharacter(argument + 1, '"');
if (endquote != NULL) return endquote + 1;
else return NULL;
} else if (argument[0] == '\'') {
char* endquote = nextUnescapedCharacter(argument + 1, '\'');
if (endquote != NULL) return endquote + 1;
else return NULL;
}
else return nextUnescapedCharacter(argument + 1, ' ');
}
// remove quotes at the beginning of argument if there's a balancing one at the end
static char* unquoteArgument(char* argument) {
if (argument[0] == '"') {
if (argument[strlen(argument) - 1] == '"') {
argument[strlen(argument) - 1] = 0x0;
return argument + 1;
}
}
if (argument[0] == '\'') {
if (argument[strlen(argument) - 1] == '\'') {
argument[strlen(argument) - 1] = 0x0;
return argument + 1;
}
}
// no quotes at the beginning: replace all escaped characters:
// '\x' -> x
char* nextOccurence = strchr(argument, '\\');
while ((nextOccurence != NULL) && (strlen(nextOccurence) > 0)) {
memmove(nextOccurence, nextOccurence + 1, strlen(nextOccurence + 1) + 1);
// strcpy(nextOccurence, nextOccurence + 1);
nextOccurence = strchr(nextOccurence + 1, '\\');
}
return argument;
}
int ios_system(const char* inputCmd) {
char* command;
// The names of the files for stdin, stdout, stderr
char* inputFileName = 0;
char* outputFileName = 0;
char* errorFileName = 0;
// Where the symbols "<", ">" or "2>" were.
// to be replaced by 0x0 later.
char* outputFileMarker = 0;
char* inputFileMarker = 0;
char* errorFileMarker = 0;
char* scriptName = 0; // interpreted commands
bool sharedErrorOutput = false;
NSFileManager *fileManager = [[NSFileManager alloc] init];
if (currentSession == NULL) {
currentSession = [[sessionParameters alloc] init];
}
// initialize:
if (thread_stdin == 0) thread_stdin = currentSession.stdin;
if (thread_stdout == 0) thread_stdout = currentSession.stdout;
if (thread_stderr == 0) thread_stderr = currentSession.stderr;
if (thread_context == 0) thread_context = currentSession.context;
char* cmd = strdup(inputCmd);
char* maxPointer = cmd + strlen(cmd);
char* originalCommand = cmd;
// fprintf(thread_stderr, "Command sent: %s \n", cmd); fflush(stderr);
if (cmd[0] == '"') {
// Command was enclosed in quotes (almost always with Vim)
char* endCmd = strstrquoted(cmd + 1, "\""); // find closing quote
if (endCmd) {
cmd = cmd + 1; // remove starting quote
endCmd[0] = 0x0;
assert(endCmd < maxPointer);
}
// assert(cmd + strlen(cmd) < maxPointer);
}
if (cmd[0] == '(') {