sh.c 38 KB

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