sh.c 42 KB

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