sh.c 50 KB

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