forked from holzschu/ios_system
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ios_system.m
3829 lines (3631 loc) · 182 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 <UIKit/UIKit.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: chgrp, chown, 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;
static NSString* ios_bookmarkDictionaryName = @"bookmarkNames";
// Include file for getrlimit/setrlimit:
#include <sys/resource.h>
static struct rlimit limitFilesOpen;
extern void display_alert(NSString* title, NSString* message);
extern __thread int __db_getopt_reset;
__thread FILE* thread_stdin;
__thread FILE* thread_stdout;
__thread FILE* thread_stderr;
__thread void* thread_context;
FILE* ios_stdin(void) {
return thread_stdin;
}
FILE* ios_stdout(void) {
return thread_stdout;
}
FILE* ios_stderr(void) {
return thread_stderr;
}
void* ios_context(void) {
return 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.
pthread_t mainThreadId; // thread ID of parent command, if any (e.g. vim, which starts "sh -c cd dir && flake8 file")
FILE* stdin;
FILE* stdout;
FILE* stderr;
FILE* tty;
void* context;
int global_errno;
int numCommandsAllocated;
int numCommand;
char** commandName;
char columns[5];
char lines[5];
bool activePager;
} sessionParameters;
static void initSessionParameters(sessionParameters* sp) {
NSFileManager *fileManager = [[NSFileManager alloc] init];
sp->isMainThread = TRUE;
sp->current_command_root_thread = 0;
sp->lastThreadId = 0;
sp->mainThreadId = 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->numCommandsAllocated = 10; // 10 slots available to store commands, will realloc if more needed.
sp->commandName = malloc(sizeof(char*) * sp->numCommandsAllocated);
for (int i = 0; i < sp->numCommandsAllocated; i++) {
sp->commandName[i] = malloc(sizeof(char) * NAME_MAX);
}
sp->commandName[0][0] = 0;
sp->numCommand = 0;
strcpy(sp->columns, "80");
strcpy(sp->lines, "80");
sp->activePager = FALSE;
}
void ios_setBookmarkDictionaryName(NSString* name) {
ios_bookmarkDictionaryName = name;
}
const char* ios_getBookmarkedVersion(const char* p) {
// p is a directory. Get the bookmarked version to make it shorter:
NSString* pathString = [NSString stringWithUTF8String:p];
NSString* privatePrefix = @"/private";
if ([pathString hasPrefix:privatePrefix]) {
pathString = [pathString substringFromIndex:[privatePrefix length]];
}
NSString *homePath;
homePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByDeletingLastPathComponent];
if ([homePath hasPrefix:privatePrefix]) {
homePath = [homePath substringFromIndex:[privatePrefix length]];
}
// NSLog(@"ios_getBookmarkedVersion: %s %s", homePath.UTF8String, pathString.UTF8String);
if ([pathString hasPrefix:homePath]) {
pathString = [pathString stringByReplacingOccurrencesOfString:homePath withString:@"~"];
return pathString.UTF8String;
}
if (ios_bookmarkDictionaryName == nil) {
return p;
}
NSDictionary *tildeExpansionDictionary = [[NSUserDefaults standardUserDefaults] dictionaryForKey:ios_bookmarkDictionaryName];
if (tildeExpansionDictionary == nil) {
return p;
}
NSString* foundString = @"";
for (NSString* bookmark in tildeExpansionDictionary) {
NSString* bookmarkPath = tildeExpansionDictionary[bookmark];
if ([bookmarkPath hasPrefix:privatePrefix]) {
bookmarkPath = [bookmarkPath substringFromIndex:[privatePrefix length]];
}
if ([pathString hasPrefix:bookmarkPath]) {
NSString* testString = [pathString stringByReplacingOccurrencesOfString:bookmarkPath withString:[@"~" stringByAppendingString: bookmark]];
if ((foundString.length == 0) || (testString.length < foundString.length))
foundString = testString;
}
}
if (foundString.length > 0)
return foundString.UTF8String;
return p;
}
static NSMutableDictionary* sessionList;
static NSMutableDictionary* aliasDictionary;
// 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.
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;
static bool showPythonInterpreterAlert = true;
// Same with perl:
static const int MaxPerlInterpreters = 4; // const so we can allocate an array
// cpan starts perl Makefile.PL, which starts perl -e print Version, so at least 3.
int numPerlInterpreters = MaxPerlInterpreters; // Apps can overwrite this
static bool PerlIsRunning[MaxPerlInterpreters];
static int currentPerlInterpreter = 0;
// same with TeX, with a twist:
static const int MaxTeXInterpreters = 2; // const so we can allocate an array
// (La)TeX can start another (La)TeX command for TikZ
int numTeXInterpreters = MaxTeXInterpreters; // Apps can overwrite this
static bool TeXIsRunning[MaxTeXInterpreters];
static int currentTeXInterpreter = 0;
NSArray *TeXcommands = nil; // initialized later
// Multiple dash:
// limit to 6 (for now)
static const int MaxDashCommands = 6; // const so we can allocate an array
int numDashCommands = MaxDashCommands; // Apps can overwrite this
static bool dashIsRunning[MaxDashCommands];
static int currentDashCommand = 0;
// multiple ssh (limit to 2):
static const int MaxSshCommands = 2; // const so we can allocate an array
int numSshCommands = MaxSshCommands; // Apps can overwrite this
static bool sshIsRunning[MaxSshCommands];
static int currentSshCommand = 0;
// pointers for sh sessions:
char* sh_session = "sh_session";
// replace system-provided exit() by our own:
void ios_exit(int n) {
if (currentSession != NULL) {
currentSession->global_errno = n;
}
pthread_exit(NULL);
}
void set_session_errno(int n) {
if (currentSession != NULL) {
currentSession->global_errno = n;
}
}
// Replace standard abort and exit functions with ours:
// We also do this using #define, but this is for the unmodified code.
void abort(void) {
ios_exit(1);
}
void exit(int n) {
ios_exit(n);
}
void _exit(int n) {
ios_exit(n);
}
//
void ios_signal(int signal) {
// This function is probably obsolete now. If we keep using it, remember that currentSession is not necessarily the currentSession
// (if currentSession started sh_session, then we might be sending the signal to the wrong session).
// 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);
}
if (currentSession->mainThreadId != NULL) {
pthread_kill(currentSession->mainThreadId, signal);
}
}
}
NSString *ios_getLogicalPWD(const void* sessionId) {
id sessionKey = @((NSUInteger)sessionId);
if (sessionList == nil) {
return nil;
}
sessionParameters *session = (sessionParameters*)[[sessionList objectForKey: sessionKey] pointerValue];
if (session == nil) {
return nil;
}
return @(session->currentDir);
}
#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", MIN(width, 9999));
sprintf(resizedSession->lines, "%d", MIN(height, 9999));
// Also send SIGWINCH to the main thread of resizedSession:
if (resizedSession->current_command_root_thread != NULL) {
pthread_kill(resizedSession->current_command_root_thread, SIGWINCH);
}
if (resizedSession->lastThreadId != NULL) {
pthread_kill(resizedSession->lastThreadId, SIGWINCH);
}
if (resizedSession->mainThreadId != NULL) {
pthread_kill(resizedSession->mainThreadId, SIGWINCH);
}
}
extern char* libc_getenv(const char* variableName);
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;
}
if (strcmp(name, "PWD") == 0) {
return currentSession->currentDir;
}
return libc_getenv(name);
}
void ios_IsMainThread(bool value) {
currentSession->isMainThread = value;
}
int ios_getCommandStatus(void) {
if (currentSession != NULL) return currentSession->global_errno;
else return 0;
}
extern const char* ios_progname(void) {
if (currentSession != NULL) {
if (currentSession->numCommand <= 0)
return currentSession->commandName[0];
else
return currentSession->commandName[currentSession->numCommand - 1];
}
else return getprogname();
}
const char* ios_expandtilde(const char *login) {
// expand "~something" with the content of userPreference dictionary (to be set by each app)
// About the same behaviour as:
// struct passwd *pw = getpwnam(name);
// return pw ? pw->pw_dir : 0;
NSDictionary *tildeExpansionDictionary = [[NSUserDefaults standardUserDefaults] dictionaryForKey:ios_bookmarkDictionaryName];
if (tildeExpansionDictionary != nil) {
NSString* name = [NSString stringWithUTF8String:login];
NSString* expandedPath = tildeExpansionDictionary[name];
if (expandedPath != nil) {
return [expandedPath UTF8String];
}
}
return NULL;
}
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 isPipeIn;
bool isPipeOut;
bool isPipeErr;
bool backgroundCommand;
int numInterpreter;
bool storeRootThread;
sessionParameters* session;
} functionParameters;
extern pthread_mutex_t pid_mtx;
extern _Atomic(int) cleanup_counter;
extern void ios_releaseBackgroundThread(pthread_t thread);
extern void startedPreparingWebAssemblyCommand(void);
static void cleanup_function(void* parameters) {
// This function is called when pthread_exit() or ios_kill() is called
pthread_t current_thread = pthread_self();
functionParameters *p = (functionParameters *) parameters;
bool backgroundCommand = p->backgroundCommand;
char* commandName = p->argv[0];
char* currentSessionCommandName = NULL;
bool toNonInteractive = false;
if (currentSession->numCommand <= 0)
currentSessionCommandName = currentSession->commandName[0];
else
currentSessionCommandName = currentSession->commandName[currentSession->numCommand - 1];
NSLog(@"cleanup_function: %s thread_id %x pid: %d stdin %d stdout %d stderr %d isPipeOut %d", commandName, current_thread, ios_currentPid(), fileno(p->stdin), fileno(p->stdout), fileno(p->stderr), p->isPipeOut);
NSLog(@"currentSession->commandName: %s root_thread: %x", currentSessionCommandName, currentSession->current_command_root_thread);
NSLog(@"Num commands stored: %d", currentSession->numCommand);
if ((strcmp(commandName, "less") == 0) || (strcmp(commandName, "more") == 0)) {
if ((strlen(currentSessionCommandName) > 0)
&& (strcmp(currentSessionCommandName, "less") != 0)
&& (strcmp(currentSessionCommandName, "more") != 0)) {
// Command was "root_command | sthg | less". We need to kill root command.
// If less itself started another command, then currentSession->commandName is "".
// Unless less / more was started as a pager, in which case don't kill root command (e.g. for man and ipython help).
pthread_kill(currentSession->current_command_root_thread, SIGINT);
while (fgetc(thread_stdin) != EOF) { } // flush input, otherwise previous command gets blocked.
} else {
// but for python or ipython help(), flush the content of stdin:
if ((currentSession->numCommand > 1) &&
((strncmp(currentSession->commandName[currentSession->numCommand - 2], "ipython", 7) == 0) ||
(strncmp(currentSession->commandName[currentSession->numCommand - 2], "isympy", 6) == 0) ||
(strncmp(currentSession->commandName[currentSession->numCommand - 2], "python", 6) == 0))) {
while (fgetc(thread_stdin) != EOF) { } // flush input to help() command
if (strncmp(currentSession->commandName[currentSession->numCommand - 2], "python", 6) == 0) {
toNonInteractive = true;
}
}
}
currentSession->activePager = FALSE;
}
// If the command was started as a pipe, we wait for the first command to finish sending data
// There is an exception for ssh, which can be started by scp or sftp. They will wait for it.
if ((!joinMainThread) && p->isPipeOut && (strcmp(commandName, "ssh") != 0)) {
if (currentSession->current_command_root_thread != 0) {
if (currentSession->current_command_root_thread != current_thread) {
NSLog(@"Thread %x is waiting for root_thread of currentSession: %x \n", current_thread, currentSession->current_command_root_thread);
while ((currentSession->current_command_root_thread != 0) && (currentSession->current_command_root_thread != current_thread)) {
fflush(thread_stdout);
fflush(thread_stderr);
}
NSLog(@"Thread %x is done waiting for root_thread of currentSession: %x \n", current_thread, currentSession->current_command_root_thread);
} else {
NSLog(@"Terminating root_thread of currentSession %x \n", current_thread);
currentSession->current_command_root_thread = 0;
}
}
}
fcntl(fileno(thread_stdin), F_SETNOSIGPIPE);
fcntl(fileno(thread_stdout), F_SETNOSIGPIPE);
fcntl(fileno(thread_stderr), F_SETNOSIGPIPE);
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, current_thread, fileno(p->stdin), fileno(p->stdout), fileno(p->stderr), p->isPipeOut);
// Specific to run multiple python3 interpreters:
NSString* commandNameString = [NSString stringWithCString: commandName encoding:NSUTF8StringEncoding];
// Can we close stdin too?
bool mustCloseStdin = fileno(p->stdin) != fileno(stdin);
if (strncmp(commandName, "python", 6) == 0) {
// It could be one of the multiple python3 interpreters
PythonIsRunning[p->numInterpreter] = false;
mustCloseStdin = false;
}
// Same with multiple perl or TeX interpreters:
else if (strncmp(commandName, "perl", 4) == 0) {
NSLog(@"Ending a Perl interpreter: %d", p->numInterpreter);
PerlIsRunning[p->numInterpreter] = false;
} else if ([TeXcommands containsObject: commandNameString]) {
NSLog(@"Ending a TeX command: %d", p->numInterpreter);
TeXIsRunning[p->numInterpreter] = false;
} else if (strcmp(commandName, "dash") == 0) {
NSLog(@"Ending a dash command: %d", p->numInterpreter);
dashIsRunning[p->numInterpreter] = false;
} else if (strcmp(commandName, "ssh") == 0) {
NSLog(@"Ending a ssh command: %d", p->numInterpreter);
sshIsRunning[p->numInterpreter] = false;
}
if (currentSession->numCommand > 0)
currentSession->numCommand -= 1;
else
currentSession->commandName[0][0] = 0;
// if (strcmp(currentSession->commandName, commandName) == 0) {
// currentSession->commandName[0] = 0;
// }
bool isSh = strcmp(p->argv[0], "sh") == 0;
bool isWasm = strcmp(p->argv[0], "wasm") == 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 == current_thread);
bool mustCloseStderr = (fileno(p->stderr) != fileno(stderr)) && (fileno(p->stderr) != fileno(p->stdout)) && (fileno(p->stdout) != fileno(p->stdin));
if (!isSh) {
mustCloseStderr &= p->isPipeErr;
if (currentSession != nil) {
mustCloseStderr &= fileno(p->stderr) != fileno(currentSession->stderr);
mustCloseStderr &= fileno(p->stderr) != fileno(currentSession->stdout);
}
}
// Some programs stop waiting as soon as stdout/stderr close (which makes sense)
// This fclose does close the fileno, but I find it re-opened later.
cleanup_counter++;
while (pthread_mutex_trylock(&pid_mtx) != 0) { } // Someone else has the lock, so we wait.
pthread_mutex_unlock(&pid_mtx);
if (mustCloseStderr) {
NSLog(@"Closing stderr (mustCloseStderr): %d \n", fileno(p->stderr));
int res = fclose(p->stderr);
}
// In some cases, we find that stdout is equal to stdin after executing the command. We should not close stdin!
bool mustCloseStdout = (fileno(p->stdout) != fileno(stdout)) && (fileno(p->stdout) != fileno(p->stdin));
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));
int res = fclose(p->stdout);
}
if (!isSh) {
mustCloseStdin &= p->isPipeIn;
if (currentSession != nil) {
mustCloseStdin &= fileno(p->stdin) != fileno(currentSession->stdin);
}
// we cannot close stdin for wasm commands:
mustCloseStdin &= !isWasm;
// commands started by Python: Python will close stdin (Lua and Perl? not broken, AFAIK)
if ((currentSession->numCommand > 0) && (strncmp(currentSession->commandName[currentSession->numCommand - 1], "python", 6) == 0)) {
// NSLog(@"Command started by Python, not closing stdin: %d \n", fileno(p->stdin));
mustCloseStdin &= false;
}
}
if (mustCloseStdin) {
NSLog(@"Closing stdin (mustCloseStdin): %d \n", fileno(p->stdin));
int res = fclose(p->stdin);
}
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 pid: %d\n", current_thread, currentSession->lastThreadId, ios_currentPid());
currentSession->lastThreadId = 0;
} else {
NSLog(@"Current thread %x lastthread %x pid: %d\n", pthread_self(), currentSession->lastThreadId, ios_currentPid());
}
if (backgroundCommand) {
// If it's a background command, call ios_releaseBackgroundThread:
// NSLog(@"Releasing a backgroundCommand\n");
ios_releaseBackgroundThread(current_thread);
} else {
if (toNonInteractive) {
ios_stopInteractive();
}
ios_releaseThread(current_thread);
}
if (currentSession->current_command_root_thread == current_thread) {
currentSession->current_command_root_thread = 0;
}
if (currentSession->mainThreadId == current_thread) {
currentSession->mainThreadId = 0;
}
cleanup_counter--;
NSLog(@"returning from cleanup_function\n");
}
// Avoir calling crash_handler several times:
static __thread bool crash_handler_called = false;
void crash_handler(int sig) {
if (thread_stderr == NULL) thread_stderr = stderr;
if (!crash_handler_called) {
crash_handler_called = true;
if (sig == SIGSEGV) {
fputs("segmentation fault\n", thread_stderr);
} else if (sig == SIGBUS) {
fputs("bus error\n", thread_stderr);
} else if (sig == SIGPIPE) {
fputs("pipe error\n", thread_stderr);
return;
}
ios_exit(1);
}
}
static void* run_function(void* parameters) {
functionParameters *p = (functionParameters *) parameters;
NSLog(@"Storing thread_id: %x pid: %d isPipeOut: %x isPipeErr: %x stdin %d stdout %d stderr %d command= %s\n", pthread_self(), ios_currentPid(), p->isPipeOut, p->isPipeErr,
(p->stdin == nil) ? -1 : fileno(p->stdin),
(p->stdout == nil) ? -1 : fileno(p->stdout),
(p->stderr == nil) ? -1 : fileno(p->stderr), p->argv[0]);
ios_storeThreadId(pthread_self());
if (p->storeRootThread && (p->session != NULL)) {
NSLog(@"Storing thread_id: %x as root_thread\n", pthread_self());
p->session->current_command_root_thread = pthread_self();
}
// 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;
if ((strcmp(p->argv[0], "less") == 0) || (strcmp(p->argv[0], "more") == 0)) {
if (currentSession != nil) currentSession->activePager = TRUE;
}
signal(SIGSEGV, crash_handler);
signal(SIGBUS, crash_handler);
signal(SIGPIPE, 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 );
fprintf(thread_stderr, "Command %s was interrupted because it triggered a system exception: %s: %s\n", p->argv[0], exception.name.UTF8String, exception.reason.UTF8String);
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;
NSArray *backgroundCommandList = nil;
// do recompute directoriesInPath only if $PATH has changed
static NSString* fullCommandPath = @"";
static NSArray *directoriesInPath;
void initializeEnvironment(void) {
// 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("CURLOPT_SSH_KNOWNHOSTS", [docsPath stringByAppendingPathComponent:@".ssh/known_hosts"].UTF8String, 0);
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;
for (int i = 0; i < MaxPerlInterpreters; i++) PerlIsRunning[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);
// Initialize the array with the name of TeX commands (this might be too many commands):
TeXcommands = @[@"amstex", @"cslatex", @"csplain", @"eplain", @"etex", @"jadetex", @"latex", @"mex", @"mllatex", @"mltex", @"pdfsclatex", @"pdfcsplain", @"pdfetex", @"pdfjadetex", @"pdflatex", @"pdfmex", @"pdftex", @"pdfxmltex", @"tex", @"texsis", @"utf8mex", @"xmltex", @"texlua", @"texluac", @"dvilualatex", @"dviluatex", @"lualatex", @"luatex", @"luahbtex", @"mptopdf", @"optex",
@"xetex", @"xelatex", @"dvipdfmx", @"xdvipdfmx",
@"amstexA", @"cslatexA", @"csplainA", @"eplainA", @"etexA", @"jadetexA", @"latexA", @"mexA", @"mllatexA", @"mltexA", @"pdfsclatexA", @"pdfcsplainA", @"pdfetexA", @"pdfjadetexA", @"pdflatexA", @"pdfmexA", @"pdftexA", @"pdfxmltexA", @"texA", @"texsisA", @"utf8mexA", @"xmltexA", @"texluaA", @"texluacA", @"dvilualatexA", @"dviluatexA", @"lualatexA", @"luatexA", @"luahbtexA", @"mptopdfA", @"optexA",
@"xetexA", @"xelatexA", @"dvipdfmxA", @"xdvipdfmxA"];
}
NSString * pathJoin(NSString * segmentA, NSString * segmentB);
static char* unquoteArgument(char* argument);
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];
// NSLog(@"parsing argument, argumentString= %s", argumentString.UTF8String);
// If command == "export", first extract the value string here.
NSString* variableName;
if (strcmp(command, "export") == 0) {
char* equalSign=strchr(argument,'=');
if (equalSign && (strlen(equalSign) > 0)) {
char* argumentCString=equalSign+1;
argumentCString = unquoteArgument(argumentCString);
variableName = [argumentString substringToIndex:(equalSign - argument)];
argumentString = [NSString stringWithCString:argumentCString encoding:NSUTF8StringEncoding];
// NSLog(@"parsing argument, variable name= %s argument= %s", variableName.UTF8String, argumentString.UTF8String);
} else {
// No equal sign, or nothing after. export_main will take care of this.
return argument;
}
}
// 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 = ios_getenv([variable_string UTF8String]);
if (variable) {
// Okay, so this one exists.
variable_string = [[NSString stringWithCString:"$" encoding:NSUTF8StringEncoding] stringByAppendingString:variable_string];
NSString* replacement_string = [NSString stringWithCString:variable encoding:NSUTF8StringEncoding];
argumentString = [argumentString stringByReplacingOccurrencesOfString:variable_string withString:replacement_string];
if ([replacement_string containsString:variable_string]) // avoid an infinite loop here
cannotExpand = true;
} 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.
// We also expand ~bookmarkName to the path for that bookmark.
// 2a) ~ expansion. (old behaviour, kept as is for compatibility)
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)];
} else {
// 2b) expand "~something" with the content of userPreference dictionary (to be set by each app)
NSDictionary *tildeExpansionDictionary = [[NSUserDefaults standardUserDefaults] dictionaryForKey:ios_bookmarkDictionaryName];
if (tildeExpansionDictionary != nil) {
NSCharacterSet* separators = [NSCharacterSet characterSetWithCharactersInString:@":/"];
NSArray<NSString*>* components = [argumentString componentsSeparatedByCharactersInSet:separators];
NSString* name = [components[0] substringFromIndex:1]; // remove the "~"
NSString* expandedPath = tildeExpansionDictionary[name];
if (expandedPath != nil) {
argumentString = [argumentString stringByReplacingOccurrencesOfString:components[0] withString:expandedPath options:NULL range:NSMakeRange(0, [components[0] length])];
}
}
}
}
// Also convert ":~something" in PATH style variables
// We don't use these yet, but we could.
// We do this expansion only for setenv and export
if ((strcmp(command, "setenv") == 0) || (strcmp(command, "export") == 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) {
NSString* replacement_string = [@":" stringByAppendingString:homeDir];
if ([argumentString containsString:@":~/"]) {
NSString* test_string = @":~/";
replacement_string = [replacement_string stringByAppendingString:[NSString stringWithCString:"/" encoding:NSUTF8StringEncoding]];
argumentString = [argumentString stringByReplacingOccurrencesOfString:test_string withString:replacement_string];
} else if ([argumentString hasSuffix:@":~"]) {
NSString* test_string = @":~";
argumentString = [argumentString stringByReplacingOccurrencesOfString:test_string withString:replacement_string options:NULL range:NSMakeRange([argumentString length] - 2, 2)];
} else if ([argumentString hasSuffix:@":"]) {
NSString* test_string = @":";
argumentString = [argumentString stringByReplacingOccurrencesOfString:test_string withString:replacement_string options:NULL range:NSMakeRange([argumentString length] - 2, 2)];
}
}
NSDictionary *tildeExpansionDictionary = [[NSUserDefaults standardUserDefaults] dictionaryForKey:ios_bookmarkDictionaryName];
if (tildeExpansionDictionary != nil) {
// TODO: add :~bookmarkName/ :~bookmarkName
NSArray<NSString*>* components = [argumentString componentsSeparatedByString:@":~"];
NSString* result = components[0];
for (int i = 1; i < components.count; i++) {
NSString* stringToAdd = components[i];
NSArray<NSString*>* names = [components[i] componentsSeparatedByString:@"/"];
NSString* test_string = names[0];
NSString* replacement_string = tildeExpansionDictionary[names[0]];
if (replacement_string != nil) {
// we found a name to expand
stringToAdd = [stringToAdd stringByReplacingOccurrencesOfString:test_string withString:replacement_string];
result = [[result stringByAppendingString:@":"] stringByAppendingString:stringToAdd];
} else {
result = [[result stringByAppendingString:@":~"] stringByAppendingString:stringToAdd];
}
}
argumentString = result;
}
}
}
if ([argumentString hasPrefix:@"../"] || [argumentString hasPrefix:@"./.."] || [argumentString isEqualToString:@".."]) {
argumentString = pathJoin(@(currentSession->currentDir), argumentString);
}
if (strcmp(command, "export") == 0) {
argumentString = [[variableName stringByAppendingString:@"="] stringByAppendingString:argumentString];
}
const char* newArgument = [argumentString UTF8String];
// NSLog(@"After parsing: %s", newArgument);
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 const char* ios_expandFilename(const char *filename) {
// expand a filename for opening if it begins with "~" or contains an environment variable
if (strlen(filename) == 0) return filename;
NSString* nameString = [NSString stringWithUTF8String:filename];
if([nameString 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 (([nameString hasPrefix:@"~/"]) || ([nameString length] == 1)) {
NSString* test_string = @"~";
nameString = [nameString stringByReplacingOccurrencesOfString:test_string withString:replacement_string options:NULL range:NSMakeRange(0, 1)];
} else {
// 2b) expand "~something" with the content of userPreference dictionary (to be set by each app)
NSDictionary *tildeExpansionDictionary = [[NSUserDefaults standardUserDefaults] dictionaryForKey:ios_bookmarkDictionaryName];
if (tildeExpansionDictionary != nil) {
NSCharacterSet* separators = [NSCharacterSet characterSetWithCharactersInString:@":/"];
NSArray<NSString*>* components = [nameString componentsSeparatedByCharactersInSet:separators];
NSString* name = [components[0] substringFromIndex:1]; // remove the "~"
NSString* expandedPath = tildeExpansionDictionary[name];
if (expandedPath != nil) {
nameString = [nameString stringByReplacingOccurrencesOfString:components[0] withString:expandedPath options:NULL range:NSMakeRange(0, [components[0] length])];
}
}
}
}
bool cannotExpand = false;
while ([nameString containsString:@"$"] && !cannotExpand) {
// It has environment variables inside. Work on them one by one.
// position of first "$" sign:
NSRange r1 = [nameString rangeOfString:@"$"];
// position of first "/" after this $ sign:
NSRange r2 = [nameString rangeOfString:@"/" options:NULL range:NSMakeRange(r1.location + r1.length, [nameString length] - r1.location - r1.length)];
if (r2.location == NSNotFound) r2.location = [nameString length];
NSRange rSub = NSMakeRange(r1.location + r1.length, r2.location - r1.location - r1.length);
NSString *variable_string = [nameString substringWithRange:rSub];
const char* variable = ios_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];
nameString = [nameString stringByReplacingOccurrencesOfString:variable_string withString:replacement_string];
} else cannotExpand = true; // found a variable we can't expand. stop trying for this fileName
}
return [nameString UTF8String];
}
static void initializeCommandList(void)
{
// 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) {
// NSLog(@"__allowed_cd_to_path: %@ miniRoot: %@\n", path, miniRoot);
if (miniRoot == nil) {
return YES;
}
if ([path hasPrefix:miniRoot]) {
return YES;