cdb0b74dad3e8fd7762427e1c241b4b23ebca092
[oweals/busybox.git] / shell / hush.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * sh.c -- a prototype Bourne shell grammar parser
4  *      Intended to follow the original Thompson and Ritchie
5  *      "small and simple is beautiful" philosophy, which
6  *      incidentally is a good match to today's BusyBox.
7  *
8  * Copyright (C) 2000,2001  Larry Doolittle  <larry@doolittle.boa.org>
9  *
10  * Credits:
11  *      The parser routines proper are all original material, first
12  *      written Dec 2000 and Jan 2001 by Larry Doolittle.  The
13  *      execution engine, the builtins, and much of the underlying
14  *      support has been adapted from busybox-0.49pre's lash, which is
15  *      Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
16  *      written by Erik Andersen <andersen@codepoet.org>.  That, in turn,
17  *      is based in part on ladsh.c, by Michael K. Johnson and Erik W.
18  *      Troan, which they placed in the public domain.  I don't know
19  *      how much of the Johnson/Troan code has survived the repeated
20  *      rewrites.
21  *
22  * Other credits:
23  *      b_addchr() derived from similar w_addchar function in glibc-2.2
24  *      setup_redirect(), redirect_opt_num(), and big chunks of main()
25  *      and many builtins derived from contributions by Erik Andersen
26  *      miscellaneous bugfixes from Matt Kraai
27  *
28  * There are two big (and related) architecture differences between
29  * this parser and the lash parser.  One is that this version is
30  * actually designed from the ground up to understand nearly all
31  * of the Bourne grammar.  The second, consequential change is that
32  * the parser and input reader have been turned inside out.  Now,
33  * the parser is in control, and asks for input as needed.  The old
34  * way had the input reader in control, and it asked for parsing to
35  * take place as needed.  The new way makes it much easier to properly
36  * handle the recursion implicit in the various substitutions, especially
37  * across continuation lines.
38  *
39  * Bash grammar not implemented: (how many of these were in original sh?)
40  *      $@ (those sure look like weird quoting rules)
41  *      $_
42  *      ! negation operator for pipes
43  *      &> and >& redirection of stdout+stderr
44  *      Brace Expansion
45  *      Tilde Expansion
46  *      fancy forms of Parameter Expansion
47  *      aliases
48  *      Arithmetic Expansion
49  *      <(list) and >(list) Process Substitution
50  *      reserved words: case, esac, select, function
51  *      Here Documents ( << word )
52  *      Functions
53  * Major bugs:
54  *      job handling woefully incomplete and buggy (improved --vda)
55  *      reserved word execution woefully incomplete and buggy
56  * to-do:
57  *      port selected bugfixes from post-0.49 busybox lash - done?
58  *      finish implementing reserved words: for, while, until, do, done
59  *      change { and } from special chars to reserved words
60  *      builtins: break, continue, eval, return, set, trap, ulimit
61  *      test magic exec
62  *      handle children going into background
63  *      clean up recognition of null pipes
64  *      check setting of global_argc and global_argv
65  *      control-C handling, probably with longjmp
66  *      follow IFS rules more precisely, including update semantics
67  *      figure out what to do with backslash-newline
68  *      explain why we use signal instead of sigaction
69  *      propagate syntax errors, die on resource errors?
70  *      continuation lines, both explicit and implicit - done?
71  *      memory leak finding and plugging - done?
72  *      more testing, especially quoting rules and redirection
73  *      document how quoting rules not precisely followed for variable assignments
74  *      maybe change map[] to use 2-bit entries
75  *      (eventually) remove all the printf's
76  *
77  * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
78  */
79
80 #include "busybox.h"
81 #include <glob.h>      /* glob, of course */
82 #include <getopt.h>    /* should be pretty obvious */
83 /* #include <dmalloc.h> */
84
85
86 /* If you comment out one of these below, it will be #defined later
87  * to perform debug printfs to stderr: */
88 #define debug_printf(...)      do {} while (0)
89 /* Finer-grained debug switch */
90 #define debug_printf_jobs(...) do {} while (0)
91 #define debug_printf_exec(...) do {} while (0)
92
93
94 #ifndef debug_printf
95 #define debug_printf(...) fprintf(stderr, __VA_ARGS__)
96 /* broken, of course, but OK for testing */
97 static const char *indenter(int i)
98 {
99         static const char blanks[] = "                                    ";
100         return &blanks[sizeof(blanks) - i - 1];
101 }
102 #endif
103 #define final_printf debug_printf
104
105 #ifndef debug_printf_jobs
106 #define debug_printf_jobs(...) fprintf(stderr, __VA_ARGS__)
107 #define DEBUG_SHELL_JOBS 1
108 #endif
109
110 #ifndef debug_printf_exec
111 #define debug_printf_exec(...) fprintf(stderr, __VA_ARGS__)
112 #endif
113
114
115 #if !ENABLE_HUSH_INTERACTIVE
116 #undef ENABLE_FEATURE_EDITING
117 #define ENABLE_FEATURE_EDITING 0
118 #undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
119 #define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
120 #endif
121
122 #define SPECIAL_VAR_SYMBOL 03
123 #define FLAG_EXIT_FROM_LOOP 1
124 #define FLAG_PARSE_SEMICOLON (1 << 1)           /* symbol ';' is special for parser */
125 #define FLAG_REPARSING       (1 << 2)           /* >=2nd pass */
126
127 typedef enum {
128         REDIRECT_INPUT     = 1,
129         REDIRECT_OVERWRITE = 2,
130         REDIRECT_APPEND    = 3,
131         REDIRECT_HEREIS    = 4,
132         REDIRECT_IO        = 5
133 } redir_type;
134
135 /* The descrip member of this structure is only used to make debugging
136  * output pretty */
137 static const struct {
138         int mode;
139         signed char default_fd;
140         char descrip[3];
141 } redir_table[] = {
142         { 0,                         0, "()" },
143         { O_RDONLY,                  0, "<"  },
144         { O_CREAT|O_TRUNC|O_WRONLY,  1, ">"  },
145         { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
146         { O_RDONLY,                 -1, "<<" },
147         { O_RDWR,                    1, "<>" }
148 };
149
150 typedef enum {
151         PIPE_SEQ = 1,
152         PIPE_AND = 2,
153         PIPE_OR  = 3,
154         PIPE_BG  = 4,
155 } pipe_style;
156
157 /* might eventually control execution */
158 typedef enum {
159         RES_NONE  = 0,
160         RES_IF    = 1,
161         RES_THEN  = 2,
162         RES_ELIF  = 3,
163         RES_ELSE  = 4,
164         RES_FI    = 5,
165         RES_FOR   = 6,
166         RES_WHILE = 7,
167         RES_UNTIL = 8,
168         RES_DO    = 9,
169         RES_DONE  = 10,
170         RES_XXXX  = 11,
171         RES_IN    = 12,
172         RES_SNTX  = 13
173 } reserved_style;
174 enum {
175         FLAG_END   = (1 << RES_NONE ),
176         FLAG_IF    = (1 << RES_IF   ),
177         FLAG_THEN  = (1 << RES_THEN ),
178         FLAG_ELIF  = (1 << RES_ELIF ),
179         FLAG_ELSE  = (1 << RES_ELSE ),
180         FLAG_FI    = (1 << RES_FI   ),
181         FLAG_FOR   = (1 << RES_FOR  ),
182         FLAG_WHILE = (1 << RES_WHILE),
183         FLAG_UNTIL = (1 << RES_UNTIL),
184         FLAG_DO    = (1 << RES_DO   ),
185         FLAG_DONE  = (1 << RES_DONE ),
186         FLAG_IN    = (1 << RES_IN   ),
187         FLAG_START = (1 << RES_XXXX ),
188 };
189
190 /* This holds pointers to the various results of parsing */
191 struct p_context {
192         struct child_prog *child;
193         struct pipe *list_head;
194         struct pipe *pipe;
195         struct redir_struct *pending_redirect;
196         reserved_style w;
197         int old_flag;               /* for figuring out valid reserved words */
198         struct p_context *stack;
199         int type;           /* define type of parser : ";$" common or special symbol */
200         /* How about quoting status? */
201 };
202
203 struct redir_struct {
204         struct redir_struct *next;  /* pointer to the next redirect in the list */
205         redir_type type;            /* type of redirection */
206         int fd;                     /* file descriptor being redirected */
207         int dup;                    /* -1, or file descriptor being duplicated */
208         glob_t word;                /* *word.gl_pathv is the filename */
209 };
210
211 struct child_prog {
212         pid_t pid;                  /* 0 if exited */
213         char **argv;                /* program name and arguments */
214         struct pipe *group;         /* if non-NULL, first in group or subshell */
215         int subshell;               /* flag, non-zero if group must be forked */
216         struct redir_struct *redirects; /* I/O redirections */
217         glob_t glob_result;         /* result of parameter globbing */
218         int is_stopped;             /* is the program currently running? */
219         struct pipe *family;        /* pointer back to the child's parent pipe */
220         int sp;                     /* number of SPECIAL_VAR_SYMBOL */
221         int type;
222 };
223
224 struct pipe {
225         struct pipe *next;
226         int num_progs;              /* total number of programs in job */
227         int running_progs;          /* number of programs running (not exited) */
228         char *cmdbuf;               /* buffer various argv's point into */
229 #if ENABLE_HUSH_JOB
230         int jobid;                  /* job number */
231         char *cmdtext;              /* name of job */
232         pid_t pgrp;                 /* process group ID for the job */
233 #endif
234         struct child_prog *progs;   /* array of commands in pipe */
235         int stopped_progs;          /* number of programs alive, but stopped */
236         int job_context;            /* bitmask defining current context */
237         pipe_style followup;        /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
238         reserved_style r_mode;      /* supports if, for, while, until */
239 };
240
241 struct close_me {
242         struct close_me *next;
243         int fd;
244 };
245
246 struct variables {
247         struct variables *next;
248         const char *name;
249         const char *value;
250         int flg_export;
251         int flg_read_only;
252 };
253
254 /* globals, connect us to the outside world
255  * the first three support $?, $#, and $1 */
256 static char **global_argv;
257 static int global_argc;
258 static int last_return_code;
259 extern char **environ; /* This is in <unistd.h>, but protected with __USE_GNU */
260
261 /* "globals" within this file */
262 static const char *ifs;
263 static unsigned char map[256];
264 static int fake_mode;
265 static struct close_me *close_me_head;
266 static const char *cwd;
267 static unsigned last_bg_pid;
268 #if !ENABLE_HUSH_INTERACTIVE
269 enum { interactive_fd = 0 };
270 #else
271 /* 'interactive_fd' is a fd# open to ctty, if we have one
272  * _AND_ if we decided to mess with job control */
273 static int interactive_fd;
274 #if ENABLE_HUSH_JOB
275 static pid_t saved_task_pgrp;
276 static pid_t saved_tty_pgrp;
277 static int last_jobid;
278 static struct pipe *job_list;
279 #endif
280 static const char *PS1;
281 static const char *PS2;
282 #endif
283
284 #define HUSH_VER_STR "0.02"
285 static struct variables shell_ver = { NULL, "HUSH_VERSION", HUSH_VER_STR, 1, 1 };
286 static struct variables *top_vars = &shell_ver;
287
288 #define B_CHUNK  100
289 #define B_NOSPAC 1
290
291 typedef struct {
292         char *data;
293         int length;
294         int maxlen;
295         int quote;
296         int nonnull;
297 } o_string;
298 #define NULL_O_STRING {NULL,0,0,0,0}
299 /* used for initialization:
300         o_string foo = NULL_O_STRING; */
301
302 /* I can almost use ordinary FILE *.  Is open_memstream() universally
303  * available?  Where is it documented? */
304 struct in_str {
305         const char *p;
306         char peek_buf[2];
307 #if ENABLE_HUSH_INTERACTIVE
308         int __promptme;
309         int promptmode;
310 #endif
311         FILE *file;
312         int (*get) (struct in_str *);
313         int (*peek) (struct in_str *);
314 };
315 #define b_getch(input) ((input)->get(input))
316 #define b_peek(input) ((input)->peek(input))
317
318 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
319
320 struct built_in_command {
321         const char *cmd;                /* name */
322         const char *descr;              /* description */
323         int (*function) (char **argv);  /* function ptr */
324 };
325
326 static void __syntax(int line)
327 {
328         bb_error_msg("syntax error hush.c:%d", line);
329 }
330 #define syntax() __syntax(__LINE__)
331
332 /* Index of subroutines: */
333 /*   function prototypes for builtins */
334 static int builtin_cd(char **argv);
335 static int builtin_env(char **argv);
336 static int builtin_eval(char **argv);
337 static int builtin_exec(char **argv);
338 static int builtin_exit(char **argv);
339 static int builtin_export(char **argv);
340 #if ENABLE_HUSH_JOB
341 static int builtin_fg_bg(char **argv);
342 static int builtin_jobs(char **argv);
343 #endif
344 static int builtin_help(char **argv);
345 static int builtin_pwd(char **argv);
346 static int builtin_read(char **argv);
347 static int builtin_set(char **argv);
348 static int builtin_shift(char **argv);
349 static int builtin_source(char **argv);
350 static int builtin_umask(char **argv);
351 static int builtin_unset(char **argv);
352 static int builtin_not_written(char **argv);
353 /*   o_string manipulation: */
354 static int b_check_space(o_string *o, int len);
355 static int b_addchr(o_string *o, int ch);
356 static void b_reset(o_string *o);
357 static int b_addqchr(o_string *o, int ch, int quote);
358 static int b_adduint(o_string *o, unsigned i);
359 /*  in_str manipulations: */
360 static int static_get(struct in_str *i);
361 static int static_peek(struct in_str *i);
362 static int file_get(struct in_str *i);
363 static int file_peek(struct in_str *i);
364 static void setup_file_in_str(struct in_str *i, FILE *f);
365 static void setup_string_in_str(struct in_str *i, const char *s);
366 /*  close_me manipulations: */
367 static void mark_open(int fd);
368 static void mark_closed(int fd);
369 static void close_all(void);
370 /*  "run" the final data structures: */
371 static int free_pipe_list(struct pipe *head, int indent);
372 static int free_pipe(struct pipe *pi, int indent);
373 /*  really run the final data structures: */
374 static int setup_redirects(struct child_prog *prog, int squirrel[]);
375 static int run_list_real(struct pipe *pi);
376 static void pseudo_exec_argv(char **argv) ATTRIBUTE_NORETURN;
377 static void pseudo_exec(struct child_prog *child) ATTRIBUTE_NORETURN;
378 static int run_pipe_real(struct pipe *pi);
379 /*   extended glob support: */
380 static int globhack(const char *src, int flags, glob_t *pglob);
381 static int glob_needed(const char *s);
382 static int xglob(o_string *dest, int flags, glob_t *pglob);
383 /*   variable assignment: */
384 static int is_assignment(const char *s);
385 /*   data structure manipulation: */
386 static int setup_redirect(struct p_context *ctx, int fd, redir_type style, struct in_str *input);
387 static void initialize_context(struct p_context *ctx);
388 static int done_word(o_string *dest, struct p_context *ctx);
389 static int done_command(struct p_context *ctx);
390 static int done_pipe(struct p_context *ctx, pipe_style type);
391 /*   primary string parsing: */
392 static int redirect_dup_num(struct in_str *input);
393 static int redirect_opt_num(o_string *o);
394 static int process_command_subs(o_string *dest, struct p_context *ctx, struct in_str *input, int subst_end);
395 static int parse_group(o_string *dest, struct p_context *ctx, struct in_str *input, int ch);
396 static const char *lookup_param(const char *src);
397 static char *make_string(char **inp);
398 static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input);
399 static int parse_string(o_string *dest, struct p_context *ctx, const char *src);
400 static int parse_stream(o_string *dest, struct p_context *ctx, struct in_str *input0, int end_trigger);
401 /*   setup: */
402 static int parse_stream_outer(struct in_str *inp, int flag);
403 static int parse_string_outer(const char *s, int flag);
404 static int parse_file_outer(FILE *f);
405 /*   job management: */
406 static int checkjobs(struct pipe* fg_pipe);
407 #if ENABLE_HUSH_JOB
408 static int checkjobs_and_fg_shell(struct pipe* fg_pipe);
409 static void insert_bg_job(struct pipe *pi);
410 static void remove_bg_job(struct pipe *pi);
411 static void delete_finished_bg_job(struct pipe *pi);
412 #else
413 int checkjobs_and_fg_shell(struct pipe* fg_pipe); /* never called */
414 #endif
415 /*     local variable support */
416 static char **make_list_in(char **inp, char *name);
417 static char *insert_var_value(char *inp);
418 static const char *get_local_var(const char *var);
419 static int set_local_var(const char *s, int flg_export);
420 static void unset_local_var(const char *name);
421
422 /* Table of built-in functions.  They can be forked or not, depending on
423  * context: within pipes, they fork.  As simple commands, they do not.
424  * When used in non-forking context, they can change global variables
425  * in the parent shell process.  If forked, of course they cannot.
426  * For example, 'unset foo | whatever' will parse and run, but foo will
427  * still be set at the end. */
428 static const struct built_in_command bltins[] = {
429 #if ENABLE_HUSH_JOB
430         { "bg", "Resume a job in the background", builtin_fg_bg },
431 #endif
432         { "break", "Exit for, while or until loop", builtin_not_written },
433         { "cd", "Change working directory", builtin_cd },
434         { "continue", "Continue for, while or until loop", builtin_not_written },
435         { "env", "Print all environment variables", builtin_env },
436         { "eval", "Construct and run shell command", builtin_eval },
437         { "exec", "Exec command, replacing this shell with the exec'd process",
438                 builtin_exec },
439         { "exit", "Exit from shell()", builtin_exit },
440         { "export", "Set environment variable", builtin_export },
441 #if ENABLE_HUSH_JOB
442         { "fg", "Bring job into the foreground", builtin_fg_bg },
443         { "jobs", "Lists the active jobs", builtin_jobs },
444 #endif
445         { "pwd", "Print current directory", builtin_pwd },
446         { "read", "Input environment variable", builtin_read },
447         { "return", "Return from a function", builtin_not_written },
448         { "set", "Set/unset shell local variables", builtin_set },
449         { "shift", "Shift positional parameters", builtin_shift },
450         { "trap", "Trap signals", builtin_not_written },
451         { "ulimit","Controls resource limits", builtin_not_written },
452         { "umask","Sets file creation mask", builtin_umask },
453         { "unset", "Unset environment variable", builtin_unset },
454         { ".", "Source-in and run commands in a file", builtin_source },
455         { "help", "List shell built-in commands", builtin_help },
456         { NULL, NULL, NULL }
457 };
458
459 #if ENABLE_HUSH_JOB
460
461 #if ENABLE_FEATURE_SH_STANDALONE
462 /* move to libbb? */
463 static void signal_SA_RESTART(int sig, void (*handler)(int))
464 {
465         struct sigaction sa;
466         sa.sa_handler = handler;
467         sa.sa_flags = SA_RESTART;
468         sigemptyset(&sa.sa_mask);
469         sigaction(sig, &sa, NULL);
470 }
471 #endif
472
473 /* Signals are grouped, we handle them in batches */
474 static void set_fatal_sighandler(void (*handler)(int))
475 {
476         signal(SIGILL , handler);
477         signal(SIGTRAP, handler);
478         signal(SIGABRT, handler);
479         signal(SIGFPE , handler);
480         signal(SIGBUS , handler);
481         signal(SIGSEGV, handler);
482         /* bash 3.2 seems to handle these just like 'fatal' ones */
483         signal(SIGHUP , handler);
484         signal(SIGPIPE, handler);
485         signal(SIGALRM, handler);
486 }
487 static void set_jobctrl_sighandler(void (*handler)(int))
488 {
489         signal(SIGTSTP, handler);
490         signal(SIGTTIN, handler);
491         signal(SIGTTOU, handler);
492 }
493 static void set_misc_sighandler(void (*handler)(int))
494 {
495         signal(SIGINT , handler);
496         signal(SIGQUIT, handler);
497         signal(SIGTERM, handler);
498 }
499 /* SIGCHLD is special and handled separately */
500
501 #if ENABLE_FEATURE_SH_STANDALONE
502 static void set_every_sighandler(void (*handler)(int))
503 {
504         set_fatal_sighandler(handler);
505         set_jobctrl_sighandler(handler);
506         set_misc_sighandler(handler);
507         signal(SIGCHLD, handler);
508 }
509
510 static struct pipe *nofork_pipe;
511 struct nofork_save_area nofork_save;
512 static sigjmp_buf nofork_jb;
513
514 static void handler_ctrl_c(int sig)
515 {
516         debug_printf_jobs("got sig %d\n", sig);
517 // as usual we can have all kinds of nasty problems with leaked malloc data here
518         siglongjmp(nofork_jb, 1);
519 }
520
521 static void handler_ctrl_z(int sig)
522 {
523         pid_t pid;
524
525         debug_printf_jobs("got tty sig %d\n", sig);
526         pid = fork();
527         if (pid < 0) /* can't fork. Pretend there were no Ctrl-Z */
528                 return;
529         debug_printf_jobs("bg'ing nofork\n");
530         nofork_save.saved = 0; /* flag the fact that Ctrl-Z was handled */
531         nofork_pipe->running_progs = 1;
532         nofork_pipe->stopped_progs = 0;
533         if (!pid) { /* child */
534                 debug_printf_jobs("setting pgrp for child\n");
535                 setpgrp();
536                 set_every_sighandler(SIG_DFL);
537                 raise(SIGTSTP); /* resend TSTP so that child will be stopped */
538                 debug_printf_jobs("returning to child\n");
539                 /* return to nofork, it will eventually exit now,
540                  * not return back to shell */
541                 return;
542         }
543         /* parent */
544         /* finish filling up pipe info */
545         nofork_pipe->pgrp = pid; /* child is in its own pgrp */
546         nofork_pipe->progs[0].pid = pid;
547         nofork_pipe->running_progs = 1;
548         nofork_pipe->stopped_progs = 0;
549         /* parent needs to longjmp out of running nofork.
550          * we will "return" exitcode 0, with child put in background */
551 // as usual we can have all kinds of nasty problems with leaked malloc data here
552         siglongjmp(nofork_jb, 1);
553 }
554
555 #endif
556
557 /* Restores tty foreground process group, and exits.
558  * May be called as signal handler for fatal signal
559  * (will faithfully resend signal to itself, producing correct exit state)
560  * or called directly with -EXITCODE.
561  * We also call it if xfunc is exiting. */
562 static void sigexit(int sig) ATTRIBUTE_NORETURN;
563 static void sigexit(int sig)
564 {
565         sigset_t block_all;
566
567         /* Disable all signals: job control, SIGPIPE, etc. */
568         sigfillset(&block_all);
569         sigprocmask(SIG_SETMASK, &block_all, NULL);
570
571         if (interactive_fd)
572                 tcsetpgrp(interactive_fd, saved_tty_pgrp);
573
574         /* Not a signal, just exit */
575         if (sig <= 0)
576                 _exit(- sig);
577
578         /* Enable only this sig and kill ourself with it */
579         signal(sig, SIG_DFL);
580         sigdelset(&block_all, sig);
581         sigprocmask(SIG_SETMASK, &block_all, NULL);
582         raise(sig);
583         _exit(1); /* Should not reach it */
584 }
585
586 /* Restores tty foreground process group, and exits. */
587 static void hush_exit(int exitcode) ATTRIBUTE_NORETURN;
588 static void hush_exit(int exitcode)
589 {
590         fflush(NULL); /* flush all streams */
591         sigexit(- (exitcode & 0xff));
592 }
593
594 #else /* !JOB */
595
596 #define set_fatal_sighandler(handler)   ((void)0)
597 #define set_jobctrl_sighandler(handler) ((void)0)
598 #define set_misc_sighandler(handler)    ((void)0)
599 #define hush_exit(e)                    exit(e)
600
601 #endif /* JOB */
602
603
604 static const char *set_cwd(void)
605 {
606         if (cwd == bb_msg_unknown)
607                 cwd = NULL;     /* xrealloc_getcwd_or_warn(arg) calls free(arg)! */
608         cwd = xrealloc_getcwd_or_warn((char *)cwd);
609         if (!cwd)
610                 cwd = bb_msg_unknown;
611         return cwd;
612 }
613
614 /* built-in 'eval' handler */
615 static int builtin_eval(char **argv)
616 {
617         char *str = NULL;
618         int rcode = EXIT_SUCCESS;
619
620         if (argv[1]) {
621                 str = make_string(argv + 1);
622                 parse_string_outer(str, FLAG_EXIT_FROM_LOOP |
623                                         FLAG_PARSE_SEMICOLON);
624                 free(str);
625                 rcode = last_return_code;
626         }
627         return rcode;
628 }
629
630 /* built-in 'cd <path>' handler */
631 static int builtin_cd(char **argv)
632 {
633         char *newdir;
634         if (argv[1] == NULL)
635                 newdir = getenv("HOME");
636         else
637                 newdir = argv[1];
638         if (chdir(newdir)) {
639                 printf("cd: %s: %s\n", newdir, strerror(errno));
640                 return EXIT_FAILURE;
641         }
642         set_cwd();
643         return EXIT_SUCCESS;
644 }
645
646 /* built-in 'env' handler */
647 static int builtin_env(char **argv ATTRIBUTE_UNUSED)
648 {
649 /* TODO: call env applet's code instead */
650         char **e = environ;
651         if (e == NULL)
652                 return EXIT_FAILURE;
653         while (*e) {
654                 puts(*e++);
655         }
656         return EXIT_SUCCESS;
657 }
658
659 /* built-in 'exec' handler */
660 static int builtin_exec(char **argv)
661 {
662         if (argv[1] == NULL)
663                 return EXIT_SUCCESS;   /* Really? */
664         pseudo_exec_argv(argv + 1);
665         /* never returns */
666 }
667
668 /* built-in 'exit' handler */
669 static int builtin_exit(char **argv)
670 {
671 // TODO: bash does it ONLY on top-level sh exit (+interacive only?)
672         //puts("exit"); /* bash does it */
673
674         if (argv[1] == NULL)
675                 hush_exit(last_return_code);
676         /* mimic bash: exit 123abc == exit 255 + error msg */
677         xfunc_error_retval = 255;
678         /* bash: exit -2 == exit 254, no error msg */
679         hush_exit(xatoi(argv[1]));
680 }
681
682 /* built-in 'export VAR=value' handler */
683 static int builtin_export(char **argv)
684 {
685         int res = 0;
686         char *name = argv[1];
687
688         if (name == NULL) {
689                 return builtin_env(argv);
690         }
691
692         name = strdup(name);
693
694         if (name) {
695                 const char *value = strchr(name, '=');
696
697                 if (!value) {
698                         char *tmp;
699                         /* They are exporting something without an =VALUE */
700
701                         value = get_local_var(name);
702                         if (value) {
703                                 size_t ln = strlen(name);
704
705                                 tmp = realloc(name, ln+strlen(value)+2);
706                                 if (tmp == NULL)
707                                         res = -1;
708                                 else {
709                                         sprintf(tmp+ln, "=%s", value);
710                                         name = tmp;
711                                 }
712                         } else {
713                                 /* bash does not return an error when trying to export
714                                  * an undefined variable.  Do likewise. */
715                                 res = 1;
716                         }
717                 }
718         }
719         if (res < 0)
720                 bb_perror_msg("export");
721         else if (res == 0)
722                 res = set_local_var(name, 1);
723         else
724                 res = 0;
725         free(name);
726         return res;
727 }
728
729 #if ENABLE_HUSH_JOB
730 /* built-in 'fg' and 'bg' handler */
731 static int builtin_fg_bg(char **argv)
732 {
733         int i, jobnum;
734         struct pipe *pi;
735
736         if (!interactive_fd)
737                 return EXIT_FAILURE;
738         /* If they gave us no args, assume they want the last backgrounded task */
739         if (!argv[1]) {
740                 for (pi = job_list; pi; pi = pi->next) {
741                         if (pi->jobid == last_jobid) {
742                                 goto found;
743                         }
744                 }
745                 bb_error_msg("%s: no current job", argv[0]);
746                 return EXIT_FAILURE;
747         }
748         if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
749                 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
750                 return EXIT_FAILURE;
751         }
752         for (pi = job_list; pi; pi = pi->next) {
753                 if (pi->jobid == jobnum) {
754                         goto found;
755                 }
756         }
757         bb_error_msg("%s: %d: no such job", argv[0], jobnum);
758         return EXIT_FAILURE;
759  found:
760         // TODO: bash prints a string representation
761         // of job being foregrounded (like "sleep 1 | cat")
762         if (*argv[0] == 'f') {
763                 /* Put the job into the foreground.  */
764                 tcsetpgrp(interactive_fd, pi->pgrp);
765         }
766
767         /* Restart the processes in the job */
768         debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_progs, pi->pgrp);
769         for (i = 0; i < pi->num_progs; i++) {
770                 debug_printf_jobs("reviving pid %d\n", pi->progs[i].pid);
771                 pi->progs[i].is_stopped = 0;
772         }
773         pi->stopped_progs = 0;
774
775         i = kill(- pi->pgrp, SIGCONT);
776         if (i < 0) {
777                 if (errno == ESRCH) {
778                         delete_finished_bg_job(pi);
779                         return EXIT_SUCCESS;
780                 } else {
781                         bb_perror_msg("kill (SIGCONT)");
782                 }
783         }
784
785         if (*argv[0] == 'f') {
786                 remove_bg_job(pi);
787                 return checkjobs_and_fg_shell(pi);
788         }
789         return EXIT_SUCCESS;
790 }
791 #endif
792
793 /* built-in 'help' handler */
794 static int builtin_help(char **argv ATTRIBUTE_UNUSED)
795 {
796         const struct built_in_command *x;
797
798         printf("\nBuilt-in commands:\n");
799         printf("-------------------\n");
800         for (x = bltins; x->cmd; x++) {
801                 if (x->descr == NULL)
802                         continue;
803                 printf("%s\t%s\n", x->cmd, x->descr);
804         }
805         printf("\n\n");
806         return EXIT_SUCCESS;
807 }
808
809 #if ENABLE_HUSH_JOB
810 /* built-in 'jobs' handler */
811 static int builtin_jobs(char **argv ATTRIBUTE_UNUSED)
812 {
813         struct pipe *job;
814         const char *status_string;
815
816         for (job = job_list; job; job = job->next) {
817                 if (job->running_progs == job->stopped_progs)
818                         status_string = "Stopped";
819                 else
820                         status_string = "Running";
821
822                 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
823         }
824         return EXIT_SUCCESS;
825 }
826 #endif
827
828 /* built-in 'pwd' handler */
829 static int builtin_pwd(char **argv ATTRIBUTE_UNUSED)
830 {
831         puts(set_cwd());
832         return EXIT_SUCCESS;
833 }
834
835 /* built-in 'read VAR' handler */
836 static int builtin_read(char **argv)
837 {
838         int res;
839
840         if (argv[1]) {
841                 char string[BUFSIZ];
842                 char *var = NULL;
843
844                 string[0] = '\0';  /* In case stdin has only EOF */
845                 /* read string */
846                 fgets(string, sizeof(string), stdin);
847                 chomp(string);
848                 var = malloc(strlen(argv[1]) + strlen(string) + 2);
849                 if (var) {
850                         sprintf(var, "%s=%s", argv[1], string);
851                         res = set_local_var(var, 0);
852                 } else
853                         res = -1;
854                 if (res)
855                         bb_perror_msg("read");
856                 free(var);      /* So not move up to avoid breaking errno */
857                 return res;
858         }
859         do res = getchar(); while (res != '\n' && res != EOF);
860         return 0;
861 }
862
863 /* built-in 'set VAR=value' handler */
864 static int builtin_set(char **argv)
865 {
866         char *temp = argv[1];
867         struct variables *e;
868
869         if (temp == NULL)
870                 for (e = top_vars; e; e = e->next)
871                         printf("%s=%s\n", e->name, e->value);
872         else
873                 set_local_var(temp, 0);
874
875         return EXIT_SUCCESS;
876 }
877
878
879 /* Built-in 'shift' handler */
880 static int builtin_shift(char **argv)
881 {
882         int n = 1;
883         if (argv[1]) {
884                 n = atoi(argv[1]);
885         }
886         if (n >= 0 && n < global_argc) {
887                 /* XXX This probably breaks $0 */
888                 global_argc -= n;
889                 global_argv += n;
890                 return EXIT_SUCCESS;
891         }
892         return EXIT_FAILURE;
893 }
894
895 /* Built-in '.' handler (read-in and execute commands from file) */
896 static int builtin_source(char **argv)
897 {
898         FILE *input;
899         int status;
900
901         if (argv[1] == NULL)
902                 return EXIT_FAILURE;
903
904         /* XXX search through $PATH is missing */
905         input = fopen(argv[1], "r");
906         if (!input) {
907                 bb_error_msg("cannot open '%s'", argv[1]);
908                 return EXIT_FAILURE;
909         }
910
911         /* Now run the file */
912         /* XXX argv and argc are broken; need to save old global_argv
913          * (pointer only is OK!) on this stack frame,
914          * set global_argv=argv+1, recurse, and restore. */
915         mark_open(fileno(input));
916         status = parse_file_outer(input);
917         mark_closed(fileno(input));
918         fclose(input);
919         return status;
920 }
921
922 static int builtin_umask(char **argv)
923 {
924         mode_t new_umask;
925         const char *arg = argv[1];
926         char *end;
927         if (arg) {
928                 new_umask = strtoul(arg, &end, 8);
929                 if (*end != '\0' || end == arg) {
930                         return EXIT_FAILURE;
931                 }
932         } else {
933                 new_umask = umask(0);
934                 printf("%.3o\n", (unsigned) new_umask);
935         }
936         umask(new_umask);
937         return EXIT_SUCCESS;
938 }
939
940 /* built-in 'unset VAR' handler */
941 static int builtin_unset(char **argv)
942 {
943         /* bash returned already true */
944         unset_local_var(argv[1]);
945         return EXIT_SUCCESS;
946 }
947
948 static int builtin_not_written(char **argv)
949 {
950         printf("builtin_%s not written\n", argv[0]);
951         return EXIT_FAILURE;
952 }
953
954 static int b_check_space(o_string *o, int len)
955 {
956         /* It would be easy to drop a more restrictive policy
957          * in here, such as setting a maximum string length */
958         if (o->length + len > o->maxlen) {
959                 char *old_data = o->data;
960                 /* assert(data == NULL || o->maxlen != 0); */
961                 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
962                 o->data = realloc(o->data, 1 + o->maxlen);
963                 if (o->data == NULL) {
964                         free(old_data);
965                 }
966         }
967         return o->data == NULL;
968 }
969
970 static int b_addchr(o_string *o, int ch)
971 {
972         debug_printf("b_addchr: %c %d %p\n", ch, o->length, o);
973         if (b_check_space(o, 1))
974                 return B_NOSPAC;
975         o->data[o->length] = ch;
976         o->length++;
977         o->data[o->length] = '\0';
978         return 0;
979 }
980
981 static void b_reset(o_string *o)
982 {
983         o->length = 0;
984         o->nonnull = 0;
985         if (o->data != NULL)
986                 *o->data = '\0';
987 }
988
989 static void b_free(o_string *o)
990 {
991         b_reset(o);
992         free(o->data);
993         o->data = NULL;
994         o->maxlen = 0;
995 }
996
997 /* My analysis of quoting semantics tells me that state information
998  * is associated with a destination, not a source.
999  */
1000 static int b_addqchr(o_string *o, int ch, int quote)
1001 {
1002         if (quote && strchr("*?[\\", ch)) {
1003                 int rc;
1004                 rc = b_addchr(o, '\\');
1005                 if (rc)
1006                         return rc;
1007         }
1008         return b_addchr(o, ch);
1009 }
1010
1011 static int b_adduint(o_string *o, unsigned i)
1012 {
1013         int r;
1014         char buf[sizeof(unsigned)*3 + 1];
1015         char *p = buf;
1016         *(utoa_to_buf(i, buf, sizeof(buf))) = '\0';
1017         /* no escape checking necessary */
1018         do r = b_addchr(o, *p++); while (r == 0 && *p);
1019         return r;
1020 }
1021
1022 static int static_get(struct in_str *i)
1023 {
1024         int ch = *i->p++;
1025         if (ch == '\0') return EOF;
1026         return ch;
1027 }
1028
1029 static int static_peek(struct in_str *i)
1030 {
1031         return *i->p;
1032 }
1033
1034 #if ENABLE_HUSH_INTERACTIVE
1035 static void cmdedit_set_initial_prompt(void)
1036 {
1037 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1038         PS1 = NULL;
1039 #else
1040         PS1 = getenv("PS1");
1041         if (PS1 == NULL)
1042                 PS1 = "\\w \\$ ";
1043 #endif
1044 }
1045
1046 static const char* setup_prompt_string(int promptmode)
1047 {
1048         const char *prompt_str;
1049         debug_printf("setup_prompt_string %d ", promptmode);
1050 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1051         /* Set up the prompt */
1052         if (promptmode == 1) {
1053                 char *ns;
1054                 free((char*)PS1);
1055                 ns = xmalloc(strlen(cwd)+4);
1056                 sprintf(ns, "%s %s", cwd, (geteuid() != 0) ? "$ " : "# ");
1057                 prompt_str = ns;
1058                 PS1 = ns;
1059         } else {
1060                 prompt_str = PS2;
1061         }
1062 #else
1063         prompt_str = (promptmode == 1) ? PS1 : PS2;
1064 #endif
1065         debug_printf("result %s\n", prompt_str);
1066         return prompt_str;
1067 }
1068 #endif
1069
1070 #if ENABLE_FEATURE_EDITING
1071 static line_input_t *line_input_state;
1072 #endif
1073
1074 #if ENABLE_HUSH_INTERACTIVE
1075 static int get_user_input(struct in_str *i)
1076 {
1077         static char the_command[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
1078
1079         int r;
1080         const char *prompt_str;
1081         prompt_str = setup_prompt_string(i->promptmode);
1082 #if ENABLE_FEATURE_EDITING
1083         /*
1084          ** enable command line editing only while a command line
1085          ** is actually being read; otherwise, we'll end up bequeathing
1086          ** atexit() handlers and other unwanted stuff to our
1087          ** child processes (rob@sysgo.de)
1088          */
1089         r = read_line_input(prompt_str, the_command, BUFSIZ, line_input_state);
1090 #else
1091         fputs(prompt_str, stdout);
1092         fflush(stdout);
1093         the_command[0] = r = fgetc(i->file);
1094         the_command[1] = '\0';
1095 #endif
1096         fflush(stdout);
1097         i->p = the_command;
1098         return r; /* < 0 == EOF. Not meaningful otherwise */
1099 }
1100 #endif
1101
1102 /* This is the magic location that prints prompts
1103  * and gets data back from the user */
1104 static int file_get(struct in_str *i)
1105 {
1106         int ch;
1107
1108         ch = 0;
1109         /* If there is data waiting, eat it up */
1110         if (i->p && *i->p) {
1111                 ch = *i->p++;
1112         } else {
1113                 /* need to double check i->file because we might be doing something
1114                  * more complicated by now, like sourcing or substituting. */
1115 #if ENABLE_HUSH_INTERACTIVE
1116                 if (interactive_fd && i->__promptme && i->file == stdin) {
1117                         while (!i->p || !(interactive_fd && i->p[0])) {
1118                                 if (get_user_input(i) < 0)
1119                                         return EOF;
1120                         }
1121                         i->promptmode = 2;
1122                         i->__promptme = 0;
1123                         if (i->p && *i->p) {
1124                                 ch = *i->p++;
1125                         }
1126                 } else
1127 #endif
1128                 {
1129                         ch = fgetc(i->file);
1130                 }
1131                 debug_printf("b_getch: got a %d\n", ch);
1132         }
1133 #if ENABLE_HUSH_INTERACTIVE
1134         if (ch == '\n')
1135                 i->__promptme = 1;
1136 #endif
1137         return ch;
1138 }
1139
1140 /* All the callers guarantee this routine will never be
1141  * used right after a newline, so prompting is not needed.
1142  */
1143 static int file_peek(struct in_str *i)
1144 {
1145         if (i->p && *i->p) {
1146                 return *i->p;
1147         }
1148         i->peek_buf[0] = fgetc(i->file);
1149         i->peek_buf[1] = '\0';
1150         i->p = i->peek_buf;
1151         debug_printf("b_peek: got a %d\n", *i->p);
1152         return *i->p;
1153 }
1154
1155 static void setup_file_in_str(struct in_str *i, FILE *f)
1156 {
1157         i->peek = file_peek;
1158         i->get = file_get;
1159 #if ENABLE_HUSH_INTERACTIVE
1160         i->__promptme = 1;
1161         i->promptmode = 1;
1162 #endif
1163         i->file = f;
1164         i->p = NULL;
1165 }
1166
1167 static void setup_string_in_str(struct in_str *i, const char *s)
1168 {
1169         i->peek = static_peek;
1170         i->get = static_get;
1171 #if ENABLE_HUSH_INTERACTIVE
1172         i->__promptme = 1;
1173         i->promptmode = 1;
1174 #endif
1175         i->p = s;
1176 }
1177
1178 static void mark_open(int fd)
1179 {
1180         struct close_me *new = xmalloc(sizeof(struct close_me));
1181         new->fd = fd;
1182         new->next = close_me_head;
1183         close_me_head = new;
1184 }
1185
1186 static void mark_closed(int fd)
1187 {
1188         struct close_me *tmp;
1189         if (close_me_head == NULL || close_me_head->fd != fd)
1190                 bb_error_msg_and_die("corrupt close_me");
1191         tmp = close_me_head;
1192         close_me_head = close_me_head->next;
1193         free(tmp);
1194 }
1195
1196 static void close_all(void)
1197 {
1198         struct close_me *c;
1199         for (c = close_me_head; c; c = c->next) {
1200                 close(c->fd);
1201         }
1202         close_me_head = NULL;
1203 }
1204
1205 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
1206  * and stderr if they are redirected. */
1207 static int setup_redirects(struct child_prog *prog, int squirrel[])
1208 {
1209         int openfd, mode;
1210         struct redir_struct *redir;
1211
1212         for (redir = prog->redirects; redir; redir = redir->next) {
1213                 if (redir->dup == -1 && redir->word.gl_pathv == NULL) {
1214                         /* something went wrong in the parse.  Pretend it didn't happen */
1215                         continue;
1216                 }
1217                 if (redir->dup == -1) {
1218                         mode = redir_table[redir->type].mode;
1219                         openfd = open_or_warn(redir->word.gl_pathv[0], mode);
1220                         if (openfd < 0) {
1221                         /* this could get lost if stderr has been redirected, but
1222                            bash and ash both lose it as well (though zsh doesn't!) */
1223                                 return 1;
1224                         }
1225                 } else {
1226                         openfd = redir->dup;
1227                 }
1228
1229                 if (openfd != redir->fd) {
1230                         if (squirrel && redir->fd < 3) {
1231                                 squirrel[redir->fd] = dup(redir->fd);
1232                         }
1233                         if (openfd == -3) {
1234                                 close(openfd);
1235                         } else {
1236                                 dup2(openfd, redir->fd);
1237                                 if (redir->dup == -1)
1238                                         close(openfd);
1239                         }
1240                 }
1241         }
1242         return 0;
1243 }
1244
1245 static void restore_redirects(int squirrel[])
1246 {
1247         int i, fd;
1248         for (i = 0; i < 3; i++) {
1249                 fd = squirrel[i];
1250                 if (fd != -1) {
1251                         /* No error checking.  I sure wouldn't know what
1252                          * to do with an error if I found one! */
1253                         dup2(fd, i);
1254                         close(fd);
1255                 }
1256         }
1257 }
1258
1259 /* never returns */
1260 /* XXX no exit() here.  If you don't exec, use _exit instead.
1261  * The at_exit handlers apparently confuse the calling process,
1262  * in particular stdin handling.  Not sure why? -- because of vfork! (vda) */
1263 static void pseudo_exec_argv(char **argv)
1264 {
1265         int i, rcode;
1266         char *p;
1267         const struct built_in_command *x;
1268
1269         for (i = 0; is_assignment(argv[i]); i++) {
1270                 debug_printf("pid %d environment modification: %s\n",
1271                                 getpid(), argv[i]);
1272         // FIXME: vfork case??
1273                 p = insert_var_value(argv[i]);
1274                 putenv(strdup(p));
1275                 if (p != argv[i])
1276                         free(p);
1277         }
1278         argv += i;
1279         /* If a variable is assigned in a forest, and nobody listens,
1280          * was it ever really set?
1281          */
1282         if (argv[0] == NULL) {
1283                 _exit(EXIT_SUCCESS);
1284         }
1285
1286         /*
1287          * Check if the command matches any of the builtins.
1288          * Depending on context, this might be redundant.  But it's
1289          * easier to waste a few CPU cycles than it is to figure out
1290          * if this is one of those cases.
1291          */
1292         for (x = bltins; x->cmd; x++) {
1293                 if (strcmp(argv[0], x->cmd) == 0) {
1294                         debug_printf("builtin exec %s\n", argv[0]);
1295                         rcode = x->function(argv);
1296                         fflush(stdout);
1297                         _exit(rcode);
1298                 }
1299         }
1300
1301         /* Check if the command matches any busybox internal commands
1302          * ("applets") here.
1303          * FIXME: This feature is not 100% safe, since
1304          * BusyBox is not fully reentrant, so we have no guarantee the things
1305          * from the .bss are still zeroed, or that things from .data are still
1306          * at their defaults.  We could exec ourself from /proc/self/exe, but I
1307          * really dislike relying on /proc for things.  We could exec ourself
1308          * from global_argv[0], but if we are in a chroot, we may not be able
1309          * to find ourself... */
1310 #if ENABLE_FEATURE_SH_STANDALONE
1311         debug_printf("running applet %s\n", argv[0]);
1312         run_applet_and_exit(argv[0], argv);
1313 // is it ok that run_applet_and_exit() does exit(), not _exit()?
1314 // NB: IIRC on NOMMU we are after _vfork_, not fork!
1315 #endif
1316         debug_printf("exec of %s\n", argv[0]);
1317         execvp(argv[0], argv);
1318         bb_perror_msg("cannot exec '%s'", argv[0]);
1319         _exit(1);
1320 }
1321
1322 static void pseudo_exec(struct child_prog *child)
1323 {
1324         int rcode;
1325
1326         if (child->argv) {
1327                 pseudo_exec_argv(child->argv);
1328         }
1329
1330         if (child->group) {
1331         // FIXME: do not modify globals! Think vfork!
1332 #if ENABLE_HUSH_INTERACTIVE
1333                 interactive_fd = 0;    /* crucial!!!! */
1334 #endif
1335                 debug_printf_exec("pseudo_exec: run_list_real\n");
1336                 rcode = run_list_real(child->group);
1337                 /* OK to leak memory by not calling free_pipe_list,
1338                  * since this process is about to exit */
1339                 _exit(rcode);
1340         }
1341
1342         /* Can happen.  See what bash does with ">foo" by itself. */
1343         debug_printf("trying to pseudo_exec null command\n");
1344         _exit(EXIT_SUCCESS);
1345 }
1346
1347 #if ENABLE_HUSH_JOB
1348 static const char *get_cmdtext(struct pipe *pi)
1349 {
1350         char **argv;
1351         char *p;
1352         int len;
1353
1354         /* This is subtle. ->cmdtext is created only on first backgrounding.
1355          * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
1356          * On subsequent bg argv can be trashed, but we won't use it */
1357         if (pi->cmdtext)
1358                 return pi->cmdtext;
1359         argv = pi->progs[0].argv;
1360         if (!argv || !argv[0])
1361                 return (pi->cmdtext = xzalloc(1));
1362
1363         len = 0;
1364         do len += strlen(*argv) + 1; while (*++argv);
1365         pi->cmdtext = p = xmalloc(len);
1366         argv = pi->progs[0].argv;
1367         do {
1368                 len = strlen(*argv);
1369                 memcpy(p, *argv, len);
1370                 p += len;
1371                 *p++ = ' ';
1372         } while (*++argv);
1373         p[-1] = '\0';
1374         return pi->cmdtext;
1375 }
1376 #endif
1377
1378 #if ENABLE_HUSH_JOB
1379 static void insert_bg_job(struct pipe *pi)
1380 {
1381         struct pipe *thejob;
1382
1383         /* Linear search for the ID of the job to use */
1384         pi->jobid = 1;
1385         for (thejob = job_list; thejob; thejob = thejob->next)
1386                 if (thejob->jobid >= pi->jobid)
1387                         pi->jobid = thejob->jobid + 1;
1388
1389         /* add thejob to the list of running jobs */
1390         if (!job_list) {
1391                 thejob = job_list = xmalloc(sizeof(*thejob));
1392         } else {
1393                 for (thejob = job_list; thejob->next; thejob = thejob->next)
1394                         continue;
1395                 thejob->next = xmalloc(sizeof(*thejob));
1396                 thejob = thejob->next;
1397         }
1398
1399         /* physically copy the struct job */
1400         memcpy(thejob, pi, sizeof(struct pipe));
1401         thejob->progs = xmalloc(sizeof(pi->progs[0]) * pi->num_progs);
1402         memcpy(thejob->progs, pi->progs, sizeof(pi->progs[0]) * pi->num_progs);
1403         thejob->next = NULL;
1404         /*seems to be wrong:*/
1405         /*thejob->running_progs = thejob->num_progs;*/
1406         /*thejob->stopped_progs = 0;*/
1407         thejob->cmdtext = xstrdup(get_cmdtext(pi));
1408
1409         /* we don't wait for background thejobs to return -- append it
1410            to the list of backgrounded thejobs and leave it alone */
1411         printf("[%d] %d %s\n", thejob->jobid, thejob->progs[0].pid, thejob->cmdtext);
1412         last_bg_pid = thejob->progs[0].pid;
1413         last_jobid = thejob->jobid;
1414 }
1415
1416 static void remove_bg_job(struct pipe *pi)
1417 {
1418         struct pipe *prev_pipe;
1419
1420         if (pi == job_list) {
1421                 job_list = pi->next;
1422         } else {
1423                 prev_pipe = job_list;
1424                 while (prev_pipe->next != pi)
1425                         prev_pipe = prev_pipe->next;
1426                 prev_pipe->next = pi->next;
1427         }
1428         if (job_list)
1429                 last_jobid = job_list->jobid;
1430         else
1431                 last_jobid = 0;
1432 }
1433
1434 /* remove a backgrounded job */
1435 static void delete_finished_bg_job(struct pipe *pi)
1436 {
1437         remove_bg_job(pi);
1438         pi->stopped_progs = 0;
1439         free_pipe(pi, 0);
1440         free(pi);
1441 }
1442 #endif
1443
1444 /* Checks to see if any processes have exited -- if they
1445    have, figure out why and see if a job has completed */
1446 static int checkjobs(struct pipe* fg_pipe)
1447 {
1448         int attributes;
1449         int status;
1450 #if ENABLE_HUSH_JOB
1451         int prognum = 0;
1452         struct pipe *pi;
1453 #endif
1454         pid_t childpid;
1455         int rcode = 0;
1456
1457         attributes = WUNTRACED;
1458         if (fg_pipe == NULL) {
1459                 attributes |= WNOHANG;
1460         }
1461
1462 /* Do we do this right?
1463  * bash-3.00# sleep 20 | false
1464  * <Ctrl-Z pressed>
1465  * [3]+  Stopped          sleep 20 | false
1466  * bash-3.00# echo $?
1467  * 1   <========== bg pipe is not fully done, but exitcode is already known!
1468  */
1469
1470 //FIXME: non-interactive bash does not continue even if all processes in fg pipe
1471 //are stopped. Testcase: "cat | cat" in a script (not on command line)
1472 // + killall -STOP cat
1473
1474  wait_more:
1475         while ((childpid = waitpid(-1, &status, attributes)) > 0) {
1476                 const int dead = WIFEXITED(status) || WIFSIGNALED(status);
1477
1478 #ifdef DEBUG_SHELL_JOBS
1479                 if (WIFSTOPPED(status))
1480                         debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
1481                                         childpid, WSTOPSIG(status), WEXITSTATUS(status));
1482                 if (WIFSIGNALED(status))
1483                         debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
1484                                         childpid, WTERMSIG(status), WEXITSTATUS(status));
1485                 if (WIFEXITED(status))
1486                         debug_printf_jobs("pid %d exited, exitcode %d\n",
1487                                         childpid, WEXITSTATUS(status));
1488 #endif
1489                 /* Were we asked to wait for fg pipe? */
1490                 if (fg_pipe) {
1491                         int i;
1492                         for (i = 0; i < fg_pipe->num_progs; i++) {
1493                                 debug_printf_jobs("check pid %d\n", fg_pipe->progs[i].pid);
1494                                 if (fg_pipe->progs[i].pid == childpid) {
1495                                         /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
1496                                         if (dead) {
1497                                                 fg_pipe->progs[i].pid = 0;
1498                                                 fg_pipe->running_progs--;
1499                                                 if (i == fg_pipe->num_progs-1)
1500                                                         /* last process gives overall exitstatus */
1501                                                         rcode = WEXITSTATUS(status);
1502                                         } else {
1503                                                 fg_pipe->progs[i].is_stopped = 1;
1504                                                 fg_pipe->stopped_progs++;
1505                                         }
1506                                         debug_printf_jobs("fg_pipe: running_progs %d stopped_progs %d\n",
1507                                                         fg_pipe->running_progs, fg_pipe->stopped_progs);
1508                                         if (fg_pipe->running_progs - fg_pipe->stopped_progs <= 0) {
1509                                                 /* All processes in fg pipe have exited/stopped */
1510 #if ENABLE_HUSH_JOB
1511                                                 if (fg_pipe->running_progs)
1512                                                         insert_bg_job(fg_pipe);
1513 #endif
1514                                                 return rcode;
1515                                         }
1516                                         /* There are still running processes in the fg pipe */
1517                                         goto wait_more;
1518                                 }
1519                         }
1520                         /* fall through to searching process in bg pipes */
1521                 }
1522
1523 #if ENABLE_HUSH_JOB
1524                 /* We asked to wait for bg or orphaned children */
1525                 /* No need to remember exitcode in this case */
1526                 for (pi = job_list; pi; pi = pi->next) {
1527                         prognum = 0;
1528                         while (prognum < pi->num_progs) {
1529                                 if (pi->progs[prognum].pid == childpid)
1530                                         goto found_pi_and_prognum;
1531                                 prognum++;
1532                         }
1533                 }
1534 #endif
1535
1536                 /* Happens when shell is used as init process (init=/bin/sh) */
1537                 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
1538                 goto wait_more;
1539
1540 #if ENABLE_HUSH_JOB
1541  found_pi_and_prognum:
1542                 if (dead) {
1543                         /* child exited */
1544                         pi->progs[prognum].pid = 0;
1545                         pi->running_progs--;
1546                         if (!pi->running_progs) {
1547                                 printf(JOB_STATUS_FORMAT, pi->jobid,
1548                                                         "Done", pi->cmdtext);
1549                                 delete_finished_bg_job(pi);
1550                         }
1551                 } else {
1552                         /* child stopped */
1553                         pi->stopped_progs++;
1554                         pi->progs[prognum].is_stopped = 1;
1555                 }
1556 #endif
1557         }
1558
1559         /* wait found no children or failed */
1560
1561         if (childpid && errno != ECHILD)
1562                 bb_perror_msg("waitpid");
1563
1564         /* move the shell to the foreground */
1565         //if (interactive_fd && tcsetpgrp(interactive_fd, getpgid(0)))
1566         //      bb_perror_msg("tcsetpgrp-2");
1567         return rcode;
1568 }
1569
1570 #if ENABLE_HUSH_JOB
1571 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
1572 {
1573         pid_t p;
1574         int rcode = checkjobs(fg_pipe);
1575         /* Job finished, move the shell to the foreground */
1576         p = getpgid(0);
1577         debug_printf("fg'ing ourself: getpgid(0)=%d\n", (int)p);
1578         if (tcsetpgrp(interactive_fd, p) && errno != ENOTTY)
1579                 bb_perror_msg("tcsetpgrp-4a");
1580         return rcode;
1581 }
1582 #endif
1583
1584 #if ENABLE_FEATURE_SH_STANDALONE
1585 /* run_pipe_real's helper */
1586 static int run_single_fg_nofork(struct pipe *pi, const struct bb_applet *a,
1587                 char **argv)
1588 {
1589 #if ENABLE_HUSH_JOB
1590         int rcode;
1591         /* TSTP handler will store pid etc in pi */
1592         nofork_pipe = pi;
1593         save_nofork_data(&nofork_save);
1594         if (sigsetjmp(nofork_jb, 1) == 0) {
1595                 signal_SA_RESTART(SIGTSTP, handler_ctrl_z);
1596                 signal(SIGINT, handler_ctrl_c);
1597                 rcode = run_nofork_applet_prime(&nofork_save, a, argv);
1598                 if (--nofork_save.saved != 0) {
1599                         /* Ctrl-Z forked, we are child */
1600                         exit(rcode);
1601                 }
1602                 return rcode;
1603         }
1604         /* Ctrl-Z forked, we are parent; or Ctrl-C.
1605          * Sighandler has longjmped us here */
1606         signal(SIGINT, SIG_IGN);
1607         signal(SIGTSTP, SIG_IGN);
1608         debug_printf_jobs("Exiting nofork early\n");
1609         restore_nofork_data(&nofork_save);
1610         if (nofork_save.saved == 0) /* Ctrl-Z, not Ctrl-C */
1611                 insert_bg_job(pi);
1612         else
1613                 putchar('\n'); /* bash does this on Ctrl-C */
1614         return 0;
1615 #else
1616         return run_nofork_applet(a, argv);
1617 #endif
1618 }
1619 #endif
1620
1621 /* run_pipe_real() starts all the jobs, but doesn't wait for anything
1622  * to finish.  See checkjobs().
1623  *
1624  * return code is normally -1, when the caller has to wait for children
1625  * to finish to determine the exit status of the pipe.  If the pipe
1626  * is a simple builtin command, however, the action is done by the
1627  * time run_pipe_real returns, and the exit code is provided as the
1628  * return value.
1629  *
1630  * The input of the pipe is always stdin, the output is always
1631  * stdout.  The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
1632  * because it tries to avoid running the command substitution in
1633  * subshell, when that is in fact necessary.  The subshell process
1634  * now has its stdout directed to the input of the appropriate pipe,
1635  * so this routine is noticeably simpler.
1636  */
1637 static int run_pipe_real(struct pipe *pi)
1638 {
1639         int i;
1640         int nextin, nextout;
1641         int pipefds[2];                         /* pipefds[0] is for reading */
1642         struct child_prog *child;
1643         const struct built_in_command *x;
1644         char *p;
1645         /* it is not always needed, but we aim to smaller code */
1646         int squirrel[] = { -1, -1, -1 };
1647         int rcode;
1648         const int single_fg = (pi->num_progs == 1 && pi->followup != PIPE_BG);
1649
1650         debug_printf_exec("run_pipe_real start:\n");
1651
1652         nextin = 0;
1653 #if ENABLE_HUSH_JOB
1654         pi->pgrp = -1;
1655 #endif
1656         pi->running_progs = 0;
1657         pi->stopped_progs = 0;
1658
1659         /* Check if this is a simple builtin (not part of a pipe).
1660          * Builtins within pipes have to fork anyway, and are handled in
1661          * pseudo_exec.  "echo foo | read bar" doesn't work on bash, either.
1662          */
1663         child = &(pi->progs[0]);
1664         if (single_fg && child->group && child->subshell == 0) {
1665                 debug_printf("non-subshell grouping\n");
1666                 setup_redirects(child, squirrel);
1667                 /* XXX could we merge code with following builtin case,
1668                  * by creating a pseudo builtin that calls run_list_real? */
1669                 debug_printf_exec(": run_list_real\n");
1670                 rcode = run_list_real(child->group);
1671                 restore_redirects(squirrel);
1672                 debug_printf_exec("run_pipe_real return %d\n", rcode);
1673                 return rcode;
1674         }
1675
1676         if (single_fg && child->argv != NULL) {
1677                 char **argv = child->argv;
1678
1679                 for (i = 0; is_assignment(argv[i]); i++)
1680                         continue;
1681                 if (i != 0 && argv[i] == NULL) {
1682                         /* assignments, but no command: set the local environment */
1683                         for (i = 0; argv[i] != NULL; i++) {
1684                                 /* Ok, this case is tricky.  We have to decide if this is a
1685                                  * local variable, or an already exported variable.  If it is
1686                                  * already exported, we have to export the new value.  If it is
1687                                  * not exported, we need only set this as a local variable.
1688                                  * This junk is all to decide whether or not to export this
1689                                  * variable. */
1690                                 int export_me = 0;
1691                                 char *name, *value;
1692                                 name = xstrdup(argv[i]);
1693                                 debug_printf("Local environment set: %s\n", name);
1694                                 value = strchr(name, '=');
1695                                 if (value)
1696                                         *value = 0;
1697                                 if (get_local_var(name)) {
1698                                         export_me = 1;
1699                                 }
1700                                 free(name);
1701                                 p = insert_var_value(argv[i]);
1702                                 set_local_var(p, export_me);
1703                                 if (p != argv[i])
1704                                         free(p);
1705                         }
1706                         return EXIT_SUCCESS;   /* don't worry about errors in set_local_var() yet */
1707                 }
1708                 for (i = 0; is_assignment(argv[i]); i++) {
1709                         p = insert_var_value(argv[i]);
1710                         putenv(strdup(p));
1711                         if (p != argv[i]) {
1712                                 child->sp--;
1713                                 free(p);
1714                         }
1715                 }
1716                 if (child->sp) {
1717                         char *str;
1718
1719                         str = make_string(argv + i);
1720                         debug_printf_exec(": parse_string_outer '%s'\n", str);
1721                         parse_string_outer(str, FLAG_EXIT_FROM_LOOP | FLAG_REPARSING);
1722                         free(str);
1723                         debug_printf_exec("run_pipe_real return %d\n", last_return_code);
1724                         return last_return_code;
1725                 }
1726                 for (x = bltins; x->cmd; x++) {
1727                         if (strcmp(argv[i], x->cmd) == 0) {
1728                                 if (x->function == builtin_exec && argv[i+1] == NULL) {
1729                                         debug_printf("magic exec\n");
1730                                         setup_redirects(child, NULL);
1731                                         return EXIT_SUCCESS;
1732                                 }
1733                                 debug_printf("builtin inline %s\n", argv[0]);
1734                                 /* XXX setup_redirects acts on file descriptors, not FILEs.
1735                                  * This is perfect for work that comes after exec().
1736                                  * Is it really safe for inline use?  Experimentally,
1737                                  * things seem to work with glibc. */
1738 // TODO: fflush(NULL)?
1739                                 setup_redirects(child, squirrel);
1740                                 debug_printf_exec(": builtin '%s' '%s'...\n", x->cmd, argv[i+1]);
1741                                 rcode = x->function(argv + i);
1742                                 restore_redirects(squirrel);
1743                                 debug_printf_exec("run_pipe_real return %d\n", rcode);
1744                                 return rcode;
1745                         }
1746                 }
1747 #if ENABLE_FEATURE_SH_STANDALONE
1748                 {
1749                         const struct bb_applet *a = find_applet_by_name(argv[i]);
1750                         if (a && a->nofork) {
1751                                 setup_redirects(child, squirrel);
1752                                 debug_printf_exec(": run_single_fg_nofork '%s' '%s'...\n", argv[i], argv[i+1]);
1753                                 rcode = run_single_fg_nofork(pi, a, argv + i);
1754                                 restore_redirects(squirrel);
1755                                 debug_printf_exec("run_pipe_real return %d\n", rcode);
1756                                 return rcode;
1757                         }
1758                 }
1759 #endif
1760         }
1761
1762         /* Going to fork a child per each pipe member */
1763
1764         /* Disable job control signals for shell (parent) and
1765          * for initial child code after fork */
1766         set_jobctrl_sighandler(SIG_IGN);
1767
1768         for (i = 0; i < pi->num_progs; i++) {
1769                 child = &(pi->progs[i]);
1770                 debug_printf_exec(": pipe member '%s' '%s'...\n", child->argv[0], child->argv[1]);
1771
1772                 /* pipes are inserted between pairs of commands */
1773                 if ((i + 1) < pi->num_progs) {
1774                         if (pipe(pipefds) < 0)
1775                                 bb_perror_msg_and_die("pipe");
1776                         nextout = pipefds[1];
1777                 } else {
1778                         nextout = 1;
1779                         pipefds[0] = -1;
1780                 }
1781
1782                 /* XXX test for failed fork()? */
1783 #if BB_MMU
1784                 child->pid = fork();
1785 #else
1786                 child->pid = vfork();
1787 #endif
1788                 if (!child->pid) { /* child */
1789                         /* Every child adds itself to new process group
1790                          * with pgid == pid of first child in pipe */
1791 #if ENABLE_HUSH_JOB
1792                         if (interactive_fd) {
1793                                 /* Don't do pgrp restore anymore on fatal signals */
1794                                 set_fatal_sighandler(SIG_DFL);
1795                                 if (pi->pgrp < 0) /* true for 1st process only */
1796                                         pi->pgrp = getpid();
1797                                 if (setpgid(0, pi->pgrp) == 0 && pi->followup != PIPE_BG) {
1798                                         /* We do it in *every* child, not just first,
1799                                          * to avoid races */
1800                                         tcsetpgrp(interactive_fd, pi->pgrp);
1801                                 }
1802                         }
1803 #endif
1804                         // in non-interactive case fatal sigs are already SIG_DFL
1805                         close_all();
1806                         if (nextin != 0) {
1807                                 dup2(nextin, 0);
1808                                 close(nextin);
1809                         }
1810                         if (nextout != 1) {
1811                                 dup2(nextout, 1);
1812                                 close(nextout);
1813                         }
1814                         if (pipefds[0] != -1) {
1815                                 close(pipefds[0]);  /* opposite end of our output pipe */
1816                         }
1817                         /* Like bash, explicit redirects override pipes,
1818                          * and the pipe fd is available for dup'ing. */
1819                         setup_redirects(child, NULL);
1820
1821                         /* Restore default handlers just prior to exec */
1822                         set_jobctrl_sighandler(SIG_DFL);
1823                         set_misc_sighandler(SIG_DFL);
1824                         signal(SIGCHLD, SIG_DFL);
1825                         pseudo_exec(child);
1826                 }
1827
1828                 pi->running_progs++;
1829
1830 #if ENABLE_HUSH_JOB
1831                 /* Second and next children need to know pid of first one */
1832                 if (pi->pgrp < 0)
1833                         pi->pgrp = child->pid;
1834 #endif
1835
1836                 /* Don't check for errors.  The child may be dead already,
1837                  * in which case setpgid returns error code EACCES. */
1838                 //why we do it at all?? child does it itself
1839                 //if (interactive_fd)
1840                 //      setpgid(child->pid, pi->pgrp);
1841
1842                 if (nextin != 0)
1843                         close(nextin);
1844                 if (nextout != 1)
1845                         close(nextout);
1846
1847                 /* If there isn't another process, nextin is garbage
1848                    but it doesn't matter */
1849                 nextin = pipefds[0];
1850         }
1851         debug_printf_exec("run_pipe_real return -1\n");
1852         return -1;
1853 }
1854
1855 static int run_list_real(struct pipe *pi)
1856 {
1857         char *save_name = NULL;
1858         char **list = NULL;
1859         char **save_list = NULL;
1860         struct pipe *rpipe;
1861         int flag_rep = 0;
1862         int save_num_progs;
1863         int rcode = 0, flag_skip = 1;
1864         int flag_restore = 0;
1865         int if_code = 0, next_if_code = 0;  /* need double-buffer to handle elif */
1866         reserved_style rmode, skip_more_in_this_rmode = RES_XXXX;
1867
1868         debug_printf_exec("run_list_real start:\n");
1869
1870         /* check syntax for "for" */
1871         for (rpipe = pi; rpipe; rpipe = rpipe->next) {
1872                 if ((rpipe->r_mode == RES_IN || rpipe->r_mode == RES_FOR)
1873                  && (rpipe->next == NULL)
1874                 ) {
1875                         syntax();
1876                         debug_printf_exec("run_list_real return 1\n");
1877                         return 1;
1878                 }
1879                 if ((rpipe->r_mode == RES_IN && rpipe->next->r_mode == RES_IN && rpipe->next->progs->argv != NULL)
1880                  || (rpipe->r_mode == RES_FOR && rpipe->next->r_mode != RES_IN)
1881                 ) {
1882                         syntax();
1883                         debug_printf_exec("run_list_real return 1\n");
1884                         return 1;
1885                 }
1886         }
1887         for (; pi; pi = (flag_restore != 0) ? rpipe : pi->next) {
1888                 if (pi->r_mode == RES_WHILE || pi->r_mode == RES_UNTIL
1889                  || pi->r_mode == RES_FOR
1890                 ) {
1891                         flag_restore = 0;
1892                         if (!rpipe) {
1893                                 flag_rep = 0;
1894                                 rpipe = pi;
1895                         }
1896                 }
1897                 rmode = pi->r_mode;
1898                 debug_printf("rmode=%d  if_code=%d  next_if_code=%d skip_more=%d\n",
1899                                 rmode, if_code, next_if_code, skip_more_in_this_rmode);
1900                 if (rmode == skip_more_in_this_rmode && flag_skip) {
1901                         if (pi->followup == PIPE_SEQ)
1902                                 flag_skip = 0;
1903                         continue;
1904                 }
1905                 flag_skip = 1;
1906                 skip_more_in_this_rmode = RES_XXXX;
1907                 if (rmode == RES_THEN || rmode == RES_ELSE)
1908                         if_code = next_if_code;
1909                 if (rmode == RES_THEN && if_code)
1910                         continue;
1911                 if (rmode == RES_ELSE && !if_code)
1912                         continue;
1913                 if (rmode == RES_ELIF && !if_code)
1914                         break;
1915                 if (rmode == RES_FOR && pi->num_progs) {
1916                         if (!list) {
1917                                 /* if no variable values after "in" we skip "for" */
1918                                 if (!pi->next->progs->argv)
1919                                         continue;
1920                                 /* create list of variable values */
1921                                 list = make_list_in(pi->next->progs->argv,
1922                                                 pi->progs->argv[0]);
1923                                 save_list = list;
1924                                 save_name = pi->progs->argv[0];
1925                                 pi->progs->argv[0] = NULL;
1926                                 flag_rep = 1;
1927                         }
1928                         if (!*list) {
1929                                 free(pi->progs->argv[0]);
1930                                 free(save_list);
1931                                 list = NULL;
1932                                 flag_rep = 0;
1933                                 pi->progs->argv[0] = save_name;
1934                                 pi->progs->glob_result.gl_pathv[0] = pi->progs->argv[0];
1935                                 continue;
1936                         }
1937                         /* insert new value from list for variable */
1938                         if (pi->progs->argv[0])
1939                                 free(pi->progs->argv[0]);
1940                         pi->progs->argv[0] = *list++;
1941                         pi->progs->glob_result.gl_pathv[0] = pi->progs->argv[0];
1942                 }
1943                 if (rmode == RES_IN)
1944                         continue;
1945                 if (rmode == RES_DO) {
1946                         if (!flag_rep)
1947                                 continue;
1948                 }
1949                 if (rmode == RES_DONE) {
1950                         if (flag_rep) {
1951                                 flag_restore = 1;
1952                         } else {
1953                                 rpipe = NULL;
1954                         }
1955                 }
1956                 if (pi->num_progs == 0)
1957                         continue;
1958                 save_num_progs = pi->num_progs; /* save number of programs */
1959                 debug_printf_exec(": run_pipe_real with %d members\n", pi->num_progs);
1960                 rcode = run_pipe_real(pi);
1961                 if (rcode != -1) {
1962                         /* We only ran a builtin: rcode was set by the return value
1963                          * of run_pipe_real(), and we don't need to wait for anything. */
1964                 } else if (pi->followup == PIPE_BG) {
1965                         /* XXX check bash's behavior with nontrivial pipes */
1966                         /* XXX compute jobid */
1967                         /* XXX what does bash do with attempts to background builtins? */
1968 #if ENABLE_HUSH_JOB
1969                         insert_bg_job(pi);
1970 #endif
1971                         rcode = EXIT_SUCCESS;
1972                 } else {
1973 #if ENABLE_HUSH_JOB
1974                         if (interactive_fd) {
1975                                 rcode = checkjobs_and_fg_shell(pi);
1976                         } else
1977 #endif
1978                         {
1979                                 rcode = checkjobs(pi);
1980                         }
1981                         debug_printf("checkjobs returned %d\n", rcode);
1982                 }
1983                 last_return_code = rcode;
1984                 pi->num_progs = save_num_progs; /* restore number of programs */
1985                 if (rmode == RES_IF || rmode == RES_ELIF)
1986                         next_if_code = rcode;  /* can be overwritten a number of times */
1987                 if (rmode == RES_WHILE)
1988                         flag_rep = !last_return_code;
1989                 if (rmode == RES_UNTIL)
1990                         flag_rep = last_return_code;
1991                 if ((rcode == EXIT_SUCCESS && pi->followup == PIPE_OR)
1992                  || (rcode != EXIT_SUCCESS && pi->followup == PIPE_AND)
1993                 ) {
1994                         skip_more_in_this_rmode = rmode;
1995                 }
1996                 checkjobs(NULL);
1997         }
1998         debug_printf_exec("run_list_real return %d\n", rcode);
1999         return rcode;
2000 }
2001
2002 /* return code is the exit status of the pipe */
2003 static int free_pipe(struct pipe *pi, int indent)
2004 {
2005         char **p;
2006         struct child_prog *child;
2007         struct redir_struct *r, *rnext;
2008         int a, i, ret_code = 0;
2009
2010         if (pi->stopped_progs > 0)
2011                 return ret_code;
2012         final_printf("%s run pipe: (pid %d)\n", indenter(indent), getpid());
2013         for (i = 0; i < pi->num_progs; i++) {
2014                 child = &pi->progs[i];
2015                 final_printf("%s  command %d:\n", indenter(indent), i);
2016                 if (child->argv) {
2017                         for (a = 0, p = child->argv; *p; a++, p++) {
2018                                 final_printf("%s   argv[%d] = %s\n", indenter(indent), a, *p);
2019                         }
2020                         globfree(&child->glob_result);
2021                         child->argv = NULL;
2022                 } else if (child->group) {
2023                         final_printf("%s   begin group (subshell:%d)\n", indenter(indent), child->subshell);
2024                         ret_code = free_pipe_list(child->group, indent+3);
2025                         final_printf("%s   end group\n", indenter(indent));
2026                 } else {
2027                         final_printf("%s   (nil)\n", indenter(indent));
2028                 }
2029                 for (r = child->redirects; r; r = rnext) {
2030                         final_printf("%s   redirect %d%s", indenter(indent), r->fd, redir_table[r->type].descrip);
2031                         if (r->dup == -1) {
2032                                 /* guard against the case >$FOO, where foo is unset or blank */
2033                                 if (r->word.gl_pathv) {
2034                                         final_printf(" %s\n", *r->word.gl_pathv);
2035                                         globfree(&r->word);
2036                                 }
2037                         } else {
2038                                 final_printf("&%d\n", r->dup);
2039                         }
2040                         rnext = r->next;
2041                         free(r);
2042                 }
2043                 child->redirects = NULL;
2044         }
2045         free(pi->progs);   /* children are an array, they get freed all at once */
2046         pi->progs = NULL;
2047 #if ENABLE_HUSH_JOB
2048         free(pi->cmdtext);
2049         pi->cmdtext = NULL;
2050 #endif
2051         return ret_code;
2052 }
2053
2054 static int free_pipe_list(struct pipe *head, int indent)
2055 {
2056         int rcode = 0;   /* if list has no members */
2057         struct pipe *pi, *next;
2058         for (pi = head; pi; pi = next) {
2059                 final_printf("%s pipe reserved mode %d\n", indenter(indent), pi->r_mode);
2060                 rcode = free_pipe(pi, indent);
2061                 final_printf("%s pipe followup code %d\n", indenter(indent), pi->followup);
2062                 next = pi->next;
2063                 /*pi->next = NULL;*/
2064                 free(pi);
2065         }
2066         return rcode;
2067 }
2068
2069 /* Select which version we will use */
2070 static int run_list(struct pipe *pi)
2071 {
2072         int rcode = 0;
2073         if (fake_mode == 0) {
2074                 debug_printf_exec("run_list: run_list_real with %d members\n", pi->num_progs);
2075                 rcode = run_list_real(pi);
2076         }
2077         /* free_pipe_list has the side effect of clearing memory
2078          * In the long run that function can be merged with run_list_real,
2079          * but doing that now would hobble the debugging effort. */
2080         free_pipe_list(pi,0);
2081         return rcode;
2082 }
2083
2084 /* The API for glob is arguably broken.  This routine pushes a non-matching
2085  * string into the output structure, removing non-backslashed backslashes.
2086  * If someone can prove me wrong, by performing this function within the
2087  * original glob(3) api, feel free to rewrite this routine into oblivion.
2088  * Return code (0 vs. GLOB_NOSPACE) matches glob(3).
2089  * XXX broken if the last character is '\\', check that before calling.
2090  */
2091 static int globhack(const char *src, int flags, glob_t *pglob)
2092 {
2093         int cnt = 0, pathc;
2094         const char *s;
2095         char *dest;
2096         for (cnt = 1, s = src; s && *s; s++) {
2097                 if (*s == '\\') s++;
2098                 cnt++;
2099         }
2100         dest = malloc(cnt);
2101         if (!dest)
2102                 return GLOB_NOSPACE;
2103         if (!(flags & GLOB_APPEND)) {
2104                 pglob->gl_pathv = NULL;
2105                 pglob->gl_pathc = 0;
2106                 pglob->gl_offs = 0;
2107                 pglob->gl_offs = 0;
2108         }
2109         pathc = ++pglob->gl_pathc;
2110         pglob->gl_pathv = realloc(pglob->gl_pathv, (pathc+1)*sizeof(*pglob->gl_pathv));
2111         if (pglob->gl_pathv == NULL)
2112                 return GLOB_NOSPACE;
2113         pglob->gl_pathv[pathc-1] = dest;
2114         pglob->gl_pathv[pathc] = NULL;
2115         for (s = src; s && *s; s++, dest++) {
2116                 if (*s == '\\') s++;
2117                 *dest = *s;
2118         }
2119         *dest = '\0';
2120         return 0;
2121 }
2122
2123 /* XXX broken if the last character is '\\', check that before calling */
2124 static int glob_needed(const char *s)
2125 {
2126         for (; *s; s++) {
2127                 if (*s == '\\') s++;
2128                 if (strchr("*[?", *s)) return 1;
2129         }
2130         return 0;
2131 }
2132
2133 static int xglob(o_string *dest, int flags, glob_t *pglob)
2134 {
2135         int gr;
2136
2137         /* short-circuit for null word */
2138         /* we can code this better when the debug_printf's are gone */
2139         if (dest->length == 0) {
2140                 if (dest->nonnull) {
2141                         /* bash man page calls this an "explicit" null */
2142                         gr = globhack(dest->data, flags, pglob);
2143                         debug_printf("globhack returned %d\n", gr);
2144                 } else {
2145                         return 0;
2146                 }
2147         } else if (glob_needed(dest->data)) {
2148                 gr = glob(dest->data, flags, NULL, pglob);
2149                 debug_printf("glob returned %d\n", gr);
2150                 if (gr == GLOB_NOMATCH) {
2151                         /* quote removal, or more accurately, backslash removal */
2152                         gr = globhack(dest->data, flags, pglob);
2153                         debug_printf("globhack returned %d\n", gr);
2154                 }
2155         } else {
2156                 gr = globhack(dest->data, flags, pglob);
2157                 debug_printf("globhack returned %d\n", gr);
2158         }
2159         if (gr == GLOB_NOSPACE)
2160                 bb_error_msg_and_die("out of memory during glob");
2161         if (gr != 0) { /* GLOB_ABORTED ? */
2162                 bb_error_msg("glob(3) error %d", gr);
2163         }
2164         /* globprint(glob_target); */
2165         return gr;
2166 }
2167
2168 static char **make_list_in(char **inp, char *name)
2169 {
2170         int len, i;
2171         int name_len = strlen(name);
2172         int n = 0;
2173         char **list;
2174         char *p1, *p2, *p3;
2175
2176         /* create list of variable values */
2177         list = xmalloc(sizeof(*list));
2178         for (i = 0; inp[i]; i++) {
2179                 p3 = insert_var_value(inp[i]);
2180                 p1 = p3;
2181                 while (*p1) {
2182                         if ((*p1 == ' ')) {
2183                                 p1++;
2184                                 continue;
2185                         }
2186                         p2 = strchr(p1, ' ');
2187                         if (p2) {
2188                                 len = p2 - p1;
2189                         } else {
2190                                 len = strlen(p1);
2191                                 p2 = p1 + len;
2192                         }
2193                         /* we use n + 2 in realloc for list, because we add
2194                          * new element and then we will add NULL element */
2195                         list = xrealloc(list, sizeof(*list) * (n + 2));
2196                         list[n] = xmalloc(2 + name_len + len);
2197                         strcpy(list[n], name);
2198                         strcat(list[n], "=");
2199                         strncat(list[n], p1, len);
2200                         list[n++][name_len + len + 1] = '\0';
2201                         p1 = p2;
2202                 }
2203                 if (p3 != inp[i]) free(p3);
2204         }
2205         list[n] = NULL;
2206         return list;
2207 }
2208
2209 static char *insert_var_value(char *inp)
2210 {
2211         int res_str_len = 0;
2212         int len;
2213         int done = 0;
2214         char *p, *res_str = NULL;
2215         const char *p1;
2216
2217         while ((p = strchr(inp, SPECIAL_VAR_SYMBOL))) {
2218                 if (p != inp) {
2219                         len = p - inp;
2220                         res_str = xrealloc(res_str, (res_str_len + len));
2221                         strncpy((res_str + res_str_len), inp, len);
2222                         res_str_len += len;
2223                 }
2224                 inp = ++p;
2225                 p = strchr(inp, SPECIAL_VAR_SYMBOL);
2226                 *p = '\0';
2227                 p1 = lookup_param(inp);
2228                 if (p1) {
2229                         len = res_str_len + strlen(p1);
2230                         res_str = xrealloc(res_str, (1 + len));
2231                         strcpy((res_str + res_str_len), p1);
2232                         res_str_len = len;
2233                 }
2234                 *p = SPECIAL_VAR_SYMBOL;
2235                 inp = ++p;
2236                 done = 1;
2237         }
2238         if (done) {
2239                 res_str = xrealloc(res_str, (1 + res_str_len + strlen(inp)));
2240                 strcpy((res_str + res_str_len), inp);
2241                 while ((p = strchr(res_str, '\n'))) {
2242                         *p = ' ';
2243                 }
2244         }
2245         return (res_str == NULL) ? inp : res_str;
2246 }
2247
2248 /* This is used to get/check local shell variables */
2249 static const char *get_local_var(const char *s)
2250 {
2251         struct variables *cur;
2252
2253         if (!s)
2254                 return NULL;
2255         for (cur = top_vars; cur; cur = cur->next)
2256                 if (strcmp(cur->name, s) == 0)
2257                         return cur->value;
2258         return NULL;
2259 }
2260
2261 /* This is used to set local shell variables
2262    flg_export == 0 if only local (not exporting) variable
2263    flg_export == 1 if "new" exporting environ
2264    flg_export > 1  if current startup environ (not call putenv()) */
2265 static int set_local_var(const char *s, int flg_export)
2266 {
2267         char *name, *value;
2268         int result = 0;
2269         struct variables *cur;
2270
2271         name = strdup(s);
2272
2273         /* Assume when we enter this function that we are already in
2274          * NAME=VALUE format.  So the first order of business is to
2275          * split 's' on the '=' into 'name' and 'value' */
2276         value = strchr(name, '=');
2277         /*if (value == 0 && ++value == 0) ??? -vda */
2278         if (value == NULL || value[1] == '\0') {
2279                 free(name);
2280                 return -1;
2281         }
2282         *value++ = '\0';
2283
2284         for (cur = top_vars; cur; cur = cur->next) {
2285                 if (strcmp(cur->name, name) == 0)
2286                         break;
2287         }
2288
2289         if (cur) {
2290                 if (strcmp(cur->value, value) == 0) {
2291                         if (flg_export > 0 && cur->flg_export == 0)
2292                                 cur->flg_export = flg_export;
2293                         else
2294                                 result++;
2295                 } else if (cur->flg_read_only) {
2296                         bb_error_msg("%s: readonly variable", name);
2297                         result = -1;
2298                 } else {
2299                         if (flg_export > 0 || cur->flg_export > 1)
2300                                 cur->flg_export = 1;
2301                         free((char*)cur->value);
2302
2303                         cur->value = strdup(value);
2304                 }
2305         } else {
2306                 cur = malloc(sizeof(struct variables));
2307                 if (!cur) {
2308                         result = -1;
2309                 } else {
2310                         cur->name = strdup(name);
2311                         if (cur->name) {
2312                                 free(cur);
2313                                 result = -1;
2314                         } else {
2315                                 struct variables *bottom = top_vars;
2316                                 cur->value = strdup(value);
2317                                 cur->next = 0;
2318                                 cur->flg_export = flg_export;
2319                                 cur->flg_read_only = 0;
2320                                 while (bottom->next)
2321                                         bottom = bottom->next;
2322                                 bottom->next = cur;
2323                         }
2324                 }
2325         }
2326
2327         if (result == 0 && cur->flg_export == 1) {
2328                 *(value-1) = '=';
2329                 result = putenv(name);
2330         } else {
2331                 free(name);
2332                 if (result > 0)            /* equivalent to previous set */
2333                         result = 0;
2334         }
2335         return result;
2336 }
2337
2338 static void unset_local_var(const char *name)
2339 {
2340         struct variables *cur, *next;
2341
2342         if (!name)
2343                 return;
2344         for (cur = top_vars; cur; cur = cur->next) {
2345                 if (strcmp(cur->name, name) == 0) {
2346                         if (cur->flg_read_only) {
2347                                 bb_error_msg("%s: readonly variable", name);
2348                                 return;
2349                         }
2350                         if (cur->flg_export)
2351                                 unsetenv(cur->name);
2352                         free((char*)cur->name);
2353                         free((char*)cur->value);
2354                         next = top_vars;
2355                         while (next->next != cur)
2356                                 next = next->next;
2357                         next->next = cur->next;
2358                         free(cur);
2359                         return;
2360                 }
2361         }
2362 }
2363
2364 static int is_assignment(const char *s)
2365 {
2366         if (!s || !isalpha(*s))
2367                 return 0;
2368         s++;
2369         while (isalnum(*s) || *s == '_')
2370                 s++;
2371         return *s == '=';
2372 }
2373
2374 /* the src parameter allows us to peek forward to a possible &n syntax
2375  * for file descriptor duplication, e.g., "2>&1".
2376  * Return code is 0 normally, 1 if a syntax error is detected in src.
2377  * Resource errors (in xmalloc) cause the process to exit */
2378 static int setup_redirect(struct p_context *ctx, int fd, redir_type style,
2379         struct in_str *input)
2380 {
2381         struct child_prog *child = ctx->child;
2382         struct redir_struct *redir = child->redirects;
2383         struct redir_struct *last_redir = NULL;
2384
2385         /* Create a new redir_struct and drop it onto the end of the linked list */
2386         while (redir) {
2387                 last_redir = redir;
2388                 redir = redir->next;
2389         }
2390         redir = xmalloc(sizeof(struct redir_struct));
2391         redir->next = NULL;
2392         redir->word.gl_pathv = NULL;
2393         if (last_redir) {
2394                 last_redir->next = redir;
2395         } else {
2396                 child->redirects = redir;
2397         }
2398
2399         redir->type = style;
2400         redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
2401
2402         debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
2403
2404         /* Check for a '2>&1' type redirect */
2405         redir->dup = redirect_dup_num(input);
2406         if (redir->dup == -2) return 1;  /* syntax error */
2407         if (redir->dup != -1) {
2408                 /* Erik had a check here that the file descriptor in question
2409                  * is legit; I postpone that to "run time"
2410                  * A "-" representation of "close me" shows up as a -3 here */
2411                 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
2412         } else {
2413                 /* We do _not_ try to open the file that src points to,
2414                  * since we need to return and let src be expanded first.
2415                  * Set ctx->pending_redirect, so we know what to do at the
2416                  * end of the next parsed word.
2417                  */
2418                 ctx->pending_redirect = redir;
2419         }
2420         return 0;
2421 }
2422
2423 static struct pipe *new_pipe(void)
2424 {
2425         struct pipe *pi;
2426         pi = xzalloc(sizeof(struct pipe));
2427         /*pi->num_progs = 0;*/
2428         /*pi->progs = NULL;*/
2429         /*pi->next = NULL;*/
2430         /*pi->followup = 0;  invalid */
2431         if (RES_NONE)
2432                 pi->r_mode = RES_NONE;
2433         return pi;
2434 }
2435
2436 static void initialize_context(struct p_context *ctx)
2437 {
2438         ctx->pipe = NULL;
2439         ctx->pending_redirect = NULL;
2440         ctx->child = NULL;
2441         ctx->list_head = new_pipe();
2442         ctx->pipe = ctx->list_head;
2443         ctx->w = RES_NONE;
2444         ctx->stack = NULL;
2445         ctx->old_flag = 0;
2446         done_command(ctx);   /* creates the memory for working child */
2447 }
2448
2449 /* normal return is 0
2450  * if a reserved word is found, and processed, return 1
2451  * should handle if, then, elif, else, fi, for, while, until, do, done.
2452  * case, function, and select are obnoxious, save those for later.
2453  */
2454 static int reserved_word(o_string *dest, struct p_context *ctx)
2455 {
2456         struct reserved_combo {
2457                 char literal[7];
2458                 unsigned char code;
2459                 int flag;
2460         };
2461         /* Mostly a list of accepted follow-up reserved words.
2462          * FLAG_END means we are done with the sequence, and are ready
2463          * to turn the compound list into a command.
2464          * FLAG_START means the word must start a new compound list.
2465          */
2466         static const struct reserved_combo reserved_list[] = {
2467                 { "if",    RES_IF,    FLAG_THEN | FLAG_START },
2468                 { "then",  RES_THEN,  FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2469                 { "elif",  RES_ELIF,  FLAG_THEN },
2470                 { "else",  RES_ELSE,  FLAG_FI   },
2471                 { "fi",    RES_FI,    FLAG_END  },
2472                 { "for",   RES_FOR,   FLAG_IN   | FLAG_START },
2473                 { "while", RES_WHILE, FLAG_DO   | FLAG_START },
2474                 { "until", RES_UNTIL, FLAG_DO   | FLAG_START },
2475                 { "in",    RES_IN,    FLAG_DO   },
2476                 { "do",    RES_DO,    FLAG_DONE },
2477                 { "done",  RES_DONE,  FLAG_END  }
2478         };
2479         enum { NRES = sizeof(reserved_list)/sizeof(reserved_list[0]) };
2480         const struct reserved_combo *r;
2481
2482         for (r = reserved_list; r < reserved_list+NRES; r++) {
2483                 if (strcmp(dest->data, r->literal) == 0) {
2484                         debug_printf("found reserved word %s, code %d\n", r->literal, r->code);
2485                         if (r->flag & FLAG_START) {
2486                                 struct p_context *new = xmalloc(sizeof(struct p_context));
2487                                 debug_printf("push stack\n");
2488                                 if (ctx->w == RES_IN || ctx->w == RES_FOR) {
2489                                         syntax();
2490                                         free(new);
2491                                         ctx->w = RES_SNTX;
2492                                         b_reset(dest);
2493                                         return 1;
2494                                 }
2495                                 *new = *ctx;   /* physical copy */
2496                                 initialize_context(ctx);
2497                                 ctx->stack = new;
2498                         } else if (ctx->w == RES_NONE || !(ctx->old_flag & (1 << r->code))) {
2499                                 syntax();
2500                                 ctx->w = RES_SNTX;
2501                                 b_reset(dest);
2502                                 return 1;
2503                         }
2504                         ctx->w = r->code;
2505                         ctx->old_flag = r->flag;
2506                         if (ctx->old_flag & FLAG_END) {
2507                                 struct p_context *old;
2508                                 debug_printf("pop stack\n");
2509                                 done_pipe(ctx, PIPE_SEQ);
2510                                 old = ctx->stack;
2511                                 old->child->group = ctx->list_head;
2512                                 old->child->subshell = 0;
2513                                 *ctx = *old;   /* physical copy */
2514                                 free(old);
2515                         }
2516                         b_reset(dest);
2517                         return 1;
2518                 }
2519         }
2520         return 0;
2521 }
2522
2523 /* normal return is 0.
2524  * Syntax or xglob errors return 1. */
2525 static int done_word(o_string *dest, struct p_context *ctx)
2526 {
2527         struct child_prog *child = ctx->child;
2528         glob_t *glob_target;
2529         int gr, flags = 0;
2530
2531         debug_printf("done_word: %s %p\n", dest->data, child);
2532         if (dest->length == 0 && !dest->nonnull) {
2533                 debug_printf("  true null, ignored\n");
2534                 return 0;
2535         }
2536         if (ctx->pending_redirect) {
2537                 glob_target = &ctx->pending_redirect->word;
2538         } else {
2539                 if (child->group) {
2540                         syntax();
2541                         return 1;  /* syntax error, groups and arglists don't mix */
2542                 }
2543                 if (!child->argv && (ctx->type & FLAG_PARSE_SEMICOLON)) {
2544                         debug_printf("checking %s for reserved-ness\n", dest->data);
2545                         if (reserved_word(dest, ctx))
2546                                 return (ctx->w == RES_SNTX);
2547                 }
2548                 glob_target = &child->glob_result;
2549                 if (child->argv) flags |= GLOB_APPEND;
2550         }
2551         gr = xglob(dest, flags, glob_target);
2552         if (gr != 0) return 1;
2553
2554         b_reset(dest);
2555         if (ctx->pending_redirect) {
2556                 ctx->pending_redirect = NULL;
2557                 if (glob_target->gl_pathc != 1) {
2558                         bb_error_msg("ambiguous redirect");
2559                         return 1;
2560                 }
2561         } else {
2562                 child->argv = glob_target->gl_pathv;
2563         }
2564         if (ctx->w == RES_FOR) {
2565                 done_word(dest, ctx);
2566                 done_pipe(ctx, PIPE_SEQ);
2567         }
2568         return 0;
2569 }
2570
2571 /* The only possible error here is out of memory, in which case
2572  * xmalloc exits. */
2573 static int done_command(struct p_context *ctx)
2574 {
2575         /* The child is really already in the pipe structure, so
2576          * advance the pipe counter and make a new, null child.
2577          * Only real trickiness here is that the uncommitted
2578          * child structure, to which ctx->child points, is not
2579          * counted in pi->num_progs. */
2580         struct pipe *pi = ctx->pipe;
2581         struct child_prog *prog = ctx->child;
2582
2583         if (prog && prog->group == NULL
2584          && prog->argv == NULL
2585          && prog->redirects == NULL
2586         ) {
2587                 debug_printf("done_command: skipping null command\n");
2588                 return 0;
2589         }
2590         if (prog) {
2591                 pi->num_progs++;
2592                 debug_printf("done_command: num_progs incremented to %d\n", pi->num_progs);
2593         } else {
2594                 debug_printf("done_command: initializing\n");
2595         }
2596         pi->progs = xrealloc(pi->progs, sizeof(*pi->progs) * (pi->num_progs+1));
2597
2598         prog = pi->progs + pi->num_progs;
2599         memset(prog, 0, sizeof(*prog));
2600         /*prog->redirects = NULL;*/
2601         /*prog->argv = NULL; */
2602         /*prog->is_stopped = 0;*/
2603         /*prog->group = NULL;*/
2604         /*prog->glob_result.gl_pathv = NULL;*/
2605         prog->family = pi;
2606         /*prog->sp = 0;*/
2607         ctx->child = prog;
2608         prog->type = ctx->type;
2609
2610         /* but ctx->pipe and ctx->list_head remain unchanged */
2611         return 0;
2612 }
2613
2614 static int done_pipe(struct p_context *ctx, pipe_style type)
2615 {
2616         struct pipe *new_p;
2617         done_command(ctx);  /* implicit closure of previous command */
2618         debug_printf("done_pipe, type %d\n", type);
2619         ctx->pipe->followup = type;
2620         ctx->pipe->r_mode = ctx->w;
2621         new_p = new_pipe();
2622         ctx->pipe->next = new_p;
2623         ctx->pipe = new_p;
2624         ctx->child = NULL;
2625         done_command(ctx);  /* set up new pipe to accept commands */
2626         return 0;
2627 }
2628
2629 /* peek ahead in the in_str to find out if we have a "&n" construct,
2630  * as in "2>&1", that represents duplicating a file descriptor.
2631  * returns either -2 (syntax error), -1 (no &), or the number found.
2632  */
2633 static int redirect_dup_num(struct in_str *input)
2634 {
2635         int ch, d = 0, ok = 0;
2636         ch = b_peek(input);
2637         if (ch != '&') return -1;
2638
2639         b_getch(input);  /* get the & */
2640         ch = b_peek(input);
2641         if (ch == '-') {
2642                 b_getch(input);
2643                 return -3;  /* "-" represents "close me" */
2644         }
2645         while (isdigit(ch)) {
2646                 d = d*10 + (ch-'0');
2647                 ok = 1;
2648                 b_getch(input);
2649                 ch = b_peek(input);
2650         }
2651         if (ok) return d;
2652
2653         bb_error_msg("ambiguous redirect");
2654         return -2;
2655 }
2656
2657 /* If a redirect is immediately preceded by a number, that number is
2658  * supposed to tell which file descriptor to redirect.  This routine
2659  * looks for such preceding numbers.  In an ideal world this routine
2660  * needs to handle all the following classes of redirects...
2661  *     echo 2>foo     # redirects fd  2 to file "foo", nothing passed to echo
2662  *     echo 49>foo    # redirects fd 49 to file "foo", nothing passed to echo
2663  *     echo -2>foo    # redirects fd  1 to file "foo",    "-2" passed to echo
2664  *     echo 49x>foo   # redirects fd  1 to file "foo",   "49x" passed to echo
2665  * A -1 output from this program means no valid number was found, so the
2666  * caller should use the appropriate default for this redirection.
2667  */
2668 static int redirect_opt_num(o_string *o)
2669 {
2670         int num;
2671
2672         if (o->length == 0)
2673                 return -1;
2674         for (num = 0; num < o->length; num++) {
2675                 if (!isdigit(*(o->data + num))) {
2676                         return -1;
2677                 }
2678         }
2679         /* reuse num (and save an int) */
2680         num = atoi(o->data);
2681         b_reset(o);
2682         return num;
2683 }
2684
2685 static FILE *generate_stream_from_list(struct pipe *head)
2686 {
2687         FILE *pf;
2688         int pid, channel[2];
2689         if (pipe(channel) < 0) bb_perror_msg_and_die("pipe");
2690 #if BB_MMU
2691         pid = fork();
2692 #else
2693         pid = vfork();
2694 #endif
2695         if (pid < 0) {
2696                 bb_perror_msg_and_die("fork");
2697         } else if (pid == 0) {
2698                 close(channel[0]);
2699                 if (channel[1] != 1) {
2700                         dup2(channel[1], 1);
2701                         close(channel[1]);
2702                 }
2703                 _exit(run_list_real(head));   /* leaks memory */
2704         }
2705         debug_printf("forked child %d\n", pid);
2706         close(channel[1]);
2707         pf = fdopen(channel[0], "r");
2708         debug_printf("pipe on FILE *%p\n", pf);
2709         return pf;
2710 }
2711
2712 /* this version hacked for testing purposes */
2713 /* return code is exit status of the process that is run. */
2714 static int process_command_subs(o_string *dest, struct p_context *ctx, struct in_str *input, int subst_end)
2715 {
2716         int retcode;
2717         o_string result = NULL_O_STRING;
2718         struct p_context inner;
2719         FILE *p;
2720         struct in_str pipe_str;
2721         initialize_context(&inner);
2722
2723         /* recursion to generate command */
2724         retcode = parse_stream(&result, &inner, input, subst_end);
2725         if (retcode != 0) return retcode;  /* syntax error or EOF */
2726         done_word(&result, &inner);
2727         done_pipe(&inner, PIPE_SEQ);
2728         b_free(&result);
2729
2730         p = generate_stream_from_list(inner.list_head);
2731         if (p == NULL) return 1;
2732         mark_open(fileno(p));
2733         setup_file_in_str(&pipe_str, p);
2734
2735         /* now send results of command back into original context */
2736         retcode = parse_stream(dest, ctx, &pipe_str, '\0');
2737         /* XXX In case of a syntax error, should we try to kill the child?
2738          * That would be tough to do right, so just read until EOF. */
2739         if (retcode == 1) {
2740                 while (b_getch(&pipe_str) != EOF)
2741                         /* discard */;
2742         }
2743
2744         debug_printf("done reading from pipe, pclose()ing\n");
2745         /* This is the step that wait()s for the child.  Should be pretty
2746          * safe, since we just read an EOF from its stdout.  We could try
2747          * to better, by using wait(), and keeping track of background jobs
2748          * at the same time.  That would be a lot of work, and contrary
2749          * to the KISS philosophy of this program. */
2750         mark_closed(fileno(p));
2751         retcode = pclose(p);
2752         free_pipe_list(inner.list_head, 0);
2753         debug_printf("pclosed, retcode=%d\n", retcode);
2754         /* XXX this process fails to trim a single trailing newline */
2755         return retcode;
2756 }
2757
2758 static int parse_group(o_string *dest, struct p_context *ctx,
2759         struct in_str *input, int ch)
2760 {
2761         int rcode, endch = 0;
2762         struct p_context sub;
2763         struct child_prog *child = ctx->child;
2764         if (child->argv) {
2765                 syntax();
2766                 return 1;  /* syntax error, groups and arglists don't mix */
2767         }
2768         initialize_context(&sub);
2769         switch (ch) {
2770         case '(':
2771                 endch = ')';
2772                 child->subshell = 1;
2773                 break;
2774         case '{':
2775                 endch = '}';
2776                 break;
2777         default:
2778                 syntax();   /* really logic error */
2779         }
2780         rcode = parse_stream(dest, &sub, input, endch);
2781         done_word(dest, &sub); /* finish off the final word in the subcontext */
2782         done_pipe(&sub, PIPE_SEQ);  /* and the final command there, too */
2783         child->group = sub.list_head;
2784         return rcode;
2785         /* child remains "open", available for possible redirects */
2786 }
2787
2788 /* basically useful version until someone wants to get fancier,
2789  * see the bash man page under "Parameter Expansion" */
2790 static const char *lookup_param(const char *src)
2791 {
2792         const char *p = NULL;
2793         if (src) {
2794                 p = getenv(src);
2795                 if (!p)
2796                         p = get_local_var(src);
2797         }
2798         return p;
2799 }
2800
2801 /* Make new string for parser */
2802 static char* make_string(char ** inp)
2803 {
2804         char *p;
2805         char *str = NULL;
2806         int n;
2807         int len = 2;
2808
2809         for (n = 0; inp[n]; n++) {
2810                 p = insert_var_value(inp[n]);
2811                 str = xrealloc(str, (len + strlen(p)));
2812                 if (n) {
2813                         strcat(str, " ");
2814                 } else {
2815                         *str = '\0';
2816                 }
2817                 strcat(str, p);
2818                 len = strlen(str) + 3;
2819                 if (p != inp[n]) free(p);
2820         }
2821         len = strlen(str);
2822         str[len] = '\n';
2823         str[len+1] = '\0';
2824         return str;
2825 }
2826
2827 /* return code: 0 for OK, 1 for syntax error */
2828 static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input)
2829 {
2830         int i, advance = 0;
2831         char sep[] = " ";
2832         int ch = input->peek(input);  /* first character after the $ */
2833         debug_printf("handle_dollar: ch=%c\n", ch);
2834         if (isalpha(ch)) {
2835                 b_addchr(dest, SPECIAL_VAR_SYMBOL);
2836                 ctx->child->sp++;
2837                 while (ch = b_peek(input), isalnum(ch) || ch == '_') {
2838                         b_getch(input);
2839                         b_addchr(dest, ch);
2840                 }
2841                 b_addchr(dest, SPECIAL_VAR_SYMBOL);
2842         } else if (isdigit(ch)) {
2843                 i = ch - '0';  /* XXX is $0 special? */
2844                 if (i < global_argc) {
2845                         parse_string(dest, ctx, global_argv[i]); /* recursion */
2846                 }
2847                 advance = 1;
2848         } else switch (ch) {
2849                 case '$':
2850                         b_adduint(dest, getpid());
2851                         advance = 1;
2852                         break;
2853                 case '!':
2854                         if (last_bg_pid > 0) b_adduint(dest, last_bg_pid);
2855                         advance = 1;
2856                         break;
2857                 case '?':
2858                         b_adduint(dest, last_return_code);
2859                         advance = 1;
2860                         break;
2861                 case '#':
2862                         b_adduint(dest, global_argc ? global_argc-1 : 0);
2863                         advance = 1;
2864                         break;
2865                 case '{':
2866                         b_addchr(dest, SPECIAL_VAR_SYMBOL);
2867                         ctx->child->sp++;
2868                         b_getch(input);
2869                         /* XXX maybe someone will try to escape the '}' */
2870                         while (1) {
2871                                 ch = b_getch(input);
2872                                 if (ch == EOF || ch == '}')
2873                                         break;
2874                                 b_addchr(dest, ch);
2875                         }
2876                         if (ch != '}') {
2877                                 syntax();
2878                                 return 1;
2879                         }
2880                         b_addchr(dest, SPECIAL_VAR_SYMBOL);
2881                         break;
2882                 case '(':
2883                         b_getch(input);
2884                         process_command_subs(dest, ctx, input, ')');
2885                         break;
2886                 case '*':
2887                         sep[0] = ifs[0];
2888                         for (i = 1; i < global_argc; i++) {
2889                                 parse_string(dest, ctx, global_argv[i]);
2890                                 if (i+1 < global_argc)
2891                                         parse_string(dest, ctx, sep);
2892                         }
2893                         break;
2894                 case '@':
2895                 case '-':
2896                 case '_':
2897                         /* still unhandled, but should be eventually */
2898                         bb_error_msg("unhandled syntax: $%c", ch);
2899                         return 1;
2900                         break;
2901                 default:
2902                         b_addqchr(dest,'$', dest->quote);
2903         }
2904         /* Eat the character if the flag was set.  If the compiler
2905          * is smart enough, we could substitute "b_getch(input);"
2906          * for all the "advance = 1;" above, and also end up with
2907          * a nice size-optimized program.  Hah!  That'll be the day.
2908          */
2909         if (advance) b_getch(input);
2910         return 0;
2911 }
2912
2913 static int parse_string(o_string *dest, struct p_context *ctx, const char *src)
2914 {
2915         struct in_str foo;
2916         setup_string_in_str(&foo, src);
2917         return parse_stream(dest, ctx, &foo, '\0');
2918 }
2919
2920 /* return code is 0 for normal exit, 1 for syntax error */
2921 static int parse_stream(o_string *dest, struct p_context *ctx,
2922         struct in_str *input, int end_trigger)
2923 {
2924         int ch, m;
2925         int redir_fd;
2926         redir_type redir_style;
2927         int next;
2928
2929         /* Only double-quote state is handled in the state variable dest->quote.
2930          * A single-quote triggers a bypass of the main loop until its mate is
2931          * found.  When recursing, quote state is passed in via dest->quote. */
2932
2933         debug_printf("parse_stream, end_trigger=%d\n", end_trigger);
2934         while ((ch = b_getch(input)) != EOF) {
2935                 m = map[ch];
2936                 next = (ch == '\n') ? 0 : b_peek(input);
2937                 debug_printf("parse_stream: ch=%c (%d) m=%d quote=%d\n",
2938                                                 ch, ch, m, dest->quote);
2939                 if (m == 0 || ((m == 1 || m == 2) && dest->quote)) {
2940                         b_addqchr(dest, ch, dest->quote);
2941                         continue;
2942                 }
2943                 if (m == 2) {  /* unquoted IFS */
2944                         if (done_word(dest, ctx)) {
2945                                 return 1;
2946                         }
2947                         /* If we aren't performing a substitution, treat a newline as a
2948                          * command separator.  */
2949                         if (end_trigger != '\0' && ch == '\n')
2950                                 done_pipe(ctx, PIPE_SEQ);
2951                 }
2952                 if (ch == end_trigger && !dest->quote && ctx->w == RES_NONE) {
2953                         debug_printf("leaving parse_stream (triggered)\n");
2954                         return 0;
2955                 }
2956                 if (m == 2)
2957                         continue;
2958                 switch (ch) {
2959                 case '#':
2960                         if (dest->length == 0 && !dest->quote) {
2961                                 while (1) {
2962                                         ch = b_peek(input);
2963                                         if (ch == EOF || ch == '\n')
2964                                                 break;
2965                                         b_getch(input);
2966                                 }
2967                         } else {
2968                                 b_addqchr(dest, ch, dest->quote);
2969                         }
2970                         break;
2971                 case '\\':
2972                         if (next == EOF) {
2973                                 syntax();
2974                                 return 1;
2975                         }
2976                         b_addqchr(dest, '\\', dest->quote);
2977                         b_addqchr(dest, b_getch(input), dest->quote);
2978                         break;
2979                 case '$':
2980                         if (handle_dollar(dest, ctx, input) != 0) return 1;
2981                         break;
2982                 case '\'':
2983                         dest->nonnull = 1;
2984                         while (1) {
2985                                 ch = b_getch(input);
2986                                 if (ch == EOF || ch == '\'')
2987                                         break;
2988                                 b_addchr(dest, ch);
2989                         }
2990                         if (ch == EOF) {
2991                                 syntax();
2992                                 return 1;
2993                         }
2994                         break;
2995                 case '"':
2996                         dest->nonnull = 1;
2997                         dest->quote = !dest->quote;
2998                         break;
2999                 case '`':
3000                         process_command_subs(dest, ctx, input, '`');
3001                         break;
3002                 case '>':
3003                         redir_fd = redirect_opt_num(dest);
3004                         done_word(dest, ctx);
3005                         redir_style = REDIRECT_OVERWRITE;
3006                         if (next == '>') {
3007                                 redir_style = REDIRECT_APPEND;
3008                                 b_getch(input);
3009                         } else if (next == '(') {
3010                                 syntax();   /* until we support >(list) Process Substitution */
3011                                 return 1;
3012                         }
3013                         setup_redirect(ctx, redir_fd, redir_style, input);
3014                         break;
3015                 case '<':
3016                         redir_fd = redirect_opt_num(dest);
3017                         done_word(dest, ctx);
3018                         redir_style = REDIRECT_INPUT;
3019                         if (next == '<') {
3020                                 redir_style = REDIRECT_HEREIS;
3021                                 b_getch(input);
3022                         } else if (next == '>') {
3023                                 redir_style = REDIRECT_IO;
3024                                 b_getch(input);
3025                         } else if (next == '(') {
3026                                 syntax();   /* until we support <(list) Process Substitution */
3027                                 return 1;
3028                         }
3029                         setup_redirect(ctx, redir_fd, redir_style, input);
3030                         break;
3031                 case ';':
3032                         done_word(dest, ctx);
3033                         done_pipe(ctx, PIPE_SEQ);
3034                         break;
3035                 case '&':
3036                         done_word(dest, ctx);
3037                         if (next == '&') {
3038                                 b_getch(input);
3039                                 done_pipe(ctx, PIPE_AND);
3040                         } else {
3041                                 done_pipe(ctx, PIPE_BG);
3042                         }
3043                         break;
3044                 case '|':
3045                         done_word(dest, ctx);
3046                         if (next == '|') {
3047                                 b_getch(input);
3048                                 done_pipe(ctx, PIPE_OR);
3049                         } else {
3050                                 /* we could pick up a file descriptor choice here
3051                                  * with redirect_opt_num(), but bash doesn't do it.
3052                                  * "echo foo 2| cat" yields "foo 2". */
3053                                 done_command(ctx);
3054                         }
3055                         break;
3056                 case '(':
3057                 case '{':
3058                         if (parse_group(dest, ctx, input, ch) != 0)
3059                                 return 1;
3060                         break;
3061                 case ')':
3062                 case '}':
3063                         syntax();   /* Proper use of this character caught by end_trigger */
3064                         return 1;
3065                 default:
3066                         syntax();   /* this is really an internal logic error */
3067                         return 1;
3068                 }
3069         }
3070         /* complain if quote?  No, maybe we just finished a command substitution
3071          * that was quoted.  Example:
3072          * $ echo "`cat foo` plus more"
3073          * and we just got the EOF generated by the subshell that ran "cat foo"
3074          * The only real complaint is if we got an EOF when end_trigger != '\0',
3075          * that is, we were really supposed to get end_trigger, and never got
3076          * one before the EOF.  Can't use the standard "syntax error" return code,
3077          * so that parse_stream_outer can distinguish the EOF and exit smoothly. */
3078         debug_printf("leaving parse_stream (EOF)\n");
3079         if (end_trigger != '\0')
3080                 return -1;
3081         return 0;
3082 }
3083
3084 static void mapset(const char *set, int code)
3085 {
3086         while (*set)
3087                 map[(unsigned char)*set++] = code;
3088 }
3089
3090 static void update_ifs_map(void)
3091 {
3092         /* char *ifs and char map[256] are both globals. */
3093         ifs = getenv("IFS");
3094         if (ifs == NULL) ifs = " \t\n";
3095         /* Precompute a list of 'flow through' behavior so it can be treated
3096          * quickly up front.  Computation is necessary because of IFS.
3097          * Special case handling of IFS == " \t\n" is not implemented.
3098          * The map[] array only really needs two bits each, and on most machines
3099          * that would be faster because of the reduced L1 cache footprint.
3100          */
3101         memset(map, 0, sizeof(map)); /* most characters flow through always */
3102         mapset("\\$'\"`", 3);        /* never flow through */
3103         mapset("<>;&|(){}#", 1);     /* flow through if quoted */
3104         mapset(ifs, 2);              /* also flow through if quoted */
3105 }
3106
3107 /* most recursion does not come through here, the exception is
3108  * from builtin_source() */
3109 static int parse_stream_outer(struct in_str *inp, int flag)
3110 {
3111 // FIXME: 'true | exit 3; echo $?' is parsed as a whole,
3112 // as a result $? is replaced by 0, not 3!
3113 // Need to stop & execute stuff at ';', not parse till EOL!
3114
3115         struct p_context ctx;
3116         o_string temp = NULL_O_STRING;
3117         int rcode;
3118         do {
3119                 ctx.type = flag;
3120                 initialize_context(&ctx);
3121                 update_ifs_map();
3122                 if (!(flag & FLAG_PARSE_SEMICOLON) || (flag & FLAG_REPARSING))
3123                          mapset(";$&|", 0);
3124 #if ENABLE_HUSH_INTERACTIVE
3125                 inp->promptmode = 1;
3126 #endif
3127                 rcode = parse_stream(&temp, &ctx, inp, '\n');
3128                 if (rcode != 1 && ctx.old_flag != 0) {
3129                         syntax();
3130                 }
3131                 if (rcode != 1 && ctx.old_flag == 0) {
3132                         done_word(&temp, &ctx);
3133                         done_pipe(&ctx, PIPE_SEQ);
3134                         debug_printf_exec("parse_stream_outer: run_list\n");
3135                         run_list(ctx.list_head);
3136                 } else {
3137                         if (ctx.old_flag != 0) {
3138                                 free(ctx.stack);
3139                                 b_reset(&temp);
3140                         }
3141                         temp.nonnull = 0;
3142                         temp.quote = 0;
3143                         inp->p = NULL;
3144                         free_pipe_list(ctx.list_head, 0);
3145                 }
3146                 b_free(&temp);
3147         } while (rcode != -1 && !(flag & FLAG_EXIT_FROM_LOOP));   /* loop on syntax errors, return on EOF */
3148         return 0;
3149 }
3150
3151 static int parse_string_outer(const char *s, int flag)
3152 {
3153         struct in_str input;
3154         setup_string_in_str(&input, s);
3155         return parse_stream_outer(&input, flag);
3156 }
3157
3158 static int parse_file_outer(FILE *f)
3159 {
3160         int rcode;
3161         struct in_str input;
3162         setup_file_in_str(&input, f);
3163         rcode = parse_stream_outer(&input, FLAG_PARSE_SEMICOLON);
3164         return rcode;
3165 }
3166
3167 #if ENABLE_HUSH_JOB
3168 /* Make sure we have a controlling tty.  If we get started under a job
3169  * aware app (like bash for example), make sure we are now in charge so
3170  * we don't fight over who gets the foreground */
3171 static void setup_job_control(void)
3172 {
3173         pid_t shell_pgrp;
3174
3175         saved_task_pgrp = shell_pgrp = getpgrp();
3176         debug_printf("saved_task_pgrp=%d\n", saved_task_pgrp);
3177         fcntl(interactive_fd, F_SETFD, FD_CLOEXEC);
3178
3179         /* If we were ran as 'hush &',
3180          * sleep until we are in the foreground.  */
3181         while (tcgetpgrp(interactive_fd) != shell_pgrp) {
3182                 /* Send TTIN to ourself (should stop us) */
3183                 kill(- shell_pgrp, SIGTTIN);
3184                 shell_pgrp = getpgrp();
3185         }
3186
3187         /* Ignore job-control and misc signals.  */
3188         set_jobctrl_sighandler(SIG_IGN);
3189         set_misc_sighandler(SIG_IGN);
3190 //huh?  signal(SIGCHLD, SIG_IGN);
3191
3192         /* We _must_ restore tty pgrp fatal signals */
3193         set_fatal_sighandler(sigexit);
3194
3195         /* Put ourselves in our own process group.  */
3196         setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
3197         /* Grab control of the terminal.  */
3198         tcsetpgrp(interactive_fd, getpid());
3199 }
3200 #endif
3201
3202 int hush_main(int argc, char **argv);
3203 int hush_main(int argc, char **argv)
3204 {
3205         int opt;
3206         FILE *input;
3207         char **e;
3208
3209 #if ENABLE_FEATURE_EDITING
3210         line_input_state = new_line_input_t(FOR_SHELL);
3211 #endif
3212
3213         /* XXX what should these be while sourcing /etc/profile? */
3214         global_argc = argc;
3215         global_argv = argv;
3216
3217         /* (re?) initialize globals.  Sometimes hush_main() ends up calling
3218          * hush_main(), therefore we cannot rely on the BSS to zero out this
3219          * stuff.  Reset these to 0 every time. */
3220         ifs = NULL;
3221         /* map[] is taken care of with call to update_ifs_map() */
3222         fake_mode = 0;
3223         close_me_head = NULL;
3224 #if ENABLE_HUSH_INTERACTIVE
3225         interactive_fd = 0;
3226 #endif
3227 #if ENABLE_HUSH_JOB
3228         last_bg_pid = 0;
3229         job_list = NULL;
3230         last_jobid = 0;
3231 #endif
3232
3233         /* Initialize some more globals to non-zero values */
3234         set_cwd();
3235 #if ENABLE_HUSH_INTERACTIVE
3236 #if ENABLE_FEATURE_EDITING
3237         cmdedit_set_initial_prompt();
3238 #else
3239         PS1 = NULL;
3240 #endif
3241         PS2 = "> ";
3242 #endif
3243         /* initialize our shell local variables with the values
3244          * currently living in the environment */
3245         e = environ;
3246         if (e)
3247                 while (*e)
3248                         set_local_var(*e++, 2);   /* without call putenv() */
3249
3250         last_return_code = EXIT_SUCCESS;
3251
3252         if (argv[0] && argv[0][0] == '-') {
3253                 debug_printf("\nsourcing /etc/profile\n");
3254                 input = fopen("/etc/profile", "r");
3255                 if (input != NULL) {
3256                         mark_open(fileno(input));
3257                         parse_file_outer(input);
3258                         mark_closed(fileno(input));
3259                         fclose(input);
3260                 }
3261         }
3262         input = stdin;
3263
3264         while ((opt = getopt(argc, argv, "c:xif")) > 0) {
3265                 switch (opt) {
3266                 case 'c':
3267                         global_argv = argv + optind;
3268                         global_argc = argc - optind;
3269                         opt = parse_string_outer(optarg, FLAG_PARSE_SEMICOLON);
3270                         goto final_return;
3271                 case 'i':
3272                         // Well, we cannot just declare interactiveness,
3273                         // we have to have some stuff (ctty, etc)
3274                         /*interactive_fd++;*/
3275                         break;
3276                 case 'f':
3277                         fake_mode++;
3278                         break;
3279                 default:
3280 #ifndef BB_VER
3281                         fprintf(stderr, "Usage: sh [FILE]...\n"
3282                                         "   or: sh -c command [args]...\n\n");
3283                         exit(EXIT_FAILURE);
3284 #else
3285                         bb_show_usage();
3286 #endif
3287                 }
3288         }
3289 #if ENABLE_HUSH_JOB
3290         /* A shell is interactive if the '-i' flag was given, or if all of
3291          * the following conditions are met:
3292          *    no -c command
3293          *    no arguments remaining or the -s flag given
3294          *    standard input is a terminal
3295          *    standard output is a terminal
3296          *    Refer to Posix.2, the description of the 'sh' utility. */
3297         if (argv[optind] == NULL && input == stdin
3298          && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3299         ) {
3300                 saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
3301                 debug_printf("saved_tty_pgrp=%d\n", saved_tty_pgrp);
3302                 if (saved_tty_pgrp >= 0) {
3303                         /* try to dup to high fd#, >= 255 */
3304                         interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3305                         if (interactive_fd < 0) {
3306                                 /* try to dup to any fd */
3307                                 interactive_fd = dup(STDIN_FILENO);
3308                                 if (interactive_fd < 0)
3309                                         /* give up */
3310                                         interactive_fd = 0;
3311                         }
3312                         // TODO: track & disallow any attempts of user
3313                         // to (inadvertently) close/redirect it
3314                 }
3315         }
3316         debug_printf("\ninteractive_fd=%d\n", interactive_fd);
3317         if (interactive_fd) {
3318                 /* Looks like they want an interactive shell */
3319                 setup_job_control();
3320                 /* Make xfuncs do cleanup on exit */
3321                 die_sleep = -1; /* flag */
3322                 if (setjmp(die_jmp)) {
3323                         /* xfunc has failed! die die die */
3324                         hush_exit(xfunc_error_retval);
3325                 }
3326 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
3327                 printf("\n\n%s hush - the humble shell v"HUSH_VER_STR"\n", BB_BANNER);
3328                 printf("Enter 'help' for a list of built-in commands.\n\n");
3329 #endif
3330         }
3331 #elif ENABLE_HUSH_INTERACTIVE
3332 /* no job control compiled, only prompt/line editing */
3333         if (argv[optind] == NULL && input == stdin
3334          && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3335         ) {
3336                 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3337                 if (interactive_fd < 0) {
3338                         /* try to dup to any fd */
3339                         interactive_fd = dup(STDIN_FILENO);
3340                         if (interactive_fd < 0)
3341                                 /* give up */
3342                                 interactive_fd = 0;
3343                 }
3344         }
3345
3346 #endif
3347
3348         if (argv[optind] == NULL) {
3349                 opt = parse_file_outer(stdin);
3350                 goto final_return;
3351         }
3352
3353         debug_printf("\nrunning script '%s'\n", argv[optind]);
3354         global_argv = argv + optind;
3355         global_argc = argc - optind;
3356         input = xfopen(argv[optind], "r");
3357         opt = parse_file_outer(input);
3358
3359 #if ENABLE_FEATURE_CLEAN_UP
3360         fclose(input);
3361         if (cwd != bb_msg_unknown)
3362                 free((char*)cwd);
3363         {
3364                 struct variables *cur, *tmp;
3365                 for (cur = top_vars; cur; cur = tmp) {
3366                         tmp = cur->next;
3367                         if (!cur->flg_read_only) {
3368                                 free((char*)cur->name);
3369                                 free((char*)cur->value);
3370                                 free(cur);
3371                         }
3372                 }
3373         }
3374 #endif
3375
3376  final_return:
3377         hush_exit(opt ? opt : last_return_code);
3378 }