sh.c 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316
  1. /* vim: tabstop=4 shiftwidth=4 noexpandtab
  2. * This file is part of ToaruOS and is released under the terms
  3. * of the NCSA / University of Illinois License - see LICENSE.md
  4. * Copyright (C) 2013-2018 K. Lange
  5. *
  6. * E-Shell
  7. *
  8. * This is "experimental shell" - a vaguely-unix-like command
  9. * interface. It has a very rudimentary parser that understands
  10. * some things like pipes or writing out to a file. It has a
  11. * handful of built-in commands, including ones that implement
  12. * some more useful shell syntax such as loops and conditionals.
  13. * There is support for tab completion of filenames and commands.
  14. */
  15. #define _XOPEN_SOURCE 500
  16. #define _POSIX_C_SOURCE 200112L
  17. #include <stdio.h>
  18. #include <stdint.h>
  19. #include <string.h>
  20. #include <stdlib.h>
  21. #include <unistd.h>
  22. #include <time.h>
  23. #include <dirent.h>
  24. #include <signal.h>
  25. #include <getopt.h>
  26. #include <termios.h>
  27. #include <errno.h>
  28. #include <fcntl.h>
  29. #include <ctype.h>
  30. #include <sys/time.h>
  31. #include <sys/wait.h>
  32. #include <sys/utsname.h>
  33. #include <sys/stat.h>
  34. #include <toaru/list.h>
  35. #include <toaru/hashmap.h>
  36. #include <toaru/kbd.h>
  37. #include <toaru/rline.h>
  38. #include <toaru/rline_exp.h>
  39. #ifndef environ
  40. extern char **environ;
  41. #endif
  42. #define PIPE_TOKEN "\xFF\xFFPIPE\xFF\xFF"
  43. #define STAR_TOKEN "\xFF\xFFSTAR\xFF\xFF"
  44. #define WRITE_TOKEN "\xFF\xFFWRITE\xFF\xFF"
  45. #define WRITE_ERR_TOKEN "\xFF\xFFWRITEERR\xFF\xFF"
  46. #define APPEND_TOKEN "\xFF\xFF""APPEND\xFF"
  47. /* A shell command is like a C program */
  48. typedef uint32_t(*shell_command_t) (int argc, char ** argv);
  49. /* We have a static array that fits a certain number of them. */
  50. int SHELL_COMMANDS = 64;
  51. char ** shell_commands; /* Command names */
  52. shell_command_t * shell_pointers; /* Command functions */
  53. char ** shell_descript; /* Command descriptions */
  54. /* This is the number of actual commands installed */
  55. int shell_commands_len = 0;
  56. int shell_interactive = 1;
  57. int last_ret = 0;
  58. char ** shell_argv = NULL;
  59. int shell_argc = 0;
  60. int experimental_rline = 1;
  61. static int current_line = 0;
  62. static char * current_file = NULL;
  63. int pid; /* Process ID of the shell */
  64. int my_pgid;
  65. int is_subshell = 0;
  66. struct semaphore {
  67. int fds[2];
  68. };
  69. struct semaphore create_semaphore(void) {
  70. struct semaphore out;
  71. pipe(out.fds);
  72. return out;
  73. }
  74. void raise_semaphore(struct semaphore s){
  75. close(s.fds[0]);
  76. close(s.fds[1]);
  77. }
  78. void wait_semaphore(struct semaphore s) {
  79. close(s.fds[1]);
  80. char buf;
  81. read(s.fds[0], &buf, 1);
  82. close(s.fds[0]);
  83. }
  84. void set_pgid(int pgid) {
  85. if (shell_interactive == 1) {
  86. setpgid(0, pgid);
  87. }
  88. }
  89. void set_pgrp(int pgid) {
  90. if (shell_interactive == 1 && !is_subshell) {
  91. tcsetpgrp(STDIN_FILENO, pgid);
  92. }
  93. }
  94. void reset_pgrp() {
  95. if (shell_interactive == 1 && !is_subshell) {
  96. tcsetpgrp(STDIN_FILENO, my_pgid);
  97. }
  98. }
  99. void shell_install_command(char * name, shell_command_t func, char * desc) {
  100. if (shell_commands_len == SHELL_COMMANDS-1) {
  101. SHELL_COMMANDS *= 2;
  102. shell_commands = realloc(shell_commands, sizeof(char *) * SHELL_COMMANDS);
  103. shell_pointers = realloc(shell_pointers, sizeof(shell_command_t) * SHELL_COMMANDS);
  104. shell_descript = realloc(shell_descript, sizeof(char *) * SHELL_COMMANDS);
  105. }
  106. shell_commands[shell_commands_len] = name;
  107. shell_pointers[shell_commands_len] = func;
  108. shell_descript[shell_commands_len] = desc;
  109. shell_commands_len++;
  110. shell_commands[shell_commands_len] = NULL;
  111. }
  112. shell_command_t shell_find(char * str) {
  113. for (int i = 0; i < shell_commands_len; ++i) {
  114. if (!strcmp(str, shell_commands[i])) {
  115. return shell_pointers[i];
  116. }
  117. }
  118. return NULL;
  119. }
  120. void install_commands();
  121. /* Maximum command length */
  122. #define LINE_LEN 4096
  123. /* Current working directory */
  124. char cwd[1024] = {'/',0};
  125. /* Username */
  126. char username[1024];
  127. /* Hostname for prompt */
  128. char _hostname[256];
  129. /* function to update the cached username */
  130. void getuser() {
  131. char * tmp = getenv("USER");
  132. if (tmp) {
  133. strcpy(username, tmp);
  134. } else {
  135. sprintf(username, "%d", getuid());
  136. }
  137. }
  138. /* function to update the cached hostname */
  139. void gethost() {
  140. struct utsname buf;
  141. uname(&buf);
  142. int len = strlen(buf.nodename);
  143. memcpy(_hostname, buf.nodename, len+1);
  144. }
  145. void print_extended_ps(char * format, char * buffer, int * display_width) {
  146. /* Get the time */
  147. struct tm * timeinfo;
  148. struct timeval now;
  149. gettimeofday(&now, NULL); //time(NULL);
  150. timeinfo = localtime((time_t *)&now.tv_sec);
  151. /* Format the date and time for prompt display */
  152. char date_buffer[80];
  153. strftime(date_buffer, 80, "%m/%d", timeinfo);
  154. char time_buffer[80];
  155. strftime(time_buffer, 80, "%H:%M:%S", timeinfo);
  156. /* Collect the current working directory */
  157. getcwd(cwd, 512);
  158. char _cwd[512];
  159. strcpy(_cwd, cwd);
  160. /* Collect the user's home directory and apply it to cwd */
  161. char * home = getenv("HOME");
  162. if (home && strstr(cwd, home) == cwd) {
  163. char * c = cwd + strlen(home);
  164. if (*c == '/' || *c == 0) {
  165. sprintf(_cwd, "~%s", c);
  166. }
  167. }
  168. char ret[80] = {0};
  169. if (last_ret != 0) {
  170. sprintf(ret, "%d ", last_ret);
  171. }
  172. size_t offset = 0;
  173. int is_visible = 1;
  174. *display_width = 0;
  175. while (*format) {
  176. if (*format == '\\') {
  177. format++;
  178. switch (*format) {
  179. case '\\':
  180. buffer[offset++] = *format;
  181. (*display_width) += is_visible ? 1 : 0;
  182. format++;
  183. break;
  184. case '[':
  185. is_visible = 0;
  186. format++;
  187. break;
  188. case ']':
  189. is_visible = 1;
  190. format++;
  191. break;
  192. case '0':
  193. case '1':
  194. case '2':
  195. case '3':
  196. case '4':
  197. case '5':
  198. case '6':
  199. case '7':
  200. {
  201. int i = (*format) - '0';
  202. format++;
  203. if (*format >= '0' && *format <= '7') {
  204. i *= 8;
  205. i += (*format) - '0';
  206. format++;
  207. if (*format >= '0' && *format <= '7') {
  208. i *= 8;
  209. i += (*format) - '0';
  210. format++;
  211. }
  212. }
  213. buffer[offset++] = i;
  214. (*display_width) += is_visible ? 1 : 0;
  215. }
  216. break;
  217. case 'e':
  218. buffer[offset++] = '\033';
  219. (*display_width) += is_visible ? 1 : 0;
  220. format++;
  221. break;
  222. case 'd':
  223. {
  224. int size = sprintf(buffer+offset, "%s", date_buffer);
  225. offset += size;
  226. (*display_width) += is_visible ? size : 0;
  227. }
  228. format++;
  229. break;
  230. case 't':
  231. {
  232. int size = sprintf(buffer+offset, "%s", time_buffer);
  233. offset += size;
  234. (*display_width) += is_visible ? size : 0;
  235. }
  236. format++;
  237. break;
  238. case 'h':
  239. {
  240. int size = sprintf(buffer+offset, "%s", _hostname);
  241. offset += size;
  242. (*display_width) += is_visible ? size : 0;
  243. }
  244. format++;
  245. break;
  246. case 'u':
  247. {
  248. int size = sprintf(buffer+offset, "%s", username);
  249. offset += size;
  250. (*display_width) += is_visible ? size : 0;
  251. }
  252. format++;
  253. break;
  254. case 'w':
  255. {
  256. int size = sprintf(buffer+offset, "%s", _cwd);
  257. offset += size;
  258. (*display_width) += is_visible ? size : 0;
  259. }
  260. format++;
  261. break;
  262. case '$':
  263. buffer[offset++] = (getuid() == 0 ? '#' : '$');
  264. (*display_width) += is_visible ? 1 : 0;
  265. format++;
  266. break;
  267. case 'U': /* prompt color string */
  268. {
  269. int size = sprintf(buffer+offset, "%s", getuid() == 0 ? "\033[1;38;5;196m" : "\033[1;38;5;47m");
  270. offset += size;
  271. /* Does not affect size */
  272. }
  273. format++;
  274. break;
  275. case 'r':
  276. {
  277. int size = sprintf(buffer+offset, "%s", ret);
  278. offset += size;
  279. (*display_width) += is_visible ? size : 0;
  280. }
  281. format++;
  282. break;
  283. default:
  284. {
  285. int size = sprintf(buffer+offset, "\\%c", *format);
  286. offset += size;
  287. (*display_width) += is_visible ? size : 0;
  288. }
  289. format++;
  290. break;
  291. }
  292. } else {
  293. buffer[offset++] = *format;
  294. (*display_width) += is_visible ? 1 : 0;
  295. format++;
  296. }
  297. }
  298. buffer[offset] = '\0';
  299. }
  300. #define FALLBACK_PS1 "\\u@\\h \\w\\$ "
  301. /* Draw the user prompt */
  302. void draw_prompt(void) {
  303. char * ps1 = getenv("PS1");
  304. char buf[1024];
  305. int display_width;
  306. print_extended_ps(ps1 ? ps1 : FALLBACK_PS1, buf, &display_width);
  307. fprintf(stdout, "%s", buf);
  308. fflush(stdout);
  309. }
  310. volatile int break_while = 0;
  311. pid_t suspended_pgid = 0;
  312. hashmap_t * job_hash = NULL;
  313. void sig_break_loop(int sig) {
  314. /* Interrupt handler */
  315. if ((shell_interactive == 1 && !is_subshell)) {
  316. break_while = sig;
  317. signal(sig, sig_break_loop);
  318. } else {
  319. signal(sig, SIG_DFL);
  320. raise(sig);
  321. }
  322. }
  323. void redraw_prompt_func(rline_context_t * context) {
  324. draw_prompt();
  325. }
  326. void draw_prompt_c() {
  327. char * ps2 = getenv("PS2");
  328. if (ps2) {
  329. char buf[1024];
  330. int display_width;
  331. print_extended_ps(ps2, buf, &display_width);
  332. fprintf(stdout, "%s", buf);
  333. } else {
  334. printf("> ");
  335. }
  336. fflush(stdout);
  337. }
  338. void redraw_prompt_func_c(rline_context_t * context) {
  339. draw_prompt_c();
  340. }
  341. void tab_complete_func(rline_context_t * c) {
  342. char * dup = malloc(LINE_LEN);
  343. memcpy(dup, c->buffer, LINE_LEN);
  344. char *pch, *save;
  345. char *argv[1024];
  346. int argc = 0;
  347. int cursor = 0;
  348. pch = strtok_r(dup, " ", &save);
  349. if (!pch) {
  350. argv[0] = "";
  351. argc = 0;
  352. }
  353. while (pch != NULL) {
  354. if (pch - dup <= c->offset) cursor = argc;
  355. argv[argc] = pch;
  356. ++argc;
  357. pch = strtok_r(NULL, " ", &save);
  358. }
  359. argv[argc] = NULL;
  360. if (c->offset && c->buffer[c->offset-1] == ' ' && argc) {
  361. cursor++;
  362. }
  363. char * word = argv[cursor];
  364. int word_offset = word ? (c->offset - (argv[cursor] - dup)) : 0;
  365. char * prefix = malloc(word_offset + 1);
  366. if (word) memcpy(prefix, word, word_offset);
  367. prefix[word_offset] = '\0';
  368. /* Complete file path */
  369. list_t * matches = list_create();
  370. char * match = NULL;
  371. int free_matches = 0;
  372. int no_space_if_only = 0;
  373. /* TODO custom auto-complete as a configuration file? */
  374. #define COMPLETE_FILE 1
  375. #define COMPLETE_COMMAND 2
  376. #define COMPLETE_CUSTOM 3
  377. #define COMPLETE_VARIABLE 4
  378. int complete_mode = COMPLETE_FILE;
  379. int with_dollar = 0;
  380. int command_adj = 0;
  381. int cursor_adj = cursor;
  382. while (command_adj < argc && strstr(argv[command_adj],"=")) {
  383. cursor_adj -= 1;
  384. command_adj += 1;
  385. }
  386. /* sudo should shift commands */
  387. if (command_adj < argc && (!strcmp(argv[command_adj], "sudo") || !strcmp(argv[command_adj], "gsudo"))) {
  388. cursor_adj -= 1;
  389. command_adj += 1;
  390. }
  391. /* initial tab completion should be commands, unless typing a file path */
  392. if (cursor_adj == 0 && !strchr(prefix,'/')) {
  393. complete_mode = COMPLETE_COMMAND;
  394. }
  395. if (cursor_adj >= 1 && !strcmp(argv[command_adj], "toggle-abs-mouse")) {
  396. complete_mode = COMPLETE_CUSTOM;
  397. }
  398. if (cursor_adj >= 1 && !strcmp(argv[command_adj], "msk")) {
  399. complete_mode = COMPLETE_CUSTOM;
  400. }
  401. if (cursor_adj >= 1 && !strcmp(argv[command_adj], "unset")) {
  402. complete_mode = COMPLETE_VARIABLE;
  403. }
  404. /* complete variable names */
  405. if (*prefix == '$') {
  406. complete_mode = COMPLETE_VARIABLE;
  407. with_dollar = 1;
  408. }
  409. if (complete_mode == COMPLETE_COMMAND) {
  410. /* Complete a command name */
  411. for (int i = 0; i < shell_commands_len; ++i) {
  412. if (strstr(shell_commands[i], prefix) == shell_commands[i]) {
  413. list_insert(matches, shell_commands[i]);
  414. match = shell_commands[i];
  415. }
  416. }
  417. } else if (complete_mode == COMPLETE_FILE) {
  418. /* Complete a file path */
  419. free_matches = 1;
  420. char * tmp = strdup(prefix);
  421. char * last_slash = strrchr(tmp, '/');
  422. DIR * dirp;
  423. char * compare = prefix;
  424. if (last_slash) {
  425. *last_slash = '\0';
  426. word = word + (last_slash - tmp) + 1;
  427. word_offset = word_offset - (last_slash - tmp + 1);
  428. compare = word;
  429. if (last_slash == tmp) {
  430. dirp = opendir("/");
  431. } else {
  432. char * home;
  433. if (*tmp == '~' && (home = getenv("HOME"))) {
  434. char * t = malloc(strlen(tmp) + strlen(home) + 4);
  435. sprintf(t, "%s%s",home,tmp+1);
  436. dirp = opendir(t);
  437. free(t);
  438. } else {
  439. dirp = opendir(tmp);
  440. }
  441. }
  442. } else {
  443. dirp = opendir(".");
  444. }
  445. if (!dirp) {
  446. free(tmp);
  447. goto finish_tab;
  448. }
  449. struct dirent * ent = readdir(dirp);
  450. while (ent != NULL) {
  451. if (ent->d_name[0] != '.' || compare[0] == '.') {
  452. if (!word || strstr(ent->d_name, compare) == ent->d_name) {
  453. struct stat statbuf;
  454. /* stat it */
  455. if (last_slash) {
  456. char * x;
  457. char * home;
  458. if (tmp[0] == '~' && (home = getenv("HOME"))) {
  459. x = malloc(strlen(tmp) + 1 + strlen(ent->d_name) + 1 + strlen(home) + 1);
  460. snprintf(x, strlen(tmp) + 1 + strlen(ent->d_name) + 1 + strlen(home) + 1, "%s%s/%s",home,tmp+1,ent->d_name);
  461. } else {
  462. x = malloc(strlen(tmp) + 1 + strlen(ent->d_name) + 1);
  463. snprintf(x, strlen(tmp) + 1 + strlen(ent->d_name) + 1, "%s/%s",tmp,ent->d_name);
  464. }
  465. lstat(x, &statbuf);
  466. free(x);
  467. } else {
  468. lstat(ent->d_name, &statbuf);
  469. }
  470. char * s;
  471. if (S_ISDIR(statbuf.st_mode)) {
  472. s = malloc(strlen(ent->d_name) + 2);
  473. sprintf(s,"%s/", ent->d_name);
  474. no_space_if_only = 1;
  475. } else {
  476. s = strdup(ent->d_name);
  477. }
  478. list_insert(matches, s);
  479. match = s;
  480. }
  481. }
  482. ent = readdir(dirp);
  483. }
  484. closedir(dirp);
  485. free(tmp);
  486. } else if (complete_mode == COMPLETE_CUSTOM) {
  487. char * none[] = {NULL};
  488. char ** completions = none;
  489. char * toggle_abs_mouse_completions[] = {"relative","absolute",NULL};
  490. char * msk_commands[] = {"update","install","list","count","--version",NULL};
  491. if (!strcmp(argv[command_adj],"toggle-abs-mouse")) {
  492. completions = toggle_abs_mouse_completions;
  493. } else if (!strcmp(argv[command_adj], "msk")) {
  494. if (cursor_adj == 1) {
  495. completions = msk_commands;
  496. } else if (cursor_adj > 1 && !strcmp(argv[command_adj+1],"install")) {
  497. FILE * f = fopen("/var/msk/manifest","r");
  498. list_t * packages = list_create();
  499. if (f) {
  500. while (!feof(f)) {
  501. char tmp[4096] = {0};
  502. if (!fgets(tmp, 4096, f)) break;
  503. if (tmp[0] == '[') {
  504. char * s = strstr(tmp, "]");
  505. if (s) { *s = '\0'; }
  506. list_insert(packages, strdup(tmp+1));
  507. }
  508. }
  509. completions = malloc(sizeof(char *) * (packages->length + 1));
  510. free_matches = 1;
  511. size_t i = 0;
  512. foreach(node, packages) {
  513. completions[i++] = node->value;
  514. }
  515. completions[i] = NULL;
  516. list_free(packages);
  517. }
  518. }
  519. }
  520. while (*completions) {
  521. if (strstr(*completions, prefix) == *completions) {
  522. list_insert(matches, *completions);
  523. match = *completions;
  524. }
  525. completions++;
  526. }
  527. } else if (complete_mode == COMPLETE_VARIABLE) {
  528. char ** envvar = environ;
  529. free_matches = 1;
  530. while (*envvar) {
  531. char * tmp = strdup(*envvar);
  532. char * c = strchr(tmp, '=');
  533. *c = '\0';
  534. if (strstr(tmp, prefix+with_dollar) == tmp) {
  535. char * m = malloc(strlen(tmp)+1+with_dollar);
  536. sprintf(m, "%s%s", with_dollar ? "$" : "", tmp);
  537. list_insert(matches, m);
  538. match = m;
  539. }
  540. free(tmp);
  541. envvar++;
  542. }
  543. }
  544. if (matches->length == 1) {
  545. /* Insert */
  546. rline_insert(c, &match[word_offset]);
  547. if (word && word_offset == (int)strlen(word) && !no_space_if_only) {
  548. rline_insert(c, " ");
  549. }
  550. rline_redraw(c);
  551. } else if (matches->length > 1) {
  552. if (!c->tabbed) {
  553. /* see if there is a minimum subset we can fill in */
  554. size_t j = word_offset;
  555. do {
  556. char d = match[j];
  557. int diff = 0;
  558. foreach(node, matches) {
  559. char * match = (char *)node->value;
  560. if (match[j] != d || match[j] == '\0') diff = 1;
  561. }
  562. if (diff) break;
  563. j++;
  564. } while (j < (size_t)c->requested);
  565. if (j > (size_t)word_offset) {
  566. char * tmp = strdup(match);
  567. tmp[j] = '\0';
  568. rline_insert(c, &tmp[word_offset]);
  569. rline_redraw(c);
  570. free(tmp);
  571. } else {
  572. c->tabbed = 1;
  573. }
  574. } else {
  575. /* Print matches */
  576. fprintf(stderr,"\n\033[0m");
  577. size_t j = 0;
  578. foreach(node, matches) {
  579. char * match = (char *)node->value;
  580. fprintf(stderr, "%s", match);
  581. ++j;
  582. if (j < matches->length) {
  583. fprintf(stderr, ", ");
  584. }
  585. }
  586. fprintf(stderr,"\n");
  587. c->callbacks->redraw_prompt(c);
  588. fprintf(stderr, "\033[s");
  589. rline_redraw(c);
  590. }
  591. }
  592. finish_tab:
  593. if (free_matches) list_destroy(matches);
  594. list_free(matches);
  595. free(prefix);
  596. free(dup);
  597. }
  598. void add_argument(list_t * argv, char * buf) {
  599. char * c = malloc(strlen(buf) + 1);
  600. memcpy(c, buf, strlen(buf) + 1);
  601. list_insert(argv, c);
  602. }
  603. void add_environment(list_t * env) {
  604. if (env->length) {
  605. foreach (node, env) {
  606. char * c = node->value;
  607. putenv(strdup(c));
  608. }
  609. }
  610. }
  611. int read_entry(char * buffer) {
  612. if (experimental_rline) {
  613. char lprompt[1024], rprompt[1024];
  614. int lwidth, rwidth;
  615. char * ps1 = getenv("PS1_LEFT");
  616. print_extended_ps(ps1 ? ps1 : FALLBACK_PS1, lprompt, &lwidth);
  617. char * ps1r = getenv("PS1_RIGHT");
  618. print_extended_ps(ps1r ? ps1r : "", rprompt, &rwidth);
  619. rline_exit_string="exit";
  620. rline_exp_set_syntax("esh");
  621. rline_exp_set_prompts(lprompt, rprompt, lwidth, rwidth);
  622. rline_exp_set_shell_commands(shell_commands, shell_commands_len);
  623. rline_exp_set_tab_complete_func(tab_complete_func);
  624. return rline_experimental(buffer, LINE_LEN);
  625. } else {
  626. rline_callbacks_t callbacks = {
  627. tab_complete_func, redraw_prompt_func, NULL,
  628. NULL, NULL, NULL, NULL, NULL
  629. };
  630. draw_prompt();
  631. return rline((char *)buffer, LINE_LEN, &callbacks);
  632. }
  633. }
  634. int read_entry_continued(char * buffer) {
  635. if (experimental_rline) {
  636. rline_exit_string="exit";
  637. rline_exp_set_syntax("esh");
  638. rline_exp_set_prompts("> ", "", 2, 0);
  639. rline_exp_set_shell_commands(shell_commands, shell_commands_len);
  640. rline_exp_set_tab_complete_func(tab_complete_func);
  641. return rline_experimental(buffer, LINE_LEN);
  642. } else {
  643. rline_callbacks_t callbacks = {
  644. tab_complete_func, redraw_prompt_func_c, NULL,
  645. NULL, NULL, NULL, NULL, NULL
  646. };
  647. draw_prompt_c();
  648. return rline((char *)buffer, LINE_LEN, &callbacks);
  649. }
  650. }
  651. int variable_char(uint8_t c) {
  652. if (c >= 'A' && c <= 'Z') return 1;
  653. if (c >= 'a' && c <= 'z') return 1;
  654. if (c >= '0' && c <= '9') return 1;
  655. if (c == '_') return 1;
  656. return 0;
  657. }
  658. int variable_char_first(uint8_t c) {
  659. if (c == '?') return 1;
  660. if (c == '$') return 1;
  661. if (c == '#') return 1;
  662. return 0;
  663. }
  664. struct alternative {
  665. const char * command;
  666. const char * replacement;
  667. const char * description;
  668. };
  669. #define ALT_BIM "bim", "vi-like text editor"
  670. #define ALT_FETCH "fetch", "URL downloader"
  671. #define ALT_NETIF "cat /proc/netif", "to see network configuration"
  672. static struct alternative cmd_alternatives[] = {
  673. /* Propose bim as an alternative for common text editors */
  674. {"vim", ALT_BIM},
  675. {"vi", ALT_BIM},
  676. {"emacs", ALT_BIM},
  677. {"nano", ALT_BIM},
  678. /* Propose fetch for some common URL-getting tools */
  679. {"curl", ALT_FETCH},
  680. {"wget", ALT_FETCH},
  681. /* We don't have ip or ifconfig commands, suggest cat /proc/netif */
  682. {"ifconfig", ALT_NETIF},
  683. {"ipconfig", ALT_NETIF},
  684. {"ip", ALT_NETIF},
  685. /* Some random other stuff */
  686. {"grep", "fgrep", "non-regex-capable grep"},
  687. {"more", "bim -", "paging to a text editor"},
  688. {"less", "bim -", "paging to a text editor"},
  689. {NULL, NULL, NULL},
  690. };
  691. void run_cmd(char ** args) {
  692. int i = execvp(*args, args);
  693. shell_command_t func = shell_find(*args);
  694. if (func) {
  695. int argc = 0;
  696. while (args[argc]) {
  697. argc++;
  698. }
  699. i = func(argc, args);
  700. } else {
  701. if (i != 0) {
  702. if (errno == ENOENT) {
  703. fprintf(stderr, "%s: Command not found\n", *args);
  704. for (struct alternative * alt = cmd_alternatives; alt->command; alt++) {
  705. if (!strcmp(*args, alt->command)) {
  706. fprintf(stderr, "Consider this alternative:\n\n\t%s -- \033[3m%s\033[0m\n\n",
  707. alt->replacement,
  708. alt->description);
  709. break;
  710. }
  711. }
  712. } else if (errno == ELOOP) {
  713. fprintf(stderr, "esh: Bad interpreter (maximum recursion depth reached)\n");
  714. } else if (errno == ENOEXEC) {
  715. fprintf(stderr, "esh: Bad interpreter\n");
  716. } else {
  717. fprintf(stderr, "esh: Invalid executable\n");
  718. }
  719. i = 127;
  720. }
  721. }
  722. exit(i);
  723. }
  724. int is_number(const char * c) {
  725. while (*c) {
  726. if (!isdigit(*c)) return 0;
  727. c++;
  728. }
  729. return 1;
  730. }
  731. static char * _strsignal(int sig) {
  732. static char str[256];
  733. memset(str, 0, sizeof(str));
  734. switch (sig) {
  735. case SIGILL:
  736. sprintf(str, "Illegal instruction");
  737. break;
  738. case SIGSEGV:
  739. sprintf(str, "Segmentation fault");
  740. break;
  741. case SIGTERM:
  742. sprintf(str, "Terminated");
  743. break;
  744. case SIGQUIT:
  745. sprintf(str, "Quit");
  746. break;
  747. case SIGKILL:
  748. sprintf(str, "Killed");
  749. break;
  750. case SIGHUP:
  751. sprintf(str, "Hangup");
  752. break;
  753. case SIGUSR1:
  754. sprintf(str, "User defined signal 1");
  755. break;
  756. case SIGUSR2:
  757. sprintf(str, "User defined signal 2");
  758. break;
  759. case SIGINT:
  760. sprintf(str, "Interrupt");
  761. break;
  762. case SIGPIPE:
  763. sprintf(str, "Broken pipe");
  764. break;
  765. default:
  766. sprintf(str, "Killed by unhandled signal %d",sig);
  767. break;
  768. }
  769. return str;
  770. }
  771. /**
  772. * Prints "Segmentation fault", etc.
  773. */
  774. static void handle_status(int ret_code) {
  775. if (WIFSIGNALED(ret_code)) {
  776. int sig = WTERMSIG(ret_code);
  777. if (sig == SIGINT || sig == SIGPIPE) return;
  778. char * str = _strsignal(sig);
  779. if (shell_interactive == 1) {
  780. fprintf(stderr, "%s\n", str);
  781. } else if (shell_interactive == 2) {
  782. fprintf(stderr, "%s: line %d: %s\n", current_file, current_line, str);
  783. }
  784. }
  785. }
  786. int wait_for_child(int pgid, char * name) {
  787. int waitee = (shell_interactive == 1 && !is_subshell) ? -pgid : pgid;
  788. int outpid;
  789. int ret_code = 0;
  790. int e;
  791. do {
  792. outpid = waitpid(waitee, &ret_code, WSTOPPED);
  793. e = errno;
  794. if (WIFSTOPPED(ret_code)) {
  795. suspended_pgid = pgid;
  796. if (name) {
  797. hashmap_set(job_hash, (void*)(intptr_t)pgid, strdup(name));
  798. }
  799. fprintf(stderr, "[%d] Stopped\t\t%s\n", pgid, (char*)hashmap_get(job_hash, (void*)(intptr_t)pgid));
  800. break;
  801. } else {
  802. suspended_pgid = 0;
  803. if (hashmap_has(job_hash, (void*)(intptr_t)pgid)) {
  804. hashmap_remove(job_hash, (void*)(intptr_t)pgid);
  805. }
  806. }
  807. } while (outpid != -1 || (outpid == -1 && e != ECHILD));
  808. reset_pgrp();
  809. handle_status(ret_code);
  810. return WEXITSTATUS(ret_code);
  811. }
  812. int shell_exec(char * buffer, size_t size, FILE * file, char ** out_buffer) {
  813. *out_buffer = NULL;
  814. /* Read previous history entries */
  815. if (buffer[0] == '!') {
  816. int x = atoi((char *)((uintptr_t)buffer + 1));
  817. if (x > 0 && x <= rline_history_count) {
  818. buffer = rline_history_get(x - 1);
  819. } else {
  820. fprintf(stderr, "esh: !%d: event not found\n", x);
  821. return 0;
  822. }
  823. }
  824. char * argv[1024];
  825. int tokenid = 0;
  826. char quoted = 0;
  827. char backtick = 0;
  828. char buffer_[512] = {0};
  829. int collected = 0;
  830. int force_collected = 0;
  831. list_t * args = list_create();
  832. int have_star = 0;
  833. while (1) {
  834. char * p = buffer;
  835. while (*p) {
  836. switch (*p) {
  837. case '$':
  838. if (quoted == '\'') {
  839. goto _just_add;
  840. } else {
  841. if (backtick) {
  842. goto _just_add;
  843. }
  844. p++;
  845. char var[100];
  846. int coll = 0;
  847. if (*p == '{') {
  848. p++;
  849. while (*p != '}' && *p != '\0' && (coll < 100)) {
  850. var[coll] = *p;
  851. coll++;
  852. var[coll] = '\0';
  853. p++;
  854. }
  855. if (*p == '}') {
  856. p++;
  857. }
  858. } else {
  859. while (*p != '\0' && (variable_char(*p) || (coll == 0 && variable_char_first(*p))) && (coll < 100)) {
  860. var[coll] = *p;
  861. coll++;
  862. var[coll] = '\0';
  863. if (coll == 1 && (isdigit(*p) || *p == '?' || *p == '$' || *p == '#')) {
  864. p++;
  865. break; /* Don't let these keep going */
  866. }
  867. p++;
  868. }
  869. }
  870. /* Special cases */
  871. char *c = NULL;
  872. char tmp[128];
  873. if (!strcmp(var, "?")) {
  874. sprintf(tmp,"%d",last_ret);
  875. c = tmp;
  876. } else if (!strcmp(var, "$")) {
  877. sprintf(tmp,"%d",getpid());
  878. c = tmp;
  879. } else if (!strcmp(var, "#")) {
  880. sprintf(tmp,"%d",shell_argc ? shell_argc-1 : 0);
  881. c = tmp;
  882. } else if (is_number(var)) {
  883. int a = atoi(var);
  884. if (a >= 0 && a < shell_argc) {
  885. c = shell_argv[a];
  886. }
  887. } else if (!strcmp(var, "RANDOM")) {
  888. sprintf(tmp,"%d",rand()%32768); /* sure, modulo is bad for range restriction, shut up */
  889. c = tmp;
  890. } else {
  891. c = getenv(var);
  892. }
  893. if (c) {
  894. backtick = 0;
  895. for (int i = 0; i < (int)strlen(c); ++i) {
  896. if (c[i] == ' ' && !quoted) {
  897. /* If we are not quoted and we reach a space, it signals a new argument */
  898. if (collected || force_collected) {
  899. buffer_[collected] = '\0';
  900. add_argument(args, buffer_);
  901. buffer_[0] = '\0';
  902. have_star = 0;
  903. collected = 0;
  904. force_collected = 0;
  905. }
  906. } else {
  907. buffer_[collected] = c[i];
  908. collected++;
  909. }
  910. }
  911. buffer_[collected] = '\0';
  912. }
  913. continue;
  914. }
  915. case '~':
  916. if (quoted || collected || backtick) {
  917. goto _just_add;
  918. } else {
  919. if (p[1] == 0 || p[1] == '/' || p[1] == '\n' || p[1] == ' ' || p[1] == ';') {
  920. char * c = getenv("HOME");
  921. if (!c) {
  922. goto _just_add;
  923. }
  924. for (int i = 0; i < (int)strlen(c); ++i) {
  925. buffer_[collected] = c[i];
  926. collected++;
  927. }
  928. buffer_[collected] = '\0';
  929. goto _next;
  930. } else {
  931. goto _just_add;
  932. }
  933. }
  934. break;
  935. case '\"':
  936. force_collected = 1;
  937. if (quoted == '\"') {
  938. if (backtick) {
  939. goto _just_add;
  940. }
  941. quoted = 0;
  942. goto _next;
  943. } else if (!quoted) {
  944. if (backtick) {
  945. goto _just_add;
  946. }
  947. quoted = *p;
  948. goto _next;
  949. }
  950. goto _just_add;
  951. case '\'':
  952. force_collected = 1;
  953. if (quoted == '\'') {
  954. if (backtick) {
  955. goto _just_add;
  956. }
  957. quoted = 0;
  958. goto _next;
  959. } else if (!quoted) {
  960. if (backtick) {
  961. goto _just_add;
  962. }
  963. quoted = *p;
  964. goto _next;
  965. }
  966. goto _just_add;
  967. case '*':
  968. if (quoted) {
  969. goto _just_add;
  970. }
  971. if (backtick) {
  972. goto _just_add;
  973. }
  974. if (have_star) {
  975. goto _just_add; /* TODO multiple globs */
  976. }
  977. have_star = 1;
  978. collected += sprintf(&buffer_[collected], STAR_TOKEN);
  979. goto _next;
  980. case '\\':
  981. if (quoted == '\'') {
  982. goto _just_add;
  983. }
  984. if (backtick) {
  985. goto _just_add;
  986. }
  987. backtick = 1;
  988. goto _next;
  989. case ' ':
  990. if (backtick) {
  991. goto _just_add;
  992. }
  993. if (!quoted) {
  994. goto _new_arg;
  995. }
  996. goto _just_add;
  997. case '\n':
  998. if (!quoted) {
  999. goto _done;
  1000. }
  1001. goto _just_add;
  1002. case '|':
  1003. if (!quoted && !backtick) {
  1004. if (collected || force_collected) {
  1005. add_argument(args, buffer_);
  1006. }
  1007. force_collected = 0;
  1008. collected = sprintf(buffer_, "%s", PIPE_TOKEN);
  1009. goto _new_arg;
  1010. }
  1011. goto _just_add;
  1012. case '>':
  1013. if (!quoted && !backtick) {
  1014. if (collected || force_collected) {
  1015. if (!strcmp(buffer_,"2")) {
  1016. /* Special case */
  1017. force_collected = 0;
  1018. collected = sprintf(buffer_,"%s", WRITE_ERR_TOKEN);
  1019. goto _new_arg;
  1020. }
  1021. add_argument(args, buffer_);
  1022. }
  1023. force_collected = 0;
  1024. collected = sprintf(buffer_, "%s", WRITE_TOKEN);
  1025. goto _new_arg;
  1026. }
  1027. goto _just_add;
  1028. case ';':
  1029. if (!quoted && !backtick) {
  1030. *out_buffer = ++p;
  1031. goto _done;
  1032. }
  1033. case '#':
  1034. if (!quoted && !backtick) {
  1035. goto _done; /* Support comments; must not be part of an existing arg */
  1036. }
  1037. goto _just_add;
  1038. default:
  1039. if (backtick) {
  1040. buffer_[collected] = '\\';
  1041. collected++;
  1042. buffer_[collected] = '\0';
  1043. }
  1044. _just_add:
  1045. backtick = 0;
  1046. buffer_[collected] = *p;
  1047. collected++;
  1048. buffer_[collected] = '\0';
  1049. goto _next;
  1050. }
  1051. _new_arg:
  1052. backtick = 0;
  1053. if (collected || force_collected) {
  1054. add_argument(args, buffer_);
  1055. buffer_[0] = '\0';
  1056. have_star = 0;
  1057. collected = 0;
  1058. force_collected = 0;
  1059. }
  1060. _next:
  1061. p++;
  1062. }
  1063. _done:
  1064. if (quoted || backtick) {
  1065. backtick = 0;
  1066. if (shell_interactive == 1) {
  1067. read_entry_continued(buffer);
  1068. rline_history_append_line(buffer);
  1069. continue;
  1070. } else if (shell_interactive == 2) {
  1071. fgets(buffer, size, file);
  1072. continue;
  1073. } else {
  1074. fprintf(stderr, "Syntax error: Unterminated quoted string.\n");
  1075. return 127;
  1076. }
  1077. }
  1078. if (collected || force_collected) {
  1079. add_argument(args, buffer_);
  1080. break;
  1081. }
  1082. break;
  1083. }
  1084. int cmdi = 0;
  1085. char ** arg_starts[100] = { &argv[0], NULL };
  1086. char * output_files[100] = { NULL };
  1087. int file_args[100] = {0};
  1088. int argcs[100] = {0};
  1089. char * err_files[100] = { NULL };
  1090. int err_args[100] = {0};
  1091. int next_is_file = 0;
  1092. int next_is_err = 0;
  1093. list_t * extra_env = list_create();
  1094. list_t * glob_args = list_create();
  1095. int i = 0;
  1096. foreach(node, args) {
  1097. char * c = node->value;
  1098. if (next_is_err) {
  1099. if (next_is_err == 1 && !strcmp(c, WRITE_TOKEN)) {
  1100. next_is_err = 2;
  1101. err_args[cmdi] = O_WRONLY | O_CREAT | O_APPEND;
  1102. continue;
  1103. }
  1104. err_files[cmdi] = c;
  1105. continue;
  1106. }
  1107. if (!strcmp(c, WRITE_ERR_TOKEN)) {
  1108. next_is_err = 1;
  1109. err_args[cmdi] = O_WRONLY | O_CREAT | O_TRUNC;
  1110. continue;
  1111. }
  1112. if (next_is_file) {
  1113. if (next_is_file == 1 && !strcmp(c, WRITE_TOKEN)) {
  1114. next_is_file = 2;
  1115. file_args[cmdi] = O_WRONLY | O_CREAT | O_APPEND;
  1116. continue;
  1117. }
  1118. output_files[cmdi] = c;
  1119. continue;
  1120. }
  1121. if (!strcmp(c, WRITE_TOKEN)) {
  1122. next_is_file = 1;
  1123. file_args[cmdi] = O_WRONLY | O_CREAT | O_TRUNC;
  1124. continue;
  1125. }
  1126. if (!strcmp(c, PIPE_TOKEN)) {
  1127. if (arg_starts[cmdi] == &argv[i]) {
  1128. fprintf(stderr, "Syntax error: Unexpected pipe token\n");
  1129. return 2;
  1130. }
  1131. argv[i] = 0;
  1132. i++;
  1133. cmdi++;
  1134. arg_starts[cmdi] = &argv[i];
  1135. continue;
  1136. }
  1137. if (i == 0 && strstr(c,"=")) {
  1138. list_insert(extra_env, c);
  1139. continue;
  1140. }
  1141. char * glob = strstr(c, STAR_TOKEN);
  1142. if (glob) {
  1143. /* Globbing */
  1144. glob[0] = '\0';
  1145. glob[1] = '\0';
  1146. char * before = c;
  1147. char * after = &glob[8];
  1148. char * dir = NULL;
  1149. int has_before = !!strlen(before);
  1150. int has_after = !!strlen(after);
  1151. if (1) {
  1152. /* read current directory, add all */
  1153. DIR * dirp;
  1154. char * prepend = "";
  1155. if (has_before) {
  1156. dir = strrchr(before,'/');
  1157. if (!dir) {
  1158. dirp = opendir(".");
  1159. } else if (dir == before) {
  1160. dirp = opendir("/");
  1161. prepend = before;
  1162. before++;
  1163. } else {
  1164. *dir = '\0';
  1165. dirp = opendir(before);
  1166. prepend = before;
  1167. before = dir+1;
  1168. }
  1169. } else {
  1170. dirp = opendir(".");
  1171. }
  1172. int before_i = i;
  1173. if (dirp) {
  1174. struct dirent * ent = readdir(dirp);
  1175. while (ent != NULL) {
  1176. if (ent->d_name[0] != '.' || (dir ? (dir[1] == '.') : (before && before[0] == '.'))) {
  1177. char * s = malloc(sizeof(char) * (strlen(ent->d_name) + 1));
  1178. memcpy(s, ent->d_name, strlen(ent->d_name) + 1);
  1179. char * t = s;
  1180. if (has_before) {
  1181. if (strstr(s,before) != s) {
  1182. free(s);
  1183. goto _nope;
  1184. }
  1185. t = &s[strlen(before)];
  1186. }
  1187. if (has_after) {
  1188. if (strlen(t) >= strlen(after)) {
  1189. if (!strcmp(after,&t[strlen(t)-strlen(after)])) {
  1190. char * out = malloc(strlen(s) + 2 + strlen(prepend));
  1191. sprintf(out,"%s%s%s", prepend, !!*prepend ? "/" : "", s);
  1192. list_insert(glob_args, out);
  1193. argv[i] = out;
  1194. i++;
  1195. argcs[cmdi]++;
  1196. }
  1197. }
  1198. } else {
  1199. char * out = malloc(strlen(s) + 2 + strlen(prepend));
  1200. sprintf(out,"%s%s%s", prepend, !!*prepend ? "/" : "", s);
  1201. list_insert(glob_args, out);
  1202. argv[i] = out;
  1203. i++;
  1204. argcs[cmdi]++;
  1205. }
  1206. free(s);
  1207. }
  1208. _nope:
  1209. ent = readdir(dirp);
  1210. }
  1211. closedir(dirp);
  1212. }
  1213. if (before_i == i) {
  1214. /* no matches */
  1215. glob[0] = '*';
  1216. if (dir) {
  1217. *dir = '/';
  1218. }
  1219. memmove(&glob[1], after, strlen(after)+1);
  1220. argv[i] = c;
  1221. i++;
  1222. argcs[cmdi]++;
  1223. }
  1224. }
  1225. } else {
  1226. argv[i] = c;
  1227. i++;
  1228. argcs[cmdi]++;
  1229. }
  1230. }
  1231. argv[i] = NULL;
  1232. /* Ensure globs get freed */
  1233. foreach(node, glob_args) {
  1234. list_insert(args, node->value);
  1235. }
  1236. list_free(glob_args);
  1237. free(glob_args);
  1238. if (i == 0) {
  1239. add_environment(extra_env);
  1240. list_free(extra_env);
  1241. free(extra_env);
  1242. list_destroy(args);
  1243. free(args);
  1244. return -1;
  1245. }
  1246. if (!*arg_starts[cmdi]) {
  1247. fprintf(stderr, "Syntax error: Unexpected end of input\n");
  1248. list_free(extra_env);
  1249. free(extra_env);
  1250. list_destroy(args);
  1251. free(args);
  1252. return 2;
  1253. }
  1254. tokenid = i;
  1255. unsigned int child_pid;
  1256. int last_child;
  1257. int nowait = (!strcmp(argv[tokenid-1],"&"));
  1258. if (nowait) {
  1259. argv[tokenid-1] = NULL;
  1260. }
  1261. int pgid = 0;
  1262. if (cmdi > 0) {
  1263. int last_output[2];
  1264. pipe(last_output);
  1265. struct semaphore s = create_semaphore();
  1266. child_pid = fork();
  1267. if (!child_pid) {
  1268. set_pgid(0);
  1269. if (!nowait) set_pgrp(getpid());
  1270. raise_semaphore(s);
  1271. is_subshell = 1;
  1272. dup2(last_output[1], STDOUT_FILENO);
  1273. close(last_output[0]);
  1274. add_environment(extra_env);
  1275. run_cmd(arg_starts[0]);
  1276. }
  1277. wait_semaphore(s);
  1278. pgid = child_pid;
  1279. for (int j = 1; j < cmdi; ++j) {
  1280. int tmp_out[2];
  1281. pipe(tmp_out);
  1282. if (!fork()) {
  1283. is_subshell = 1;
  1284. set_pgid(pgid);
  1285. dup2(tmp_out[1], STDOUT_FILENO);
  1286. dup2(last_output[0], STDIN_FILENO);
  1287. close(tmp_out[0]);
  1288. close(last_output[1]);
  1289. add_environment(extra_env);
  1290. run_cmd(arg_starts[j]);
  1291. }
  1292. close(last_output[0]);
  1293. close(last_output[1]);
  1294. last_output[0] = tmp_out[0];
  1295. last_output[1] = tmp_out[1];
  1296. }
  1297. last_child = fork();
  1298. if (!last_child) {
  1299. is_subshell = 1;
  1300. set_pgid(pgid);
  1301. if (output_files[cmdi]) {
  1302. int fd = open(output_files[cmdi], file_args[cmdi], 0666);
  1303. if (fd < 0) {
  1304. fprintf(stderr, "sh: %s: %s\n", output_files[cmdi], strerror(errno));
  1305. return -1;
  1306. } else {
  1307. dup2(fd, STDOUT_FILENO);
  1308. }
  1309. }
  1310. if (err_files[cmdi]) {
  1311. int fd = open(err_files[cmdi], err_args[cmdi], 0666);
  1312. if (fd < 0) {
  1313. fprintf(stderr, "sh: %s: %s\n", err_files[cmdi], strerror(errno));
  1314. return -1;
  1315. } else {
  1316. dup2(fd, STDERR_FILENO);
  1317. }
  1318. }
  1319. dup2(last_output[0], STDIN_FILENO);
  1320. close(last_output[1]);
  1321. add_environment(extra_env);
  1322. run_cmd(arg_starts[cmdi]);
  1323. }
  1324. close(last_output[0]);
  1325. close(last_output[1]);
  1326. /* Now execute the last piece and wait on all of them */
  1327. } else {
  1328. shell_command_t func = shell_find(*arg_starts[0]);
  1329. if (func) {
  1330. int old_out = -1;
  1331. int old_err = -1;
  1332. if (output_files[0]) {
  1333. old_out = dup(STDOUT_FILENO);
  1334. int fd = open(output_files[cmdi], file_args[cmdi], 0666);
  1335. if (fd < 0) {
  1336. fprintf(stderr, "sh: %s: %s\n", output_files[cmdi], strerror(errno));
  1337. return -1;
  1338. } else {
  1339. dup2(fd, STDOUT_FILENO);
  1340. }
  1341. }
  1342. if (err_files[0]) {
  1343. old_err = dup(STDERR_FILENO);
  1344. int fd = open(err_files[cmdi], err_args[cmdi], 0666);
  1345. if (fd < 0) {
  1346. fprintf(stderr, "sh: %s: %s\n", err_files[cmdi], strerror(errno));
  1347. return -1;
  1348. } else {
  1349. dup2(fd, STDERR_FILENO);
  1350. }
  1351. }
  1352. int result = func(argcs[0], arg_starts[0]);
  1353. if (old_out != -1) dup2(old_out, STDOUT_FILENO);
  1354. if (old_err != -1) dup2(old_err, STDERR_FILENO);
  1355. return result;
  1356. } else {
  1357. struct semaphore s = create_semaphore();
  1358. child_pid = fork();
  1359. if (!child_pid) {
  1360. set_pgid(0);
  1361. if (!nowait) set_pgrp(getpid());
  1362. raise_semaphore(s);
  1363. is_subshell = 1;
  1364. if (output_files[cmdi]) {
  1365. int fd = open(output_files[cmdi], file_args[cmdi], 0666);
  1366. if (fd < 0) {
  1367. fprintf(stderr, "sh: %s: %s\n", output_files[cmdi], strerror(errno));
  1368. return -1;
  1369. } else {
  1370. dup2(fd, STDOUT_FILENO);
  1371. }
  1372. }
  1373. if (err_files[cmdi]) {
  1374. int fd = open(err_files[cmdi], err_args[cmdi], 0666);
  1375. if (fd < 0) {
  1376. fprintf(stderr, "sh: %s: %s\n", err_files[cmdi], strerror(errno));
  1377. return -1;
  1378. } else {
  1379. dup2(fd, STDERR_FILENO);
  1380. }
  1381. }
  1382. add_environment(extra_env);
  1383. run_cmd(arg_starts[0]);
  1384. }
  1385. wait_semaphore(s);
  1386. pgid = child_pid;
  1387. last_child = child_pid;
  1388. }
  1389. }
  1390. if (nowait) {
  1391. if (shell_interactive == 1) {
  1392. fprintf(stderr, "[%d] %s\n", pgid, arg_starts[0][0]);
  1393. hashmap_set(job_hash, (void*)(intptr_t)pgid, strdup(arg_starts[0][0]));
  1394. } else {
  1395. hashmap_set(job_hash, (void*)(intptr_t)last_child, strdup(arg_starts[0][0]));
  1396. }
  1397. list_free(extra_env);
  1398. free(extra_env);
  1399. list_destroy(args);
  1400. free(args);
  1401. return 0;
  1402. }
  1403. int ret = wait_for_child(shell_interactive == 1 ? pgid : last_child, arg_starts[0][0]);
  1404. list_free(extra_env);
  1405. free(extra_env);
  1406. list_destroy(args);
  1407. free(args);
  1408. return ret;
  1409. }
  1410. void add_path_contents(char * path) {
  1411. DIR * dirp = opendir(path);
  1412. if (!dirp) return; /* Failed to load directly */
  1413. struct dirent * ent = readdir(dirp);
  1414. while (ent != NULL) {
  1415. if (ent->d_name[0] != '.') {
  1416. char * s = malloc(sizeof(char) * (strlen(ent->d_name) + 1));
  1417. memcpy(s, ent->d_name, strlen(ent->d_name) + 1);
  1418. shell_install_command(s, NULL, NULL);
  1419. }
  1420. ent = readdir(dirp);
  1421. }
  1422. closedir(dirp);
  1423. }
  1424. struct command {
  1425. char * string;
  1426. void * func;
  1427. char * desc;
  1428. };
  1429. static int comp_shell_commands(const void *p1, const void *p2) {
  1430. return strcmp(((struct command *)p1)->string, ((struct command *)p2)->string);
  1431. }
  1432. void sort_commands() {
  1433. struct command commands[SHELL_COMMANDS];
  1434. for (int i = 0; i < shell_commands_len; ++i) {
  1435. commands[i].string = shell_commands[i];
  1436. commands[i].func = shell_pointers[i];
  1437. commands[i].desc = shell_descript[i];
  1438. }
  1439. qsort(&commands, shell_commands_len, sizeof(struct command), comp_shell_commands);
  1440. for (int i = 0; i < shell_commands_len; ++i) {
  1441. shell_commands[i] = commands[i].string;
  1442. shell_pointers[i] = commands[i].func;
  1443. shell_descript[i] = commands[i].desc;
  1444. }
  1445. }
  1446. void show_version(void) {
  1447. printf("esh 1.10.0\n");
  1448. }
  1449. void show_usage(int argc, char * argv[]) {
  1450. printf(
  1451. "Esh: The Experimental Shell\n"
  1452. "\n"
  1453. "usage: %s [-lha] [path]\n"
  1454. "\n"
  1455. " -c \033[4mcmd\033[0m \033[3mparse and execute cmd\033[0m\n"
  1456. //-c cmd \033[...
  1457. " -R \033[3mdisable experimental line editor\033[0m\n"
  1458. " -v \033[3mshow version information\033[0m\n"
  1459. " -? \033[3mshow this help text\033[0m\n"
  1460. "\n", argv[0]);
  1461. }
  1462. void add_path(void) {
  1463. char * envvar = getenv("PATH");
  1464. if (!envvar) {
  1465. add_path_contents("/bin");
  1466. return;
  1467. }
  1468. char * tmp = strdup(envvar);
  1469. do {
  1470. char * end = strstr(tmp,":");
  1471. if (end) {
  1472. *end = '\0';
  1473. end++;
  1474. }
  1475. add_path_contents(tmp);
  1476. tmp = end;
  1477. } while (tmp);
  1478. free(tmp);
  1479. }
  1480. int run_script(FILE * f) {
  1481. current_line = 1;
  1482. while (!feof(f)) {
  1483. char buf[LINE_LEN] = {0};
  1484. fgets(buf, LINE_LEN, f);
  1485. int ret;
  1486. char * out = NULL;
  1487. char * b = buf;
  1488. do {
  1489. ret = shell_exec(b, LINE_LEN, f, &out);
  1490. b = out;
  1491. } while (b);
  1492. current_line++;
  1493. if (ret >= 0) last_ret = ret;
  1494. }
  1495. fclose(f);
  1496. return last_ret;
  1497. }
  1498. void source_eshrc(void) {
  1499. char * home = getenv("HOME");
  1500. if (!home) return;
  1501. char tmp[512];
  1502. sprintf(tmp, "%s/.eshrc", home);
  1503. FILE * f = fopen(tmp, "r");
  1504. if (!f) return;
  1505. current_file = tmp;
  1506. run_script(f);
  1507. }
  1508. int main(int argc, char ** argv) {
  1509. pid = getpid();
  1510. signal(SIGINT, sig_break_loop);
  1511. srand(getpid() + time(0));
  1512. job_hash = hashmap_create_int(10);
  1513. getuser();
  1514. gethost();
  1515. install_commands();
  1516. if (argc > 1) {
  1517. int c;
  1518. while ((c = getopt(argc, argv, "Rc:v?")) != -1) {
  1519. switch (c) {
  1520. case 'R':
  1521. experimental_rline = 0;
  1522. break;
  1523. case 'c':
  1524. shell_interactive = 0;
  1525. {
  1526. char * out = NULL;
  1527. do {
  1528. last_ret = shell_exec(optarg, strlen(optarg), NULL, &out);
  1529. optarg = out;
  1530. } while (optarg);
  1531. }
  1532. return (last_ret == -1) ? 0 : last_ret;
  1533. case 'v':
  1534. show_version();
  1535. return 0;
  1536. case '?':
  1537. show_usage(argc, argv);
  1538. return 0;
  1539. }
  1540. }
  1541. }
  1542. if (optind < argc) {
  1543. shell_interactive = 2;
  1544. FILE * f = fopen(argv[optind],"r");
  1545. if (!f) {
  1546. fprintf(stderr, "%s: %s: %s\n", argv[0], argv[optind], strerror(errno));
  1547. return 1;
  1548. }
  1549. shell_argc = argc - 1;
  1550. shell_argv = &argv[optind];
  1551. current_file = argv[optind];
  1552. return run_script(f);
  1553. }
  1554. shell_interactive = 1;
  1555. my_pgid = getpgid(0);
  1556. signal(SIGTTOU, SIG_IGN);
  1557. signal(SIGTTIN, SIG_IGN);
  1558. source_eshrc();
  1559. add_path();
  1560. sort_commands();
  1561. while (1) {
  1562. char buffer[LINE_LEN] = {0};
  1563. list_t * keys = hashmap_keys(job_hash);
  1564. foreach(node, keys) {
  1565. int pid = (intptr_t)node->value;
  1566. int status = 0;
  1567. if (waitpid(-pid, &status, WNOHANG) > 0) {
  1568. char * desc = "Done";
  1569. if (WTERMSIG(status) != 0) {
  1570. desc = _strsignal(WTERMSIG(status));
  1571. }
  1572. fprintf(stderr, "[%d] %s\t\t%s\n", pid, desc, (char*)hashmap_get(job_hash, (void*)(intptr_t)pid));
  1573. if (hashmap_has(job_hash, (void*)(intptr_t)pid)) {
  1574. hashmap_remove(job_hash, (void*)(intptr_t)pid);
  1575. }
  1576. }
  1577. }
  1578. list_free(keys);
  1579. free(keys);
  1580. read_entry(buffer);
  1581. char * history = malloc(strlen(buffer) + 1);
  1582. memcpy(history, buffer, strlen(buffer) + 1);
  1583. if (buffer[0] != ' ' && buffer[0] != '\n' && buffer[0] != '!') {
  1584. rline_history_insert(history);
  1585. } else {
  1586. free(history);
  1587. }
  1588. int ret;
  1589. char * out = NULL;
  1590. char * b = buffer;
  1591. do {
  1592. ret = shell_exec(b, LINE_LEN, stdin, &out);
  1593. b = out;
  1594. } while (b);
  1595. if (ret >= 0) last_ret = ret;
  1596. rline_scroll = 0;
  1597. }
  1598. return 0;
  1599. }
  1600. /*
  1601. * cd [path]
  1602. */
  1603. uint32_t shell_cmd_cd(int argc, char * argv[]) {
  1604. if (argc > 1) {
  1605. if (chdir(argv[1])) {
  1606. goto cd_error;
  1607. } /* else success */
  1608. } else /* argc < 2 */ {
  1609. char * home = getenv("HOME");
  1610. if (home) {
  1611. if (chdir(home)) {
  1612. goto cd_error;
  1613. }
  1614. } else {
  1615. char home_path[512];
  1616. sprintf(home_path, "/home/%s", username);
  1617. if (chdir(home_path)) {
  1618. goto cd_error;
  1619. }
  1620. }
  1621. }
  1622. return 0;
  1623. cd_error:
  1624. fprintf(stderr, "%s: could not cd '%s': %s\n", argv[0], argv[1], strerror(errno));
  1625. return 1;
  1626. }
  1627. /*
  1628. * history
  1629. */
  1630. uint32_t shell_cmd_history(int argc, char * argv[]) {
  1631. for (int i = 0; i < rline_history_count; ++i) {
  1632. printf("%d\t%s\n", i + 1, rline_history_get(i));
  1633. }
  1634. return 0;
  1635. }
  1636. uint32_t shell_cmd_export(int argc, char * argv[]) {
  1637. if (argc > 1) {
  1638. putenv(argv[1]);
  1639. }
  1640. return 0;
  1641. }
  1642. uint32_t shell_cmd_exit(int argc, char * argv[]) {
  1643. if (argc > 1) {
  1644. exit(atoi(argv[1]));
  1645. } else {
  1646. exit(0);
  1647. }
  1648. return -1;
  1649. }
  1650. uint32_t shell_cmd_help(int argc, char * argv[]) {
  1651. show_version();
  1652. printf("\nThis shell is not POSIX-compliant, please be careful.\n\n");
  1653. printf("Built-in commands:\n");
  1654. /* First, determine max width of command names */
  1655. unsigned int max_len = 0;
  1656. for (int i = 0; i < shell_commands_len; ++i) {
  1657. if (!shell_descript[i]) continue;
  1658. if (strlen(shell_commands[i]) > max_len) {
  1659. max_len = strlen(shell_commands[i]);
  1660. }
  1661. }
  1662. /* Then print the commands their help text */
  1663. for (int i = 0; i < shell_commands_len; ++i) {
  1664. if (!shell_descript[i]) continue;
  1665. printf(" %-*s - %s\n", max_len + 1, shell_commands[i], shell_descript[i]);
  1666. }
  1667. return 0;
  1668. }
  1669. uint32_t shell_cmd_if(int argc, char * argv[]) {
  1670. char ** if_args = &argv[1];
  1671. char ** then_args = NULL;
  1672. char ** else_args = NULL;
  1673. for (int i = 2; i < argc; ++i) {
  1674. if (!strcmp(argv[i],"then")) {
  1675. argv[i] = NULL;
  1676. then_args = &argv[i+1];
  1677. } else if (!strcmp(argv[i],"else")) {
  1678. argv[i] = NULL;
  1679. else_args = &argv[i+1];
  1680. }
  1681. }
  1682. if (!then_args) {
  1683. fprintf(stderr, "%s: syntax error: expected 'then' clause\n", argv[0]);
  1684. return 1;
  1685. }
  1686. if (else_args && else_args < then_args) {
  1687. fprintf(stderr, "%s: syntax error: 'else' clause before 'then' clase\n", argv[0]);
  1688. return 1;
  1689. }
  1690. pid_t child_pid = fork();
  1691. if (!child_pid) {
  1692. set_pgid(0);
  1693. set_pgrp(getpid());
  1694. is_subshell = 1;
  1695. run_cmd(if_args);
  1696. }
  1697. int pid, ret_code = 0;
  1698. do {
  1699. pid = waitpid(child_pid, &ret_code, 0);
  1700. } while (pid != -1 || (pid == -1 && errno != ECHILD));
  1701. handle_status(ret_code);
  1702. if (WEXITSTATUS(ret_code) == 0) {
  1703. shell_command_t func = shell_find(*then_args);
  1704. if (func) {
  1705. int argc = 0;
  1706. while (then_args[argc]) {
  1707. argc++;
  1708. }
  1709. return func(argc, then_args);
  1710. } else {
  1711. child_pid = fork();
  1712. if (!child_pid) {
  1713. set_pgid(0);
  1714. set_pgrp(getpid());
  1715. is_subshell = 1;
  1716. run_cmd(then_args);
  1717. }
  1718. do {
  1719. pid = waitpid(child_pid, &ret_code, 0);
  1720. } while (pid != -1 || (pid == -1 && errno != ECHILD));
  1721. reset_pgrp();
  1722. handle_status(ret_code);
  1723. return WEXITSTATUS(ret_code);
  1724. }
  1725. } else if (else_args) {
  1726. shell_command_t func = shell_find(*else_args);
  1727. if (func) {
  1728. int argc = 0;
  1729. while (else_args[argc]) {
  1730. argc++;
  1731. }
  1732. return func(argc, else_args);
  1733. } else {
  1734. child_pid = fork();
  1735. if (!child_pid) {
  1736. set_pgid(0);
  1737. set_pgrp(getpid());
  1738. is_subshell = 1;
  1739. run_cmd(else_args);
  1740. }
  1741. do {
  1742. pid = waitpid(child_pid, &ret_code, 0);
  1743. } while (pid != -1 || (pid == -1 && errno != ECHILD));
  1744. handle_status(ret_code);
  1745. return WEXITSTATUS(ret_code);
  1746. }
  1747. }
  1748. reset_pgrp();
  1749. return 0;
  1750. }
  1751. uint32_t shell_cmd_while(int argc, char * argv[]) {
  1752. char ** while_args = &argv[1];
  1753. char ** do_args = NULL;
  1754. for (int i = 2; i < argc; ++i) {
  1755. if (!strcmp(argv[i],"do")) {
  1756. argv[i] = NULL;
  1757. do_args = &argv[i+1];
  1758. }
  1759. }
  1760. if (!do_args) {
  1761. fprintf(stderr, "%s: syntax error: expected 'do' clause\n", argv[0]);
  1762. return 1;
  1763. }
  1764. break_while = 0;
  1765. reset_pgrp();
  1766. do {
  1767. pid_t child_pid = fork();
  1768. if (!child_pid) {
  1769. set_pgid(0);
  1770. set_pgrp(getpid());
  1771. is_subshell = 1;
  1772. run_cmd(while_args);
  1773. }
  1774. int pid, ret_code = 0;
  1775. do {
  1776. pid = waitpid(child_pid, &ret_code, 0);
  1777. } while (pid != -1 || (pid == -1 && errno != ECHILD));
  1778. handle_status(ret_code);
  1779. if (WEXITSTATUS(ret_code) == 0) {
  1780. child_pid = fork();
  1781. if (!child_pid) {
  1782. set_pgid(0);
  1783. set_pgrp(getpid());
  1784. is_subshell = 1;
  1785. run_cmd(do_args);
  1786. }
  1787. do {
  1788. pid = waitpid(child_pid, &ret_code, 0);
  1789. if (pid != -1 && WIFSIGNALED(ret_code)) {
  1790. int sig = WTERMSIG(ret_code);
  1791. if (sig == SIGINT) return 127; /* break */
  1792. }
  1793. } while (pid != -1 || (pid == -1 && errno != ECHILD));
  1794. } else {
  1795. reset_pgrp();
  1796. return WEXITSTATUS(ret_code);
  1797. }
  1798. } while (!break_while);
  1799. return 127;
  1800. }
  1801. uint32_t shell_cmd_export_cmd(int argc, char * argv[]) {
  1802. if (argc < 3) {
  1803. fprintf(stderr, "%s: syntax error: not enough arguments\n", argv[0]);
  1804. return 1;
  1805. }
  1806. int pipe_fds[2];
  1807. pipe(pipe_fds);
  1808. pid_t child_pid = fork();
  1809. if (!child_pid) {
  1810. set_pgid(0);
  1811. set_pgrp(getpid());
  1812. is_subshell = 1;
  1813. dup2(pipe_fds[1], STDOUT_FILENO);
  1814. close(pipe_fds[0]);
  1815. run_cmd(&argv[2]);
  1816. }
  1817. close(pipe_fds[1]);
  1818. char buf[1024];
  1819. size_t accum = 0;
  1820. do {
  1821. int r = read(pipe_fds[0], buf+accum, 1023-accum);
  1822. if (r == 0) break;
  1823. if (r < 0) {
  1824. return -r;
  1825. }
  1826. accum += r;
  1827. } while (accum < 1023);
  1828. waitpid(child_pid, NULL, 0);
  1829. reset_pgrp();
  1830. buf[accum] = '\0';
  1831. if (accum && buf[accum-1] == '\n') {
  1832. buf[accum-1] = '\0';
  1833. }
  1834. setenv(argv[1], buf, 1);
  1835. return 0;
  1836. }
  1837. uint32_t shell_cmd_empty(int argc, char * argv[]) {
  1838. for (int i = 1; i < argc; i++) {
  1839. if (argv[i] && *argv[i]) return 1;
  1840. }
  1841. return 0;
  1842. }
  1843. uint32_t shell_cmd_equals(int argc, char * argv[]) {
  1844. if (argc < 3) return 1;
  1845. return !!strcmp(argv[1], argv[2]);
  1846. }
  1847. uint32_t shell_cmd_return(int argc, char * argv[]) {
  1848. if (argc < 2) return 0;
  1849. return atoi(argv[1]);
  1850. }
  1851. uint32_t shell_cmd_source(int argc, char * argv[]) {
  1852. if (argc < 2) return 0;
  1853. FILE * f = fopen(argv[1], "r");
  1854. if (!f) {
  1855. fprintf(stderr, "%s: %s: %s\n", argv[0], argv[1], strerror(errno));
  1856. return 1;
  1857. }
  1858. current_file = argv[1];
  1859. return run_script(f);
  1860. }
  1861. uint32_t shell_cmd_exec(int argc, char * argv[]) {
  1862. if (argc < 2) return 1;
  1863. return execvp(argv[1], &argv[1]);
  1864. }
  1865. uint32_t shell_cmd_not(int argc, char * argv[]) {
  1866. if (argc < 2) {
  1867. fprintf(stderr, "%s: expected command argument\n", argv[0]);
  1868. return 1;
  1869. }
  1870. int ret_code = 0;
  1871. pid_t child_pid = fork();
  1872. if (!child_pid) {
  1873. set_pgid(0);
  1874. set_pgrp(getpid());
  1875. is_subshell = 1;
  1876. run_cmd(&argv[1]);
  1877. }
  1878. do {
  1879. pid = waitpid(child_pid, &ret_code, 0);
  1880. } while (pid != -1 || (pid == -1 && errno != ECHILD));
  1881. reset_pgrp();
  1882. handle_status(ret_code);
  1883. return !WEXITSTATUS(ret_code);
  1884. }
  1885. uint32_t shell_cmd_unset(int argc, char * argv[]) {
  1886. if (argc < 2) {
  1887. fprintf(stderr, "%s: expected command argument\n", argv[0]);
  1888. return 1;
  1889. }
  1890. return unsetenv(argv[1]);
  1891. }
  1892. uint32_t shell_cmd_read(int argc, char * argv[]) {
  1893. int raw = 0;
  1894. int i = 1;
  1895. char * var = "REPLY";
  1896. if (i < argc && !strcmp(argv[i], "-r")) {
  1897. raw = 1;
  1898. i++;
  1899. }
  1900. if (i < argc) {
  1901. var = argv[i];
  1902. }
  1903. char tmp[4096];
  1904. fgets(tmp, 4096, stdin);
  1905. if (*tmp && tmp[strlen(tmp)-1] == '\n') {
  1906. tmp[strlen(tmp)-1] = '\0';
  1907. }
  1908. if (raw) {
  1909. setenv(var, tmp, 1);
  1910. return 0;
  1911. }
  1912. char tmp2[4096] = {0};
  1913. char * out = tmp2;
  1914. char * in = tmp;
  1915. /* TODO: This needs to actually read more if a \ at the end of the line is found */
  1916. while (*in) {
  1917. if (*in == '\\') {
  1918. in++;
  1919. if (*in == '\n') {
  1920. in++;
  1921. }
  1922. } else {
  1923. *out = *in;
  1924. out++;
  1925. in++;
  1926. }
  1927. }
  1928. setenv(var, tmp2, 1);
  1929. return 0;
  1930. }
  1931. int get_available_job(int argc, char * argv[]) {
  1932. if (argc < 2) {
  1933. if (!suspended_pgid) {
  1934. list_t * keys = hashmap_keys(job_hash);
  1935. foreach(node, keys) {
  1936. suspended_pgid = (intptr_t)node->value;
  1937. break;
  1938. }
  1939. list_free(keys);
  1940. free(keys);
  1941. if (!suspended_pgid) {
  1942. return 0;
  1943. }
  1944. }
  1945. return suspended_pgid;
  1946. } else {
  1947. return atoi(argv[1]);
  1948. }
  1949. }
  1950. uint32_t shell_cmd_fg(int argc, char * argv[]) {
  1951. int pid = get_available_job(argc,argv);
  1952. if (!pid || !hashmap_has(job_hash, (void*)(intptr_t)pid)) {
  1953. fprintf(stderr, "no current job\n");
  1954. return 1;
  1955. }
  1956. set_pgrp(pid);
  1957. if (kill(-pid, SIGCONT) < 0) {
  1958. fprintf(stderr, "no current job / bad pid\n");
  1959. if (hashmap_has(job_hash, (void*)(intptr_t)pid)) {
  1960. hashmap_remove(job_hash, (void*)(intptr_t)pid);
  1961. }
  1962. return 1;
  1963. }
  1964. return wait_for_child(pid, NULL);
  1965. }
  1966. uint32_t shell_cmd_bg(int argc, char * argv[]) {
  1967. int pid = get_available_job(argc,argv);
  1968. if (!pid || !hashmap_has(job_hash, (void*)(intptr_t)pid)) {
  1969. fprintf(stderr, "no current job\n");
  1970. return 1;
  1971. }
  1972. if (kill(-pid, SIGCONT) < 0) {
  1973. fprintf(stderr, "no current job / bad pid\n");
  1974. if (hashmap_has(job_hash, (void*)(intptr_t)pid)) {
  1975. hashmap_remove(job_hash, (void*)(intptr_t)pid);
  1976. }
  1977. return 1;
  1978. }
  1979. fprintf(stderr, "[%d] %s\n", pid, (char*)hashmap_get(job_hash, (void*)(intptr_t)pid));
  1980. return 0;
  1981. }
  1982. uint32_t shell_cmd_jobs(int argc, char * argv[]) {
  1983. list_t * keys = hashmap_keys(job_hash);
  1984. foreach(node, keys) {
  1985. int pid = (intptr_t)node->value;
  1986. char * c = hashmap_get(job_hash, (void*)(intptr_t)pid);
  1987. fprintf(stdout, "%5d %s\n", pid, c);
  1988. }
  1989. list_free(keys);
  1990. free(keys);
  1991. return 0;
  1992. }
  1993. uint32_t shell_cmd_rehash(int argc, char * argv[]) {
  1994. /* PATH commands are malloc'd */
  1995. for (int i = 0; i < shell_commands_len; ++i) {
  1996. if (!shell_pointers[i]) {
  1997. free(shell_commands[i]);
  1998. }
  1999. }
  2000. /* Clear array */
  2001. shell_commands_len = 0;
  2002. /* Reset capacity */
  2003. SHELL_COMMANDS = 64;
  2004. /* Free existing */
  2005. free(shell_commands);
  2006. free(shell_pointers);
  2007. free(shell_descript);
  2008. /* Reallocate + install builtins */
  2009. install_commands();
  2010. /* Reload PATH */
  2011. add_path();
  2012. return 0;
  2013. }
  2014. void install_commands() {
  2015. shell_commands = malloc(sizeof(char *) * SHELL_COMMANDS);
  2016. shell_pointers = malloc(sizeof(shell_command_t) * SHELL_COMMANDS);
  2017. shell_descript = malloc(sizeof(char *) * SHELL_COMMANDS);
  2018. shell_install_command("cd", shell_cmd_cd, "change directory");
  2019. shell_install_command("exit", shell_cmd_exit, "exit the shell");
  2020. shell_install_command("export", shell_cmd_export, "set environment variables: export VAR=value");
  2021. shell_install_command("help", shell_cmd_help, "display this help text");
  2022. shell_install_command("history", shell_cmd_history, "list command history");
  2023. shell_install_command("if", shell_cmd_if, "if ... then ... [else ...]");
  2024. shell_install_command("while", shell_cmd_while, "while ... do ...");
  2025. shell_install_command("empty?", shell_cmd_empty, "empty? args...");
  2026. shell_install_command("equals?", shell_cmd_equals, "equals? arg1 arg2");
  2027. shell_install_command("return", shell_cmd_return, "return status code");
  2028. shell_install_command("export-cmd", shell_cmd_export_cmd, "set variable to result of command: export-cmd VAR command...");
  2029. shell_install_command("source", shell_cmd_source, "run a shell script in the context of this shell");
  2030. shell_install_command(".", shell_cmd_source, "alias for 'source'");
  2031. shell_install_command("exec", shell_cmd_exec, "replace shell (or subshell) with command");
  2032. shell_install_command("not", shell_cmd_not, "invert status of command");
  2033. shell_install_command("unset", shell_cmd_unset, "unset variable");
  2034. shell_install_command("read", shell_cmd_read, "read user input");
  2035. shell_install_command("fg", shell_cmd_fg, "resume a suspended job");
  2036. shell_install_command("jobs", shell_cmd_jobs, "list stopped jobs");
  2037. shell_install_command("bg", shell_cmd_bg, "restart suspended job in the background");
  2038. shell_install_command("rehash", shell_cmd_rehash, "reset shell command memory");
  2039. }