3
0

lash_unused.c 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576
  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 "libbb.h"
  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) 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 UNUSED_PARAM *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 UNUSED_PARAM *dummy)
  264. {
  265. const struct built_in_command *x;
  266. printf(
  267. "Built-in commands:\n"
  268. "------------------\n");
  269. for (x = bltins; x <= &VEC_LAST(bltins); x++) {
  270. if (x->descr == NULL)
  271. continue;
  272. printf("%s\t%s\n", x->cmd, x->descr);
  273. }
  274. bb_putchar('\n');
  275. return EXIT_SUCCESS;
  276. }
  277. /* built-in 'jobs' handler */
  278. static int builtin_jobs(struct child_prog *child)
  279. {
  280. struct job *job;
  281. const char *status_string;
  282. for (job = child->family->job_list->head; job; job = job->next) {
  283. if (job->running_progs == job->stopped_progs)
  284. status_string = "Stopped";
  285. else
  286. status_string = "Running";
  287. printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->text);
  288. }
  289. return EXIT_SUCCESS;
  290. }
  291. /* built-in 'pwd' handler */
  292. static int builtin_pwd(struct child_prog UNUSED_PARAM *dummy)
  293. {
  294. update_cwd();
  295. puts(cwd);
  296. return EXIT_SUCCESS;
  297. }
  298. /* built-in 'export VAR=value' handler */
  299. static int builtin_export(struct child_prog *child)
  300. {
  301. int res;
  302. char *v = child->argv[1];
  303. if (v == NULL) {
  304. char **e;
  305. for (e = environ; *e; e++) {
  306. puts(*e);
  307. }
  308. return 0;
  309. }
  310. res = putenv(v);
  311. if (res)
  312. bb_perror_msg("export");
  313. #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
  314. if (strncmp(v, "PS1=", 4) == 0)
  315. PS1 = getenv("PS1");
  316. #endif
  317. #if ENABLE_LOCALE_SUPPORT
  318. // TODO: why getenv? "" would be just as good...
  319. if (strncmp(v, "LC_ALL=", 7) == 0)
  320. setlocale(LC_ALL, getenv("LC_ALL"));
  321. if (strncmp(v, "LC_CTYPE=", 9) == 0)
  322. setlocale(LC_CTYPE, getenv("LC_CTYPE"));
  323. #endif
  324. return res;
  325. }
  326. /* built-in 'read VAR' handler */
  327. static int builtin_read(struct child_prog *child)
  328. {
  329. int res = 0, len;
  330. char *s;
  331. char string[MAX_READ];
  332. if (child->argv[1]) {
  333. /* argument (VAR) given: put "VAR=" into buffer */
  334. safe_strncpy(string, child->argv[1], MAX_READ-1);
  335. len = strlen(string);
  336. string[len++] = '=';
  337. string[len] = '\0';
  338. fgets(&string[len], sizeof(string) - len, stdin); /* read string */
  339. res = strlen(string);
  340. if (res > len)
  341. string[--res] = '\0'; /* chomp trailing newline */
  342. /*
  343. ** string should now contain "VAR=<value>"
  344. ** copy it (putenv() won't do that, so we must make sure
  345. ** the string resides in a static buffer!)
  346. */
  347. res = -1;
  348. s = strdup(string);
  349. if (s)
  350. res = putenv(s);
  351. if (res)
  352. bb_perror_msg("read");
  353. } else
  354. fgets(string, sizeof(string), stdin);
  355. return res;
  356. }
  357. /* Built-in '.' handler (read-in and execute commands from file) */
  358. static int builtin_source(struct child_prog *child)
  359. {
  360. FILE *input;
  361. int status;
  362. input = fopen_or_warn(child->argv[1], "r");
  363. if (!input) {
  364. return EXIT_FAILURE;
  365. }
  366. llist_add_to(&close_me_list, (void *)(long)fileno(input));
  367. /* Now run the file */
  368. status = busy_loop(input);
  369. fclose(input);
  370. llist_pop(&close_me_list);
  371. return status;
  372. }
  373. /* built-in 'unset VAR' handler */
  374. static int builtin_unset(struct child_prog *child)
  375. {
  376. if (child->argv[1] == NULL) {
  377. printf(bb_msg_requires_arg, "unset");
  378. return EXIT_FAILURE;
  379. }
  380. unsetenv(child->argv[1]);
  381. return EXIT_SUCCESS;
  382. }
  383. #if ENABLE_LASH_JOB_CONTROL
  384. /* free up all memory from a job */
  385. static void free_job(struct job *cmd)
  386. {
  387. int i;
  388. struct jobset *keep;
  389. for (i = 0; i < cmd->num_progs; i++) {
  390. free(cmd->progs[i].argv);
  391. #if ENABLE_LASH_PIPE_N_REDIRECTS
  392. free(cmd->progs[i].redirects);
  393. #endif
  394. }
  395. free(cmd->progs);
  396. free(cmd->text);
  397. free(cmd->cmdbuf);
  398. keep = cmd->job_list;
  399. memset(cmd, 0, sizeof(struct job));
  400. cmd->job_list = keep;
  401. }
  402. /* remove a job from a jobset */
  403. static void remove_job(struct jobset *j_list, struct job *job)
  404. {
  405. struct job *prevjob;
  406. free_job(job);
  407. if (job == j_list->head) {
  408. j_list->head = job->next;
  409. } else {
  410. prevjob = j_list->head;
  411. while (prevjob->next != job)
  412. prevjob = prevjob->next;
  413. prevjob->next = job->next;
  414. }
  415. if (j_list->head)
  416. last_jobid = j_list->head->jobid;
  417. else
  418. last_jobid = 0;
  419. free(job);
  420. }
  421. /* Checks to see if any background processes have exited -- if they
  422. have, figure out why and see if a job has completed */
  423. static void checkjobs(struct jobset *j_list)
  424. {
  425. struct job *job;
  426. pid_t childpid;
  427. int status;
  428. int prognum = 0;
  429. while ((childpid = waitpid(-1, &status, WNOHANG | WUNTRACED)) > 0) {
  430. for (job = j_list->head; job; job = job->next) {
  431. prognum = 0;
  432. while (prognum < job->num_progs &&
  433. job->progs[prognum].pid != childpid) prognum++;
  434. if (prognum < job->num_progs)
  435. break;
  436. }
  437. /* This happens on backticked commands */
  438. if (job == NULL)
  439. return;
  440. if (WIFEXITED(status) || WIFSIGNALED(status)) {
  441. /* child exited */
  442. job->running_progs--;
  443. job->progs[prognum].pid = 0;
  444. if (!job->running_progs) {
  445. printf(JOB_STATUS_FORMAT, job->jobid, "Done", job->text);
  446. last_jobid = 0;
  447. remove_job(j_list, job);
  448. }
  449. } else {
  450. /* child stopped */
  451. job->stopped_progs++;
  452. job->progs[prognum].is_stopped = 1;
  453. }
  454. }
  455. if (childpid == -1 && errno != ECHILD)
  456. bb_perror_msg("waitpid");
  457. }
  458. #else
  459. static void checkjobs(struct jobset *j_list)
  460. {
  461. }
  462. static void free_job(struct job *cmd)
  463. {
  464. }
  465. static void remove_job(struct jobset *j_list, struct job *job)
  466. {
  467. }
  468. #endif
  469. #if ENABLE_LASH_PIPE_N_REDIRECTS
  470. /* squirrel != NULL means we squirrel away copies of stdin, stdout,
  471. * and stderr if they are redirected. */
  472. static int setup_redirects(struct child_prog *prog, int squirrel[])
  473. {
  474. int i;
  475. int openfd;
  476. int mode = O_RDONLY;
  477. struct redir_struct *redir = prog->redirects;
  478. for (i = 0; i < prog->num_redirects; i++, redir++) {
  479. switch (redir->type) {
  480. case REDIRECT_INPUT:
  481. mode = O_RDONLY;
  482. break;
  483. case REDIRECT_OVERWRITE:
  484. mode = O_WRONLY | O_CREAT | O_TRUNC;
  485. break;
  486. case REDIRECT_APPEND:
  487. mode = O_WRONLY | O_CREAT | O_APPEND;
  488. break;
  489. }
  490. openfd = open_or_warn(redir->filename, mode);
  491. if (openfd < 0) {
  492. /* this could get lost if stderr has been redirected, but
  493. bash and ash both lose it as well (though zsh doesn't!) */
  494. return 1;
  495. }
  496. if (openfd != redir->fd) {
  497. if (squirrel && redir->fd < 3) {
  498. squirrel[redir->fd] = dup(redir->fd);
  499. close_on_exec_on(squirrel[redir->fd]);
  500. }
  501. dup2(openfd, redir->fd);
  502. close(openfd);
  503. }
  504. }
  505. return 0;
  506. }
  507. static void restore_redirects(int squirrel[])
  508. {
  509. int i, fd;
  510. for (i = 0; i < 3; i++) {
  511. fd = squirrel[i];
  512. if (fd != -1) {
  513. /* No error checking. I sure wouldn't know what
  514. * to do with an error if I found one! */
  515. dup2(fd, i);
  516. close(fd);
  517. }
  518. }
  519. }
  520. #else
  521. static inline int setup_redirects(struct child_prog *prog, int squirrel[])
  522. {
  523. return 0;
  524. }
  525. static inline void restore_redirects(int squirrel[])
  526. {
  527. }
  528. #endif
  529. static inline void cmdedit_set_initial_prompt(void)
  530. {
  531. #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
  532. PS1 = NULL;
  533. #else
  534. PS1 = getenv("PS1");
  535. if (PS1 == 0)
  536. PS1 = "\\w \\$ ";
  537. #endif
  538. }
  539. static inline const char* setup_prompt_string(void)
  540. {
  541. #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
  542. /* Set up the prompt */
  543. if (shell_context == 0) {
  544. char *ns;
  545. free((char*)PS1);
  546. ns = xmalloc(strlen(cwd)+4);
  547. sprintf(ns, "%s %c ", cwd, (geteuid() != 0) ? '$': '#');
  548. PS1 = ns;
  549. return ns;
  550. } else {
  551. return PS2;
  552. }
  553. #else
  554. return (shell_context == 0)? PS1 : PS2;
  555. #endif
  556. }
  557. #if ENABLE_FEATURE_EDITING
  558. static line_input_t *line_input_state;
  559. #endif
  560. static int get_command_bufsiz(FILE *source, char *command)
  561. {
  562. const char *prompt_str;
  563. if (source == NULL) {
  564. if (local_pending_command) {
  565. /* a command specified (-c option): return it & mark it done */
  566. strncpy(command, local_pending_command, BUFSIZ);
  567. local_pending_command = NULL;
  568. return 0;
  569. }
  570. return 1;
  571. }
  572. if (source == stdin) {
  573. prompt_str = setup_prompt_string();
  574. #if ENABLE_FEATURE_EDITING
  575. /*
  576. ** enable command line editing only while a command line
  577. ** is actually being read; otherwise, we'll end up bequeathing
  578. ** atexit() handlers and other unwanted stuff to our
  579. ** child processes (rob@sysgo.de)
  580. */
  581. read_line_input(prompt_str, command, BUFSIZ, line_input_state);
  582. return 0;
  583. #else
  584. fputs(prompt_str, stdout);
  585. #endif
  586. }
  587. if (!fgets(command, BUFSIZ - 2, source)) {
  588. if (source == stdin)
  589. bb_putchar('\n');
  590. return 1;
  591. }
  592. return 0;
  593. }
  594. static char * strsep_space(char *string, int * ix)
  595. {
  596. /* Short circuit the trivial case */
  597. if (!string || ! string[*ix])
  598. return NULL;
  599. /* Find the end of the token. */
  600. while (string[*ix] && !isspace(string[*ix]) ) {
  601. (*ix)++;
  602. }
  603. /* Find the end of any whitespace trailing behind
  604. * the token and let that be part of the token */
  605. while (string[*ix] && isspace(string[*ix])) {
  606. (*ix)++;
  607. }
  608. if (!*ix) {
  609. /* Nothing useful was found */
  610. return NULL;
  611. }
  612. return xstrndup(string, *ix);
  613. }
  614. static int expand_arguments(char *command)
  615. {
  616. static const char out_of_space[] ALIGN1 = "out of space during expansion";
  617. int total_length = 0, length, i, retval, ix = 0;
  618. expand_t expand_result;
  619. char *tmpcmd, *cmd, *cmd_copy;
  620. char *src, *dst, *var;
  621. int flags = GLOB_NOCHECK
  622. #ifdef GLOB_BRACE
  623. | GLOB_BRACE
  624. #endif
  625. #ifdef GLOB_TILDE
  626. | GLOB_TILDE
  627. #endif
  628. ;
  629. /* get rid of the terminating \n */
  630. chomp(command);
  631. /* Fix up escape sequences to be the Real Thing(tm) */
  632. while (command && command[ix]) {
  633. if (command[ix] == '\\') {
  634. const char *tmp = command+ix+1;
  635. command[ix] = bb_process_escape_sequence( &tmp );
  636. memmove(command+ix + 1, tmp, strlen(tmp)+1);
  637. }
  638. ix++;
  639. }
  640. /* Use glob and then fixup environment variables and such */
  641. /* It turns out that glob is very stupid. We have to feed it one word at a
  642. * time since it can't cope with a full string. Here we convert command
  643. * (char*) into cmd (char**, one word per string) */
  644. /* We need a clean copy, so strsep can mess up the copy while
  645. * we write stuff into the original (in a minute) */
  646. cmd = cmd_copy = xstrdup(command);
  647. *command = '\0';
  648. for (ix = 0, tmpcmd = cmd;
  649. (tmpcmd = strsep_space(cmd, &ix)) != NULL; cmd += ix, ix = 0) {
  650. if (*tmpcmd == '\0')
  651. break;
  652. /* we need to trim() the result for glob! */
  653. trim(tmpcmd);
  654. retval = glob(tmpcmd, flags, NULL, &expand_result);
  655. free(tmpcmd); /* Free mem allocated by strsep_space */
  656. if (retval == GLOB_NOSPACE) {
  657. /* Mem may have been allocated... */
  658. globfree(&expand_result);
  659. bb_error_msg(out_of_space);
  660. return FALSE;
  661. } else if (retval != 0) {
  662. /* Some other error. GLOB_NOMATCH shouldn't
  663. * happen because of the GLOB_NOCHECK flag in
  664. * the glob call. */
  665. bb_error_msg("syntax error");
  666. return FALSE;
  667. } else {
  668. /* Convert from char** (one word per string) to a simple char*,
  669. * but don't overflow command which is BUFSIZ in length */
  670. for (i = 0; i < expand_result.gl_pathc; i++) {
  671. length = strlen(expand_result.gl_pathv[i]);
  672. if (total_length+length+1 >= BUFSIZ) {
  673. bb_error_msg(out_of_space);
  674. return FALSE;
  675. }
  676. strcat(command+total_length, " ");
  677. total_length += 1;
  678. strcat(command+total_length, expand_result.gl_pathv[i]);
  679. total_length += length;
  680. }
  681. globfree(&expand_result);
  682. }
  683. }
  684. free(cmd_copy);
  685. trim(command);
  686. /* Now do the shell variable substitutions which
  687. * wordexp can't do for us, namely $? and $! */
  688. src = command;
  689. while ((dst = strchr(src,'$')) != NULL) {
  690. var = NULL;
  691. switch (*(dst+1)) {
  692. case '?':
  693. var = itoa(last_return_code);
  694. break;
  695. case '!':
  696. if (last_bg_pid == -1)
  697. *var = '\0';
  698. else
  699. var = itoa(last_bg_pid);
  700. break;
  701. /* Everything else like $$, $#, $[0-9], etc. should all be
  702. * expanded by wordexp(), so we can in theory skip that stuff
  703. * here, but just to be on the safe side (i.e., since uClibc
  704. * wordexp doesn't do this stuff yet), lets leave it in for
  705. * now. */
  706. case '$':
  707. var = itoa(getpid());
  708. break;
  709. case '#':
  710. var = itoa(global_argc - 1);
  711. break;
  712. case '0':case '1':case '2':case '3':case '4':
  713. case '5':case '6':case '7':case '8':case '9':
  714. {
  715. int ixx = *(dst+1)-48+1;
  716. if (ixx >= global_argc) {
  717. var = '\0';
  718. } else {
  719. var = global_argv[ixx];
  720. }
  721. }
  722. break;
  723. }
  724. if (var) {
  725. /* a single character construction was found, and
  726. * already handled in the case statement */
  727. src = dst + 2;
  728. } else {
  729. /* Looks like an environment variable */
  730. char delim_hold;
  731. int num_skip_chars = 0;
  732. int dstlen = strlen(dst);
  733. /* Is this a ${foo} type variable? */
  734. if (dstlen >= 2 && *(dst+1) == '{') {
  735. src = strchr(dst+1, '}');
  736. num_skip_chars = 1;
  737. } else {
  738. src = dst + 1;
  739. while (isalnum(*src) || *src == '_') src++;
  740. }
  741. if (src == NULL) {
  742. src = dst+dstlen;
  743. }
  744. delim_hold = *src;
  745. *src = '\0'; /* temporary */
  746. var = getenv(dst + 1 + num_skip_chars);
  747. *src = delim_hold;
  748. src += num_skip_chars;
  749. }
  750. if (var == NULL) {
  751. /* Seems we got an un-expandable variable. So delete it. */
  752. var = (char*)"";
  753. }
  754. {
  755. int subst_len = strlen(var);
  756. int trail_len = strlen(src);
  757. if (dst+subst_len+trail_len >= command+BUFSIZ) {
  758. bb_error_msg(out_of_space);
  759. return FALSE;
  760. }
  761. /* Move stuff to the end of the string to accommodate
  762. * filling the created gap with the new stuff */
  763. memmove(dst+subst_len, src, trail_len+1);
  764. /* Now copy in the new stuff */
  765. memcpy(dst, var, subst_len);
  766. src = dst+subst_len;
  767. }
  768. }
  769. return TRUE;
  770. }
  771. /* Return cmd->num_progs as 0 if no command is present (e.g. an empty
  772. line). If a valid command is found, command_ptr is set to point to
  773. the beginning of the next command (if the original command had more
  774. then one job associated with it) or NULL if no more commands are
  775. present. */
  776. static int parse_command(char **command_ptr, struct job *job, int *inbg)
  777. {
  778. char *command;
  779. char *return_command = NULL;
  780. char *src, *buf;
  781. int argc_l;
  782. int flag;
  783. int argv_alloced;
  784. char quote = '\0';
  785. struct child_prog *prog;
  786. #if ENABLE_LASH_PIPE_N_REDIRECTS
  787. int i;
  788. char *chptr;
  789. #endif
  790. /* skip leading white space */
  791. *command_ptr = skip_whitespace(*command_ptr);
  792. /* this handles empty lines or leading '#' characters */
  793. if (!**command_ptr || (**command_ptr == '#')) {
  794. job->num_progs = 0;
  795. return 0;
  796. }
  797. *inbg = 0;
  798. job->num_progs = 1;
  799. job->progs = xmalloc(sizeof(*job->progs));
  800. /* We set the argv elements to point inside of this string. The
  801. memory is freed by free_job(). Allocate twice the original
  802. length in case we need to quote every single character.
  803. Getting clean memory relieves us of the task of NULL
  804. terminating things and makes the rest of this look a bit
  805. cleaner (though it is, admittedly, a tad less efficient) */
  806. job->cmdbuf = command = xzalloc(2*strlen(*command_ptr) + 1);
  807. job->text = NULL;
  808. prog = job->progs;
  809. prog->num_redirects = 0;
  810. prog->is_stopped = 0;
  811. prog->family = job;
  812. #if ENABLE_LASH_PIPE_N_REDIRECTS
  813. prog->redirects = NULL;
  814. #endif
  815. argv_alloced = 5;
  816. prog->argv = xmalloc(sizeof(*prog->argv) * argv_alloced);
  817. prog->argv[0] = job->cmdbuf;
  818. flag = argc_l = 0;
  819. buf = command;
  820. src = *command_ptr;
  821. while (*src && !(flag & LASH_OPT_DONE)) {
  822. if (quote == *src) {
  823. quote = '\0';
  824. } else if (quote) {
  825. if (*src == '\\') {
  826. src++;
  827. if (!*src) {
  828. bb_error_msg("character expected after \\");
  829. free_job(job);
  830. return 1;
  831. }
  832. /* in shell, "\'" should yield \' */
  833. if (*src != quote) {
  834. *buf++ = '\\';
  835. *buf++ = '\\';
  836. }
  837. } else
  838. if (*src == '*' || *src == '?'
  839. || *src == '[' || *src == ']'
  840. ) {
  841. *buf++ = '\\';
  842. }
  843. *buf++ = *src;
  844. } else if (isspace(*src)) {
  845. if (*prog->argv[argc_l] || (flag & LASH_OPT_SAW_QUOTE)) {
  846. buf++, argc_l++;
  847. /* +1 here leaves room for the NULL which ends argv */
  848. if ((argc_l + 1) == argv_alloced) {
  849. argv_alloced += 5;
  850. prog->argv = xrealloc(prog->argv,
  851. sizeof(*prog->argv) * argv_alloced);
  852. }
  853. prog->argv[argc_l] = buf;
  854. flag ^= LASH_OPT_SAW_QUOTE;
  855. }
  856. } else
  857. switch (*src) {
  858. case '"':
  859. case '\'':
  860. quote = *src;
  861. flag |= LASH_OPT_SAW_QUOTE;
  862. break;
  863. case '#': /* comment */
  864. if (*(src-1)== '$')
  865. *buf++ = *src;
  866. else
  867. flag |= LASH_OPT_DONE;
  868. break;
  869. #if ENABLE_LASH_PIPE_N_REDIRECTS
  870. case '>': /* redirects */
  871. case '<':
  872. i = prog->num_redirects++;
  873. prog->redirects = xrealloc(prog->redirects,
  874. sizeof(*prog->redirects) * (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. #if ENABLE_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. const 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. /* Check if the command matches any of the forking builtins. */
  1001. for (x = bltins; x <= &VEC_LAST(bltins); x++) {
  1002. if (strcmp(child->argv[0], x->cmd) == 0) {
  1003. _exit(x->function(child));
  1004. }
  1005. }
  1006. /* Check if the command matches any busybox internal
  1007. * commands ("applets") here. Following discussions from
  1008. * November 2000 on busybox@busybox.net, don't use
  1009. * bb_get_last_path_component_nostrip(). This way explicit
  1010. * (with slashes) filenames will never be interpreted as an
  1011. * applet, just like with builtins. This way the user can
  1012. * override an applet with an explicit filename reference.
  1013. * The only downside to this change is that an explicit
  1014. * /bin/foo invocation will fork and exec /bin/foo, even if
  1015. * /bin/foo is a symlink to busybox.
  1016. */
  1017. if (ENABLE_FEATURE_SH_STANDALONE) {
  1018. run_applet_and_exit(child->argv[0], child->argv);
  1019. }
  1020. execvp(child->argv[0], child->argv);
  1021. /* Do not use bb_perror_msg_and_die() here, since we must not
  1022. * call exit() but should call _exit() instead */
  1023. bb_simple_perror_msg(child->argv[0]);
  1024. _exit(EXIT_FAILURE);
  1025. }
  1026. static void insert_job(struct job *newjob, int inbg)
  1027. {
  1028. struct job *thejob;
  1029. struct jobset *j_list = newjob->job_list;
  1030. /* find the ID for thejob to use */
  1031. newjob->jobid = 1;
  1032. for (thejob = j_list->head; thejob; thejob = thejob->next)
  1033. if (thejob->jobid >= newjob->jobid)
  1034. newjob->jobid = thejob->jobid + 1;
  1035. /* add thejob to the list of running jobs */
  1036. if (!j_list->head) {
  1037. thejob = j_list->head = xmalloc(sizeof(*thejob));
  1038. } else {
  1039. for (thejob = j_list->head; thejob->next; thejob = thejob->next) /* nothing */;
  1040. thejob->next = xmalloc(sizeof(*thejob));
  1041. thejob = thejob->next;
  1042. }
  1043. *thejob = *newjob; /* physically copy the struct job */
  1044. thejob->next = NULL;
  1045. thejob->running_progs = thejob->num_progs;
  1046. thejob->stopped_progs = 0;
  1047. #if ENABLE_LASH_JOB_CONTROL
  1048. if (inbg) {
  1049. /* we don't wait for background thejobs to return -- append it
  1050. to the list of backgrounded thejobs and leave it alone */
  1051. printf("[%d] %d\n", thejob->jobid,
  1052. newjob->progs[newjob->num_progs - 1].pid);
  1053. last_jobid = newjob->jobid;
  1054. last_bg_pid = newjob->progs[newjob->num_progs - 1].pid;
  1055. } else {
  1056. newjob->job_list->fg = thejob;
  1057. /* move the new process group into the foreground */
  1058. /* Ignore errors since child could have already exited */
  1059. tcsetpgrp(shell_terminal, newjob->pgrp);
  1060. }
  1061. #endif
  1062. }
  1063. static int run_command(struct job *newjob, int inbg, int outpipe[2])
  1064. {
  1065. /* struct job *thejob; */
  1066. int i;
  1067. int nextin, nextout;
  1068. int pipefds[2]; /* pipefd[0] is for reading */
  1069. const struct built_in_command *x;
  1070. struct child_prog *child;
  1071. nextin = 0;
  1072. for (i = 0; i < newjob->num_progs; i++) {
  1073. child = &(newjob->progs[i]);
  1074. nextout = 1;
  1075. if ((i + 1) < newjob->num_progs) {
  1076. xpipe(pipefds);
  1077. nextout = pipefds[1];
  1078. } else if (outpipe[1] != -1) {
  1079. nextout = outpipe[1];
  1080. }
  1081. /* Check if the command matches any non-forking builtins,
  1082. * but only if this is a simple command.
  1083. * Non-forking builtins within pipes have to fork anyway,
  1084. * and are handled in pseudo_exec. "echo foo | read bar"
  1085. * is doomed to failure, and doesn't work on bash, either.
  1086. */
  1087. if (newjob->num_progs == 1) {
  1088. int rcode;
  1089. int squirrel[] = {-1, -1, -1};
  1090. /* Check if the command sets an environment variable. */
  1091. if (strchr(child->argv[0], '=') != NULL) {
  1092. child->argv[1] = child->argv[0];
  1093. return builtin_export(child);
  1094. }
  1095. for (x = bltins; x <= &VEC_LAST(bltins); x++) {
  1096. if (strcmp(child->argv[0], x->cmd) == 0) {
  1097. setup_redirects(child, squirrel);
  1098. rcode = x->function(child);
  1099. restore_redirects(squirrel);
  1100. return rcode;
  1101. }
  1102. }
  1103. #if ENABLE_FEATURE_SH_STANDALONE
  1104. {
  1105. int a = find_applet_by_name(child->argv[i]);
  1106. if (a >= 0 && APPLET_IS_NOFORK(a)) {
  1107. setup_redirects(child, squirrel);
  1108. rcode = run_nofork_applet(a, child->argv + i);
  1109. restore_redirects(squirrel);
  1110. return rcode;
  1111. }
  1112. }
  1113. #endif
  1114. }
  1115. #if BB_MMU
  1116. child->pid = fork();
  1117. #else
  1118. child->pid = vfork();
  1119. #endif
  1120. if (!child->pid) {
  1121. /* Set the handling for job control signals back to the default. */
  1122. signal(SIGINT, SIG_DFL);
  1123. signal(SIGQUIT, SIG_DFL);
  1124. signal(SIGTSTP, SIG_DFL);
  1125. signal(SIGTTIN, SIG_DFL);
  1126. signal(SIGTTOU, SIG_DFL);
  1127. signal(SIGCHLD, SIG_DFL);
  1128. /* Close all open filehandles. */
  1129. while (close_me_list)
  1130. close((long)llist_pop(&close_me_list));
  1131. if (outpipe[1] != -1) {
  1132. close(outpipe[0]);
  1133. }
  1134. if (nextin != 0) {
  1135. dup2(nextin, 0);
  1136. close(nextin);
  1137. }
  1138. if (nextout != 1) {
  1139. dup2(nextout, 1);
  1140. dup2(nextout, 2); /* Really? */
  1141. close(nextout);
  1142. close(pipefds[0]);
  1143. }
  1144. /* explicit redirects override pipes */
  1145. setup_redirects(child,NULL);
  1146. pseudo_exec(child);
  1147. }
  1148. if (outpipe[1] != -1) {
  1149. close(outpipe[1]);
  1150. }
  1151. /* put our child in the process group whose leader is the
  1152. first process in this pipe */
  1153. setpgid(child->pid, newjob->progs[0].pid);
  1154. if (nextin != 0)
  1155. close(nextin);
  1156. if (nextout != 1)
  1157. close(nextout);
  1158. /* If there isn't another process, nextin is garbage
  1159. but it doesn't matter */
  1160. nextin = pipefds[0];
  1161. }
  1162. newjob->pgrp = newjob->progs[0].pid;
  1163. insert_job(newjob, inbg);
  1164. return 0;
  1165. }
  1166. static int busy_loop(FILE *input)
  1167. {
  1168. char *command;
  1169. char *next_command = NULL;
  1170. struct job newjob;
  1171. int i;
  1172. int inbg = 0;
  1173. int status;
  1174. #if ENABLE_LASH_JOB_CONTROL
  1175. pid_t parent_pgrp;
  1176. /* save current owner of TTY so we can restore it on exit */
  1177. parent_pgrp = tcgetpgrp(shell_terminal);
  1178. #endif
  1179. newjob.job_list = &job_list;
  1180. newjob.job_context = DEFAULT_CONTEXT;
  1181. command = xzalloc(BUFSIZ);
  1182. while (1) {
  1183. if (!job_list.fg) {
  1184. /* no job is in the foreground */
  1185. /* see if any background processes have exited */
  1186. checkjobs(&job_list);
  1187. if (!next_command) {
  1188. if (get_command_bufsiz(input, command))
  1189. break;
  1190. next_command = command;
  1191. }
  1192. if (!expand_arguments(next_command)) {
  1193. free(command);
  1194. command = xzalloc(BUFSIZ);
  1195. next_command = NULL;
  1196. continue;
  1197. }
  1198. if (!parse_command(&next_command, &newjob, &inbg)
  1199. && newjob.num_progs
  1200. ) {
  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 = 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. #if ENABLE_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. #if ENABLE_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. #if ENABLE_FEATURE_CLEAN_UP
  1264. static void free_memory(void)
  1265. {
  1266. free(cwd);
  1267. if (job_list.fg && !job_list.fg->running_progs) {
  1268. remove_job(&job_list, job_list.fg);
  1269. }
  1270. }
  1271. #else
  1272. void free_memory(void);
  1273. #endif
  1274. #if ENABLE_LASH_JOB_CONTROL
  1275. /* Make sure we have a controlling tty. If we get started under a job
  1276. * aware app (like bash for example), make sure we are now in charge so
  1277. * we don't fight over who gets the foreground */
  1278. static void setup_job_control(void)
  1279. {
  1280. int status;
  1281. pid_t shell_pgrp;
  1282. /* Loop until we are in the foreground. */
  1283. while ((status = tcgetpgrp(shell_terminal)) >= 0) {
  1284. shell_pgrp = getpgrp();
  1285. if (status == shell_pgrp) {
  1286. break;
  1287. }
  1288. kill(- shell_pgrp, SIGTTIN);
  1289. }
  1290. /* Ignore interactive and job-control signals. */
  1291. signal(SIGINT, SIG_IGN);
  1292. signal(SIGQUIT, SIG_IGN);
  1293. signal(SIGTSTP, SIG_IGN);
  1294. signal(SIGTTIN, SIG_IGN);
  1295. signal(SIGTTOU, SIG_IGN);
  1296. signal(SIGCHLD, SIG_IGN);
  1297. /* Put ourselves in our own process group. */
  1298. setsid();
  1299. shell_pgrp = getpid();
  1300. setpgid(shell_pgrp, shell_pgrp);
  1301. /* Grab control of the terminal. */
  1302. tcsetpgrp(shell_terminal, shell_pgrp);
  1303. }
  1304. #else
  1305. static inline void setup_job_control(void)
  1306. {
  1307. }
  1308. #endif
  1309. int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  1310. int lash_main(int argc, char **argv)
  1311. {
  1312. unsigned opt;
  1313. FILE *input = stdin;
  1314. global_argc = argc;
  1315. global_argv = argv;
  1316. #if ENABLE_FEATURE_EDITING
  1317. line_input_state = new_line_input_t(FOR_SHELL);
  1318. #endif
  1319. /* These variables need re-initializing when recursing */
  1320. last_jobid = 0;
  1321. close_me_list = NULL;
  1322. job_list.head = NULL;
  1323. job_list.fg = NULL;
  1324. last_return_code = 1;
  1325. if (global_argv[0] && global_argv[0][0] == '-') {
  1326. FILE *prof_input;
  1327. prof_input = fopen_for_read("/etc/profile");
  1328. if (prof_input) {
  1329. llist_add_to(&close_me_list, (void *)(long)fileno(prof_input));
  1330. /* Now run the file */
  1331. busy_loop(prof_input);
  1332. fclose_if_not_stdin(prof_input);
  1333. llist_pop(&close_me_list);
  1334. }
  1335. }
  1336. opt = getopt32(argv, "+ic:", &local_pending_command);
  1337. #define LASH_OPT_i (1<<0)
  1338. #define LASH_OPT_c (1<<1)
  1339. if (opt & LASH_OPT_c) {
  1340. input = NULL;
  1341. optind++;
  1342. global_argv += optind;
  1343. }
  1344. /* A shell is interactive if the `-i' flag was given, or if all of
  1345. * the following conditions are met:
  1346. * no -c command
  1347. * no arguments remaining or the -s flag given
  1348. * standard input is a terminal
  1349. * standard output is a terminal
  1350. * Refer to Posix.2, the description of the `sh' utility. */
  1351. if (global_argv[optind] == NULL && input == stdin
  1352. && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
  1353. ) {
  1354. opt |= LASH_OPT_i;
  1355. }
  1356. setup_job_control();
  1357. if (opt & LASH_OPT_i) {
  1358. /* Looks like they want an interactive shell */
  1359. if (!ENABLE_FEATURE_SH_EXTRA_QUIET) {
  1360. printf("\n\n%s built-in shell (lash)\n"
  1361. "Enter 'help' for a list of built-in commands.\n\n",
  1362. bb_banner);
  1363. }
  1364. } else if (!local_pending_command && global_argv[optind]) {
  1365. //printf( "optind=%d argv[optind]='%s'\n", optind, argv[optind]);
  1366. input = xfopen_for_read(global_argv[optind]);
  1367. /* be lazy, never mark this closed */
  1368. llist_add_to(&close_me_list, (void *)(long)fileno(input));
  1369. }
  1370. /* initialize the cwd -- this is never freed...*/
  1371. update_cwd();
  1372. if (ENABLE_FEATURE_CLEAN_UP) atexit(free_memory);
  1373. if (ENABLE_FEATURE_EDITING) cmdedit_set_initial_prompt();
  1374. else PS1 = NULL;
  1375. return busy_loop(input);
  1376. }