lash.c 42 KB

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