lash.c 40 KB

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