sh.c 39 KB

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