lash.c 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * lash -- the BusyBox Lame-Ass SHell
  4. *
  5. * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
  6. *
  7. * Based in part on ladsh.c by Michael K. Johnson and Erik W. Troan, which is
  8. * under the following liberal license: "We have placed this source code in the
  9. * public domain. Use it in any project, free or commercial."
  10. *
  11. * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
  12. */
  13. /* This shell's parsing engine is officially at a dead-end. Future
  14. * work shell work should be done using hush, msh, or ash. This is
  15. * still a very useful, small shell -- it just don't need any more
  16. * features beyond what it already has...
  17. */
  18. //For debugging/development on the shell only...
  19. //#define DEBUG_SHELL
  20. #include <getopt.h>
  21. #include <glob.h>
  22. #include "busybox.h" /* for struct bb_applet */
  23. #define expand_t glob_t
  24. /* Always enable for the moment... */
  25. #define CONFIG_LASH_PIPE_N_REDIRECTS
  26. #define CONFIG_LASH_JOB_CONTROL
  27. #define ENABLE_LASH_PIPE_N_REDIRECTS 1
  28. #define ENABLE_LASH_JOB_CONTROL 1
  29. enum { MAX_READ = 128 }; /* size of input buffer for 'read' builtin */
  30. #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
  31. #if ENABLE_LASH_PIPE_N_REDIRECTS
  32. enum redir_type { REDIRECT_INPUT, REDIRECT_OVERWRITE,
  33. REDIRECT_APPEND
  34. };
  35. #endif
  36. enum {
  37. DEFAULT_CONTEXT = 0x1,
  38. IF_TRUE_CONTEXT = 0x2,
  39. IF_FALSE_CONTEXT = 0x4,
  40. THEN_EXP_CONTEXT = 0x8,
  41. ELSE_EXP_CONTEXT = 0x10
  42. };
  43. #define LASH_OPT_DONE (1)
  44. #define LASH_OPT_SAW_QUOTE (2)
  45. #if ENABLE_LASH_PIPE_N_REDIRECTS
  46. struct redir_struct {
  47. enum redir_type type; /* type of redirection */
  48. int fd; /* file descriptor being redirected */
  49. char *filename; /* file to redirect fd to */
  50. };
  51. #endif
  52. struct child_prog {
  53. pid_t pid; /* 0 if exited */
  54. char **argv; /* program name and arguments */
  55. int num_redirects; /* elements in redirection array */
  56. int is_stopped; /* is the program currently running? */
  57. struct job *family; /* pointer back to the child's parent job */
  58. #if ENABLE_LASH_PIPE_N_REDIRECTS
  59. struct redir_struct *redirects; /* I/O redirects */
  60. #endif
  61. };
  62. struct jobset {
  63. struct job *head; /* head of list of running jobs */
  64. struct job *fg; /* current foreground job */
  65. };
  66. struct job {
  67. int jobid; /* job number */
  68. int num_progs; /* total number of programs in job */
  69. int running_progs; /* number of programs running */
  70. char *text; /* name of job */
  71. char *cmdbuf; /* buffer various argv's point into */
  72. pid_t pgrp; /* process group ID for the job */
  73. struct child_prog *progs; /* array of programs in job */
  74. struct job *next; /* to track background commands */
  75. int stopped_progs; /* number of programs alive, but stopped */
  76. unsigned int job_context; /* bitmask defining current context */
  77. struct jobset *job_list;
  78. };
  79. struct built_in_command {
  80. const char *cmd; /* name */
  81. const char *descr; /* description */
  82. int (*function) (struct child_prog *); /* function ptr */
  83. };
  84. /* function prototypes for builtins */
  85. static int builtin_cd(struct child_prog *cmd);
  86. static int builtin_exec(struct child_prog *cmd);
  87. static int builtin_exit(struct child_prog *cmd);
  88. static int builtin_fg_bg(struct child_prog *cmd);
  89. static int builtin_help(struct child_prog *cmd);
  90. static int builtin_jobs(struct child_prog *dummy);
  91. static int builtin_pwd(struct child_prog *dummy);
  92. static int builtin_export(struct child_prog *cmd);
  93. static int builtin_source(struct child_prog *cmd);
  94. static int builtin_unset(struct child_prog *cmd);
  95. static int builtin_read(struct child_prog *cmd);
  96. /* function prototypes for shell stuff */
  97. static void checkjobs(struct jobset *job_list);
  98. static void remove_job(struct jobset *j_list, struct job *job);
  99. static int get_command_bufsiz(FILE * source, char *command);
  100. static int parse_command(char **command_ptr, struct job *job, int *inbg);
  101. static int run_command(struct job *newjob, int inbg, int outpipe[2]);
  102. static int pseudo_exec(struct child_prog *cmd) ATTRIBUTE_NORETURN;
  103. static int busy_loop(FILE * input);
  104. /* Table of built-in functions (these are non-forking builtins, meaning they
  105. * can change global variables in the parent shell process but they will not
  106. * work with pipes and redirects; 'unset foo | whatever' will not work) */
  107. static const struct built_in_command bltins[] = {
  108. {"bg" , "Resume a job in the background", builtin_fg_bg},
  109. {"cd" , "Change working directory", builtin_cd},
  110. {"exec" , "Exec command, replacing this shell with the exec'd process", builtin_exec},
  111. {"exit" , "Exit from shell()", builtin_exit},
  112. {"fg" , "Bring job into the foreground", builtin_fg_bg},
  113. {"jobs" , "Lists the active jobs", builtin_jobs},
  114. {"export", "Set environment variable", builtin_export},
  115. {"unset" , "Unset environment variable", builtin_unset},
  116. {"read" , "Input environment variable", builtin_read},
  117. {"." , "Source-in and run commands in a file", builtin_source},
  118. /* These were "forked applets", but distinction was nuked */
  119. /* Original comment retained: */
  120. /* Table of forking built-in functions (things that fork cannot change global
  121. * variables in the parent process, such as the current working directory) */
  122. {"pwd" , "Print current directory", builtin_pwd},
  123. {"help" , "List shell built-in commands", builtin_help},
  124. /* to do: add ulimit */
  125. };
  126. #define VEC_LAST(v) v[ARRAY_SIZE(v)-1]
  127. static int shell_context; /* Type prompt trigger (PS1 or PS2) */
  128. /* Globals that are static to this file */
  129. static char *cwd;
  130. static char *local_pending_command;
  131. static struct jobset job_list = { NULL, NULL };
  132. static int global_argc;
  133. static char **global_argv;
  134. static llist_t *close_me_list;
  135. static int last_return_code;
  136. static int last_bg_pid;
  137. static unsigned int last_jobid;
  138. static int shell_terminal;
  139. static const char *PS1;
  140. static const char *PS2 = "> ";
  141. #ifdef DEBUG_SHELL
  142. static inline void debug_printf(const char *format, ...)
  143. {
  144. va_list args;
  145. va_start(args, format);
  146. vfprintf(stderr, format, args);
  147. va_end(args);
  148. }
  149. #else
  150. static inline void debug_printf(const char ATTRIBUTE_UNUSED *format, ...) { }
  151. #endif
  152. /*
  153. Most builtins need access to the struct child_prog that has
  154. their arguments, previously coded as cmd->progs[0]. That coding
  155. can exhibit a bug, if the builtin is not the first command in
  156. a pipeline: "echo foo | exec sort" will attempt to exec foo.
  157. builtin previous use notes
  158. ------ ----------------- ---------
  159. cd cmd->progs[0]
  160. exec cmd->progs[0] squashed bug: didn't look for applets or forking builtins
  161. exit cmd->progs[0]
  162. fg_bg cmd->progs[0], job_list->head, job_list->fg
  163. help 0
  164. jobs job_list->head
  165. pwd 0
  166. export cmd->progs[0]
  167. source cmd->progs[0]
  168. unset cmd->progs[0]
  169. read cmd->progs[0]
  170. I added "struct job *family;" to struct child_prog,
  171. and switched API to builtin_foo(struct child_prog *child);
  172. So cmd->text becomes child->family->text
  173. cmd->job_context becomes child->family->job_context
  174. cmd->progs[0] becomes *child
  175. job_list becomes child->family->job_list
  176. */
  177. static void update_cwd(void)
  178. {
  179. cwd = xrealloc_getcwd_or_warn(cwd);
  180. if (!cwd)
  181. cwd = xstrdup(bb_msg_unknown);
  182. }
  183. /* built-in 'cd <path>' handler */
  184. static int builtin_cd(struct child_prog *child)
  185. {
  186. char *newdir;
  187. if (child->argv[1] == NULL)
  188. newdir = getenv("HOME");
  189. else
  190. newdir = child->argv[1];
  191. if (chdir(newdir)) {
  192. bb_perror_msg("cd: %s", newdir);
  193. return EXIT_FAILURE;
  194. }
  195. update_cwd();
  196. return EXIT_SUCCESS;
  197. }
  198. /* built-in 'exec' handler */
  199. static int builtin_exec(struct child_prog *child)
  200. {
  201. if (child->argv[1] == NULL)
  202. return EXIT_SUCCESS; /* Really? */
  203. child->argv++;
  204. while (close_me_list)
  205. close((long)llist_pop(&close_me_list));
  206. pseudo_exec(child);
  207. /* never returns */
  208. }
  209. /* built-in 'exit' handler */
  210. static int builtin_exit(struct child_prog *child)
  211. {
  212. if (child->argv[1] == NULL)
  213. exit(EXIT_SUCCESS);
  214. exit(atoi(child->argv[1]));
  215. }
  216. /* built-in 'fg' and 'bg' handler */
  217. static int builtin_fg_bg(struct child_prog *child)
  218. {
  219. int i, jobnum;
  220. struct job *job;
  221. /* If they gave us no args, assume they want the last backgrounded task */
  222. if (!child->argv[1]) {
  223. for (job = child->family->job_list->head; job; job = job->next) {
  224. if (job->jobid == last_jobid) {
  225. goto found;
  226. }
  227. }
  228. bb_error_msg("%s: no current job", child->argv[0]);
  229. return EXIT_FAILURE;
  230. }
  231. if (sscanf(child->argv[1], "%%%d", &jobnum) != 1) {
  232. bb_error_msg(bb_msg_invalid_arg, child->argv[1], child->argv[0]);
  233. return EXIT_FAILURE;
  234. }
  235. for (job = child->family->job_list->head; job; job = job->next) {
  236. if (job->jobid == jobnum) {
  237. goto found;
  238. }
  239. }
  240. bb_error_msg("%s: %d: no such job", child->argv[0], jobnum);
  241. return EXIT_FAILURE;
  242. found:
  243. if (*child->argv[0] == 'f') {
  244. /* Put the job into the foreground. */
  245. tcsetpgrp(shell_terminal, job->pgrp);
  246. child->family->job_list->fg = job;
  247. }
  248. /* Restart the processes in the job */
  249. for (i = 0; i < job->num_progs; i++)
  250. job->progs[i].is_stopped = 0;
  251. job->stopped_progs = 0;
  252. i = kill(- job->pgrp, SIGCONT);
  253. if (i < 0) {
  254. if (errno == ESRCH) {
  255. remove_job(&job_list, job);
  256. } else {
  257. bb_perror_msg("kill (SIGCONT)");
  258. }
  259. }
  260. return EXIT_SUCCESS;
  261. }
  262. /* built-in 'help' handler */
  263. static int builtin_help(struct child_prog ATTRIBUTE_UNUSED *dummy)
  264. {
  265. const struct built_in_command *x;
  266. printf("\nBuilt-in commands:\n"
  267. "-------------------\n");
  268. for (x = bltins; x <= &VEC_LAST(bltins); x++) {
  269. if (x->descr == NULL)
  270. continue;
  271. printf("%s\t%s\n", x->cmd, x->descr);
  272. }
  273. bb_putchar('\n');
  274. return EXIT_SUCCESS;
  275. }
  276. /* built-in 'jobs' handler */
  277. static int builtin_jobs(struct child_prog *child)
  278. {
  279. struct job *job;
  280. const char *status_string;
  281. for (job = child->family->job_list->head; job; job = job->next) {
  282. if (job->running_progs == job->stopped_progs)
  283. status_string = "Stopped";
  284. else
  285. status_string = "Running";
  286. printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->text);
  287. }
  288. return EXIT_SUCCESS;
  289. }
  290. /* built-in 'pwd' handler */
  291. static int builtin_pwd(struct child_prog ATTRIBUTE_UNUSED *dummy)
  292. {
  293. update_cwd();
  294. puts(cwd);
  295. return EXIT_SUCCESS;
  296. }
  297. /* built-in 'export VAR=value' handler */
  298. static int builtin_export(struct child_prog *child)
  299. {
  300. int res;
  301. char *v = child->argv[1];
  302. if (v == NULL) {
  303. char **e;
  304. for (e = environ; *e; e++) {
  305. puts(*e);
  306. }
  307. return 0;
  308. }
  309. res = putenv(v);
  310. if (res)
  311. bb_perror_msg("export");
  312. #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
  313. if (strncmp(v, "PS1=", 4) == 0)
  314. PS1 = getenv("PS1");
  315. #endif
  316. #if ENABLE_LOCALE_SUPPORT
  317. // TODO: why getenv? "" would be just as good...
  318. if (strncmp(v, "LC_ALL=", 7) == 0)
  319. setlocale(LC_ALL, getenv("LC_ALL"));
  320. if (strncmp(v, "LC_CTYPE=", 9) == 0)
  321. setlocale(LC_CTYPE, getenv("LC_CTYPE"));
  322. #endif
  323. return res;
  324. }
  325. /* built-in 'read VAR' handler */
  326. static int builtin_read(struct child_prog *child)
  327. {
  328. int res = 0, len;
  329. char *s;
  330. char string[MAX_READ];
  331. if (child->argv[1]) {
  332. /* argument (VAR) given: put "VAR=" into buffer */
  333. safe_strncpy(string, child->argv[1], MAX_READ-1);
  334. len = strlen(string);
  335. string[len++] = '=';
  336. string[len] = '\0';
  337. fgets(&string[len], sizeof(string) - len, stdin); /* read string */
  338. res = strlen(string);
  339. if (res > len)
  340. string[--res] = '\0'; /* chomp trailing newline */
  341. /*
  342. ** string should now contain "VAR=<value>"
  343. ** copy it (putenv() won't do that, so we must make sure
  344. ** the string resides in a static buffer!)
  345. */
  346. res = -1;
  347. s = strdup(string);
  348. if (s)
  349. res = putenv(s);
  350. if (res)
  351. bb_perror_msg("read");
  352. } else
  353. fgets(string, sizeof(string), stdin);
  354. return res;
  355. }
  356. /* Built-in '.' handler (read-in and execute commands from file) */
  357. static int builtin_source(struct child_prog *child)
  358. {
  359. FILE *input;
  360. int status;
  361. input = fopen_or_warn(child->argv[1], "r");
  362. if (!input) {
  363. return EXIT_FAILURE;
  364. }
  365. llist_add_to(&close_me_list, (void *)(long)fileno(input));
  366. /* Now run the file */
  367. status = busy_loop(input);
  368. fclose(input);
  369. llist_pop(&close_me_list);
  370. return status;
  371. }
  372. /* built-in 'unset VAR' handler */
  373. static int builtin_unset(struct child_prog *child)
  374. {
  375. if (child->argv[1] == NULL) {
  376. printf(bb_msg_requires_arg, "unset");
  377. return EXIT_FAILURE;
  378. }
  379. unsetenv(child->argv[1]);
  380. return EXIT_SUCCESS;
  381. }
  382. #if ENABLE_LASH_JOB_CONTROL
  383. /* free up all memory from a job */
  384. static void free_job(struct job *cmd)
  385. {
  386. int i;
  387. struct jobset *keep;
  388. for (i = 0; i < cmd->num_progs; i++) {
  389. free(cmd->progs[i].argv);
  390. #if ENABLE_LASH_PIPE_N_REDIRECTS
  391. free(cmd->progs[i].redirects);
  392. #endif
  393. }
  394. free(cmd->progs);
  395. free(cmd->text);
  396. free(cmd->cmdbuf);
  397. keep = cmd->job_list;
  398. memset(cmd, 0, sizeof(struct job));
  399. cmd->job_list = keep;
  400. }
  401. /* remove a job from a jobset */
  402. static void remove_job(struct jobset *j_list, struct job *job)
  403. {
  404. struct job *prevjob;
  405. free_job(job);
  406. if (job == j_list->head) {
  407. j_list->head = job->next;
  408. } else {
  409. prevjob = j_list->head;
  410. while (prevjob->next != job)
  411. prevjob = prevjob->next;
  412. prevjob->next = job->next;
  413. }
  414. if (j_list->head)
  415. last_jobid = j_list->head->jobid;
  416. else
  417. last_jobid = 0;
  418. free(job);
  419. }
  420. /* Checks to see if any background processes have exited -- if they
  421. have, figure out why and see if a job has completed */
  422. static void checkjobs(struct jobset *j_list)
  423. {
  424. struct job *job;
  425. pid_t childpid;
  426. int status;
  427. int prognum = 0;
  428. while ((childpid = waitpid(-1, &status, WNOHANG | WUNTRACED)) > 0) {
  429. for (job = j_list->head; job; job = job->next) {
  430. prognum = 0;
  431. while (prognum < job->num_progs &&
  432. job->progs[prognum].pid != childpid) prognum++;
  433. if (prognum < job->num_progs)
  434. break;
  435. }
  436. /* This happens on backticked commands */
  437. if (job == NULL)
  438. return;
  439. if (WIFEXITED(status) || WIFSIGNALED(status)) {
  440. /* child exited */
  441. job->running_progs--;
  442. job->progs[prognum].pid = 0;
  443. if (!job->running_progs) {
  444. printf(JOB_STATUS_FORMAT, job->jobid, "Done", job->text);
  445. last_jobid = 0;
  446. remove_job(j_list, job);
  447. }
  448. } else {
  449. /* child stopped */
  450. job->stopped_progs++;
  451. job->progs[prognum].is_stopped = 1;
  452. }
  453. }
  454. if (childpid == -1 && errno != ECHILD)
  455. bb_perror_msg("waitpid");
  456. }
  457. #else
  458. static void checkjobs(struct jobset *j_list)
  459. {
  460. }
  461. static void free_job(struct job *cmd)
  462. {
  463. }
  464. static void remove_job(struct jobset *j_list, struct job *job)
  465. {
  466. }
  467. #endif
  468. #if ENABLE_LASH_PIPE_N_REDIRECTS
  469. /* squirrel != NULL means we squirrel away copies of stdin, stdout,
  470. * and stderr if they are redirected. */
  471. static int setup_redirects(struct child_prog *prog, int squirrel[])
  472. {
  473. int i;
  474. int openfd;
  475. int mode = O_RDONLY;
  476. struct redir_struct *redir = prog->redirects;
  477. for (i = 0; i < prog->num_redirects; i++, redir++) {
  478. switch (redir->type) {
  479. case REDIRECT_INPUT:
  480. mode = O_RDONLY;
  481. break;
  482. case REDIRECT_OVERWRITE:
  483. mode = O_WRONLY | O_CREAT | O_TRUNC;
  484. break;
  485. case REDIRECT_APPEND:
  486. mode = O_WRONLY | O_CREAT | O_APPEND;
  487. break;
  488. }
  489. openfd = open3_or_warn(redir->filename, mode, 0666);
  490. if (openfd < 0) {
  491. /* this could get lost if stderr has been redirected, but
  492. bash and ash both lose it as well (though zsh doesn't!) */
  493. return 1;
  494. }
  495. if (openfd != redir->fd) {
  496. if (squirrel && redir->fd < 3) {
  497. squirrel[redir->fd] = dup(redir->fd);
  498. close_on_exec_on(squirrel[redir->fd]);
  499. }
  500. dup2(openfd, redir->fd);
  501. close(openfd);
  502. }
  503. }
  504. return 0;
  505. }
  506. static void restore_redirects(int squirrel[])
  507. {
  508. int i, fd;
  509. for (i = 0; i < 3; i++) {
  510. fd = squirrel[i];
  511. if (fd != -1) {
  512. /* No error checking. I sure wouldn't know what
  513. * to do with an error if I found one! */
  514. dup2(fd, i);
  515. close(fd);
  516. }
  517. }
  518. }
  519. #else
  520. static inline int setup_redirects(struct child_prog *prog, int squirrel[])
  521. {
  522. return 0;
  523. }
  524. static inline void restore_redirects(int squirrel[])
  525. {
  526. }
  527. #endif
  528. static inline void cmdedit_set_initial_prompt(void)
  529. {
  530. #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
  531. PS1 = NULL;
  532. #else
  533. PS1 = getenv("PS1");
  534. if (PS1 == 0)
  535. PS1 = "\\w \\$ ";
  536. #endif
  537. }
  538. static inline const char* setup_prompt_string(void)
  539. {
  540. #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
  541. /* Set up the prompt */
  542. if (shell_context == 0) {
  543. char *ns;
  544. free((char*)PS1);
  545. ns = xmalloc(strlen(cwd)+4);
  546. sprintf(ns, "%s %c ", cwd, (geteuid() != 0) ? '$': '#');
  547. PS1 = ns;
  548. return ns;
  549. } else {
  550. return PS2;
  551. }
  552. #else
  553. return (shell_context == 0)? PS1 : PS2;
  554. #endif
  555. }
  556. #if ENABLE_FEATURE_EDITING
  557. static line_input_t *line_input_state;
  558. #endif
  559. static int get_command_bufsiz(FILE * source, char *command)
  560. {
  561. const char *prompt_str;
  562. if (source == NULL) {
  563. if (local_pending_command) {
  564. /* a command specified (-c option): return it & mark it done */
  565. strncpy(command, local_pending_command, BUFSIZ);
  566. local_pending_command = NULL;
  567. return 0;
  568. }
  569. return 1;
  570. }
  571. if (source == stdin) {
  572. prompt_str = setup_prompt_string();
  573. #if ENABLE_FEATURE_EDITING
  574. /*
  575. ** enable command line editing only while a command line
  576. ** is actually being read; otherwise, we'll end up bequeathing
  577. ** atexit() handlers and other unwanted stuff to our
  578. ** child processes (rob@sysgo.de)
  579. */
  580. read_line_input(prompt_str, command, BUFSIZ, line_input_state);
  581. return 0;
  582. #else
  583. fputs(prompt_str, stdout);
  584. #endif
  585. }
  586. if (!fgets(command, BUFSIZ - 2, source)) {
  587. if (source == stdin)
  588. bb_putchar('\n');
  589. return 1;
  590. }
  591. return 0;
  592. }
  593. static char * strsep_space(char *string, int * ix)
  594. {
  595. /* Short circuit the trivial case */
  596. if (!string || ! string[*ix])
  597. return NULL;
  598. /* Find the end of the token. */
  599. while (string[*ix] && !isspace(string[*ix]) ) {
  600. (*ix)++;
  601. }
  602. /* Find the end of any whitespace trailing behind
  603. * the token and let that be part of the token */
  604. while (string[*ix] && (isspace)(string[*ix]) ) {
  605. (*ix)++;
  606. }
  607. if (!*ix) {
  608. /* Nothing useful was found */
  609. return NULL;
  610. }
  611. return xstrndup(string, *ix);
  612. }
  613. static int expand_arguments(char *command)
  614. {
  615. static const char out_of_space[] ALIGN1 = "out of space during expansion";
  616. int total_length = 0, length, i, retval, ix = 0;
  617. expand_t expand_result;
  618. char *tmpcmd, *cmd, *cmd_copy;
  619. char *src, *dst, *var;
  620. int flags = GLOB_NOCHECK
  621. #ifdef GLOB_BRACE
  622. | GLOB_BRACE
  623. #endif
  624. #ifdef GLOB_TILDE
  625. | GLOB_TILDE
  626. #endif
  627. ;
  628. /* get rid of the terminating \n */
  629. chomp(command);
  630. /* Fix up escape sequences to be the Real Thing(tm) */
  631. while (command && command[ix]) {
  632. if (command[ix] == '\\') {
  633. const char *tmp = command+ix+1;
  634. command[ix] = bb_process_escape_sequence( &tmp );
  635. memmove(command+ix + 1, tmp, strlen(tmp)+1);
  636. }
  637. ix++;
  638. }
  639. /* Use glob and then fixup environment variables and such */
  640. /* It turns out that glob is very stupid. We have to feed it one word at a
  641. * time since it can't cope with a full string. Here we convert command
  642. * (char*) into cmd (char**, one word per string) */
  643. /* We need a clean copy, so strsep can mess up the copy while
  644. * we write stuff into the original (in a minute) */
  645. cmd = cmd_copy = xstrdup(command);
  646. *command = '\0';
  647. for (ix = 0, tmpcmd = cmd;
  648. (tmpcmd = strsep_space(cmd, &ix)) != NULL; cmd += ix, ix = 0) {
  649. if (*tmpcmd == '\0')
  650. break;
  651. /* we need to trim() the result for glob! */
  652. trim(tmpcmd);
  653. retval = glob(tmpcmd, flags, NULL, &expand_result);
  654. free(tmpcmd); /* Free mem allocated by strsep_space */
  655. if (retval == GLOB_NOSPACE) {
  656. /* Mem may have been allocated... */
  657. globfree(&expand_result);
  658. bb_error_msg(out_of_space);
  659. return FALSE;
  660. } else if (retval != 0) {
  661. /* Some other error. GLOB_NOMATCH shouldn't
  662. * happen because of the GLOB_NOCHECK flag in
  663. * the glob call. */
  664. bb_error_msg("syntax error");
  665. return FALSE;
  666. } else {
  667. /* Convert from char** (one word per string) to a simple char*,
  668. * but don't overflow command which is BUFSIZ in length */
  669. for (i = 0; i < expand_result.gl_pathc; i++) {
  670. length = strlen(expand_result.gl_pathv[i]);
  671. if (total_length+length+1 >= BUFSIZ) {
  672. bb_error_msg(out_of_space);
  673. return FALSE;
  674. }
  675. strcat(command+total_length, " ");
  676. total_length += 1;
  677. strcat(command+total_length, expand_result.gl_pathv[i]);
  678. total_length += length;
  679. }
  680. globfree(&expand_result);
  681. }
  682. }
  683. free(cmd_copy);
  684. trim(command);
  685. /* Now do the shell variable substitutions which
  686. * wordexp can't do for us, namely $? and $! */
  687. src = command;
  688. while ((dst = strchr(src,'$')) != NULL) {
  689. var = NULL;
  690. switch (*(dst+1)) {
  691. case '?':
  692. var = itoa(last_return_code);
  693. break;
  694. case '!':
  695. if (last_bg_pid == -1)
  696. *var = '\0';
  697. else
  698. var = itoa(last_bg_pid);
  699. break;
  700. /* Everything else like $$, $#, $[0-9], etc. should all be
  701. * expanded by wordexp(), so we can in theory skip that stuff
  702. * here, but just to be on the safe side (i.e., since uClibc
  703. * wordexp doesn't do this stuff yet), lets leave it in for
  704. * now. */
  705. case '$':
  706. var = itoa(getpid());
  707. break;
  708. case '#':
  709. var = itoa(global_argc - 1);
  710. break;
  711. case '0':case '1':case '2':case '3':case '4':
  712. case '5':case '6':case '7':case '8':case '9':
  713. {
  714. int ixx = *(dst+1)-48+1;
  715. if (ixx >= global_argc) {
  716. var = '\0';
  717. } else {
  718. var = global_argv[ixx];
  719. }
  720. }
  721. break;
  722. }
  723. if (var) {
  724. /* a single character construction was found, and
  725. * already handled in the case statement */
  726. src = dst + 2;
  727. } else {
  728. /* Looks like an environment variable */
  729. char delim_hold;
  730. int num_skip_chars = 0;
  731. int dstlen = strlen(dst);
  732. /* Is this a ${foo} type variable? */
  733. if (dstlen >= 2 && *(dst+1) == '{') {
  734. src = strchr(dst+1, '}');
  735. num_skip_chars = 1;
  736. } else {
  737. src = dst + 1;
  738. while ((isalnum)(*src) || *src == '_') src++;
  739. }
  740. if (src == NULL) {
  741. src = dst+dstlen;
  742. }
  743. delim_hold = *src;
  744. *src = '\0'; /* temporary */
  745. var = getenv(dst + 1 + num_skip_chars);
  746. *src = delim_hold;
  747. src += num_skip_chars;
  748. }
  749. if (var == NULL) {
  750. /* Seems we got an un-expandable variable. So delete it. */
  751. var = (char*)"";
  752. }
  753. {
  754. int subst_len = strlen(var);
  755. int trail_len = strlen(src);
  756. if (dst+subst_len+trail_len >= command+BUFSIZ) {
  757. bb_error_msg(out_of_space);
  758. return FALSE;
  759. }
  760. /* Move stuff to the end of the string to accommodate
  761. * filling the created gap with the new stuff */
  762. memmove(dst+subst_len, src, trail_len+1);
  763. /* Now copy in the new stuff */
  764. memcpy(dst, var, subst_len);
  765. src = dst+subst_len;
  766. }
  767. }
  768. return TRUE;
  769. }
  770. /* Return cmd->num_progs as 0 if no command is present (e.g. an empty
  771. line). If a valid command is found, command_ptr is set to point to
  772. the beginning of the next command (if the original command had more
  773. then one job associated with it) or NULL if no more commands are
  774. present. */
  775. static int parse_command(char **command_ptr, struct job *job, int *inbg)
  776. {
  777. char *command;
  778. char *return_command = NULL;
  779. char *src, *buf;
  780. int argc_l;
  781. int flag;
  782. int argv_alloced;
  783. char quote = '\0';
  784. struct child_prog *prog;
  785. #if ENABLE_LASH_PIPE_N_REDIRECTS
  786. int i;
  787. char *chptr;
  788. #endif
  789. /* skip leading white space */
  790. *command_ptr = skip_whitespace(*command_ptr);
  791. /* this handles empty lines or leading '#' characters */
  792. if (!**command_ptr || (**command_ptr == '#')) {
  793. job->num_progs = 0;
  794. return 0;
  795. }
  796. *inbg = 0;
  797. job->num_progs = 1;
  798. job->progs = xmalloc(sizeof(*job->progs));
  799. /* We set the argv elements to point inside of this string. The
  800. memory is freed by free_job(). Allocate twice the original
  801. length in case we need to quote every single character.
  802. Getting clean memory relieves us of the task of NULL
  803. terminating things and makes the rest of this look a bit
  804. cleaner (though it is, admittedly, a tad less efficient) */
  805. job->cmdbuf = command = xzalloc(2*strlen(*command_ptr) + 1);
  806. job->text = NULL;
  807. prog = job->progs;
  808. prog->num_redirects = 0;
  809. prog->is_stopped = 0;
  810. prog->family = job;
  811. #if ENABLE_LASH_PIPE_N_REDIRECTS
  812. prog->redirects = NULL;
  813. #endif
  814. argv_alloced = 5;
  815. prog->argv = xmalloc(sizeof(*prog->argv) * argv_alloced);
  816. prog->argv[0] = job->cmdbuf;
  817. flag = argc_l = 0;
  818. buf = command;
  819. src = *command_ptr;
  820. while (*src && !(flag & LASH_OPT_DONE)) {
  821. if (quote == *src) {
  822. quote = '\0';
  823. } else if (quote) {
  824. if (*src == '\\') {
  825. src++;
  826. if (!*src) {
  827. bb_error_msg("character expected after \\");
  828. free_job(job);
  829. return 1;
  830. }
  831. /* in shell, "\'" should yield \' */
  832. if (*src != quote) {
  833. *buf++ = '\\';
  834. *buf++ = '\\';
  835. }
  836. } else if (*src == '*' || *src == '?' || *src == '[' ||
  837. *src == ']') *buf++ = '\\';
  838. *buf++ = *src;
  839. } else if (isspace(*src)) {
  840. if (*prog->argv[argc_l] || (flag & LASH_OPT_SAW_QUOTE)) {
  841. buf++, argc_l++;
  842. /* +1 here leaves room for the NULL which ends argv */
  843. if ((argc_l + 1) == argv_alloced) {
  844. argv_alloced += 5;
  845. prog->argv = xrealloc(prog->argv,
  846. sizeof(*prog->argv) * argv_alloced);
  847. }
  848. prog->argv[argc_l] = buf;
  849. flag ^= LASH_OPT_SAW_QUOTE;
  850. }
  851. } else
  852. switch (*src) {
  853. case '"':
  854. case '\'':
  855. quote = *src;
  856. flag |= LASH_OPT_SAW_QUOTE;
  857. break;
  858. case '#': /* comment */
  859. if (*(src-1)== '$')
  860. *buf++ = *src;
  861. else
  862. flag |= LASH_OPT_DONE;
  863. break;
  864. #if ENABLE_LASH_PIPE_N_REDIRECTS
  865. case '>': /* redirects */
  866. case '<':
  867. i = prog->num_redirects++;
  868. prog->redirects = xrealloc(prog->redirects,
  869. sizeof(*prog->redirects) * (i + 1));
  870. prog->redirects[i].fd = -1;
  871. if (buf != prog->argv[argc_l]) {
  872. /* the stuff before this character may be the file number
  873. being redirected */
  874. prog->redirects[i].fd =
  875. strtol(prog->argv[argc_l], &chptr, 10);
  876. if (*chptr && *prog->argv[argc_l]) {
  877. buf++, argc_l++;
  878. prog->argv[argc_l] = buf;
  879. }
  880. }
  881. if (prog->redirects[i].fd == -1) {
  882. if (*src == '>')
  883. prog->redirects[i].fd = 1;
  884. else
  885. prog->redirects[i].fd = 0;
  886. }
  887. if (*src++ == '>') {
  888. if (*src == '>')
  889. prog->redirects[i].type =
  890. REDIRECT_APPEND, src++;
  891. else
  892. prog->redirects[i].type = REDIRECT_OVERWRITE;
  893. } else {
  894. prog->redirects[i].type = REDIRECT_INPUT;
  895. }
  896. /* This isn't POSIX sh compliant. Oh well. */
  897. chptr = src;
  898. chptr = skip_whitespace(chptr);
  899. if (!*chptr) {
  900. bb_error_msg("file name expected after %c", *(src-1));
  901. free_job(job);
  902. job->num_progs = 0;
  903. return 1;
  904. }
  905. prog->redirects[i].filename = buf;
  906. while (*chptr && !isspace(*chptr))
  907. *buf++ = *chptr++;
  908. src = chptr - 1; /* we src++ later */
  909. prog->argv[argc_l] = ++buf;
  910. break;
  911. case '|': /* pipe */
  912. /* finish this command */
  913. if (*prog->argv[argc_l] || flag & LASH_OPT_SAW_QUOTE)
  914. argc_l++;
  915. if (!argc_l) {
  916. goto empty_command_in_pipe;
  917. }
  918. prog->argv[argc_l] = NULL;
  919. /* and start the next */
  920. job->num_progs++;
  921. job->progs = xrealloc(job->progs,
  922. sizeof(*job->progs) * job->num_progs);
  923. prog = job->progs + (job->num_progs - 1);
  924. prog->num_redirects = 0;
  925. prog->redirects = NULL;
  926. prog->is_stopped = 0;
  927. prog->family = job;
  928. argc_l = 0;
  929. argv_alloced = 5;
  930. prog->argv = xmalloc(sizeof(*prog->argv) * argv_alloced);
  931. prog->argv[0] = ++buf;
  932. src++;
  933. src = skip_whitespace(src);
  934. if (!*src) {
  935. empty_command_in_pipe:
  936. bb_error_msg("empty command in pipe");
  937. free_job(job);
  938. job->num_progs = 0;
  939. return 1;
  940. }
  941. src--; /* we'll ++ it at the end of the loop */
  942. break;
  943. #endif
  944. #if ENABLE_LASH_JOB_CONTROL
  945. case '&': /* background */
  946. *inbg = 1;
  947. /* fallthrough */
  948. #endif
  949. case ';': /* multiple commands */
  950. flag |= LASH_OPT_DONE;
  951. return_command = *command_ptr + (src - *command_ptr) + 1;
  952. break;
  953. case '\\':
  954. src++;
  955. if (!*src) {
  956. bb_error_msg("character expected after \\");
  957. free_job(job);
  958. return 1;
  959. }
  960. if (*src == '*' || *src == '[' || *src == ']'
  961. || *src == '?') *buf++ = '\\';
  962. /* fallthrough */
  963. default:
  964. *buf++ = *src;
  965. }
  966. src++;
  967. }
  968. if (*prog->argv[argc_l] || flag & LASH_OPT_SAW_QUOTE) {
  969. argc_l++;
  970. }
  971. if (!argc_l) {
  972. free_job(job);
  973. return 0;
  974. }
  975. prog->argv[argc_l] = NULL;
  976. if (!return_command) {
  977. job->text = xstrdup(*command_ptr);
  978. } else {
  979. /* This leaves any trailing spaces, which is a bit sloppy */
  980. job->text = xstrndup(*command_ptr, return_command - *command_ptr);
  981. }
  982. *command_ptr = return_command;
  983. return 0;
  984. }
  985. /* Run the child_prog, no matter what kind of command it uses.
  986. */
  987. static int pseudo_exec(struct child_prog *child)
  988. {
  989. const struct built_in_command *x;
  990. /* Check if the command matches any of the non-forking builtins.
  991. * Depending on context, this might be redundant. But it's
  992. * easier to waste a few CPU cycles than it is to figure out
  993. * if this is one of those cases.
  994. */
  995. /* Check if the command matches any of the forking builtins. */
  996. for (x = bltins; x <= &VEC_LAST(bltins); x++) {
  997. if (strcmp(child->argv[0], x->cmd) == 0) {
  998. _exit(x->function(child));
  999. }
  1000. }
  1001. /* Check if the command matches any busybox internal
  1002. * commands ("applets") here. Following discussions from
  1003. * November 2000 on busybox@busybox.net, don't use
  1004. * bb_get_last_path_component_nostrip(). This way explicit
  1005. * (with slashes) filenames will never be interpreted as an
  1006. * applet, just like with builtins. This way the user can
  1007. * override an applet with an explicit filename reference.
  1008. * The only downside to this change is that an explicit
  1009. * /bin/foo invocation will fork and exec /bin/foo, even if
  1010. * /bin/foo is a symlink to busybox.
  1011. */
  1012. if (ENABLE_FEATURE_SH_STANDALONE) {
  1013. run_applet_and_exit(child->argv[0], child->argv);
  1014. }
  1015. execvp(child->argv[0], child->argv);
  1016. /* Do not use bb_perror_msg_and_die() here, since we must not
  1017. * call exit() but should call _exit() instead */
  1018. bb_simple_perror_msg(child->argv[0]);
  1019. _exit(EXIT_FAILURE);
  1020. }
  1021. static void insert_job(struct job *newjob, int inbg)
  1022. {
  1023. struct job *thejob;
  1024. struct jobset *j_list = newjob->job_list;
  1025. /* find the ID for thejob to use */
  1026. newjob->jobid = 1;
  1027. for (thejob = j_list->head; thejob; thejob = thejob->next)
  1028. if (thejob->jobid >= newjob->jobid)
  1029. newjob->jobid = thejob->jobid + 1;
  1030. /* add thejob to the list of running jobs */
  1031. if (!j_list->head) {
  1032. thejob = j_list->head = xmalloc(sizeof(*thejob));
  1033. } else {
  1034. for (thejob = j_list->head; thejob->next; thejob = thejob->next) /* nothing */;
  1035. thejob->next = xmalloc(sizeof(*thejob));
  1036. thejob = thejob->next;
  1037. }
  1038. *thejob = *newjob; /* physically copy the struct job */
  1039. thejob->next = NULL;
  1040. thejob->running_progs = thejob->num_progs;
  1041. thejob->stopped_progs = 0;
  1042. #if ENABLE_LASH_JOB_CONTROL
  1043. if (inbg) {
  1044. /* we don't wait for background thejobs to return -- append it
  1045. to the list of backgrounded thejobs and leave it alone */
  1046. printf("[%d] %d\n", thejob->jobid,
  1047. newjob->progs[newjob->num_progs - 1].pid);
  1048. last_jobid = newjob->jobid;
  1049. last_bg_pid = newjob->progs[newjob->num_progs - 1].pid;
  1050. } else {
  1051. newjob->job_list->fg = thejob;
  1052. /* move the new process group into the foreground */
  1053. /* Ignore errors since child could have already exited */
  1054. tcsetpgrp(shell_terminal, newjob->pgrp);
  1055. }
  1056. #endif
  1057. }
  1058. static int run_command(struct job *newjob, int inbg, int outpipe[2])
  1059. {
  1060. /* struct job *thejob; */
  1061. int i;
  1062. int nextin, nextout;
  1063. int pipefds[2]; /* pipefd[0] is for reading */
  1064. const struct built_in_command *x;
  1065. struct child_prog *child;
  1066. nextin = 0;
  1067. for (i = 0; i < newjob->num_progs; i++) {
  1068. child = &(newjob->progs[i]);
  1069. nextout = 1;
  1070. if ((i + 1) < newjob->num_progs) {
  1071. xpipe(pipefds);
  1072. nextout = pipefds[1];
  1073. } else if (outpipe[1] != -1) {
  1074. nextout = outpipe[1];
  1075. }
  1076. /* Check if the command matches any non-forking builtins,
  1077. * but only if this is a simple command.
  1078. * Non-forking builtins within pipes have to fork anyway,
  1079. * and are handled in pseudo_exec. "echo foo | read bar"
  1080. * is doomed to failure, and doesn't work on bash, either.
  1081. */
  1082. if (newjob->num_progs == 1) {
  1083. int rcode;
  1084. int squirrel[] = {-1, -1, -1};
  1085. /* Check if the command sets an environment variable. */
  1086. if (strchr(child->argv[0], '=') != NULL) {
  1087. child->argv[1] = child->argv[0];
  1088. return builtin_export(child);
  1089. }
  1090. for (x = bltins; x <= &VEC_LAST(bltins); x++) {
  1091. if (strcmp(child->argv[0], x->cmd) == 0) {
  1092. setup_redirects(child, squirrel);
  1093. rcode = x->function(child);
  1094. restore_redirects(squirrel);
  1095. return rcode;
  1096. }
  1097. }
  1098. #if ENABLE_FEATURE_SH_STANDALONE
  1099. {
  1100. const struct bb_applet *a = find_applet_by_name(child->argv[i]);
  1101. if (a && a->nofork) {
  1102. setup_redirects(child, squirrel);
  1103. rcode = run_nofork_applet(a, child->argv + i);
  1104. restore_redirects(squirrel);
  1105. return rcode;
  1106. }
  1107. }
  1108. #endif
  1109. }
  1110. #if BB_MMU
  1111. child->pid = fork();
  1112. #else
  1113. child->pid = vfork();
  1114. #endif
  1115. if (!child->pid) {
  1116. /* Set the handling for job control signals back to the default. */
  1117. signal(SIGINT, SIG_DFL);
  1118. signal(SIGQUIT, SIG_DFL);
  1119. signal(SIGTSTP, SIG_DFL);
  1120. signal(SIGTTIN, SIG_DFL);
  1121. signal(SIGTTOU, SIG_DFL);
  1122. signal(SIGCHLD, SIG_DFL);
  1123. /* Close all open filehandles. */
  1124. while (close_me_list)
  1125. close((long)llist_pop(&close_me_list));
  1126. if (outpipe[1] != -1) {
  1127. close(outpipe[0]);
  1128. }
  1129. if (nextin != 0) {
  1130. dup2(nextin, 0);
  1131. close(nextin);
  1132. }
  1133. if (nextout != 1) {
  1134. dup2(nextout, 1);
  1135. dup2(nextout, 2); /* Really? */
  1136. close(nextout);
  1137. close(pipefds[0]);
  1138. }
  1139. /* explicit redirects override pipes */
  1140. setup_redirects(child,NULL);
  1141. pseudo_exec(child);
  1142. }
  1143. if (outpipe[1] != -1) {
  1144. close(outpipe[1]);
  1145. }
  1146. /* put our child in the process group whose leader is the
  1147. first process in this pipe */
  1148. setpgid(child->pid, newjob->progs[0].pid);
  1149. if (nextin != 0)
  1150. close(nextin);
  1151. if (nextout != 1)
  1152. close(nextout);
  1153. /* If there isn't another process, nextin is garbage
  1154. but it doesn't matter */
  1155. nextin = pipefds[0];
  1156. }
  1157. newjob->pgrp = newjob->progs[0].pid;
  1158. insert_job(newjob, inbg);
  1159. return 0;
  1160. }
  1161. static int busy_loop(FILE * input)
  1162. {
  1163. char *command;
  1164. char *next_command = NULL;
  1165. struct job newjob;
  1166. int i;
  1167. int inbg = 0;
  1168. int status;
  1169. #if ENABLE_LASH_JOB_CONTROL
  1170. pid_t parent_pgrp;
  1171. /* save current owner of TTY so we can restore it on exit */
  1172. parent_pgrp = tcgetpgrp(shell_terminal);
  1173. #endif
  1174. newjob.job_list = &job_list;
  1175. newjob.job_context = DEFAULT_CONTEXT;
  1176. command = xzalloc(BUFSIZ);
  1177. while (1) {
  1178. if (!job_list.fg) {
  1179. /* no job is in the foreground */
  1180. /* see if any background processes have exited */
  1181. checkjobs(&job_list);
  1182. if (!next_command) {
  1183. if (get_command_bufsiz(input, command))
  1184. break;
  1185. next_command = command;
  1186. }
  1187. if (!expand_arguments(next_command)) {
  1188. free(command);
  1189. command = xzalloc(BUFSIZ);
  1190. next_command = NULL;
  1191. continue;
  1192. }
  1193. if (!parse_command(&next_command, &newjob, &inbg) &&
  1194. newjob.num_progs) {
  1195. int pipefds[2] = { -1, -1 };
  1196. debug_printf("job=%p fed to run_command by busy_loop()'\n",
  1197. &newjob);
  1198. run_command(&newjob, inbg, pipefds);
  1199. }
  1200. else {
  1201. free(command);
  1202. command = xzalloc(BUFSIZ);
  1203. next_command = NULL;
  1204. }
  1205. } else {
  1206. /* a job is running in the foreground; wait for it */
  1207. i = 0;
  1208. while (!job_list.fg->progs[i].pid ||
  1209. job_list.fg->progs[i].is_stopped == 1) i++;
  1210. if (waitpid(job_list.fg->progs[i].pid, &status, WUNTRACED) < 0) {
  1211. if (errno != ECHILD) {
  1212. bb_perror_msg_and_die("waitpid(%d)", job_list.fg->progs[i].pid);
  1213. }
  1214. }
  1215. if (WIFEXITED(status) || WIFSIGNALED(status)) {
  1216. /* the child exited */
  1217. job_list.fg->running_progs--;
  1218. job_list.fg->progs[i].pid = 0;
  1219. last_return_code = WEXITSTATUS(status);
  1220. if (!job_list.fg->running_progs) {
  1221. /* child exited */
  1222. remove_job(&job_list, job_list.fg);
  1223. job_list.fg = NULL;
  1224. }
  1225. }
  1226. #if ENABLE_LASH_JOB_CONTROL
  1227. else {
  1228. /* the child was stopped */
  1229. job_list.fg->stopped_progs++;
  1230. job_list.fg->progs[i].is_stopped = 1;
  1231. if (job_list.fg->stopped_progs == job_list.fg->running_progs) {
  1232. printf("\n" JOB_STATUS_FORMAT, job_list.fg->jobid,
  1233. "Stopped", job_list.fg->text);
  1234. job_list.fg = NULL;
  1235. }
  1236. }
  1237. if (!job_list.fg) {
  1238. /* move the shell to the foreground */
  1239. /* suppress messages when run from /linuxrc mag@sysgo.de */
  1240. if (tcsetpgrp(shell_terminal, getpgrp()) && errno != ENOTTY)
  1241. bb_perror_msg("tcsetpgrp");
  1242. }
  1243. #endif
  1244. }
  1245. }
  1246. free(command);
  1247. #if ENABLE_LASH_JOB_CONTROL
  1248. /* return controlling TTY back to parent process group before exiting */
  1249. if (tcsetpgrp(shell_terminal, parent_pgrp) && errno != ENOTTY)
  1250. bb_perror_msg("tcsetpgrp");
  1251. #endif
  1252. /* return exit status if called with "-c" */
  1253. if (input == NULL && WIFEXITED(status))
  1254. return WEXITSTATUS(status);
  1255. return 0;
  1256. }
  1257. #if ENABLE_FEATURE_CLEAN_UP
  1258. static void free_memory(void)
  1259. {
  1260. free(cwd);
  1261. if (job_list.fg && !job_list.fg->running_progs) {
  1262. remove_job(&job_list, job_list.fg);
  1263. }
  1264. }
  1265. #else
  1266. void free_memory(void);
  1267. #endif
  1268. #if ENABLE_LASH_JOB_CONTROL
  1269. /* Make sure we have a controlling tty. If we get started under a job
  1270. * aware app (like bash for example), make sure we are now in charge so
  1271. * we don't fight over who gets the foreground */
  1272. static void setup_job_control(void)
  1273. {
  1274. int status;
  1275. pid_t shell_pgrp;
  1276. /* Loop until we are in the foreground. */
  1277. while ((status = tcgetpgrp(shell_terminal)) >= 0) {
  1278. shell_pgrp = getpgrp();
  1279. if (status == shell_pgrp) {
  1280. break;
  1281. }
  1282. kill(- shell_pgrp, SIGTTIN);
  1283. }
  1284. /* Ignore interactive and job-control signals. */
  1285. signal(SIGINT, SIG_IGN);
  1286. signal(SIGQUIT, SIG_IGN);
  1287. signal(SIGTSTP, SIG_IGN);
  1288. signal(SIGTTIN, SIG_IGN);
  1289. signal(SIGTTOU, SIG_IGN);
  1290. signal(SIGCHLD, SIG_IGN);
  1291. /* Put ourselves in our own process group. */
  1292. setsid();
  1293. shell_pgrp = getpid();
  1294. setpgid(shell_pgrp, shell_pgrp);
  1295. /* Grab control of the terminal. */
  1296. tcsetpgrp(shell_terminal, shell_pgrp);
  1297. }
  1298. #else
  1299. static inline void setup_job_control(void)
  1300. {
  1301. }
  1302. #endif
  1303. int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  1304. int lash_main(int argc, char **argv)
  1305. {
  1306. unsigned opt;
  1307. FILE *input = stdin;
  1308. global_argc = argc;
  1309. global_argv = argv;
  1310. #if ENABLE_FEATURE_EDITING
  1311. line_input_state = new_line_input_t(FOR_SHELL);
  1312. #endif
  1313. /* These variables need re-initializing when recursing */
  1314. last_jobid = 0;
  1315. close_me_list = NULL;
  1316. job_list.head = NULL;
  1317. job_list.fg = NULL;
  1318. last_return_code = 1;
  1319. if (global_argv[0] && global_argv[0][0] == '-') {
  1320. FILE *prof_input;
  1321. prof_input = fopen("/etc/profile", "r");
  1322. if (prof_input) {
  1323. llist_add_to(&close_me_list, (void *)(long)fileno(prof_input));
  1324. /* Now run the file */
  1325. busy_loop(prof_input);
  1326. fclose_if_not_stdin(prof_input);
  1327. llist_pop(&close_me_list);
  1328. }
  1329. }
  1330. opt = getopt32(argv, "+ic:", &local_pending_command);
  1331. #define LASH_OPT_i (1<<0)
  1332. #define LASH_OPT_c (1<<1)
  1333. if (opt & LASH_OPT_c) {
  1334. input = NULL;
  1335. optind++;
  1336. global_argv += optind;
  1337. }
  1338. /* A shell is interactive if the `-i' flag was given, or if all of
  1339. * the following conditions are met:
  1340. * no -c command
  1341. * no arguments remaining or the -s flag given
  1342. * standard input is a terminal
  1343. * standard output is a terminal
  1344. * Refer to Posix.2, the description of the `sh' utility. */
  1345. if (global_argv[optind] == NULL && input == stdin
  1346. && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
  1347. ) {
  1348. opt |= LASH_OPT_i;
  1349. }
  1350. setup_job_control();
  1351. if (opt & LASH_OPT_i) {
  1352. /* Looks like they want an interactive shell */
  1353. if (!ENABLE_FEATURE_SH_EXTRA_QUIET) {
  1354. printf("\n\n%s built-in shell (lash)\n"
  1355. "Enter 'help' for a list of built-in commands.\n\n",
  1356. bb_banner);
  1357. }
  1358. } else if (!local_pending_command && global_argv[optind]) {
  1359. //printf( "optind=%d argv[optind]='%s'\n", optind, argv[optind]);
  1360. input = xfopen(global_argv[optind], "r");
  1361. /* be lazy, never mark this closed */
  1362. llist_add_to(&close_me_list, (void *)(long)fileno(input));
  1363. }
  1364. /* initialize the cwd -- this is never freed...*/
  1365. update_cwd();
  1366. if (ENABLE_FEATURE_CLEAN_UP) atexit(free_memory);
  1367. if (ENABLE_FEATURE_EDITING) cmdedit_set_initial_prompt();
  1368. else PS1 = NULL;
  1369. return busy_loop(input);
  1370. }