sh.c 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644
  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
  16. #include <stdio.h>
  17. #include <stdint.h>
  18. #include <string.h>
  19. #include <stdlib.h>
  20. #include <unistd.h>
  21. #include <time.h>
  22. #include <dirent.h>
  23. #include <signal.h>
  24. #include <getopt.h>
  25. #include <termios.h>
  26. #include <errno.h>
  27. #include <fcntl.h>
  28. #include <ctype.h>
  29. #include <sys/time.h>
  30. #include <sys/wait.h>
  31. #include <sys/utsname.h>
  32. #include <sys/stat.h>
  33. #include <toaru/list.h>
  34. #include <toaru/kbd.h>
  35. #include <toaru/rline.h>
  36. #include <toaru/rline_exp.h>
  37. #define PIPE_TOKEN "\xFF\xFFPIPE\xFF\xFF"
  38. #define STAR_TOKEN "\xFF\xFFSTAR\xFF\xFF"
  39. #define WRITE_TOKEN "\xFF\xFFWRITE\xFF\xFF"
  40. #define APPEND_TOKEN "\xFF\xFF""APPEND\xFF"
  41. /* A shell command is like a C program */
  42. typedef uint32_t(*shell_command_t) (int argc, char ** argv);
  43. /* We have a static array that fits a certain number of them. */
  44. #define SHELL_COMMANDS 512
  45. char * shell_commands[SHELL_COMMANDS]; /* Command names */
  46. shell_command_t shell_pointers[SHELL_COMMANDS]; /* Command functions */
  47. char * shell_descript[SHELL_COMMANDS]; /* Command descriptions */
  48. /* This is the number of actual commands installed */
  49. int shell_commands_len = 0;
  50. int shell_interactive = 1;
  51. int last_ret = 0;
  52. char ** shell_argv = NULL;
  53. int shell_argc = 0;
  54. int experimental_rline = 1;
  55. int pid; /* Process ID of the shell */
  56. void shell_install_command(char * name, shell_command_t func, char * desc) {
  57. if (shell_commands_len == SHELL_COMMANDS) {
  58. fprintf(stderr, "Ran out of space for static shell commands. The maximum number of commands is %d\n", SHELL_COMMANDS);
  59. return;
  60. }
  61. shell_commands[shell_commands_len] = name;
  62. shell_pointers[shell_commands_len] = func;
  63. shell_descript[shell_commands_len] = desc;
  64. shell_commands_len++;
  65. }
  66. shell_command_t shell_find(char * str) {
  67. for (int i = 0; i < shell_commands_len; ++i) {
  68. if (!strcmp(str, shell_commands[i])) {
  69. return shell_pointers[i];
  70. }
  71. }
  72. return NULL;
  73. }
  74. void install_commands();
  75. /* Maximum command length */
  76. #define LINE_LEN 4096
  77. /* Current working directory */
  78. char cwd[1024] = {'/',0};
  79. /* Username */
  80. char username[1024];
  81. /* Hostname for prompt */
  82. char _hostname[256];
  83. /* function to update the cached username */
  84. void getuser() {
  85. char * tmp = getenv("USER");
  86. if (tmp) {
  87. strcpy(username, tmp);
  88. } else {
  89. sprintf(username, "%d", getuid());
  90. }
  91. }
  92. /* function to update the cached hostname */
  93. void gethost() {
  94. struct utsname buf;
  95. uname(&buf);
  96. int len = strlen(buf.nodename);
  97. memcpy(_hostname, buf.nodename, len+1);
  98. }
  99. void print_extended_ps(char * format, char * buffer, int * display_width) {
  100. /* Get the time */
  101. struct tm * timeinfo;
  102. struct timeval now;
  103. gettimeofday(&now, NULL); //time(NULL);
  104. timeinfo = localtime((time_t *)&now.tv_sec);
  105. /* Format the date and time for prompt display */
  106. char date_buffer[80];
  107. strftime(date_buffer, 80, "%m/%d", timeinfo);
  108. char time_buffer[80];
  109. strftime(time_buffer, 80, "%H:%M:%S", timeinfo);
  110. /* Collect the current working directory */
  111. getcwd(cwd, 512);
  112. char _cwd[512];
  113. strcpy(_cwd, cwd);
  114. /* Collect the user's home directory and apply it to cwd */
  115. char * home = getenv("HOME");
  116. if (home && strstr(cwd, home) == cwd) {
  117. char * c = cwd + strlen(home);
  118. if (*c == '/' || *c == 0) {
  119. sprintf(_cwd, "~%s", c);
  120. }
  121. }
  122. char ret[80] = {0};
  123. if (last_ret != 0) {
  124. sprintf(ret, "%d ", last_ret);
  125. }
  126. size_t offset = 0;
  127. int is_visible = 1;
  128. *display_width = 0;
  129. while (*format) {
  130. if (*format == '\\') {
  131. format++;
  132. switch (*format) {
  133. case '\\':
  134. buffer[offset++] = *format;
  135. (*display_width) += is_visible ? 1 : 0;
  136. format++;
  137. break;
  138. case '[':
  139. is_visible = 0;
  140. format++;
  141. break;
  142. case ']':
  143. is_visible = 1;
  144. format++;
  145. break;
  146. case '0':
  147. case '1':
  148. case '2':
  149. case '3':
  150. case '4':
  151. case '5':
  152. case '6':
  153. case '7':
  154. {
  155. int i = (*format) - '0';
  156. format++;
  157. if (*format >= '0' && *format <= '7') {
  158. i *= 8;
  159. i += (*format) - '0';
  160. format++;
  161. if (*format >= '0' && *format <= '7') {
  162. i *= 8;
  163. i += (*format) - '0';
  164. format++;
  165. }
  166. }
  167. buffer[offset++] = i;
  168. (*display_width) += is_visible ? 1 : 0;
  169. }
  170. break;
  171. case 'e':
  172. buffer[offset++] = '\033';
  173. (*display_width) += is_visible ? 1 : 0;
  174. format++;
  175. break;
  176. case 'd':
  177. {
  178. int size = sprintf(buffer+offset, "%s", date_buffer);
  179. offset += size;
  180. (*display_width) += is_visible ? size : 0;
  181. }
  182. format++;
  183. break;
  184. case 't':
  185. {
  186. int size = sprintf(buffer+offset, "%s", time_buffer);
  187. offset += size;
  188. (*display_width) += is_visible ? size : 0;
  189. }
  190. format++;
  191. break;
  192. case 'h':
  193. {
  194. int size = sprintf(buffer+offset, "%s", _hostname);
  195. offset += size;
  196. (*display_width) += is_visible ? size : 0;
  197. }
  198. format++;
  199. break;
  200. case 'u':
  201. {
  202. int size = sprintf(buffer+offset, "%s", username);
  203. offset += size;
  204. (*display_width) += is_visible ? size : 0;
  205. }
  206. format++;
  207. break;
  208. case 'w':
  209. {
  210. int size = sprintf(buffer+offset, "%s", _cwd);
  211. offset += size;
  212. (*display_width) += is_visible ? size : 0;
  213. }
  214. format++;
  215. break;
  216. case '$':
  217. buffer[offset++] = (getuid() == 0 ? '#' : '$');
  218. (*display_width) += is_visible ? 1 : 0;
  219. format++;
  220. break;
  221. case 'U': /* prompt color string */
  222. {
  223. int size = sprintf(buffer+offset, "%s", getuid() == 0 ? "\033[1;38;5;196m" : "\033[1;38;5;47m");
  224. offset += size;
  225. /* Does not affect size */
  226. }
  227. format++;
  228. break;
  229. case 'r':
  230. {
  231. int size = sprintf(buffer+offset, "%s", ret);
  232. offset += size;
  233. (*display_width) += is_visible ? size : 0;
  234. }
  235. format++;
  236. break;
  237. default:
  238. {
  239. int size = sprintf(buffer+offset, "\\%c", *format);
  240. offset += size;
  241. (*display_width) += is_visible ? size : 0;
  242. }
  243. format++;
  244. break;
  245. }
  246. } else {
  247. buffer[offset++] = *format;
  248. (*display_width) += is_visible ? 1 : 0;
  249. format++;
  250. }
  251. }
  252. buffer[offset] = '\0';
  253. }
  254. #define FALLBACK_PS1 "\\u@\\h \\w\\$ "
  255. /* Draw the user prompt */
  256. void draw_prompt(void) {
  257. char * ps1 = getenv("PS1");
  258. char buf[1024];
  259. int display_width;
  260. print_extended_ps(ps1 ? ps1 : FALLBACK_PS1, buf, &display_width);
  261. fprintf(stdout, "%s", buf);
  262. fflush(stdout);
  263. }
  264. volatile int break_while = 0;
  265. uint32_t child = 0;
  266. void sig_pass(int sig) {
  267. /* Interrupt handler */
  268. if (child) {
  269. kill(child, sig);
  270. }
  271. break_while = sig;
  272. }
  273. void redraw_prompt_func(rline_context_t * context) {
  274. draw_prompt();
  275. }
  276. void draw_prompt_c() {
  277. char * ps2 = getenv("PS2");
  278. if (ps2) {
  279. char buf[1024];
  280. int display_width;
  281. print_extended_ps(ps2, buf, &display_width);
  282. fprintf(stdout, "%s", buf);
  283. } else {
  284. printf("> ");
  285. }
  286. fflush(stdout);
  287. }
  288. void redraw_prompt_func_c(rline_context_t * context) {
  289. draw_prompt_c();
  290. }
  291. void tab_complete_func(rline_context_t * c) {
  292. char * dup = malloc(LINE_LEN);
  293. memcpy(dup, c->buffer, LINE_LEN);
  294. char *pch, *save;
  295. char *argv[1024];
  296. int argc = 0;
  297. int cursor = 0;
  298. pch = strtok_r(dup, " ", &save);
  299. if (!pch) {
  300. argv[0] = "";
  301. argc = 0;
  302. }
  303. while (pch != NULL) {
  304. if (pch - dup <= c->offset) cursor = argc;
  305. argv[argc] = pch;
  306. ++argc;
  307. pch = strtok_r(NULL, " ", &save);
  308. }
  309. argv[argc] = NULL;
  310. if (c->offset && c->buffer[c->offset-1] == ' ' && argc) {
  311. cursor++;
  312. }
  313. char * word = argv[cursor];
  314. int word_offset = word ? (c->offset - (argv[cursor] - dup)) : 0;
  315. char * prefix = malloc(word_offset + 1);
  316. if (word) memcpy(prefix, word, word_offset);
  317. prefix[word_offset] = '\0';
  318. /* Complete file path */
  319. list_t * matches = list_create();
  320. char * match = NULL;
  321. int free_matches = 0;
  322. int no_space_if_only = 0;
  323. /* TODO custom auto-complete as a configuration file? */
  324. #define COMPLETE_FILE 1
  325. #define COMPLETE_COMMAND 2
  326. #define COMPLETE_CUSTOM 3
  327. #define COMPLETE_VARIABLE 4
  328. int complete_mode = COMPLETE_FILE;
  329. int command_adj = 0;
  330. int cursor_adj = cursor;
  331. /* sudo should shift commands */
  332. if (cursor_adj > command_adj && (!strcmp(argv[command_adj], "sudo") || !strcmp(argv[command_adj], "gsudo"))) {
  333. cursor_adj -= 1;
  334. command_adj += 1;
  335. }
  336. /* initial tab completion should be commands, unless typing a file path */
  337. if (cursor_adj == 0 && !strchr(prefix,'/')) {
  338. complete_mode = COMPLETE_COMMAND;
  339. }
  340. if (cursor_adj >= 1 && !strcmp(argv[command_adj], "toggle-abs-mouse")) {
  341. complete_mode = COMPLETE_CUSTOM;
  342. }
  343. /* complete variable names */
  344. if (*prefix == '$') {
  345. complete_mode = COMPLETE_VARIABLE;
  346. }
  347. if (complete_mode == COMPLETE_COMMAND) {
  348. /* Complete a command name */
  349. for (int i = 0; i < shell_commands_len; ++i) {
  350. if (strstr(shell_commands[i], prefix) == shell_commands[i]) {
  351. list_insert(matches, shell_commands[i]);
  352. match = shell_commands[i];
  353. }
  354. }
  355. } else if (complete_mode == COMPLETE_FILE) {
  356. /* Complete a file path */
  357. free_matches = 1;
  358. char * tmp = strdup(prefix);
  359. char * last_slash = strrchr(tmp, '/');
  360. DIR * dirp;
  361. char * compare = prefix;
  362. if (last_slash) {
  363. *last_slash = '\0';
  364. word = word + (last_slash - tmp) + 1;
  365. word_offset = word_offset - (last_slash - tmp + 1);
  366. compare = word;
  367. if (last_slash == tmp) {
  368. dirp = opendir("/");
  369. } else {
  370. dirp = opendir(tmp);
  371. }
  372. } else {
  373. dirp = opendir(".");
  374. }
  375. if (!dirp) {
  376. free(tmp);
  377. goto finish_tab;
  378. }
  379. struct dirent * ent = readdir(dirp);
  380. while (ent != NULL) {
  381. if (ent->d_name[0] != '.' || compare[0] == '.') {
  382. if (!word || strstr(ent->d_name, compare) == ent->d_name) {
  383. struct stat statbuf;
  384. /* stat it */
  385. if (last_slash) {
  386. char * x = malloc(strlen(tmp) + 1 + strlen(ent->d_name) + 1);
  387. sprintf(x,"%s/%s",tmp,ent->d_name);
  388. lstat(x, &statbuf);
  389. free(x);
  390. } else {
  391. lstat(ent->d_name, &statbuf);
  392. }
  393. char * s;
  394. if (S_ISDIR(statbuf.st_mode)) {
  395. s = malloc(strlen(ent->d_name) + 2);
  396. sprintf(s,"%s/", ent->d_name);
  397. no_space_if_only = 1;
  398. } else {
  399. s = strdup(ent->d_name);
  400. }
  401. list_insert(matches, s);
  402. match = s;
  403. }
  404. }
  405. ent = readdir(dirp);
  406. }
  407. closedir(dirp);
  408. free(tmp);
  409. } else if (complete_mode == COMPLETE_CUSTOM) {
  410. char ** completions = NULL;
  411. char * toggle_abs_mouse_completions[] = {"relative","absolute",NULL};
  412. if (!strcmp(argv[command_adj],"toggle-abs-mouse")) {
  413. completions = toggle_abs_mouse_completions;
  414. }
  415. while (*completions) {
  416. if (strstr(*completions, prefix) == *completions) {
  417. list_insert(matches, *completions);
  418. match = *completions;
  419. }
  420. completions++;
  421. }
  422. } else if (complete_mode == COMPLETE_VARIABLE) {
  423. char ** envvar = environ;
  424. free_matches = 1;
  425. while (*envvar) {
  426. char * tmp = strdup(*envvar);
  427. char * c = strchr(tmp, '=');
  428. *c = '\0';
  429. if (strstr(tmp, prefix+1) == tmp) {
  430. char * m = malloc(strlen(tmp)+2);
  431. sprintf(m, "$%s", tmp);
  432. list_insert(matches, m);
  433. match = m;
  434. }
  435. free(tmp);
  436. envvar++;
  437. }
  438. }
  439. if (matches->length == 1) {
  440. /* Insert */
  441. rline_insert(c, &match[word_offset]);
  442. if (word && word_offset == (int)strlen(word) && !no_space_if_only) {
  443. rline_insert(c, " ");
  444. }
  445. rline_redraw(c);
  446. } else if (matches->length > 1) {
  447. if (!c->tabbed) {
  448. /* see if there is a minimum subset we can fill in */
  449. size_t j = word_offset;
  450. do {
  451. char d = match[j];
  452. int diff = 0;
  453. foreach(node, matches) {
  454. char * match = (char *)node->value;
  455. if (match[j] != d || match[j] == '\0') diff = 1;
  456. }
  457. if (diff) break;
  458. j++;
  459. } while (j < (size_t)c->requested);
  460. if (j > (size_t)word_offset) {
  461. char * tmp = strdup(match);
  462. tmp[j] = '\0';
  463. rline_insert(c, &tmp[word_offset]);
  464. rline_redraw(c);
  465. free(tmp);
  466. } else {
  467. c->tabbed = 1;
  468. }
  469. } else {
  470. /* Print matches */
  471. fprintf(stderr,"\n");
  472. size_t j = 0;
  473. foreach(node, matches) {
  474. char * match = (char *)node->value;
  475. fprintf(stderr, "%s", match);
  476. ++j;
  477. if (j < matches->length) {
  478. fprintf(stderr, ", ");
  479. }
  480. }
  481. fprintf(stderr,"\n");
  482. c->callbacks->redraw_prompt(c);
  483. fprintf(stderr, "\033[s");
  484. rline_redraw(c);
  485. }
  486. }
  487. finish_tab:
  488. if (free_matches) list_destroy(matches);
  489. list_free(matches);
  490. free(prefix);
  491. free(dup);
  492. }
  493. void add_argument(list_t * argv, char * buf) {
  494. char * c = malloc(strlen(buf) + 1);
  495. memcpy(c, buf, strlen(buf) + 1);
  496. list_insert(argv, c);
  497. }
  498. int read_entry(char * buffer) {
  499. if (experimental_rline) {
  500. char lprompt[1024], rprompt[1024];
  501. int lwidth, rwidth;
  502. char * ps1 = getenv("PS1_LEFT");
  503. print_extended_ps(ps1 ? ps1 : FALLBACK_PS1, lprompt, &lwidth);
  504. char * ps1r = getenv("PS1_RIGHT");
  505. print_extended_ps(ps1r ? ps1r : "", rprompt, &rwidth);
  506. rline_exit_string="exit";
  507. rline_exp_set_syntax("esh");
  508. rline_exp_set_prompts(lprompt, rprompt, lwidth, rwidth);
  509. rline_exp_set_shell_commands(shell_commands, shell_commands_len);
  510. rline_exp_set_tab_complete_func(tab_complete_func);
  511. return rline_experimental(buffer, LINE_LEN);
  512. } else {
  513. rline_callbacks_t callbacks = {
  514. tab_complete_func, redraw_prompt_func, NULL,
  515. NULL, NULL, NULL, NULL, NULL
  516. };
  517. return rline((char *)buffer, LINE_LEN, &callbacks);
  518. }
  519. }
  520. int read_entry_continued(char * buffer) {
  521. if (experimental_rline) {
  522. rline_exit_string="exit";
  523. rline_exp_set_syntax("esh");
  524. rline_exp_set_prompts("> ", "", 2, 0);
  525. rline_exp_set_shell_commands(shell_commands, shell_commands_len);
  526. rline_exp_set_tab_complete_func(tab_complete_func);
  527. return rline_experimental(buffer, LINE_LEN);
  528. } else {
  529. rline_callbacks_t callbacks = {
  530. tab_complete_func, redraw_prompt_func_c, NULL,
  531. NULL, NULL, NULL, NULL, NULL
  532. };
  533. return rline((char *)buffer, LINE_LEN, &callbacks);
  534. }
  535. }
  536. int variable_char(uint8_t c) {
  537. if (c >= 'A' && c <= 'Z') return 1;
  538. if (c >= 'a' && c <= 'z') return 1;
  539. if (c >= '0' && c <= '9') return 1;
  540. if (c == '_') return 1;
  541. if (c == '?') return 1;
  542. return 0;
  543. }
  544. void run_cmd(char ** args) {
  545. int i = execvp(*args, args);
  546. shell_command_t func = shell_find(*args);
  547. if (func) {
  548. int argc = 0;
  549. while (args[argc]) {
  550. argc++;
  551. }
  552. i = func(argc, args);
  553. } else {
  554. if (i != 0) {
  555. fprintf(stderr, "%s: Command not found\n", *args);
  556. i = 127;
  557. }
  558. }
  559. exit(i);
  560. }
  561. int is_number(const char * c) {
  562. while (*c) {
  563. if (!isdigit(*c)) return 0;
  564. c++;
  565. }
  566. return 1;
  567. }
  568. int shell_exec(char * buffer, size_t size, FILE * file, char ** out_buffer) {
  569. *out_buffer = NULL;
  570. /* Read previous history entries */
  571. if (buffer[0] == '!') {
  572. int x = atoi((char *)((uintptr_t)buffer + 1));
  573. if (x > 0 && x <= rline_history_count) {
  574. buffer = rline_history_get(x - 1);
  575. } else {
  576. fprintf(stderr, "esh: !%d: event not found\n", x);
  577. return 0;
  578. }
  579. }
  580. char * argv[1024];
  581. int tokenid = 0;
  582. char quoted = 0;
  583. char backtick = 0;
  584. char buffer_[512] = {0};
  585. int collected = 0;
  586. list_t * args = list_create();
  587. int have_star = 0;
  588. while (1) {
  589. char * p = buffer;
  590. while (*p) {
  591. switch (*p) {
  592. case '$':
  593. if (quoted == '\'') {
  594. goto _just_add;
  595. } else {
  596. if (backtick) {
  597. goto _just_add;
  598. }
  599. p++;
  600. char var[100];
  601. int coll = 0;
  602. if (*p == '{') {
  603. p++;
  604. while (*p != '}' && *p != '\0' && (coll < 100)) {
  605. var[coll] = *p;
  606. coll++;
  607. var[coll] = '\0';
  608. p++;
  609. }
  610. if (*p == '}') {
  611. p++;
  612. }
  613. } else {
  614. while (*p != '\0' && variable_char(*p) && (coll < 100)) {
  615. var[coll] = *p;
  616. coll++;
  617. var[coll] = '\0';
  618. if (coll == 0 && (isdigit(*p) || *p == '?')) {
  619. p++;
  620. break; /* Don't let these keep going */
  621. }
  622. p++;
  623. }
  624. }
  625. /* Special cases */
  626. char *c = NULL;
  627. char tmp[128];
  628. if (!strcmp(var, "?")) {
  629. sprintf(tmp,"%d",last_ret);
  630. c = tmp;
  631. } else if (is_number(var)) {
  632. int a = atoi(var);
  633. if (a >= 0 && a < shell_argc) {
  634. c = shell_argv[a];
  635. }
  636. } else {
  637. c = getenv(var);
  638. }
  639. if (c) {
  640. backtick = 0;
  641. for (int i = 0; i < (int)strlen(c); ++i) {
  642. if (c[i] == ' ' && !quoted) {
  643. /* If we are not quoted and we reach a space, it signals a new argument */
  644. if (collected) {
  645. buffer_[collected] = '\0';
  646. add_argument(args, buffer_);
  647. buffer_[0] = '\0';
  648. have_star = 0;
  649. collected = 0;
  650. }
  651. } else {
  652. buffer_[collected] = c[i];
  653. collected++;
  654. }
  655. }
  656. buffer_[collected] = '\0';
  657. }
  658. continue;
  659. }
  660. case '\"':
  661. if (quoted == '\"') {
  662. if (backtick) {
  663. goto _just_add;
  664. }
  665. quoted = 0;
  666. goto _next;
  667. } else if (!quoted) {
  668. if (backtick) {
  669. goto _just_add;
  670. }
  671. quoted = *p;
  672. goto _next;
  673. }
  674. goto _just_add;
  675. case '\'':
  676. if (quoted == '\'') {
  677. if (backtick) {
  678. goto _just_add;
  679. }
  680. quoted = 0;
  681. goto _next;
  682. } else if (!quoted) {
  683. if (backtick) {
  684. goto _just_add;
  685. }
  686. quoted = *p;
  687. goto _next;
  688. }
  689. goto _just_add;
  690. case '*':
  691. if (quoted) {
  692. goto _just_add;
  693. }
  694. if (backtick) {
  695. goto _just_add;
  696. }
  697. if (have_star) {
  698. goto _just_add; /* TODO multiple globs */
  699. }
  700. have_star = 1;
  701. collected += sprintf(&buffer_[collected], STAR_TOKEN);
  702. goto _next;
  703. case '\\':
  704. if (quoted == '\'') {
  705. goto _just_add;
  706. }
  707. if (backtick) {
  708. goto _just_add;
  709. }
  710. backtick = 1;
  711. goto _next;
  712. case ' ':
  713. if (backtick) {
  714. goto _just_add;
  715. }
  716. if (!quoted) {
  717. goto _new_arg;
  718. }
  719. goto _just_add;
  720. case '\n':
  721. if (!quoted) {
  722. goto _done;
  723. }
  724. goto _just_add;
  725. case '|':
  726. if (!quoted && !backtick) {
  727. if (collected) {
  728. add_argument(args, buffer_);
  729. }
  730. collected = sprintf(buffer_, "%s", PIPE_TOKEN);
  731. goto _new_arg;
  732. }
  733. goto _just_add;
  734. case '>':
  735. if (!quoted && !backtick) {
  736. if (collected) {
  737. add_argument(args, buffer_);
  738. }
  739. collected = sprintf(buffer_, "%s", WRITE_TOKEN);
  740. goto _new_arg;
  741. }
  742. goto _just_add;
  743. case ';':
  744. if (!quoted && !backtick) {
  745. *out_buffer = ++p;
  746. goto _done;
  747. }
  748. case '#':
  749. if (!quoted && !backtick) {
  750. goto _done; /* Support comments; must not be part of an existing arg */
  751. }
  752. goto _just_add;
  753. default:
  754. if (backtick) {
  755. buffer_[collected] = '\\';
  756. collected++;
  757. buffer_[collected] = '\0';
  758. }
  759. _just_add:
  760. backtick = 0;
  761. buffer_[collected] = *p;
  762. collected++;
  763. buffer_[collected] = '\0';
  764. goto _next;
  765. }
  766. _new_arg:
  767. backtick = 0;
  768. if (collected) {
  769. add_argument(args, buffer_);
  770. buffer_[0] = '\0';
  771. have_star = 0;
  772. collected = 0;
  773. }
  774. _next:
  775. p++;
  776. }
  777. _done:
  778. if (quoted || backtick) {
  779. backtick = 0;
  780. if (shell_interactive == 1) {
  781. draw_prompt_c();
  782. read_entry_continued(buffer);
  783. rline_history_append_line(buffer);
  784. continue;
  785. } else if (shell_interactive == 2) {
  786. fgets(buffer, size, file);
  787. continue;
  788. } else {
  789. fprintf(stderr, "Syntax error: Unterminated quoted string.\n");
  790. return 127;
  791. }
  792. }
  793. if (collected) {
  794. add_argument(args, buffer_);
  795. break;
  796. }
  797. break;
  798. }
  799. int cmdi = 0;
  800. char ** arg_starts[100] = { &argv[0], NULL };
  801. char * output_files[100] = { NULL };
  802. int file_args[100] = {0};
  803. int argcs[100] = {0};
  804. int next_is_file = 0;
  805. int i = 0;
  806. foreach(node, args) {
  807. char * c = node->value;
  808. if (next_is_file) {
  809. if (next_is_file == 1 && !strcmp(c, WRITE_TOKEN)) {
  810. next_is_file = 2;
  811. file_args[cmdi] = O_WRONLY | O_CREAT | O_APPEND;
  812. continue;
  813. }
  814. output_files[cmdi] = c;
  815. continue;
  816. }
  817. if (!strcmp(c, WRITE_TOKEN)) {
  818. next_is_file = 1;
  819. file_args[cmdi] = O_WRONLY | O_CREAT | O_TRUNC;
  820. continue;
  821. }
  822. if (!strcmp(c, PIPE_TOKEN)) {
  823. if (arg_starts[cmdi] == &argv[i]) {
  824. fprintf(stderr, "Syntax error: Unexpected pipe token\n");
  825. return 2;
  826. }
  827. argv[i] = 0;
  828. i++;
  829. cmdi++;
  830. arg_starts[cmdi] = &argv[i];
  831. continue;
  832. }
  833. char * glob = strstr(c, STAR_TOKEN);
  834. if (glob) {
  835. /* Globbing */
  836. glob[0] = '\0';
  837. glob[1] = '\0';
  838. char * before = c;
  839. char * after = &glob[8];
  840. int has_before = !!strlen(before);
  841. int has_after = !!strlen(after);
  842. if (!has_before || !strchr(before,'/')) {
  843. /* read current directory, add all */
  844. DIR * dirp = opendir(".");
  845. int before_i = i;
  846. struct dirent * ent = readdir(dirp);
  847. while (ent != NULL) {
  848. if (ent->d_name[0] != '.') {
  849. char * s = malloc(sizeof(char) * (strlen(ent->d_name) + 1));
  850. memcpy(s, ent->d_name, strlen(ent->d_name) + 1);
  851. char * t = s;
  852. if (has_before) {
  853. if (strstr(s,before) != s) {
  854. goto _nope;
  855. }
  856. t = &s[strlen(before)];
  857. }
  858. if (has_after) {
  859. if (strlen(t) >= strlen(after)) {
  860. if (!strcmp(after,&t[strlen(t)-strlen(after)])) {
  861. argv[i] = s;
  862. i++;
  863. argcs[cmdi]++;
  864. }
  865. }
  866. } else {
  867. argv[i] = s;
  868. i++;
  869. argcs[cmdi]++;
  870. }
  871. }
  872. _nope:
  873. ent = readdir(dirp);
  874. }
  875. closedir(dirp);
  876. if (before_i == i) {
  877. /* no matches */
  878. glob[0] = '*';
  879. memmove(&glob[1], after, strlen(after)+1);
  880. argv[i] = c;
  881. i++;
  882. argcs[cmdi]++;
  883. } else {
  884. free(c);
  885. }
  886. } else {
  887. /* directory globs not supported */
  888. glob[0] = '*';
  889. argv[i] = c;
  890. i++;
  891. argcs[cmdi]++;
  892. }
  893. } else {
  894. argv[i] = c;
  895. i++;
  896. argcs[cmdi]++;
  897. }
  898. }
  899. argv[i] = NULL;
  900. if (i == 0) {
  901. return -1;
  902. }
  903. list_free(args);
  904. if (!*arg_starts[cmdi]) {
  905. fprintf(stderr, "Syntax error: Unexpected end of input\n");
  906. return 2;
  907. }
  908. char * cmd = *arg_starts[0];
  909. tokenid = i;
  910. unsigned int child_pid;
  911. int nowait = (!strcmp(argv[tokenid-1],"&"));
  912. if (nowait) {
  913. argv[tokenid-1] = NULL;
  914. }
  915. if (cmdi > 0) {
  916. int last_output[2];
  917. pipe(last_output);
  918. child_pid = fork();
  919. if (!child_pid) {
  920. dup2(last_output[1], STDOUT_FILENO);
  921. close(last_output[0]);
  922. run_cmd(arg_starts[0]);
  923. }
  924. for (int j = 1; j < cmdi; ++j) {
  925. int tmp_out[2];
  926. pipe(tmp_out);
  927. if (!fork()) {
  928. dup2(tmp_out[1], STDOUT_FILENO);
  929. dup2(last_output[0], STDIN_FILENO);
  930. close(tmp_out[0]);
  931. close(last_output[1]);
  932. run_cmd(arg_starts[j]);
  933. }
  934. close(last_output[0]);
  935. close(last_output[1]);
  936. last_output[0] = tmp_out[0];
  937. last_output[1] = tmp_out[1];
  938. }
  939. if (!fork()) {
  940. if (output_files[cmdi]) {
  941. dup2(open(output_files[cmdi], file_args[cmdi], 0666), STDOUT_FILENO);
  942. }
  943. dup2(last_output[0], STDIN_FILENO);
  944. close(last_output[1]);
  945. run_cmd(arg_starts[cmdi]);
  946. }
  947. close(last_output[0]);
  948. close(last_output[1]);
  949. /* Now execute the last piece and wait on all of them */
  950. } else {
  951. shell_command_t func = shell_find(*arg_starts[0]);
  952. if (func) {
  953. return func(argcs[0], arg_starts[0]);
  954. } else {
  955. child_pid = fork();
  956. if (!child_pid) {
  957. if (output_files[cmdi]) {
  958. dup2(open(output_files[cmdi], file_args[cmdi], 0666), STDOUT_FILENO);
  959. }
  960. run_cmd(arg_starts[0]);
  961. }
  962. }
  963. }
  964. tcsetpgrp(STDIN_FILENO, child_pid);
  965. int ret_code = 0;
  966. if (!nowait) {
  967. child = child_pid;
  968. int pid;
  969. do {
  970. pid = waitpid(-1, &ret_code, 0);
  971. } while (pid != -1 || (pid == -1 && errno != ECHILD));
  972. child = 0;
  973. }
  974. tcsetpgrp(STDIN_FILENO, getpid());
  975. free(cmd);
  976. return ret_code;
  977. }
  978. void add_path_contents(char * path) {
  979. DIR * dirp = opendir(path);
  980. if (!dirp) return; /* Failed to load directly */
  981. struct dirent * ent = readdir(dirp);
  982. while (ent != NULL) {
  983. if (ent->d_name[0] != '.') {
  984. char * s = malloc(sizeof(char) * (strlen(ent->d_name) + 1));
  985. memcpy(s, ent->d_name, strlen(ent->d_name) + 1);
  986. shell_install_command(s, NULL, NULL);
  987. }
  988. ent = readdir(dirp);
  989. }
  990. closedir(dirp);
  991. }
  992. struct command {
  993. char * string;
  994. void * func;
  995. char * desc;
  996. };
  997. static int comp_shell_commands(const void *p1, const void *p2) {
  998. return strcmp(((struct command *)p1)->string, ((struct command *)p2)->string);
  999. }
  1000. void sort_commands() {
  1001. struct command commands[SHELL_COMMANDS];
  1002. for (int i = 0; i < shell_commands_len; ++i) {
  1003. commands[i].string = shell_commands[i];
  1004. commands[i].func = shell_pointers[i];
  1005. commands[i].desc = shell_descript[i];
  1006. }
  1007. qsort(&commands, shell_commands_len, sizeof(struct command), comp_shell_commands);
  1008. for (int i = 0; i < shell_commands_len; ++i) {
  1009. shell_commands[i] = commands[i].string;
  1010. shell_pointers[i] = commands[i].func;
  1011. shell_descript[i] = commands[i].desc;
  1012. }
  1013. }
  1014. void show_version(void) {
  1015. printf("esh 1.3.0\n");
  1016. }
  1017. void show_usage(int argc, char * argv[]) {
  1018. printf(
  1019. "Esh: The Experimental Shell\n"
  1020. "\n"
  1021. "usage: %s [-lha] [path]\n"
  1022. "\n"
  1023. " -c \033[4mcmd\033[0m \033[3mparse and execute cmd\033[0m\n"
  1024. //-c cmd \033[...
  1025. " -R \033[3mdisable experimental line editor\033[0m\n"
  1026. " -v \033[3mshow version information\033[0m\n"
  1027. " -? \033[3mshow this help text\033[0m\n"
  1028. "\n", argv[0]);
  1029. }
  1030. void add_path(void) {
  1031. char * envvar = getenv("PATH");
  1032. if (!envvar) {
  1033. add_path_contents("/bin");
  1034. return;
  1035. }
  1036. char * tmp = strdup(envvar);
  1037. do {
  1038. char * end = strstr(tmp,":");
  1039. if (end) {
  1040. *end = '\0';
  1041. end++;
  1042. }
  1043. add_path_contents(tmp);
  1044. tmp = end;
  1045. } while (tmp);
  1046. free(tmp);
  1047. }
  1048. int run_script(FILE * f) {
  1049. while (!feof(f)) {
  1050. char buf[LINE_LEN] = {0};
  1051. fgets(buf, LINE_LEN, f);
  1052. int ret;
  1053. char * out = NULL;
  1054. char * b = buf;
  1055. do {
  1056. ret = shell_exec(b, LINE_LEN, f, &out);
  1057. b = out;
  1058. } while (b);
  1059. if (ret >= 0) last_ret = ret;
  1060. }
  1061. fclose(f);
  1062. return last_ret;
  1063. }
  1064. void source_eshrc(void) {
  1065. char * home = getenv("HOME");
  1066. if (!home) return;
  1067. char tmp[512];
  1068. sprintf(tmp, "%s/.eshrc", home);
  1069. FILE * f = fopen(tmp, "r");
  1070. if (!f) return;
  1071. run_script(f);
  1072. }
  1073. int main(int argc, char ** argv) {
  1074. pid = getpid();
  1075. signal(SIGINT, sig_pass);
  1076. signal(SIGWINCH, sig_pass);
  1077. getuser();
  1078. gethost();
  1079. install_commands();
  1080. /* Parse $PATH to add contents */
  1081. add_path();
  1082. sort_commands();
  1083. if (argc > 1) {
  1084. int c;
  1085. while ((c = getopt(argc, argv, "Rc:v?")) != -1) {
  1086. switch (c) {
  1087. case 'R':
  1088. experimental_rline = 0;
  1089. break;
  1090. case 'c':
  1091. shell_interactive = 0;
  1092. {
  1093. char * out = NULL;
  1094. do {
  1095. last_ret = shell_exec(optarg, strlen(optarg), NULL, &out);
  1096. optarg = out;
  1097. } while (optarg);
  1098. }
  1099. return (last_ret == -1) ? 0 : last_ret;
  1100. case 'v':
  1101. show_version();
  1102. return 0;
  1103. case '?':
  1104. show_usage(argc, argv);
  1105. return 0;
  1106. }
  1107. }
  1108. }
  1109. if (optind < argc) {
  1110. shell_interactive = 2;
  1111. FILE * f = fopen(argv[optind],"r");
  1112. if (!f) {
  1113. fprintf(stderr, "%s: %s: %s\n", argv[0], argv[optind], strerror(errno));
  1114. return 1;
  1115. }
  1116. shell_argc = argc - 1;
  1117. shell_argv = &argv[1];
  1118. return run_script(f);
  1119. }
  1120. shell_interactive = 1;
  1121. source_eshrc();
  1122. while (1) {
  1123. draw_prompt();
  1124. char buffer[LINE_LEN] = {0};
  1125. read_entry(buffer);
  1126. char * history = malloc(strlen(buffer) + 1);
  1127. memcpy(history, buffer, strlen(buffer) + 1);
  1128. if (buffer[0] != ' ' && buffer[0] != '\n' && buffer[0] != '!') {
  1129. rline_history_insert(history);
  1130. } else {
  1131. free(history);
  1132. }
  1133. int ret;
  1134. char * out = NULL;
  1135. char * b = buffer;
  1136. do {
  1137. ret = shell_exec(b, LINE_LEN, stdin, &out);
  1138. b = out;
  1139. } while (b);
  1140. if (ret >= 0) last_ret = ret;
  1141. rline_scroll = 0;
  1142. }
  1143. return 0;
  1144. }
  1145. /*
  1146. * cd [path]
  1147. */
  1148. uint32_t shell_cmd_cd(int argc, char * argv[]) {
  1149. if (argc > 1) {
  1150. if (chdir(argv[1])) {
  1151. goto cd_error;
  1152. } /* else success */
  1153. } else /* argc < 2 */ {
  1154. char * home = getenv("HOME");
  1155. if (home) {
  1156. if (chdir(home)) {
  1157. goto cd_error;
  1158. }
  1159. } else {
  1160. char home_path[512];
  1161. sprintf(home_path, "/home/%s", username);
  1162. if (chdir(home_path)) {
  1163. goto cd_error;
  1164. }
  1165. }
  1166. }
  1167. return 0;
  1168. cd_error:
  1169. fprintf(stderr, "%s: could not cd '%s': no such file or directory\n", argv[0], argv[1]);
  1170. return 1;
  1171. }
  1172. /*
  1173. * history
  1174. */
  1175. uint32_t shell_cmd_history(int argc, char * argv[]) {
  1176. for (int i = 0; i < rline_history_count; ++i) {
  1177. printf("%d\t%s\n", i + 1, rline_history_get(i));
  1178. }
  1179. return 0;
  1180. }
  1181. uint32_t shell_cmd_export(int argc, char * argv[]) {
  1182. if (argc > 1) {
  1183. putenv(argv[1]);
  1184. }
  1185. return 0;
  1186. }
  1187. uint32_t shell_cmd_exit(int argc, char * argv[]) {
  1188. if (argc > 1) {
  1189. exit(atoi(argv[1]));
  1190. } else {
  1191. exit(0);
  1192. }
  1193. return -1;
  1194. }
  1195. uint32_t shell_cmd_help(int argc, char * argv[]) {
  1196. show_version();
  1197. printf("\nThis shell is not POSIX-compliant, please be careful.\n\n");
  1198. printf("Built-in commands:\n");
  1199. /* First, determine max width of command names */
  1200. unsigned int max_len = 0;
  1201. for (int i = 0; i < shell_commands_len; ++i) {
  1202. if (!shell_descript[i]) continue;
  1203. if (strlen(shell_commands[i]) > max_len) {
  1204. max_len = strlen(shell_commands[i]);
  1205. }
  1206. }
  1207. /* Then print the commands their help text */
  1208. for (int i = 0; i < shell_commands_len; ++i) {
  1209. if (!shell_descript[i]) continue;
  1210. printf(" %-*s - %s\n", max_len + 1, shell_commands[i], shell_descript[i]);
  1211. }
  1212. return 0;
  1213. }
  1214. uint32_t shell_cmd_if(int argc, char * argv[]) {
  1215. char ** if_args = &argv[1];
  1216. char ** then_args = NULL;
  1217. char ** else_args = NULL;
  1218. for (int i = 2; i < argc; ++i) {
  1219. if (!strcmp(argv[i],"then")) {
  1220. argv[i] = NULL;
  1221. then_args = &argv[i+1];
  1222. } else if (!strcmp(argv[i],"else")) {
  1223. argv[i] = NULL;
  1224. else_args = &argv[i+1];
  1225. }
  1226. }
  1227. if (!then_args) {
  1228. fprintf(stderr, "%s: syntax error: expected 'then' clause\n", argv[0]);
  1229. return 1;
  1230. }
  1231. if (else_args && else_args < then_args) {
  1232. fprintf(stderr, "%s: syntax error: 'else' clause before 'then' clase\n", argv[0]);
  1233. return 1;
  1234. }
  1235. pid_t child_pid = fork();
  1236. if (!child_pid) {
  1237. run_cmd(if_args);
  1238. }
  1239. tcsetpgrp(STDIN_FILENO, child_pid);
  1240. child = child_pid;
  1241. int pid, ret_code = 0;
  1242. do {
  1243. pid = waitpid(-1, &ret_code, 0);
  1244. } while (pid != -1 || (pid == -1 && errno != ECHILD));
  1245. child = 0;
  1246. if (ret_code == 0) {
  1247. shell_command_t func = shell_find(*then_args);
  1248. if (func) {
  1249. int argc = 0;
  1250. while (then_args[argc]) {
  1251. argc++;
  1252. }
  1253. return func(argc, then_args);
  1254. } else {
  1255. child_pid = fork();
  1256. if (!child_pid) {
  1257. run_cmd(then_args);
  1258. }
  1259. tcsetpgrp(STDIN_FILENO, child_pid);
  1260. child = child_pid;
  1261. do {
  1262. pid = waitpid(-1, &ret_code, 0);
  1263. } while (pid != -1 || (pid == -1 && errno != ECHILD));
  1264. child = 0;
  1265. tcsetpgrp(STDIN_FILENO, getpid());
  1266. return ret_code;
  1267. }
  1268. } else if (else_args) {
  1269. shell_command_t func = shell_find(*else_args);
  1270. if (func) {
  1271. int argc = 0;
  1272. while (else_args[argc]) {
  1273. argc++;
  1274. }
  1275. return func(argc, else_args);
  1276. } else {
  1277. child_pid = fork();
  1278. if (!child_pid) {
  1279. run_cmd(else_args);
  1280. }
  1281. tcsetpgrp(STDIN_FILENO, child_pid);
  1282. child = child_pid;
  1283. do {
  1284. pid = waitpid(-1, &ret_code, 0);
  1285. } while (pid != -1 || (pid == -1 && errno != ECHILD));
  1286. child = 0;
  1287. return ret_code;
  1288. }
  1289. }
  1290. tcsetpgrp(STDIN_FILENO, getpid());
  1291. return 0;
  1292. }
  1293. uint32_t shell_cmd_while(int argc, char * argv[]) {
  1294. char ** while_args = &argv[1];
  1295. char ** do_args = NULL;
  1296. for (int i = 2; i < argc; ++i) {
  1297. if (!strcmp(argv[i],"do")) {
  1298. argv[i] = NULL;
  1299. do_args = &argv[i+1];
  1300. }
  1301. }
  1302. if (!do_args) {
  1303. fprintf(stderr, "%s: syntax error: expected 'do' clause\n", argv[0]);
  1304. return 1;
  1305. }
  1306. break_while = 0;
  1307. tcsetpgrp(STDIN_FILENO, getpid());
  1308. do {
  1309. pid_t child_pid = fork();
  1310. if (!child_pid) {
  1311. run_cmd(while_args);
  1312. }
  1313. child = child_pid;
  1314. int pid, ret_code = 0;
  1315. do {
  1316. pid = waitpid(-1, &ret_code, 0);
  1317. } while (pid != -1 || (pid == -1 && errno != ECHILD));
  1318. child = 0;
  1319. if (ret_code == 0) {
  1320. child_pid = fork();
  1321. if (!child_pid) {
  1322. run_cmd(do_args);
  1323. }
  1324. child = child_pid;
  1325. do {
  1326. pid = waitpid(-1, &ret_code, 0);
  1327. } while (pid != -1 || (pid == -1 && errno != ECHILD));
  1328. child = 0;
  1329. } else {
  1330. return ret_code;
  1331. }
  1332. } while (!break_while);
  1333. return 127;
  1334. }
  1335. uint32_t shell_cmd_export_cmd(int argc, char * argv[]) {
  1336. if (argc < 3) {
  1337. fprintf(stderr, "%s: syntax error: not enough arguments\n", argv[0]);
  1338. return 1;
  1339. }
  1340. int pipe_fds[2];
  1341. pipe(pipe_fds);
  1342. pid_t child_pid = fork();
  1343. if (!child_pid) {
  1344. dup2(pipe_fds[1], STDOUT_FILENO);
  1345. close(pipe_fds[0]);
  1346. run_cmd(&argv[2]);
  1347. }
  1348. close(pipe_fds[1]);
  1349. tcsetpgrp(STDIN_FILENO, child_pid);
  1350. char buf[1024];
  1351. size_t accum = 0;
  1352. do {
  1353. int r = read(pipe_fds[0], buf+accum, 1023-accum);
  1354. if (r == 0) break;
  1355. if (r < 0) {
  1356. return -r;
  1357. }
  1358. accum += r;
  1359. } while (accum < 1023);
  1360. tcsetpgrp(STDIN_FILENO, getpid());
  1361. buf[accum] = '\0';
  1362. if (accum && buf[accum-1] == '\n') {
  1363. buf[accum-1] = '\0';
  1364. }
  1365. setenv(argv[1], buf, 1);
  1366. return 0;
  1367. }
  1368. uint32_t shell_cmd_empty(int argc, char * argv[]) {
  1369. for (int i = 1; i < argc; i++) {
  1370. if (argv[i] && *argv[i]) return 1;
  1371. }
  1372. return 0;
  1373. }
  1374. uint32_t shell_cmd_equals(int argc, char * argv[]) {
  1375. if (argc < 3) return 1;
  1376. return strcmp(argv[1], argv[2]);
  1377. }
  1378. uint32_t shell_cmd_return(int argc, char * argv[]) {
  1379. if (argc < 2) return 0;
  1380. return atoi(argv[1]);
  1381. }
  1382. uint32_t shell_cmd_source(int argc, char * argv[]) {
  1383. if (argc < 2) return 0;
  1384. FILE * f = fopen(argv[1], "r");
  1385. if (!f) {
  1386. fprintf(stderr, "%s: %s: %s", argv[0], argv[1], strerror(errno));
  1387. }
  1388. return run_script(f);
  1389. }
  1390. uint32_t shell_cmd_exec(int argc, char * argv[]) {
  1391. if (argc < 2) return 1;
  1392. return execvp(argv[1], &argv[1]);
  1393. }
  1394. uint32_t shell_cmd_not(int argc, char * argv[]) {
  1395. if (argc < 2) {
  1396. fprintf(stderr, "%s: expected command argument\n", argv[0]);
  1397. return 1;
  1398. }
  1399. int ret_code = 0;
  1400. pid_t child_pid = fork();
  1401. if (!child_pid) {
  1402. run_cmd(&argv[1]);
  1403. }
  1404. tcsetpgrp(STDIN_FILENO, child_pid);
  1405. child = child_pid;
  1406. do {
  1407. pid = waitpid(-1, &ret_code, 0);
  1408. } while (pid != -1 || (pid == -1 && errno != ECHILD));
  1409. child = 0;
  1410. tcsetpgrp(STDIN_FILENO, getpid());
  1411. return !ret_code;
  1412. }
  1413. void install_commands() {
  1414. shell_install_command("cd", shell_cmd_cd, "change directory");
  1415. shell_install_command("exit", shell_cmd_exit, "exit the shell");
  1416. shell_install_command("export", shell_cmd_export, "set environment variables: export VAR=value");
  1417. shell_install_command("help", shell_cmd_help, "display this help text");
  1418. shell_install_command("history", shell_cmd_history, "list command history");
  1419. shell_install_command("if", shell_cmd_if, "if ... then ... [else ...]");
  1420. shell_install_command("while", shell_cmd_while, "while ... do ...");
  1421. shell_install_command("empty?", shell_cmd_empty, "empty? args...");
  1422. shell_install_command("equals?", shell_cmd_equals, "equals? arg1 arg2");
  1423. shell_install_command("return", shell_cmd_return, "return status code");
  1424. shell_install_command("export-cmd", shell_cmd_export_cmd, "set variable to result of command: export-cmd VAR command...");
  1425. shell_install_command("source", shell_cmd_source, "run a shell script in the context of this shell");
  1426. shell_install_command("exec", shell_cmd_exec, "replace shell (or subshell) with command");
  1427. shell_install_command("not", shell_cmd_not, "invert status of command");
  1428. }