-
-
Notifications
You must be signed in to change notification settings - Fork 487
/
esh.c
2379 lines (2085 loc) · 53.7 KB
/
esh.c
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
/**
* @brief E-Shell
*
* This is "experimental shell" - a vaguely-unix-like command
* interface. It has a very rudimentary parser that understands
* some things like pipes or writing out to a file. It has a
* handful of built-in commands, including ones that implement
* some more useful shell syntax such as loops and conditionals.
* There is support for tab completion of filenames and commands.
*
* @copyright
* This file is part of ToaruOS and is released under the terms
* of the NCSA / University of Illinois License - see LICENSE.md
* Copyright (C) 2013-2022 K. Lange
*/
#define _XOPEN_SOURCE 500
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <dirent.h>
#include <signal.h>
#include <getopt.h>
#include <termios.h>
#include <errno.h>
#include <fcntl.h>
#include <ctype.h>
#include <wchar.h>
#include <sys/time.h>
#include <sys/times.h>
#include <sys/wait.h>
#include <sys/utsname.h>
#include <sys/stat.h>
#include <toaru/list.h>
#include <toaru/hashmap.h>
#include <toaru/kbd.h>
#include <toaru/rline.h>
#include <toaru/decodeutf8.h>
#ifndef environ
extern char **environ;
#endif
#define PIPE_TOKEN "\xFF\xFFPIPE\xFF\xFF"
#define STAR_TOKEN "\xFF\xFFSTAR\xFF\xFF"
#define WRITE_TOKEN "\xFF\xFFWRITE\xFF\xFF"
#define WRITE_ERR_TOKEN "\xFF\xFFWRITEERR\xFF\xFF"
#define APPEND_TOKEN "\xFF\xFF""APPEND\xFF"
/* A shell command is like a C program */
typedef uint32_t(*shell_command_t) (int argc, char ** argv);
/* We have a static array that fits a certain number of them. */
int SHELL_COMMANDS = 64;
char ** shell_commands; /* Command names */
shell_command_t * shell_pointers; /* Command functions */
char ** shell_descript; /* Command descriptions */
FILE * shell_stderr; /* specifically for `time` */
/* This is the number of actual commands installed */
int shell_commands_len = 0;
int shell_interactive = 1;
int last_ret = 0;
char ** shell_argv = NULL;
int shell_argc = 0;
static int current_line = 0;
static char * current_file = NULL;
int pid; /* Process ID of the shell */
int my_pgid;
int is_subshell = 0;
struct semaphore {
int fds[2];
};
struct semaphore create_semaphore(void) {
struct semaphore out;
pipe(out.fds);
return out;
}
void raise_semaphore(struct semaphore s){
write(s.fds[1],"x",1);
close(s.fds[0]);
close(s.fds[1]);
}
void wait_semaphore(struct semaphore s) {
close(s.fds[1]);
char buf;
read(s.fds[0], &buf, 1);
close(s.fds[0]);
}
void set_pgid(int pgid) {
if (shell_interactive == 1) {
setpgid(0, pgid);
}
}
void set_pgrp(int pgid) {
if (shell_interactive == 1 && !is_subshell) {
sigset_t ss;
sigfillset(&ss);
sigprocmask(SIG_SETMASK, &ss, NULL);
tcsetpgrp(STDIN_FILENO, pgid);
sigemptyset(&ss);
sigprocmask(SIG_SETMASK, &ss, NULL);
}
}
void reset_pgrp() {
set_pgrp(my_pgid);
}
void shell_install_command(char * name, shell_command_t func, char * desc) {
if (shell_commands_len == SHELL_COMMANDS-1) {
SHELL_COMMANDS *= 2;
shell_commands = realloc(shell_commands, sizeof(char *) * SHELL_COMMANDS);
shell_pointers = realloc(shell_pointers, sizeof(shell_command_t) * SHELL_COMMANDS);
shell_descript = realloc(shell_descript, sizeof(char *) * SHELL_COMMANDS);
}
shell_commands[shell_commands_len] = name;
shell_pointers[shell_commands_len] = func;
shell_descript[shell_commands_len] = desc;
shell_commands_len++;
shell_commands[shell_commands_len] = NULL;
}
shell_command_t shell_find(char * str) {
for (int i = 0; i < shell_commands_len; ++i) {
if (!strcmp(str, shell_commands[i])) {
return shell_pointers[i];
}
}
return NULL;
}
void install_commands();
/* Maximum command length */
#define LINE_LEN 4096
/* Current working directory */
char cwd[1024] = {'/',0};
/* Username */
char username[1024];
/* Hostname for prompt */
char _hostname[256];
/* function to update the cached username */
void getuser() {
char * tmp = getenv("USER");
if (tmp) {
strcpy(username, tmp);
} else {
sprintf(username, "%d", getuid());
}
}
/* function to update the cached hostname */
void gethost() {
struct utsname buf;
uname(&buf);
int len = strlen(buf.nodename);
memcpy(_hostname, buf.nodename, len+1);
}
int display_width_of_string(const char * str) {
uint8_t * s = (uint8_t *)str;
int out = 0;
uint32_t c, state = 0;
while (*s) {
if (!decode(&state, &c, *s)) {
out += wcwidth(c);
} else if (state == UTF8_REJECT) {
state = 0;
}
s++;
}
return out;
}
void print_extended_ps(char * format, char * buffer, int * display_width) {
/* Get the time */
struct tm * timeinfo;
struct timeval now;
gettimeofday(&now, NULL); //time(NULL);
timeinfo = localtime((time_t *)&now.tv_sec);
/* Format the date and time for prompt display */
char date_buffer[80];
strftime(date_buffer, 80, "%m/%d", timeinfo);
char time_buffer[80];
strftime(time_buffer, 80, "%H:%M:%S", timeinfo);
/* Collect the current working directory */
getcwd(cwd, 512);
char _cwd[512];
strcpy(_cwd, cwd);
/* Collect the user's home directory and apply it to cwd */
char * home = getenv("HOME");
if (home && strstr(cwd, home) == cwd) {
char * c = cwd + strlen(home);
if (*c == '/' || *c == 0) {
sprintf(_cwd, "~%s", c);
}
}
char ret[80] = {0};
if (last_ret != 0) {
sprintf(ret, "%d ", last_ret);
}
size_t offset = 0;
int is_visible = 1;
char dispchars[1024] = {0};
char * dispout = dispchars;
while (*format) {
if (*format == '\\') {
format++;
switch (*format) {
case '\\':
buffer[offset++] = *format;
if (is_visible) *dispout++ = *format;
format++;
break;
case '[':
is_visible = 0;
format++;
break;
case ']':
is_visible = 1;
format++;
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
{
int i = (*format) - '0';
format++;
if (*format >= '0' && *format <= '7') {
i *= 8;
i += (*format) - '0';
format++;
if (*format >= '0' && *format <= '7') {
i *= 8;
i += (*format) - '0';
format++;
}
}
buffer[offset++] = i;
if (is_visible) *dispout++ = i;
}
break;
case 'e':
buffer[offset++] = '\033';
if (is_visible) *dispout++ = '\033';
format++;
break;
case 'd':
{
int size = sprintf(buffer+offset, "%s", date_buffer);
offset += size;
if (is_visible) { dispout += sprintf(dispout, "%s", date_buffer); }
}
format++;
break;
case 't':
{
int size = sprintf(buffer+offset, "%s", time_buffer);
offset += size;
if (is_visible) { dispout += sprintf(dispout, "%s", time_buffer); }
}
format++;
break;
case 'h':
{
int size = sprintf(buffer+offset, "%s", _hostname);
offset += size;
if (is_visible) { dispout += sprintf(dispout, "%s", _hostname); }
}
format++;
break;
case 'u':
{
int size = sprintf(buffer+offset, "%s", username);
offset += size;
if (is_visible) { dispout += sprintf(dispout, "%s", username); }
}
format++;
break;
case 'w':
{
int size = sprintf(buffer+offset, "%s", _cwd);
offset += size;
if (is_visible) { dispout += sprintf(dispout, "%s", _cwd); }
}
format++;
break;
case '$':
buffer[offset++] = (getuid() == 0 ? '#' : '$');
if (is_visible) *dispout++ = (getuid() == 0 ? '#' : '$');
format++;
break;
case 'U': /* prompt color string */
{
int size = sprintf(buffer+offset, "%s", getuid() == 0 ? "\033[1;38;5;196m" : "\033[1;38;5;47m");
offset += size;
/* Does not affect size */
}
format++;
break;
case 'r':
{
int size = sprintf(buffer+offset, "%s", ret);
offset += size;
if (is_visible) { dispout += sprintf(dispout, "%s", ret); }
}
format++;
break;
default:
{
int size = sprintf(buffer+offset, "\\%c", *format);
offset += size;
if (is_visible) { dispout += sprintf(dispout, "\\%c", *format); }
}
format++;
break;
}
} else {
buffer[offset++] = *format;
if (is_visible) *dispout++ = *format;
format++;
}
}
*display_width = display_width_of_string(dispchars);
buffer[offset] = '\0';
}
volatile int break_while = 0;
pid_t suspended_pgid = 0;
hashmap_t * job_hash = NULL;
hashmap_t * desc_hash = NULL;
void sig_break_loop(int sig) {
/* Interrupt handler */
if ((shell_interactive == 1 && !is_subshell)) {
break_while = sig;
signal(sig, sig_break_loop);
} else {
signal(sig, SIG_DFL);
raise(sig);
}
}
void tab_complete_func(rline_context_t * c) {
char * dup = malloc(LINE_LEN);
memcpy(dup, c->buffer, LINE_LEN);
char *pch, *save;
char *argv[1024];
int argc = 0;
int cursor = 0;
pch = strtok_r(dup, " ", &save);
if (!pch) {
argv[0] = "";
argc = 0;
}
while (pch != NULL) {
if (pch - dup <= c->offset) cursor = argc;
argv[argc] = pch;
++argc;
pch = strtok_r(NULL, " ", &save);
}
argv[argc] = NULL;
if (c->offset && c->buffer[c->offset-1] == ' ' && argc) {
cursor++;
}
char * word = argv[cursor];
int word_offset = word ? (c->offset - (argv[cursor] - dup)) : 0;
char * prefix = malloc(word_offset + 1);
if (word) memcpy(prefix, word, word_offset);
prefix[word_offset] = '\0';
/* Complete file path */
list_t * matches = list_create();
char * match = NULL;
int free_matches = 0;
int no_space_if_only = 0;
/* TODO custom auto-complete as a configuration file? */
#define COMPLETE_FILE 1
#define COMPLETE_COMMAND 2
#define COMPLETE_CUSTOM 3
#define COMPLETE_VARIABLE 4
int complete_mode = COMPLETE_FILE;
int with_dollar = 0;
int command_adj = 0;
int cursor_adj = cursor;
while (command_adj < argc && strstr(argv[command_adj],"=")) {
cursor_adj -= 1;
command_adj += 1;
}
/* Various commands are generally prefixes */
if (command_adj < argc && (
!strcmp(argv[command_adj], "sudo") ||
!strcmp(argv[command_adj], "gsudo") ||
!strcmp(argv[command_adj], "time") ||
/* TODO: Both of these may take additional arguments... */
!strcmp(argv[command_adj], "strace") ||
!strcmp(argv[command_adj], "dbg")
)) {
cursor_adj -= 1;
command_adj += 1;
}
/* initial tab completion should be commands, unless typing a file path */
if (cursor_adj == 0 && !strchr(prefix,'/')) {
complete_mode = COMPLETE_COMMAND;
}
if (cursor_adj >= 1 && !strcmp(argv[command_adj], "toggle-abs-mouse")) {
complete_mode = COMPLETE_CUSTOM;
}
if (cursor_adj >= 1 && !strcmp(argv[command_adj], "msk")) {
complete_mode = COMPLETE_CUSTOM;
}
if (cursor_adj >= 1 && !strcmp(argv[command_adj], "ifconfig")) {
complete_mode = COMPLETE_CUSTOM;
}
if (cursor_adj >= 1 && !strcmp(argv[command_adj], "unset")) {
complete_mode = COMPLETE_VARIABLE;
}
/* complete variable names */
if (*prefix == '$') {
complete_mode = COMPLETE_VARIABLE;
with_dollar = 1;
}
if (complete_mode == COMPLETE_COMMAND) {
/* Complete a command name */
for (int i = 0; i < shell_commands_len; ++i) {
if (strstr(shell_commands[i], prefix) == shell_commands[i]) {
list_insert(matches, shell_commands[i]);
match = shell_commands[i];
}
}
} else if (complete_mode == COMPLETE_FILE) {
/* Complete a file path */
free_matches = 1;
char * tmp = strdup(prefix);
char * last_slash = strrchr(tmp, '/');
DIR * dirp;
char * compare = prefix;
if (last_slash) {
*last_slash = '\0';
word = word + (last_slash - tmp) + 1;
word_offset = word_offset - (last_slash - tmp + 1);
compare = word;
if (last_slash == tmp) {
dirp = opendir("/");
} else {
char * home;
if (*tmp == '~' && (home = getenv("HOME"))) {
char * t = malloc(strlen(tmp) + strlen(home) + 4);
sprintf(t, "%s%s",home,tmp+1);
dirp = opendir(t);
free(t);
} else {
dirp = opendir(tmp);
}
}
} else {
dirp = opendir(".");
}
if (!dirp) {
free(tmp);
goto finish_tab;
}
struct dirent * ent = readdir(dirp);
while (ent != NULL) {
if (ent->d_name[0] != '.' || compare[0] == '.') {
if (!word || strstr(ent->d_name, compare) == ent->d_name) {
struct stat statbuf;
/* stat it */
if (last_slash) {
char * x;
char * home;
if (tmp[0] == '~' && (home = getenv("HOME"))) {
x = malloc(strlen(tmp) + 1 + strlen(ent->d_name) + 1 + strlen(home) + 1);
snprintf(x, strlen(tmp) + 1 + strlen(ent->d_name) + 1 + strlen(home) + 1, "%s%s/%s",home,tmp+1,ent->d_name);
} else {
x = malloc(strlen(tmp) + 1 + strlen(ent->d_name) + 1);
snprintf(x, strlen(tmp) + 1 + strlen(ent->d_name) + 1, "%s/%s",tmp,ent->d_name);
}
lstat(x, &statbuf);
free(x);
} else {
lstat(ent->d_name, &statbuf);
}
char * s;
if (S_ISDIR(statbuf.st_mode)) {
s = malloc(strlen(ent->d_name) + 2);
sprintf(s,"%s/", ent->d_name);
no_space_if_only = 1;
} else {
s = strdup(ent->d_name);
}
list_insert(matches, s);
match = s;
}
}
ent = readdir(dirp);
}
closedir(dirp);
free(tmp);
} else if (complete_mode == COMPLETE_CUSTOM) {
char * none[] = {NULL};
char ** completions = none;
char * toggle_abs_mouse_completions[] = {"relative","absolute",NULL};
char * msk_commands[] = {"update","install","list","count","--version",NULL};
char * ifconfig_commands[] = {"inet","netmask","gateway",NULL};
if (!strcmp(argv[command_adj],"toggle-abs-mouse")) {
completions = toggle_abs_mouse_completions;
} else if (!strcmp(argv[command_adj], "msk")) {
if (cursor_adj == 1) {
completions = msk_commands;
} else if (cursor_adj > 1 && !strcmp(argv[command_adj+1],"install")) {
FILE * f = fopen("/var/msk/manifest","r");
list_t * packages = list_create();
if (f) {
while (!feof(f)) {
char tmp[4096] = {0};
if (!fgets(tmp, 4096, f)) break;
if (tmp[0] == '[') {
char * s = strstr(tmp, "]");
if (s) { *s = '\0'; }
list_insert(packages, strdup(tmp+1));
}
}
completions = malloc(sizeof(char *) * (packages->length + 1));
free_matches = 1;
size_t i = 0;
foreach(node, packages) {
completions[i++] = node->value;
}
completions[i] = NULL;
list_free(packages);
}
}
} else if (!strcmp(argv[command_adj], "ifconfig")) {
if (cursor_adj == 1) {
/* interface names */
DIR * d = opendir("/dev/net");
if (d) {
free_matches = 1;
list_t * interfaces = list_create();
struct dirent * ent;
while ((ent = readdir(d))) {
if (ent->d_name[0] == '.') continue;
list_insert(interfaces, strdup(ent->d_name));
}
closedir(d);
completions = malloc(sizeof(char*) * (interfaces->length + 1));
size_t i = 0;
foreach(node, interfaces) {
completions[i++] = node->value;
}
completions[i] = NULL;
list_free(interfaces);
}
} else if (cursor_adj > 1) {
completions = ifconfig_commands;
}
}
while (*completions) {
if (strstr(*completions, prefix) == *completions) {
list_insert(matches, *completions);
match = *completions;
}
completions++;
}
} else if (complete_mode == COMPLETE_VARIABLE) {
char ** envvar = environ;
free_matches = 1;
while (*envvar) {
char * tmp = strdup(*envvar);
char * c = strchr(tmp, '=');
*c = '\0';
if (strstr(tmp, prefix+with_dollar) == tmp) {
char * m = malloc(strlen(tmp)+1+with_dollar);
sprintf(m, "%s%s", with_dollar ? "$" : "", tmp);
list_insert(matches, m);
match = m;
}
free(tmp);
envvar++;
}
}
if (matches->length == 1) {
/* Insert */
rline_insert(c, &match[word_offset]);
if (word && word_offset == (int)strlen(word) && !no_space_if_only) {
rline_insert(c, " ");
}
rline_redraw(c);
} else if (matches->length > 1) {
if (!c->tabbed) {
/* see if there is a minimum subset we can fill in */
size_t j = word_offset;
do {
char d = match[j];
int diff = 0;
foreach(node, matches) {
char * match = (char *)node->value;
if (match[j] != d || match[j] == '\0') diff = 1;
}
if (diff) break;
j++;
} while (j < (size_t)c->requested);
if (j > (size_t)word_offset) {
char * tmp = strdup(match);
tmp[j] = '\0';
rline_insert(c, &tmp[word_offset]);
rline_redraw(c);
free(tmp);
} else {
c->tabbed = 1;
}
} else {
/* Print matches */
fprintf(stderr,"\n\033[0m");
size_t j = 0;
foreach(node, matches) {
char * match = (char *)node->value;
fprintf(stderr, "%s", match);
++j;
if (j < matches->length) {
fprintf(stderr, ", ");
}
}
fprintf(stderr,"\n");
c->callbacks->redraw_prompt(c);
fprintf(stderr, "\033[s");
rline_redraw(c);
}
}
finish_tab:
if (free_matches) list_destroy(matches);
list_free(matches);
free(prefix);
free(dup);
}
void add_argument(list_t * argv, char * buf) {
char * c = malloc(strlen(buf) + 1);
memcpy(c, buf, strlen(buf) + 1);
list_insert(argv, c);
}
void add_environment(list_t * env) {
if (env->length) {
foreach (node, env) {
char * c = node->value;
putenv(strdup(c));
}
}
}
#define FALLBACK_PS1 "\\u@\\h \\w\\$ "
int read_entry(char * buffer) {
char lprompt[1024], rprompt[1024];
int lwidth, rwidth;
char * ps1 = getenv("PS1_LEFT");
print_extended_ps(ps1 ? ps1 : FALLBACK_PS1, lprompt, &lwidth);
char * ps1r = getenv("PS1_RIGHT");
print_extended_ps(ps1r ? ps1r : "", rprompt, &rwidth);
rline_exit_string="exit";
rline_exp_set_syntax("esh");
rline_exp_set_prompts(lprompt, rprompt, lwidth, rwidth);
rline_exp_set_shell_commands(shell_commands, shell_commands_len);
rline_exp_set_tab_complete_func(tab_complete_func);
return rline(buffer, LINE_LEN);
}
int read_entry_continued(char * buffer) {
rline_exit_string="exit";
rline_exp_set_syntax("esh");
rline_exp_set_prompts("> ", "", 2, 0);
rline_exp_set_shell_commands(shell_commands, shell_commands_len);
rline_exp_set_tab_complete_func(tab_complete_func);
return rline(buffer, LINE_LEN);
}
int variable_char(uint8_t c) {
if (c >= 'A' && c <= 'Z') return 1;
if (c >= 'a' && c <= 'z') return 1;
if (c >= '0' && c <= '9') return 1;
if (c == '_') return 1;
return 0;
}
int variable_char_first(uint8_t c) {
if (c == '?') return 1;
if (c == '$') return 1;
if (c == '#') return 1;
return 0;
}
struct alternative {
const char * command;
const char * replacement;
const char * description;
};
#define ALT_BIM "bim", "vi-like text editor"
#define ALT_FETCH "fetch", "URL downloader"
#define ALT_NETIF "ifconfig", "to see network configuration"
static struct alternative cmd_alternatives[] = {
/* Propose bim as an alternative for common text editors */
{"vim", ALT_BIM},
{"vi", ALT_BIM},
{"emacs", ALT_BIM},
{"nano", ALT_BIM},
/* Propose fetch for some common URL-getting tools */
{"curl", ALT_FETCH},
{"wget", ALT_FETCH},
/* We don't have ip or ifconfig commands, suggest cat /proc/netif */
{"ipconfig", ALT_NETIF},
{"ip", ALT_NETIF},
/* Some random other stuff */
{"more", "bim -", "paging to a text editor"},
{"less", "bim -", "paging to a text editor"},
{NULL, NULL, NULL},
};
void run_cmd(char ** args) {
int i = execvp(*args, args);
shell_command_t func = shell_find(*args);
if (func) {
int argc = 0;
while (args[argc]) {
argc++;
}
i = func(argc, args);
} else {
if (i != 0) {
if (errno == ENOENT) {
fprintf(stderr, "%s: Command not found\n", *args);
for (struct alternative * alt = cmd_alternatives; alt->command; alt++) {
if (!strcmp(*args, alt->command)) {
fprintf(stderr, "Consider this alternative:\n\n\t%s -- \033[3m%s\033[0m\n\n",
alt->replacement,
alt->description);
break;
}
}
} else if (errno == ELOOP) {
fprintf(stderr, "esh: Bad interpreter (maximum recursion depth reached)\n");
} else if (errno == ENOEXEC) {
fprintf(stderr, "esh: Bad interpreter\n");
} else {
fprintf(stderr, "esh: Invalid executable\n");
}
i = 127;
}
}
exit(i);
}
int is_number(const char * c) {
while (*c) {
if (!isdigit(*c)) return 0;
c++;
}
return 1;
}
/**
* Prints "Segmentation fault", etc.
*/
static void handle_status(int ret_code) {
if (WIFSIGNALED(ret_code)) {
int sig = WTERMSIG(ret_code);
if (sig == SIGINT || sig == SIGPIPE) {
fprintf(stderr, "\n");
return;
}
char * str = strsignal(sig);
if (shell_interactive == 1) {
fprintf(stderr, "%s\n", str);
} else if (shell_interactive == 2) {
fprintf(stderr, "%s: line %d: %s\n", current_file, current_line, str);
}
}
}
static void describe_job(pid_t pid);
int wait_for_child(int pgid, char * name, int retpid) {
int waitee = (shell_interactive == 1 && !is_subshell) ? -pgid : pgid;
int outpid;
int ret_code = 0;
int ret_code_real = 0;
int e;
int _stopped = 0;
do {
outpid = waitpid(waitee, &ret_code, WSTOPPED);
e = errno;
if (outpid == retpid) {
ret_code_real = ret_code;
}
if (outpid != -1 && WIFSTOPPED(ret_code)) {
suspended_pgid = pgid;
if (name) {
void * old = hashmap_set(job_hash, (void*)(intptr_t)pgid, strdup(name));
if (old) free(old);
}
void * old = hashmap_set(desc_hash, (void*)(intptr_t)pgid, strdup(WSTOPSIG(ret_code) ? strsignal(WSTOPSIG(ret_code)) : "Stopped"));
if (old) free(old);
_stopped = 1;
if (!shell_interactive) continue;
break;
} else if (outpid != -1) {
suspended_pgid = 0;
if (hashmap_has(job_hash, (void*)(intptr_t)pgid)) {
hashmap_remove(job_hash, (void*)(intptr_t)pgid);
hashmap_remove(desc_hash, (void*)(intptr_t)pgid);
}
}
} while (outpid != -1 || (outpid == -1 && e != ECHILD));
reset_pgrp();
handle_status(ret_code_real);
if (_stopped && shell_interactive) {
fprintf(stderr, "\n");
describe_job(pgid);
}
return WEXITSTATUS(ret_code_real);
}
int shell_exec(char * buffer, size_t size, FILE * file, char ** out_buffer) {
*out_buffer = NULL;
/* Read previous history entries */
if (buffer[0] == '!') {
int x = atoi((char *)((uintptr_t)buffer + 1));
if (x > 0 && x <= rline_history_count) {
buffer = rline_history_get(x - 1);
} else {
fprintf(stderr, "esh: !%d: event not found\n", x);
return 0;
}
}
char * argv[1024];
int tokenid = 0;
char quoted = 0;
char backtick = 0;
char buffer_[512] = {0};
int collected = 0;
int force_collected = 0;
list_t * args = list_create();
int have_star = 0;
while (1) {
char * p = buffer;
while (*p) {
switch (*p) {
case '$':
if (quoted == '\'') {
goto _just_add;
} else {
if (backtick) {
goto _just_add;
}
p++;
char var[100];
int coll = 0;
if (*p == '{') {
p++;
while (*p != '}' && *p != '\0' && (coll < 100)) {
var[coll] = *p;
coll++;
var[coll] = '\0';
p++;
}
if (*p == '}') {
p++;
}
} else {
while (*p != '\0' && (variable_char(*p) || (coll == 0 && variable_char_first(*p))) && (coll < 100)) {
var[coll] = *p;
coll++;
var[coll] = '\0';
if (coll == 1 && (isdigit(*p) || *p == '?' || *p == '$' || *p == '#')) {
p++;
break; /* Don't let these keep going */
}
p++;
}
}
/* Special cases */
char *c = NULL;
char tmp[128];
if (!strcmp(var, "?")) {
sprintf(tmp,"%d",last_ret);
c = tmp;
} else if (!strcmp(var, "$")) {
sprintf(tmp,"%d",getpid());
c = tmp;
} else if (!strcmp(var, "#")) {
sprintf(tmp,"%d",shell_argc ? shell_argc-1 : 0);
c = tmp;
} else if (is_number(var)) {
int a = atoi(var);
if (a >= 0 && a < shell_argc) {
c = shell_argv[a];
}
} else if (!strcmp(var, "RANDOM")) {
sprintf(tmp,"%d",rand()%32768); /* sure, modulo is bad for range restriction, shut up */
c = tmp;
} else {
c = getenv(var);
}
if (c) {
backtick = 0;
for (int i = 0; i < (int)strlen(c); ++i) {