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