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