sh.c 40 KB

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