lash.c 39 KB

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