sh.c 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300
  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. if (errno == ENOENT) {
  687. fprintf(stderr, "%s: Command not found\n", *args);
  688. for (struct alternative * alt = cmd_alternatives; alt->command; alt++) {
  689. if (!strcmp(*args, alt->command)) {
  690. fprintf(stderr, "Consider this alternative:\n\n\t%s -- \033[3m%s\033[0m\n\n",
  691. alt->replacement,
  692. alt->description);
  693. break;
  694. }
  695. }
  696. } else if (errno == ELOOP) {
  697. fprintf(stderr, "esh: Bad interpreter (maximum recursion depth reached)\n");
  698. } else if (errno == ENOEXEC) {
  699. fprintf(stderr, "esh: Bad interpreter\n");
  700. } else {
  701. fprintf(stderr, "esh: Invalid executable\n");
  702. }
  703. i = 127;
  704. }
  705. }
  706. exit(i);
  707. }
  708. int is_number(const char * c) {
  709. while (*c) {
  710. if (!isdigit(*c)) return 0;
  711. c++;
  712. }
  713. return 1;
  714. }
  715. static char * _strsignal(int sig) {
  716. static char str[256];
  717. memset(str, 0, sizeof(str));
  718. switch (sig) {
  719. case SIGILL:
  720. sprintf(str, "Illegal instruction");
  721. break;
  722. case SIGSEGV:
  723. sprintf(str, "Segmentation fault");
  724. break;
  725. case SIGTERM:
  726. sprintf(str, "Terminated");
  727. break;
  728. case SIGQUIT:
  729. sprintf(str, "Quit");
  730. break;
  731. case SIGKILL:
  732. sprintf(str, "Killed");
  733. break;
  734. case SIGHUP:
  735. sprintf(str, "Hangup");
  736. break;
  737. case SIGUSR1:
  738. sprintf(str, "User defined signal 1");
  739. break;
  740. case SIGUSR2:
  741. sprintf(str, "User defined signal 2");
  742. break;
  743. case SIGINT:
  744. sprintf(str, "Interrupt");
  745. break;
  746. case SIGPIPE:
  747. sprintf(str, "Broken pipe");
  748. break;
  749. default:
  750. sprintf(str, "Killed by unhandled signal %d",sig);
  751. break;
  752. }
  753. return str;
  754. }
  755. /**
  756. * Prints "Segmentation fault", etc.
  757. */
  758. static void handle_status(int ret_code) {
  759. if (WIFSIGNALED(ret_code)) {
  760. int sig = WTERMSIG(ret_code);
  761. if (sig == SIGINT || sig == SIGPIPE) return;
  762. char * str = _strsignal(sig);
  763. if (shell_interactive == 1) {
  764. fprintf(stderr, "%s\n", str);
  765. } else if (shell_interactive == 2) {
  766. fprintf(stderr, "%s: line %d: %s\n", current_file, current_line, str);
  767. }
  768. }
  769. }
  770. int wait_for_child(int pgid, char * name) {
  771. int waitee = (shell_interactive == 1 && !is_subshell) ? -pgid : pgid;
  772. int outpid;
  773. int ret_code = 0;
  774. int e;
  775. do {
  776. outpid = waitpid(waitee, &ret_code, WSTOPPED);
  777. e = errno;
  778. if (WIFSTOPPED(ret_code)) {
  779. suspended_pgid = pgid;
  780. if (name) {
  781. hashmap_set(job_hash, (void*)(intptr_t)pgid, strdup(name));
  782. }
  783. fprintf(stderr, "[%d] Stopped\t\t%s\n", pgid, (char*)hashmap_get(job_hash, (void*)(intptr_t)pgid));
  784. break;
  785. } else {
  786. suspended_pgid = 0;
  787. if (hashmap_has(job_hash, (void*)(intptr_t)pgid)) {
  788. hashmap_remove(job_hash, (void*)(intptr_t)pgid);
  789. }
  790. }
  791. } while (outpid != -1 || (outpid == -1 && e != ECHILD));
  792. reset_pgrp();
  793. handle_status(ret_code);
  794. return WEXITSTATUS(ret_code);
  795. }
  796. int shell_exec(char * buffer, size_t size, FILE * file, char ** out_buffer) {
  797. *out_buffer = NULL;
  798. /* Read previous history entries */
  799. if (buffer[0] == '!') {
  800. int x = atoi((char *)((uintptr_t)buffer + 1));
  801. if (x > 0 && x <= rline_history_count) {
  802. buffer = rline_history_get(x - 1);
  803. } else {
  804. fprintf(stderr, "esh: !%d: event not found\n", x);
  805. return 0;
  806. }
  807. }
  808. char * argv[1024];
  809. int tokenid = 0;
  810. char quoted = 0;
  811. char backtick = 0;
  812. char buffer_[512] = {0};
  813. int collected = 0;
  814. int force_collected = 0;
  815. list_t * args = list_create();
  816. int have_star = 0;
  817. while (1) {
  818. char * p = buffer;
  819. while (*p) {
  820. switch (*p) {
  821. case '$':
  822. if (quoted == '\'') {
  823. goto _just_add;
  824. } else {
  825. if (backtick) {
  826. goto _just_add;
  827. }
  828. p++;
  829. char var[100];
  830. int coll = 0;
  831. if (*p == '{') {
  832. p++;
  833. while (*p != '}' && *p != '\0' && (coll < 100)) {
  834. var[coll] = *p;
  835. coll++;
  836. var[coll] = '\0';
  837. p++;
  838. }
  839. if (*p == '}') {
  840. p++;
  841. }
  842. } else {
  843. while (*p != '\0' && (variable_char(*p) || (coll == 0 && variable_char_first(*p))) && (coll < 100)) {
  844. var[coll] = *p;
  845. coll++;
  846. var[coll] = '\0';
  847. if (coll == 1 && (isdigit(*p) || *p == '?' || *p == '$' || *p == '#')) {
  848. p++;
  849. break; /* Don't let these keep going */
  850. }
  851. p++;
  852. }
  853. }
  854. /* Special cases */
  855. char *c = NULL;
  856. char tmp[128];
  857. if (!strcmp(var, "?")) {
  858. sprintf(tmp,"%d",last_ret);
  859. c = tmp;
  860. } else if (!strcmp(var, "$")) {
  861. sprintf(tmp,"%d",getpid());
  862. c = tmp;
  863. } else if (!strcmp(var, "#")) {
  864. sprintf(tmp,"%d",shell_argc ? shell_argc-1 : 0);
  865. c = tmp;
  866. } else if (is_number(var)) {
  867. int a = atoi(var);
  868. if (a >= 0 && a < shell_argc) {
  869. c = shell_argv[a];
  870. }
  871. } else if (!strcmp(var, "RANDOM")) {
  872. sprintf(tmp,"%d",rand()%32768); /* sure, modulo is bad for range restriction, shut up */
  873. c = tmp;
  874. } else {
  875. c = getenv(var);
  876. }
  877. if (c) {
  878. backtick = 0;
  879. for (int i = 0; i < (int)strlen(c); ++i) {
  880. if (c[i] == ' ' && !quoted) {
  881. /* If we are not quoted and we reach a space, it signals a new argument */
  882. if (collected || force_collected) {
  883. buffer_[collected] = '\0';
  884. add_argument(args, buffer_);
  885. buffer_[0] = '\0';
  886. have_star = 0;
  887. collected = 0;
  888. force_collected = 0;
  889. }
  890. } else {
  891. buffer_[collected] = c[i];
  892. collected++;
  893. }
  894. }
  895. buffer_[collected] = '\0';
  896. }
  897. continue;
  898. }
  899. case '~':
  900. if (quoted || collected || backtick) {
  901. goto _just_add;
  902. } else {
  903. if (p[1] == 0 || p[1] == '/' || p[1] == '\n' || p[1] == ' ' || p[1] == ';') {
  904. char * c = getenv("HOME");
  905. if (!c) {
  906. goto _just_add;
  907. }
  908. for (int i = 0; i < (int)strlen(c); ++i) {
  909. buffer_[collected] = c[i];
  910. collected++;
  911. }
  912. buffer_[collected] = '\0';
  913. goto _next;
  914. } else {
  915. goto _just_add;
  916. }
  917. }
  918. break;
  919. case '\"':
  920. force_collected = 1;
  921. if (quoted == '\"') {
  922. if (backtick) {
  923. goto _just_add;
  924. }
  925. quoted = 0;
  926. goto _next;
  927. } else if (!quoted) {
  928. if (backtick) {
  929. goto _just_add;
  930. }
  931. quoted = *p;
  932. goto _next;
  933. }
  934. goto _just_add;
  935. case '\'':
  936. force_collected = 1;
  937. if (quoted == '\'') {
  938. if (backtick) {
  939. goto _just_add;
  940. }
  941. quoted = 0;
  942. goto _next;
  943. } else if (!quoted) {
  944. if (backtick) {
  945. goto _just_add;
  946. }
  947. quoted = *p;
  948. goto _next;
  949. }
  950. goto _just_add;
  951. case '*':
  952. if (quoted) {
  953. goto _just_add;
  954. }
  955. if (backtick) {
  956. goto _just_add;
  957. }
  958. if (have_star) {
  959. goto _just_add; /* TODO multiple globs */
  960. }
  961. have_star = 1;
  962. collected += sprintf(&buffer_[collected], STAR_TOKEN);
  963. goto _next;
  964. case '\\':
  965. if (quoted == '\'') {
  966. goto _just_add;
  967. }
  968. if (backtick) {
  969. goto _just_add;
  970. }
  971. backtick = 1;
  972. goto _next;
  973. case ' ':
  974. if (backtick) {
  975. goto _just_add;
  976. }
  977. if (!quoted) {
  978. goto _new_arg;
  979. }
  980. goto _just_add;
  981. case '\n':
  982. if (!quoted) {
  983. goto _done;
  984. }
  985. goto _just_add;
  986. case '|':
  987. if (!quoted && !backtick) {
  988. if (collected || force_collected) {
  989. add_argument(args, buffer_);
  990. }
  991. force_collected = 0;
  992. collected = sprintf(buffer_, "%s", PIPE_TOKEN);
  993. goto _new_arg;
  994. }
  995. goto _just_add;
  996. case '>':
  997. if (!quoted && !backtick) {
  998. if (collected || force_collected) {
  999. if (!strcmp(buffer_,"2")) {
  1000. /* Special case */
  1001. force_collected = 0;
  1002. collected = sprintf(buffer_,"%s", WRITE_ERR_TOKEN);
  1003. goto _new_arg;
  1004. }
  1005. add_argument(args, buffer_);
  1006. }
  1007. force_collected = 0;
  1008. collected = sprintf(buffer_, "%s", WRITE_TOKEN);
  1009. goto _new_arg;
  1010. }
  1011. goto _just_add;
  1012. case ';':
  1013. if (!quoted && !backtick) {
  1014. *out_buffer = ++p;
  1015. goto _done;
  1016. }
  1017. case '#':
  1018. if (!quoted && !backtick) {
  1019. goto _done; /* Support comments; must not be part of an existing arg */
  1020. }
  1021. goto _just_add;
  1022. default:
  1023. if (backtick) {
  1024. buffer_[collected] = '\\';
  1025. collected++;
  1026. buffer_[collected] = '\0';
  1027. }
  1028. _just_add:
  1029. backtick = 0;
  1030. buffer_[collected] = *p;
  1031. collected++;
  1032. buffer_[collected] = '\0';
  1033. goto _next;
  1034. }
  1035. _new_arg:
  1036. backtick = 0;
  1037. if (collected || force_collected) {
  1038. add_argument(args, buffer_);
  1039. buffer_[0] = '\0';
  1040. have_star = 0;
  1041. collected = 0;
  1042. force_collected = 0;
  1043. }
  1044. _next:
  1045. p++;
  1046. }
  1047. _done:
  1048. if (quoted || backtick) {
  1049. backtick = 0;
  1050. if (shell_interactive == 1) {
  1051. read_entry_continued(buffer);
  1052. rline_history_append_line(buffer);
  1053. continue;
  1054. } else if (shell_interactive == 2) {
  1055. fgets(buffer, size, file);
  1056. continue;
  1057. } else {
  1058. fprintf(stderr, "Syntax error: Unterminated quoted string.\n");
  1059. return 127;
  1060. }
  1061. }
  1062. if (collected || force_collected) {
  1063. add_argument(args, buffer_);
  1064. break;
  1065. }
  1066. break;
  1067. }
  1068. int cmdi = 0;
  1069. char ** arg_starts[100] = { &argv[0], NULL };
  1070. char * output_files[100] = { NULL };
  1071. int file_args[100] = {0};
  1072. int argcs[100] = {0};
  1073. char * err_files[100] = { NULL };
  1074. int err_args[100] = {0};
  1075. int next_is_file = 0;
  1076. int next_is_err = 0;
  1077. list_t * extra_env = list_create();
  1078. list_t * glob_args = list_create();
  1079. int i = 0;
  1080. foreach(node, args) {
  1081. char * c = node->value;
  1082. if (next_is_err) {
  1083. if (next_is_err == 1 && !strcmp(c, WRITE_TOKEN)) {
  1084. next_is_err = 2;
  1085. err_args[cmdi] = O_WRONLY | O_CREAT | O_APPEND;
  1086. continue;
  1087. }
  1088. err_files[cmdi] = c;
  1089. continue;
  1090. }
  1091. if (!strcmp(c, WRITE_ERR_TOKEN)) {
  1092. next_is_err = 1;
  1093. err_args[cmdi] = O_WRONLY | O_CREAT | O_TRUNC;
  1094. continue;
  1095. }
  1096. if (next_is_file) {
  1097. if (next_is_file == 1 && !strcmp(c, WRITE_TOKEN)) {
  1098. next_is_file = 2;
  1099. file_args[cmdi] = O_WRONLY | O_CREAT | O_APPEND;
  1100. continue;
  1101. }
  1102. output_files[cmdi] = c;
  1103. continue;
  1104. }
  1105. if (!strcmp(c, WRITE_TOKEN)) {
  1106. next_is_file = 1;
  1107. file_args[cmdi] = O_WRONLY | O_CREAT | O_TRUNC;
  1108. continue;
  1109. }
  1110. if (!strcmp(c, PIPE_TOKEN)) {
  1111. if (arg_starts[cmdi] == &argv[i]) {
  1112. fprintf(stderr, "Syntax error: Unexpected pipe token\n");
  1113. return 2;
  1114. }
  1115. argv[i] = 0;
  1116. i++;
  1117. cmdi++;
  1118. arg_starts[cmdi] = &argv[i];
  1119. continue;
  1120. }
  1121. if (i == 0 && strstr(c,"=")) {
  1122. list_insert(extra_env, c);
  1123. continue;
  1124. }
  1125. char * glob = strstr(c, STAR_TOKEN);
  1126. if (glob) {
  1127. /* Globbing */
  1128. glob[0] = '\0';
  1129. glob[1] = '\0';
  1130. char * before = c;
  1131. char * after = &glob[8];
  1132. char * dir = NULL;
  1133. int has_before = !!strlen(before);
  1134. int has_after = !!strlen(after);
  1135. if (1) {
  1136. /* read current directory, add all */
  1137. DIR * dirp;
  1138. char * prepend = "";
  1139. if (has_before) {
  1140. dir = strrchr(before,'/');
  1141. if (!dir) {
  1142. dirp = opendir(".");
  1143. } else if (dir == before) {
  1144. dirp = opendir("/");
  1145. prepend = before;
  1146. before++;
  1147. } else {
  1148. *dir = '\0';
  1149. dirp = opendir(before);
  1150. prepend = before;
  1151. before = dir+1;
  1152. }
  1153. } else {
  1154. dirp = opendir(".");
  1155. }
  1156. int before_i = i;
  1157. if (dirp) {
  1158. struct dirent * ent = readdir(dirp);
  1159. while (ent != NULL) {
  1160. if (ent->d_name[0] != '.' || (dir ? (dir[1] == '.') : (before && before[0] == '.'))) {
  1161. char * s = malloc(sizeof(char) * (strlen(ent->d_name) + 1));
  1162. memcpy(s, ent->d_name, strlen(ent->d_name) + 1);
  1163. char * t = s;
  1164. if (has_before) {
  1165. if (strstr(s,before) != s) {
  1166. free(s);
  1167. goto _nope;
  1168. }
  1169. t = &s[strlen(before)];
  1170. }
  1171. if (has_after) {
  1172. if (strlen(t) >= strlen(after)) {
  1173. if (!strcmp(after,&t[strlen(t)-strlen(after)])) {
  1174. char * out = malloc(strlen(s) + 2 + strlen(prepend));
  1175. sprintf(out,"%s%s%s", prepend, !!*prepend ? "/" : "", s);
  1176. list_insert(glob_args, out);
  1177. argv[i] = out;
  1178. i++;
  1179. argcs[cmdi]++;
  1180. }
  1181. }
  1182. } else {
  1183. char * out = malloc(strlen(s) + 2 + strlen(prepend));
  1184. sprintf(out,"%s%s%s", prepend, !!*prepend ? "/" : "", s);
  1185. list_insert(glob_args, out);
  1186. argv[i] = out;
  1187. i++;
  1188. argcs[cmdi]++;
  1189. }
  1190. free(s);
  1191. }
  1192. _nope:
  1193. ent = readdir(dirp);
  1194. }
  1195. closedir(dirp);
  1196. }
  1197. if (before_i == i) {
  1198. /* no matches */
  1199. glob[0] = '*';
  1200. if (dir) {
  1201. *dir = '/';
  1202. }
  1203. memmove(&glob[1], after, strlen(after)+1);
  1204. argv[i] = c;
  1205. i++;
  1206. argcs[cmdi]++;
  1207. }
  1208. }
  1209. } else {
  1210. argv[i] = c;
  1211. i++;
  1212. argcs[cmdi]++;
  1213. }
  1214. }
  1215. argv[i] = NULL;
  1216. /* Ensure globs get freed */
  1217. foreach(node, glob_args) {
  1218. list_insert(args, node->value);
  1219. }
  1220. list_free(glob_args);
  1221. free(glob_args);
  1222. if (i == 0) {
  1223. add_environment(extra_env);
  1224. list_free(extra_env);
  1225. free(extra_env);
  1226. list_destroy(args);
  1227. free(args);
  1228. return -1;
  1229. }
  1230. if (!*arg_starts[cmdi]) {
  1231. fprintf(stderr, "Syntax error: Unexpected end of input\n");
  1232. list_free(extra_env);
  1233. free(extra_env);
  1234. list_destroy(args);
  1235. free(args);
  1236. return 2;
  1237. }
  1238. tokenid = i;
  1239. unsigned int child_pid;
  1240. int last_child;
  1241. int nowait = (!strcmp(argv[tokenid-1],"&"));
  1242. if (nowait) {
  1243. argv[tokenid-1] = NULL;
  1244. }
  1245. int pgid = 0;
  1246. if (cmdi > 0) {
  1247. int last_output[2];
  1248. pipe(last_output);
  1249. struct semaphore s = create_semaphore();
  1250. child_pid = fork();
  1251. if (!child_pid) {
  1252. set_pgid(0);
  1253. if (!nowait) set_pgrp(getpid());
  1254. raise_semaphore(s);
  1255. is_subshell = 1;
  1256. dup2(last_output[1], STDOUT_FILENO);
  1257. close(last_output[0]);
  1258. add_environment(extra_env);
  1259. run_cmd(arg_starts[0]);
  1260. }
  1261. wait_semaphore(s);
  1262. pgid = child_pid;
  1263. for (int j = 1; j < cmdi; ++j) {
  1264. int tmp_out[2];
  1265. pipe(tmp_out);
  1266. if (!fork()) {
  1267. is_subshell = 1;
  1268. set_pgid(pgid);
  1269. dup2(tmp_out[1], STDOUT_FILENO);
  1270. dup2(last_output[0], STDIN_FILENO);
  1271. close(tmp_out[0]);
  1272. close(last_output[1]);
  1273. add_environment(extra_env);
  1274. run_cmd(arg_starts[j]);
  1275. }
  1276. close(last_output[0]);
  1277. close(last_output[1]);
  1278. last_output[0] = tmp_out[0];
  1279. last_output[1] = tmp_out[1];
  1280. }
  1281. last_child = fork();
  1282. if (!last_child) {
  1283. is_subshell = 1;
  1284. set_pgid(pgid);
  1285. if (output_files[cmdi]) {
  1286. int fd = open(output_files[cmdi], file_args[cmdi], 0666);
  1287. if (fd < 0) {
  1288. fprintf(stderr, "sh: %s: %s\n", output_files[cmdi], strerror(errno));
  1289. return -1;
  1290. } else {
  1291. dup2(fd, STDOUT_FILENO);
  1292. }
  1293. }
  1294. if (err_files[cmdi]) {
  1295. int fd = open(err_files[cmdi], err_args[cmdi], 0666);
  1296. if (fd < 0) {
  1297. fprintf(stderr, "sh: %s: %s\n", err_files[cmdi], strerror(errno));
  1298. return -1;
  1299. } else {
  1300. dup2(fd, STDERR_FILENO);
  1301. }
  1302. }
  1303. dup2(last_output[0], STDIN_FILENO);
  1304. close(last_output[1]);
  1305. add_environment(extra_env);
  1306. run_cmd(arg_starts[cmdi]);
  1307. }
  1308. close(last_output[0]);
  1309. close(last_output[1]);
  1310. /* Now execute the last piece and wait on all of them */
  1311. } else {
  1312. shell_command_t func = shell_find(*arg_starts[0]);
  1313. if (func) {
  1314. int old_out = -1;
  1315. int old_err = -1;
  1316. if (output_files[0]) {
  1317. old_out = dup(STDOUT_FILENO);
  1318. int fd = open(output_files[cmdi], file_args[cmdi], 0666);
  1319. if (fd < 0) {
  1320. fprintf(stderr, "sh: %s: %s\n", output_files[cmdi], strerror(errno));
  1321. return -1;
  1322. } else {
  1323. dup2(fd, STDOUT_FILENO);
  1324. }
  1325. }
  1326. if (err_files[0]) {
  1327. old_err = dup(STDERR_FILENO);
  1328. int fd = open(err_files[cmdi], err_args[cmdi], 0666);
  1329. if (fd < 0) {
  1330. fprintf(stderr, "sh: %s: %s\n", err_files[cmdi], strerror(errno));
  1331. return -1;
  1332. } else {
  1333. dup2(fd, STDERR_FILENO);
  1334. }
  1335. }
  1336. int result = func(argcs[0], arg_starts[0]);
  1337. if (old_out != -1) dup2(old_out, STDOUT_FILENO);
  1338. if (old_err != -1) dup2(old_err, STDERR_FILENO);
  1339. return result;
  1340. } else {
  1341. struct semaphore s = create_semaphore();
  1342. child_pid = fork();
  1343. if (!child_pid) {
  1344. set_pgid(0);
  1345. if (!nowait) set_pgrp(getpid());
  1346. raise_semaphore(s);
  1347. is_subshell = 1;
  1348. if (output_files[cmdi]) {
  1349. int fd = open(output_files[cmdi], file_args[cmdi], 0666);
  1350. if (fd < 0) {
  1351. fprintf(stderr, "sh: %s: %s\n", output_files[cmdi], strerror(errno));
  1352. return -1;
  1353. } else {
  1354. dup2(fd, STDOUT_FILENO);
  1355. }
  1356. }
  1357. if (err_files[cmdi]) {
  1358. int fd = open(err_files[cmdi], err_args[cmdi], 0666);
  1359. if (fd < 0) {
  1360. fprintf(stderr, "sh: %s: %s\n", err_files[cmdi], strerror(errno));
  1361. return -1;
  1362. } else {
  1363. dup2(fd, STDERR_FILENO);
  1364. }
  1365. }
  1366. add_environment(extra_env);
  1367. run_cmd(arg_starts[0]);
  1368. }
  1369. wait_semaphore(s);
  1370. pgid = child_pid;
  1371. last_child = child_pid;
  1372. }
  1373. }
  1374. if (nowait) {
  1375. if (shell_interactive == 1) {
  1376. fprintf(stderr, "[%d] %s\n", pgid, arg_starts[0][0]);
  1377. hashmap_set(job_hash, (void*)(intptr_t)pgid, strdup(arg_starts[0][0]));
  1378. } else {
  1379. hashmap_set(job_hash, (void*)(intptr_t)last_child, strdup(arg_starts[0][0]));
  1380. }
  1381. list_free(extra_env);
  1382. free(extra_env);
  1383. list_destroy(args);
  1384. free(args);
  1385. return 0;
  1386. }
  1387. int ret = wait_for_child(shell_interactive == 1 ? pgid : last_child, arg_starts[0][0]);
  1388. list_free(extra_env);
  1389. free(extra_env);
  1390. list_destroy(args);
  1391. free(args);
  1392. return ret;
  1393. }
  1394. void add_path_contents(char * path) {
  1395. DIR * dirp = opendir(path);
  1396. if (!dirp) return; /* Failed to load directly */
  1397. struct dirent * ent = readdir(dirp);
  1398. while (ent != NULL) {
  1399. if (ent->d_name[0] != '.') {
  1400. char * s = malloc(sizeof(char) * (strlen(ent->d_name) + 1));
  1401. memcpy(s, ent->d_name, strlen(ent->d_name) + 1);
  1402. shell_install_command(s, NULL, NULL);
  1403. }
  1404. ent = readdir(dirp);
  1405. }
  1406. closedir(dirp);
  1407. }
  1408. struct command {
  1409. char * string;
  1410. void * func;
  1411. char * desc;
  1412. };
  1413. static int comp_shell_commands(const void *p1, const void *p2) {
  1414. return strcmp(((struct command *)p1)->string, ((struct command *)p2)->string);
  1415. }
  1416. void sort_commands() {
  1417. struct command commands[SHELL_COMMANDS];
  1418. for (int i = 0; i < shell_commands_len; ++i) {
  1419. commands[i].string = shell_commands[i];
  1420. commands[i].func = shell_pointers[i];
  1421. commands[i].desc = shell_descript[i];
  1422. }
  1423. qsort(&commands, shell_commands_len, sizeof(struct command), comp_shell_commands);
  1424. for (int i = 0; i < shell_commands_len; ++i) {
  1425. shell_commands[i] = commands[i].string;
  1426. shell_pointers[i] = commands[i].func;
  1427. shell_descript[i] = commands[i].desc;
  1428. }
  1429. }
  1430. void show_version(void) {
  1431. printf("esh 1.10.0\n");
  1432. }
  1433. void show_usage(int argc, char * argv[]) {
  1434. printf(
  1435. "Esh: The Experimental Shell\n"
  1436. "\n"
  1437. "usage: %s [-lha] [path]\n"
  1438. "\n"
  1439. " -c \033[4mcmd\033[0m \033[3mparse and execute cmd\033[0m\n"
  1440. //-c cmd \033[...
  1441. " -R \033[3mdisable experimental line editor\033[0m\n"
  1442. " -v \033[3mshow version information\033[0m\n"
  1443. " -? \033[3mshow this help text\033[0m\n"
  1444. "\n", argv[0]);
  1445. }
  1446. void add_path(void) {
  1447. char * envvar = getenv("PATH");
  1448. if (!envvar) {
  1449. add_path_contents("/bin");
  1450. return;
  1451. }
  1452. char * tmp = strdup(envvar);
  1453. do {
  1454. char * end = strstr(tmp,":");
  1455. if (end) {
  1456. *end = '\0';
  1457. end++;
  1458. }
  1459. add_path_contents(tmp);
  1460. tmp = end;
  1461. } while (tmp);
  1462. free(tmp);
  1463. }
  1464. int run_script(FILE * f) {
  1465. current_line = 1;
  1466. while (!feof(f)) {
  1467. char buf[LINE_LEN] = {0};
  1468. fgets(buf, LINE_LEN, f);
  1469. int ret;
  1470. char * out = NULL;
  1471. char * b = buf;
  1472. do {
  1473. ret = shell_exec(b, LINE_LEN, f, &out);
  1474. b = out;
  1475. } while (b);
  1476. current_line++;
  1477. if (ret >= 0) last_ret = ret;
  1478. }
  1479. fclose(f);
  1480. return last_ret;
  1481. }
  1482. void source_eshrc(void) {
  1483. char * home = getenv("HOME");
  1484. if (!home) return;
  1485. char tmp[512];
  1486. sprintf(tmp, "%s/.eshrc", home);
  1487. FILE * f = fopen(tmp, "r");
  1488. if (!f) return;
  1489. current_file = tmp;
  1490. run_script(f);
  1491. }
  1492. int main(int argc, char ** argv) {
  1493. pid = getpid();
  1494. signal(SIGINT, sig_break_loop);
  1495. srand(getpid() + time(0));
  1496. job_hash = hashmap_create_int(10);
  1497. getuser();
  1498. gethost();
  1499. install_commands();
  1500. if (argc > 1) {
  1501. int c;
  1502. while ((c = getopt(argc, argv, "Rc:v?")) != -1) {
  1503. switch (c) {
  1504. case 'R':
  1505. experimental_rline = 0;
  1506. break;
  1507. case 'c':
  1508. shell_interactive = 0;
  1509. {
  1510. char * out = NULL;
  1511. do {
  1512. last_ret = shell_exec(optarg, strlen(optarg), NULL, &out);
  1513. optarg = out;
  1514. } while (optarg);
  1515. }
  1516. return (last_ret == -1) ? 0 : last_ret;
  1517. case 'v':
  1518. show_version();
  1519. return 0;
  1520. case '?':
  1521. show_usage(argc, argv);
  1522. return 0;
  1523. }
  1524. }
  1525. }
  1526. if (optind < argc) {
  1527. shell_interactive = 2;
  1528. FILE * f = fopen(argv[optind],"r");
  1529. if (!f) {
  1530. fprintf(stderr, "%s: %s: %s\n", argv[0], argv[optind], strerror(errno));
  1531. return 1;
  1532. }
  1533. shell_argc = argc - 1;
  1534. shell_argv = &argv[optind];
  1535. current_file = argv[optind];
  1536. return run_script(f);
  1537. }
  1538. shell_interactive = 1;
  1539. my_pgid = getpgid(0);
  1540. signal(SIGTTOU, SIG_IGN);
  1541. signal(SIGTTIN, SIG_IGN);
  1542. source_eshrc();
  1543. add_path();
  1544. sort_commands();
  1545. while (1) {
  1546. char buffer[LINE_LEN] = {0};
  1547. list_t * keys = hashmap_keys(job_hash);
  1548. foreach(node, keys) {
  1549. int pid = (intptr_t)node->value;
  1550. int status = 0;
  1551. if (waitpid(-pid, &status, WNOHANG) > 0) {
  1552. char * desc = "Done";
  1553. if (WTERMSIG(status) != 0) {
  1554. desc = _strsignal(WTERMSIG(status));
  1555. }
  1556. fprintf(stderr, "[%d] %s\t\t%s\n", pid, desc, (char*)hashmap_get(job_hash, (void*)(intptr_t)pid));
  1557. if (hashmap_has(job_hash, (void*)(intptr_t)pid)) {
  1558. hashmap_remove(job_hash, (void*)(intptr_t)pid);
  1559. }
  1560. }
  1561. }
  1562. list_free(keys);
  1563. free(keys);
  1564. read_entry(buffer);
  1565. char * history = malloc(strlen(buffer) + 1);
  1566. memcpy(history, buffer, strlen(buffer) + 1);
  1567. if (buffer[0] != ' ' && buffer[0] != '\n' && buffer[0] != '!') {
  1568. rline_history_insert(history);
  1569. } else {
  1570. free(history);
  1571. }
  1572. int ret;
  1573. char * out = NULL;
  1574. char * b = buffer;
  1575. do {
  1576. ret = shell_exec(b, LINE_LEN, stdin, &out);
  1577. b = out;
  1578. } while (b);
  1579. if (ret >= 0) last_ret = ret;
  1580. rline_scroll = 0;
  1581. }
  1582. return 0;
  1583. }
  1584. /*
  1585. * cd [path]
  1586. */
  1587. uint32_t shell_cmd_cd(int argc, char * argv[]) {
  1588. if (argc > 1) {
  1589. if (chdir(argv[1])) {
  1590. goto cd_error;
  1591. } /* else success */
  1592. } else /* argc < 2 */ {
  1593. char * home = getenv("HOME");
  1594. if (home) {
  1595. if (chdir(home)) {
  1596. goto cd_error;
  1597. }
  1598. } else {
  1599. char home_path[512];
  1600. sprintf(home_path, "/home/%s", username);
  1601. if (chdir(home_path)) {
  1602. goto cd_error;
  1603. }
  1604. }
  1605. }
  1606. return 0;
  1607. cd_error:
  1608. fprintf(stderr, "%s: could not cd '%s': %s\n", argv[0], argv[1], strerror(errno));
  1609. return 1;
  1610. }
  1611. /*
  1612. * history
  1613. */
  1614. uint32_t shell_cmd_history(int argc, char * argv[]) {
  1615. for (int i = 0; i < rline_history_count; ++i) {
  1616. printf("%d\t%s\n", i + 1, rline_history_get(i));
  1617. }
  1618. return 0;
  1619. }
  1620. uint32_t shell_cmd_export(int argc, char * argv[]) {
  1621. if (argc > 1) {
  1622. putenv(argv[1]);
  1623. }
  1624. return 0;
  1625. }
  1626. uint32_t shell_cmd_exit(int argc, char * argv[]) {
  1627. if (argc > 1) {
  1628. exit(atoi(argv[1]));
  1629. } else {
  1630. exit(0);
  1631. }
  1632. return -1;
  1633. }
  1634. uint32_t shell_cmd_help(int argc, char * argv[]) {
  1635. show_version();
  1636. printf("\nThis shell is not POSIX-compliant, please be careful.\n\n");
  1637. printf("Built-in commands:\n");
  1638. /* First, determine max width of command names */
  1639. unsigned int max_len = 0;
  1640. for (int i = 0; i < shell_commands_len; ++i) {
  1641. if (!shell_descript[i]) continue;
  1642. if (strlen(shell_commands[i]) > max_len) {
  1643. max_len = strlen(shell_commands[i]);
  1644. }
  1645. }
  1646. /* Then print the commands their help text */
  1647. for (int i = 0; i < shell_commands_len; ++i) {
  1648. if (!shell_descript[i]) continue;
  1649. printf(" %-*s - %s\n", max_len + 1, shell_commands[i], shell_descript[i]);
  1650. }
  1651. return 0;
  1652. }
  1653. uint32_t shell_cmd_if(int argc, char * argv[]) {
  1654. char ** if_args = &argv[1];
  1655. char ** then_args = NULL;
  1656. char ** else_args = NULL;
  1657. for (int i = 2; i < argc; ++i) {
  1658. if (!strcmp(argv[i],"then")) {
  1659. argv[i] = NULL;
  1660. then_args = &argv[i+1];
  1661. } else if (!strcmp(argv[i],"else")) {
  1662. argv[i] = NULL;
  1663. else_args = &argv[i+1];
  1664. }
  1665. }
  1666. if (!then_args) {
  1667. fprintf(stderr, "%s: syntax error: expected 'then' clause\n", argv[0]);
  1668. return 1;
  1669. }
  1670. if (else_args && else_args < then_args) {
  1671. fprintf(stderr, "%s: syntax error: 'else' clause before 'then' clase\n", argv[0]);
  1672. return 1;
  1673. }
  1674. pid_t child_pid = fork();
  1675. if (!child_pid) {
  1676. set_pgid(0);
  1677. set_pgrp(getpid());
  1678. is_subshell = 1;
  1679. run_cmd(if_args);
  1680. }
  1681. int pid, ret_code = 0;
  1682. do {
  1683. pid = waitpid(child_pid, &ret_code, 0);
  1684. } while (pid != -1 || (pid == -1 && errno != ECHILD));
  1685. handle_status(ret_code);
  1686. if (WEXITSTATUS(ret_code) == 0) {
  1687. shell_command_t func = shell_find(*then_args);
  1688. if (func) {
  1689. int argc = 0;
  1690. while (then_args[argc]) {
  1691. argc++;
  1692. }
  1693. return func(argc, then_args);
  1694. } else {
  1695. child_pid = fork();
  1696. if (!child_pid) {
  1697. set_pgid(0);
  1698. set_pgrp(getpid());
  1699. is_subshell = 1;
  1700. run_cmd(then_args);
  1701. }
  1702. do {
  1703. pid = waitpid(child_pid, &ret_code, 0);
  1704. } while (pid != -1 || (pid == -1 && errno != ECHILD));
  1705. reset_pgrp();
  1706. handle_status(ret_code);
  1707. return WEXITSTATUS(ret_code);
  1708. }
  1709. } else if (else_args) {
  1710. shell_command_t func = shell_find(*else_args);
  1711. if (func) {
  1712. int argc = 0;
  1713. while (else_args[argc]) {
  1714. argc++;
  1715. }
  1716. return func(argc, else_args);
  1717. } else {
  1718. child_pid = fork();
  1719. if (!child_pid) {
  1720. set_pgid(0);
  1721. set_pgrp(getpid());
  1722. is_subshell = 1;
  1723. run_cmd(else_args);
  1724. }
  1725. do {
  1726. pid = waitpid(child_pid, &ret_code, 0);
  1727. } while (pid != -1 || (pid == -1 && errno != ECHILD));
  1728. handle_status(ret_code);
  1729. return WEXITSTATUS(ret_code);
  1730. }
  1731. }
  1732. reset_pgrp();
  1733. return 0;
  1734. }
  1735. uint32_t shell_cmd_while(int argc, char * argv[]) {
  1736. char ** while_args = &argv[1];
  1737. char ** do_args = NULL;
  1738. for (int i = 2; i < argc; ++i) {
  1739. if (!strcmp(argv[i],"do")) {
  1740. argv[i] = NULL;
  1741. do_args = &argv[i+1];
  1742. }
  1743. }
  1744. if (!do_args) {
  1745. fprintf(stderr, "%s: syntax error: expected 'do' clause\n", argv[0]);
  1746. return 1;
  1747. }
  1748. break_while = 0;
  1749. reset_pgrp();
  1750. do {
  1751. pid_t child_pid = fork();
  1752. if (!child_pid) {
  1753. set_pgid(0);
  1754. set_pgrp(getpid());
  1755. is_subshell = 1;
  1756. run_cmd(while_args);
  1757. }
  1758. int pid, ret_code = 0;
  1759. do {
  1760. pid = waitpid(child_pid, &ret_code, 0);
  1761. } while (pid != -1 || (pid == -1 && errno != ECHILD));
  1762. handle_status(ret_code);
  1763. if (WEXITSTATUS(ret_code) == 0) {
  1764. child_pid = fork();
  1765. if (!child_pid) {
  1766. set_pgid(0);
  1767. set_pgrp(getpid());
  1768. is_subshell = 1;
  1769. run_cmd(do_args);
  1770. }
  1771. do {
  1772. pid = waitpid(child_pid, &ret_code, 0);
  1773. if (pid != -1 && WIFSIGNALED(ret_code)) {
  1774. int sig = WTERMSIG(ret_code);
  1775. if (sig == SIGINT) return 127; /* break */
  1776. }
  1777. } while (pid != -1 || (pid == -1 && errno != ECHILD));
  1778. } else {
  1779. reset_pgrp();
  1780. return WEXITSTATUS(ret_code);
  1781. }
  1782. } while (!break_while);
  1783. return 127;
  1784. }
  1785. uint32_t shell_cmd_export_cmd(int argc, char * argv[]) {
  1786. if (argc < 3) {
  1787. fprintf(stderr, "%s: syntax error: not enough arguments\n", argv[0]);
  1788. return 1;
  1789. }
  1790. int pipe_fds[2];
  1791. pipe(pipe_fds);
  1792. pid_t child_pid = fork();
  1793. if (!child_pid) {
  1794. set_pgid(0);
  1795. set_pgrp(getpid());
  1796. is_subshell = 1;
  1797. dup2(pipe_fds[1], STDOUT_FILENO);
  1798. close(pipe_fds[0]);
  1799. run_cmd(&argv[2]);
  1800. }
  1801. close(pipe_fds[1]);
  1802. char buf[1024];
  1803. size_t accum = 0;
  1804. do {
  1805. int r = read(pipe_fds[0], buf+accum, 1023-accum);
  1806. if (r == 0) break;
  1807. if (r < 0) {
  1808. return -r;
  1809. }
  1810. accum += r;
  1811. } while (accum < 1023);
  1812. waitpid(child_pid, NULL, 0);
  1813. reset_pgrp();
  1814. buf[accum] = '\0';
  1815. if (accum && buf[accum-1] == '\n') {
  1816. buf[accum-1] = '\0';
  1817. }
  1818. setenv(argv[1], buf, 1);
  1819. return 0;
  1820. }
  1821. uint32_t shell_cmd_empty(int argc, char * argv[]) {
  1822. for (int i = 1; i < argc; i++) {
  1823. if (argv[i] && *argv[i]) return 1;
  1824. }
  1825. return 0;
  1826. }
  1827. uint32_t shell_cmd_equals(int argc, char * argv[]) {
  1828. if (argc < 3) return 1;
  1829. return !!strcmp(argv[1], argv[2]);
  1830. }
  1831. uint32_t shell_cmd_return(int argc, char * argv[]) {
  1832. if (argc < 2) return 0;
  1833. return atoi(argv[1]);
  1834. }
  1835. uint32_t shell_cmd_source(int argc, char * argv[]) {
  1836. if (argc < 2) return 0;
  1837. FILE * f = fopen(argv[1], "r");
  1838. if (!f) {
  1839. fprintf(stderr, "%s: %s: %s\n", argv[0], argv[1], strerror(errno));
  1840. return 1;
  1841. }
  1842. current_file = argv[1];
  1843. return run_script(f);
  1844. }
  1845. uint32_t shell_cmd_exec(int argc, char * argv[]) {
  1846. if (argc < 2) return 1;
  1847. return execvp(argv[1], &argv[1]);
  1848. }
  1849. uint32_t shell_cmd_not(int argc, char * argv[]) {
  1850. if (argc < 2) {
  1851. fprintf(stderr, "%s: expected command argument\n", argv[0]);
  1852. return 1;
  1853. }
  1854. int ret_code = 0;
  1855. pid_t child_pid = fork();
  1856. if (!child_pid) {
  1857. set_pgid(0);
  1858. set_pgrp(getpid());
  1859. is_subshell = 1;
  1860. run_cmd(&argv[1]);
  1861. }
  1862. do {
  1863. pid = waitpid(child_pid, &ret_code, 0);
  1864. } while (pid != -1 || (pid == -1 && errno != ECHILD));
  1865. reset_pgrp();
  1866. handle_status(ret_code);
  1867. return !WEXITSTATUS(ret_code);
  1868. }
  1869. uint32_t shell_cmd_unset(int argc, char * argv[]) {
  1870. if (argc < 2) {
  1871. fprintf(stderr, "%s: expected command argument\n", argv[0]);
  1872. return 1;
  1873. }
  1874. return unsetenv(argv[1]);
  1875. }
  1876. uint32_t shell_cmd_read(int argc, char * argv[]) {
  1877. int raw = 0;
  1878. int i = 1;
  1879. char * var = "REPLY";
  1880. if (i < argc && !strcmp(argv[i], "-r")) {
  1881. raw = 1;
  1882. i++;
  1883. }
  1884. if (i < argc) {
  1885. var = argv[i];
  1886. }
  1887. char tmp[4096];
  1888. fgets(tmp, 4096, stdin);
  1889. if (*tmp && tmp[strlen(tmp)-1] == '\n') {
  1890. tmp[strlen(tmp)-1] = '\0';
  1891. }
  1892. if (raw) {
  1893. setenv(var, tmp, 1);
  1894. return 0;
  1895. }
  1896. char tmp2[4096] = {0};
  1897. char * out = tmp2;
  1898. char * in = tmp;
  1899. /* TODO: This needs to actually read more if a \ at the end of the line is found */
  1900. while (*in) {
  1901. if (*in == '\\') {
  1902. in++;
  1903. if (*in == '\n') {
  1904. in++;
  1905. }
  1906. } else {
  1907. *out = *in;
  1908. out++;
  1909. in++;
  1910. }
  1911. }
  1912. setenv(var, tmp2, 1);
  1913. return 0;
  1914. }
  1915. int get_available_job(int argc, char * argv[]) {
  1916. if (argc < 2) {
  1917. if (!suspended_pgid) {
  1918. list_t * keys = hashmap_keys(job_hash);
  1919. foreach(node, keys) {
  1920. suspended_pgid = (intptr_t)node->value;
  1921. break;
  1922. }
  1923. list_free(keys);
  1924. free(keys);
  1925. if (!suspended_pgid) {
  1926. return 0;
  1927. }
  1928. }
  1929. return suspended_pgid;
  1930. } else {
  1931. return atoi(argv[1]);
  1932. }
  1933. }
  1934. uint32_t shell_cmd_fg(int argc, char * argv[]) {
  1935. int pid = get_available_job(argc,argv);
  1936. if (!pid || !hashmap_has(job_hash, (void*)(intptr_t)pid)) {
  1937. fprintf(stderr, "no current job\n");
  1938. return 1;
  1939. }
  1940. set_pgrp(pid);
  1941. if (kill(-pid, SIGCONT) < 0) {
  1942. fprintf(stderr, "no current job / bad pid\n");
  1943. if (hashmap_has(job_hash, (void*)(intptr_t)pid)) {
  1944. hashmap_remove(job_hash, (void*)(intptr_t)pid);
  1945. }
  1946. return 1;
  1947. }
  1948. return wait_for_child(pid, NULL);
  1949. }
  1950. uint32_t shell_cmd_bg(int argc, char * argv[]) {
  1951. int pid = get_available_job(argc,argv);
  1952. if (!pid || !hashmap_has(job_hash, (void*)(intptr_t)pid)) {
  1953. fprintf(stderr, "no current job\n");
  1954. return 1;
  1955. }
  1956. if (kill(-pid, SIGCONT) < 0) {
  1957. fprintf(stderr, "no current job / bad pid\n");
  1958. if (hashmap_has(job_hash, (void*)(intptr_t)pid)) {
  1959. hashmap_remove(job_hash, (void*)(intptr_t)pid);
  1960. }
  1961. return 1;
  1962. }
  1963. fprintf(stderr, "[%d] %s\n", pid, (char*)hashmap_get(job_hash, (void*)(intptr_t)pid));
  1964. return 0;
  1965. }
  1966. uint32_t shell_cmd_jobs(int argc, char * argv[]) {
  1967. list_t * keys = hashmap_keys(job_hash);
  1968. foreach(node, keys) {
  1969. int pid = (intptr_t)node->value;
  1970. char * c = hashmap_get(job_hash, (void*)(intptr_t)pid);
  1971. fprintf(stdout, "%5d %s\n", pid, c);
  1972. }
  1973. list_free(keys);
  1974. free(keys);
  1975. return 0;
  1976. }
  1977. uint32_t shell_cmd_rehash(int argc, char * argv[]) {
  1978. /* PATH commands are malloc'd */
  1979. for (int i = 0; i < shell_commands_len; ++i) {
  1980. if (!shell_pointers[i]) {
  1981. free(shell_commands[i]);
  1982. }
  1983. }
  1984. /* Clear array */
  1985. shell_commands_len = 0;
  1986. /* Reset capacity */
  1987. SHELL_COMMANDS = 64;
  1988. /* Free existing */
  1989. free(shell_commands);
  1990. free(shell_pointers);
  1991. free(shell_descript);
  1992. /* Reallocate + install builtins */
  1993. install_commands();
  1994. /* Reload PATH */
  1995. add_path();
  1996. return 0;
  1997. }
  1998. void install_commands() {
  1999. shell_commands = malloc(sizeof(char *) * SHELL_COMMANDS);
  2000. shell_pointers = malloc(sizeof(shell_command_t) * SHELL_COMMANDS);
  2001. shell_descript = malloc(sizeof(char *) * SHELL_COMMANDS);
  2002. shell_install_command("cd", shell_cmd_cd, "change directory");
  2003. shell_install_command("exit", shell_cmd_exit, "exit the shell");
  2004. shell_install_command("export", shell_cmd_export, "set environment variables: export VAR=value");
  2005. shell_install_command("help", shell_cmd_help, "display this help text");
  2006. shell_install_command("history", shell_cmd_history, "list command history");
  2007. shell_install_command("if", shell_cmd_if, "if ... then ... [else ...]");
  2008. shell_install_command("while", shell_cmd_while, "while ... do ...");
  2009. shell_install_command("empty?", shell_cmd_empty, "empty? args...");
  2010. shell_install_command("equals?", shell_cmd_equals, "equals? arg1 arg2");
  2011. shell_install_command("return", shell_cmd_return, "return status code");
  2012. shell_install_command("export-cmd", shell_cmd_export_cmd, "set variable to result of command: export-cmd VAR command...");
  2013. shell_install_command("source", shell_cmd_source, "run a shell script in the context of this shell");
  2014. shell_install_command(".", shell_cmd_source, "alias for 'source'");
  2015. shell_install_command("exec", shell_cmd_exec, "replace shell (or subshell) with command");
  2016. shell_install_command("not", shell_cmd_not, "invert status of command");
  2017. shell_install_command("unset", shell_cmd_unset, "unset variable");
  2018. shell_install_command("read", shell_cmd_read, "read user input");
  2019. shell_install_command("fg", shell_cmd_fg, "resume a suspended job");
  2020. shell_install_command("jobs", shell_cmd_jobs, "list stopped jobs");
  2021. shell_install_command("bg", shell_cmd_bg, "restart suspended job in the background");
  2022. shell_install_command("rehash", shell_cmd_rehash, "reset shell command memory");
  2023. }