sh.c 52 KB

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