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