sh.c 48 KB

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