sh.c 51 KB

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