sh.c 46 KB

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