*: add optimization barrier to all "G trick" locations
[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  *      $_
41  *      ! negation operator for pipes
42  *      &> and >& redirection of stdout+stderr
43  *      Brace Expansion
44  *      Tilde Expansion
45  *      fancy forms of Parameter Expansion
46  *      aliases
47  *      Arithmetic Expansion
48  *      <(list) and >(list) Process Substitution
49  *      reserved words: case, esac, select, function
50  *      Here Documents ( << word )
51  *      Functions
52  * Major bugs:
53  *      job handling woefully incomplete and buggy (improved --vda)
54  *      reserved word execution woefully incomplete and buggy
55  * to-do:
56  *      port selected bugfixes from post-0.49 busybox lash - done?
57  *      finish implementing reserved words: for, while, until, do, done
58  *      change { and } from special chars to reserved words
59  *      builtins: break, continue, eval, return, set, trap, ulimit
60  *      test magic exec
61  *      handle children going into background
62  *      clean up recognition of null pipes
63  *      check setting of global_argc and global_argv
64  *      control-C handling, probably with longjmp
65  *      follow IFS rules more precisely, including update semantics
66  *      figure out what to do with backslash-newline
67  *      explain why we use signal instead of sigaction
68  *      propagate syntax errors, die on resource errors?
69  *      continuation lines, both explicit and implicit - done?
70  *      memory leak finding and plugging - done?
71  *      more testing, especially quoting rules and redirection
72  *      document how quoting rules not precisely followed for variable assignments
73  *      maybe change charmap[] to use 2-bit entries
74  *      (eventually) remove all the printf's
75  *
76  * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
77  */
78
79
80 #include <glob.h>      /* glob, of course */
81 #include <getopt.h>    /* should be pretty obvious */
82 /* #include <dmalloc.h> */
83
84 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
85
86
87 #if !BB_MMU && ENABLE_HUSH_TICK
88 //#undef ENABLE_HUSH_TICK
89 //#define ENABLE_HUSH_TICK 0
90 #warning On NOMMU, hush command substitution is dangerous.
91 #warning Dont use it for commands which produce lots of output.
92 #warning For more info see shell/hush.c, generate_stream_from_list().
93 #endif
94
95 #if !BB_MMU && ENABLE_HUSH_JOB
96 #undef ENABLE_HUSH_JOB
97 #define ENABLE_HUSH_JOB 0
98 #endif
99
100 #if !ENABLE_HUSH_INTERACTIVE
101 #undef ENABLE_FEATURE_EDITING
102 #define ENABLE_FEATURE_EDITING 0
103 #undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
104 #define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
105 #endif
106
107
108 /* If you comment out one of these below, it will be #defined later
109  * to perform debug printfs to stderr: */
110 #define debug_printf(...)        do {} while (0)
111 /* Finer-grained debug switches */
112 #define debug_printf_parse(...)  do {} while (0)
113 #define debug_print_tree(a, b)   do {} while (0)
114 #define debug_printf_exec(...)   do {} while (0)
115 #define debug_printf_jobs(...)   do {} while (0)
116 #define debug_printf_expand(...) do {} while (0)
117 #define debug_printf_clean(...)  do {} while (0)
118
119 #ifndef debug_printf
120 #define debug_printf(...) fprintf(stderr, __VA_ARGS__)
121 #endif
122
123 #ifndef debug_printf_parse
124 #define debug_printf_parse(...) fprintf(stderr, __VA_ARGS__)
125 #endif
126
127 #ifndef debug_printf_exec
128 #define debug_printf_exec(...) fprintf(stderr, __VA_ARGS__)
129 #endif
130
131 #ifndef debug_printf_jobs
132 #define debug_printf_jobs(...) fprintf(stderr, __VA_ARGS__)
133 #define DEBUG_SHELL_JOBS 1
134 #endif
135
136 #ifndef debug_printf_expand
137 #define debug_printf_expand(...) fprintf(stderr, __VA_ARGS__)
138 #define DEBUG_EXPAND 1
139 #endif
140
141 /* Keep unconditionally on for now */
142 #define ENABLE_HUSH_DEBUG 1
143
144 #ifndef debug_printf_clean
145 /* broken, of course, but OK for testing */
146 static const char *indenter(int i)
147 {
148         static const char blanks[] ALIGN1 =
149                 "                                    ";
150         return &blanks[sizeof(blanks) - i - 1];
151 }
152 #define debug_printf_clean(...) fprintf(stderr, __VA_ARGS__)
153 #define DEBUG_CLEAN 1
154 #endif
155
156
157 /*
158  * Leak hunting. Use hush_leaktool.sh for post-processing.
159  */
160 #ifdef FOR_HUSH_LEAKTOOL
161 void *xxmalloc(int lineno, size_t size)
162 {
163         void *ptr = xmalloc((size + 0xff) & ~0xff);
164         fprintf(stderr, "line %d: malloc %p\n", lineno, ptr);
165         return ptr;
166 }
167 void *xxrealloc(int lineno, void *ptr, size_t size)
168 {
169         ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
170         fprintf(stderr, "line %d: realloc %p\n", lineno, ptr);
171         return ptr;
172 }
173 char *xxstrdup(int lineno, const char *str)
174 {
175         char *ptr = xstrdup(str);
176         fprintf(stderr, "line %d: strdup %p\n", lineno, ptr);
177         return ptr;
178 }
179 void xxfree(void *ptr)
180 {
181         fprintf(stderr, "free %p\n", ptr);
182         free(ptr);
183 }
184 #define xmalloc(s)     xxmalloc(__LINE__, s)
185 #define xrealloc(p, s) xxrealloc(__LINE__, p, s)
186 #define xstrdup(s)     xxstrdup(__LINE__, s)
187 #define free(p)        xxfree(p)
188 #endif
189
190
191 #define SPECIAL_VAR_SYMBOL   3
192
193 #define PARSEFLAG_EXIT_FROM_LOOP 1
194 #define PARSEFLAG_SEMICOLON      (1 << 1)  /* symbol ';' is special for parser */
195 #define PARSEFLAG_REPARSING      (1 << 2)  /* >= 2nd pass */
196
197 typedef enum {
198         REDIRECT_INPUT     = 1,
199         REDIRECT_OVERWRITE = 2,
200         REDIRECT_APPEND    = 3,
201         REDIRECT_HEREIS    = 4,
202         REDIRECT_IO        = 5
203 } redir_type;
204
205 /* The descrip member of this structure is only used to make debugging
206  * output pretty */
207 static const struct {
208         int mode;
209         signed char default_fd;
210         char descrip[3];
211 } redir_table[] = {
212         { 0,                         0, "()" },
213         { O_RDONLY,                  0, "<"  },
214         { O_CREAT|O_TRUNC|O_WRONLY,  1, ">"  },
215         { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
216         { O_RDONLY,                 -1, "<<" },
217         { O_RDWR,                    1, "<>" }
218 };
219
220 typedef enum {
221         PIPE_SEQ = 1,
222         PIPE_AND = 2,
223         PIPE_OR  = 3,
224         PIPE_BG  = 4,
225 } pipe_style;
226
227 /* might eventually control execution */
228 typedef enum {
229         RES_NONE  = 0,
230 #if ENABLE_HUSH_IF
231         RES_IF    = 1,
232         RES_THEN  = 2,
233         RES_ELIF  = 3,
234         RES_ELSE  = 4,
235         RES_FI    = 5,
236 #endif
237 #if ENABLE_HUSH_LOOPS
238         RES_FOR   = 6,
239         RES_WHILE = 7,
240         RES_UNTIL = 8,
241         RES_DO    = 9,
242         RES_DONE  = 10,
243         RES_IN    = 11,
244 #endif
245         RES_XXXX  = 12,
246         RES_SNTX  = 13
247 } reserved_style;
248 enum {
249         FLAG_END   = (1 << RES_NONE ),
250 #if ENABLE_HUSH_IF
251         FLAG_IF    = (1 << RES_IF   ),
252         FLAG_THEN  = (1 << RES_THEN ),
253         FLAG_ELIF  = (1 << RES_ELIF ),
254         FLAG_ELSE  = (1 << RES_ELSE ),
255         FLAG_FI    = (1 << RES_FI   ),
256 #endif
257 #if ENABLE_HUSH_LOOPS
258         FLAG_FOR   = (1 << RES_FOR  ),
259         FLAG_WHILE = (1 << RES_WHILE),
260         FLAG_UNTIL = (1 << RES_UNTIL),
261         FLAG_DO    = (1 << RES_DO   ),
262         FLAG_DONE  = (1 << RES_DONE ),
263         FLAG_IN    = (1 << RES_IN   ),
264 #endif
265         FLAG_START = (1 << RES_XXXX ),
266 };
267
268 /* This holds pointers to the various results of parsing */
269 struct p_context {
270         struct child_prog *child;
271         struct pipe *list_head;
272         struct pipe *pipe;
273         struct redir_struct *pending_redirect;
274         smallint res_w;
275         smallint parse_type;        /* bitmask of PARSEFLAG_xxx, defines type of parser : ";$" common or special symbol */
276         int old_flag;               /* bitmask of FLAG_xxx, for figuring out valid reserved words */
277         struct p_context *stack;
278         /* How about quoting status? */
279 };
280
281 struct redir_struct {
282         struct redir_struct *next;  /* pointer to the next redirect in the list */
283         redir_type type;            /* type of redirection */
284         int fd;                     /* file descriptor being redirected */
285         int dup;                    /* -1, or file descriptor being duplicated */
286         char **glob_word;           /* *word.gl_pathv is the filename */
287 };
288
289 struct child_prog {
290         pid_t pid;                  /* 0 if exited */
291         char **argv;                /* program name and arguments */
292         struct pipe *group;         /* if non-NULL, first in group or subshell */
293         smallint subshell;          /* flag, non-zero if group must be forked */
294         smallint is_stopped;        /* is the program currently running? */
295         struct redir_struct *redirects; /* I/O redirections */
296         struct pipe *family;        /* pointer back to the child's parent pipe */
297         //sp counting seems to be broken... so commented out, grep for '//sp:'
298         //sp: int sp;               /* number of SPECIAL_VAR_SYMBOL */
299         //seems to be unused, grep for '//pt:'
300         //pt: int parse_type;
301 };
302 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
303  * and on execution these are substituted with their values.
304  * Substitution can make _several_ words out of one argv[n]!
305  * Example: argv[0]=='.^C*^C.' here: echo .$*.
306  */
307
308 struct pipe {
309         struct pipe *next;
310         int num_progs;              /* total number of programs in job */
311         int running_progs;          /* number of programs running (not exited) */
312         int stopped_progs;          /* number of programs alive, but stopped */
313 #if ENABLE_HUSH_JOB
314         int jobid;                  /* job number */
315         pid_t pgrp;                 /* process group ID for the job */
316         char *cmdtext;              /* name of job */
317 #endif
318         char *cmdbuf;               /* buffer various argv's point into */
319         struct child_prog *progs;   /* array of commands in pipe */
320         int job_context;            /* bitmask defining current context */
321         smallint followup;          /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
322         smallint res_word;          /* needed for if, for, while, until... */
323 };
324
325 /* On program start, environ points to initial environment.
326  * putenv adds new pointers into it, unsetenv removes them.
327  * Neither of these (de)allocates the strings.
328  * setenv allocates new strings in malloc space and does putenv,
329  * and thus setenv is unusable (leaky) for shell's purposes */
330 #define setenv(...) setenv_is_leaky_dont_use()
331 struct variable {
332         struct variable *next;
333         char *varstr;        /* points to "name=" portion */
334         int max_len;         /* if > 0, name is part of initial env; else name is malloced */
335         smallint flg_export; /* putenv should be done on this var */
336         smallint flg_read_only;
337 };
338
339 typedef struct {
340         char *data;
341         int length;
342         int maxlen;
343         smallint o_quote;
344         smallint nonnull;
345 } o_string;
346 #define NULL_O_STRING {NULL,0,0,0,0}
347 /* used for initialization: o_string foo = NULL_O_STRING; */
348
349 /* I can almost use ordinary FILE *.  Is open_memstream() universally
350  * available?  Where is it documented? */
351 struct in_str {
352         const char *p;
353         /* eof_flag=1: last char in ->p is really an EOF */
354         char eof_flag; /* meaningless if ->p == NULL */
355         char peek_buf[2];
356 #if ENABLE_HUSH_INTERACTIVE
357         smallint promptme;
358         smallint promptmode; /* 0: PS1, 1: PS2 */
359 #endif
360         FILE *file;
361         int (*get) (struct in_str *);
362         int (*peek) (struct in_str *);
363 };
364 #define b_getch(input) ((input)->get(input))
365 #define b_peek(input) ((input)->peek(input))
366
367 enum {
368         CHAR_ORDINARY           = 0,
369         CHAR_ORDINARY_IF_QUOTED = 1, /* example: *, # */
370         CHAR_IFS                = 2, /* treated as ordinary if quoted */
371         CHAR_SPECIAL            = 3, /* example: $ */
372 };
373
374 #define HUSH_VER_STR "0.02"
375
376 /* "Globals" within this file */
377
378 /* Sorted roughly by size (smaller offsets == smaller code) */
379 struct globals {
380 #if ENABLE_HUSH_INTERACTIVE
381         /* 'interactive_fd' is a fd# open to ctty, if we have one
382          * _AND_ if we decided to act interactively */
383         int interactive_fd;
384         const char *PS1;
385         const char *PS2;
386 #endif
387 #if ENABLE_FEATURE_EDITING
388         line_input_t *line_input_state;
389 #endif
390 #if ENABLE_HUSH_JOB
391         int run_list_level;
392         pid_t saved_task_pgrp;
393         pid_t saved_tty_pgrp;
394         int last_jobid;
395         struct pipe *job_list;
396         struct pipe *toplevel_list;
397         smallint ctrl_z_flag;
398 #endif
399         smallint fake_mode;
400         /* these three support $?, $#, and $1 */
401         char **global_argv;
402         int global_argc;
403         int last_return_code;
404         const char *ifs;
405         const char *cwd;
406         unsigned last_bg_pid;
407         struct variable *top_var; /* = &shell_ver (set in main()) */
408         struct variable shell_ver;
409 #if ENABLE_FEATURE_SH_STANDALONE
410         struct nofork_save_area nofork_save;
411 #endif
412 #if ENABLE_HUSH_JOB
413         sigjmp_buf toplevel_jb;
414 #endif
415         unsigned char charmap[256];
416         char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
417 };
418
419 #define G (*ptr_to_globals)
420
421 #if !ENABLE_HUSH_INTERACTIVE
422 enum { interactive_fd = 0 };
423 #endif
424 #if !ENABLE_HUSH_JOB
425 enum { run_list_level = 0 };
426 #endif
427
428 #if ENABLE_HUSH_INTERACTIVE
429 #define interactive_fd   (G.interactive_fd  )
430 #define PS1              (G.PS1             )
431 #define PS2              (G.PS2             )
432 #endif
433 #if ENABLE_FEATURE_EDITING
434 #define line_input_state (G.line_input_state)
435 #endif
436 #if ENABLE_HUSH_JOB
437 #define run_list_level   (G.run_list_level  )
438 #define saved_task_pgrp  (G.saved_task_pgrp )
439 #define saved_tty_pgrp   (G.saved_tty_pgrp  )
440 #define last_jobid       (G.last_jobid      )
441 #define job_list         (G.job_list        )
442 #define toplevel_list    (G.toplevel_list   )
443 #define toplevel_jb      (G.toplevel_jb     )
444 #define ctrl_z_flag      (G.ctrl_z_flag     )
445 #endif /* JOB */
446 #define global_argv      (G.global_argv     )
447 #define global_argc      (G.global_argc     )
448 #define last_return_code (G.last_return_code)
449 #define ifs              (G.ifs             )
450 #define fake_mode        (G.fake_mode       )
451 #define cwd              (G.cwd             )
452 #define last_bg_pid      (G.last_bg_pid     )
453 #define top_var          (G.top_var         )
454 #define shell_ver        (G.shell_ver       )
455 #if ENABLE_FEATURE_SH_STANDALONE
456 #define nofork_save      (G.nofork_save     )
457 #endif
458 #if ENABLE_HUSH_JOB
459 #define toplevel_jb      (G.toplevel_jb     )
460 #endif
461 #define charmap          (G.charmap         )
462 #define user_input_buf   (G.user_input_buf  )
463 #define INIT_G() do { \
464         SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
465 } while (0)
466
467
468 #define B_CHUNK  100
469 #define B_NOSPAC 1
470 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
471
472 #if 1
473 /* Normal */
474 static void syntax(const char *msg)
475 {
476         /* Was using fancy stuff:
477          * (interactive_fd ? bb_error_msg : bb_error_msg_and_die)(...params...)
478          * but it SEGVs. ?! Oh well... explicit temp ptr works around that */
479         void (*fp)(const char *s, ...);
480
481         fp = (interactive_fd ? bb_error_msg : bb_error_msg_and_die);
482         fp(msg ? "%s: %s" : "syntax error", "syntax error", msg);
483 }
484
485 #else
486 /* Debug */
487 static void syntax_lineno(int line)
488 {
489         void (*fp)(const char *s, ...);
490
491         fp = (interactive_fd ? bb_error_msg : bb_error_msg_and_die);
492         fp("syntax error hush.c:%d", line);
493 }
494 #define syntax(str) syntax_lineno(__LINE__)
495 #endif
496
497 /* Index of subroutines: */
498 /*   o_string manipulation: */
499 static int b_check_space(o_string *o, int len);
500 static int b_addchr(o_string *o, int ch);
501 static void b_reset(o_string *o);
502 static int b_addqchr(o_string *o, int ch, int quote);
503 /*  in_str manipulations: */
504 static int static_get(struct in_str *i);
505 static int static_peek(struct in_str *i);
506 static int file_get(struct in_str *i);
507 static int file_peek(struct in_str *i);
508 static void setup_file_in_str(struct in_str *i, FILE *f);
509 static void setup_string_in_str(struct in_str *i, const char *s);
510 /*  "run" the final data structures: */
511 #if !defined(DEBUG_CLEAN)
512 #define free_pipe_list(head, indent) free_pipe_list(head)
513 #define free_pipe(pi, indent)        free_pipe(pi)
514 #endif
515 static int free_pipe_list(struct pipe *head, int indent);
516 static int free_pipe(struct pipe *pi, int indent);
517 /*  really run the final data structures: */
518 static int setup_redirects(struct child_prog *prog, int squirrel[]);
519 static int run_list(struct pipe *pi);
520 static void pseudo_exec_argv(char **argv) ATTRIBUTE_NORETURN;
521 static void pseudo_exec(struct child_prog *child) ATTRIBUTE_NORETURN;
522 static int run_pipe(struct pipe *pi);
523 /*   extended glob support: */
524 static char **globhack(const char *src, char **strings);
525 static int glob_needed(const char *s);
526 static int xglob(o_string *dest, char ***pglob);
527 /*   variable assignment: */
528 static int is_assignment(const char *s);
529 /*   data structure manipulation: */
530 static int setup_redirect(struct p_context *ctx, int fd, redir_type style, struct in_str *input);
531 static void initialize_context(struct p_context *ctx);
532 static int done_word(o_string *dest, struct p_context *ctx);
533 static int done_command(struct p_context *ctx);
534 static int done_pipe(struct p_context *ctx, pipe_style type);
535 /*   primary string parsing: */
536 static int redirect_dup_num(struct in_str *input);
537 static int redirect_opt_num(o_string *o);
538 #if ENABLE_HUSH_TICK
539 static int process_command_subs(o_string *dest, struct p_context *ctx, struct in_str *input, const char *subst_end);
540 #endif
541 static int parse_group(o_string *dest, struct p_context *ctx, struct in_str *input, int ch);
542 static const char *lookup_param(const char *src);
543 static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input);
544 static int parse_stream(o_string *dest, struct p_context *ctx, struct in_str *input0, const char *end_trigger);
545 /*   setup: */
546 static int parse_and_run_stream(struct in_str *inp, int parse_flag);
547 static int parse_and_run_string(const char *s, int parse_flag);
548 static int parse_and_run_file(FILE *f);
549 /*   job management: */
550 static int checkjobs(struct pipe* fg_pipe);
551 #if ENABLE_HUSH_JOB
552 static int checkjobs_and_fg_shell(struct pipe* fg_pipe);
553 static void insert_bg_job(struct pipe *pi);
554 static void remove_bg_job(struct pipe *pi);
555 static void delete_finished_bg_job(struct pipe *pi);
556 #else
557 int checkjobs_and_fg_shell(struct pipe* fg_pipe); /* never called */
558 #endif
559 /*     local variable support */
560 static char **expand_strvec_to_strvec(char **argv);
561 /* used for eval */
562 static char *expand_strvec_to_string(char **argv);
563 /* used for expansion of right hand of assignments */
564 static char *expand_string_to_string(const char *str);
565 static struct variable *get_local_var(const char *name);
566 static int set_local_var(char *str, int flg_export);
567 static void unset_local_var(const char *name);
568
569
570 static char **add_strings_to_strings(int need_xstrdup, char **strings, char **add)
571 {
572         int i;
573         unsigned count1;
574         unsigned count2;
575         char **v;
576
577         v = strings;
578         count1 = 0;
579         if (v) {
580                 while (*v) {
581                         count1++;
582                         v++;
583                 }
584         }
585         count2 = 0;
586         v = add;
587         while (*v) {
588                 count2++;
589                 v++;
590         }
591         v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
592         v[count1 + count2] = NULL;
593         i = count2;
594         while (--i >= 0)
595                 v[count1 + i] = need_xstrdup ? xstrdup(add[i]) : add[i];
596         return v;
597 }
598
599 /* 'add' should be a malloced pointer */
600 static char **add_string_to_strings(char **strings, char *add)
601 {
602         char *v[2];
603
604         v[0] = add;
605         v[1] = NULL;
606
607         return add_strings_to_strings(0, strings, v);
608 }
609
610 static void free_strings(char **strings)
611 {
612         if (strings) {
613                 char **v = strings;
614                 while (*v)
615                         free(*v++);
616                 free(strings);
617         }
618 }
619
620
621 /* Function prototypes for builtins */
622 static int builtin_cd(char **argv);
623 static int builtin_echo(char **argv);
624 static int builtin_eval(char **argv);
625 static int builtin_exec(char **argv);
626 static int builtin_exit(char **argv);
627 static int builtin_export(char **argv);
628 #if ENABLE_HUSH_JOB
629 static int builtin_fg_bg(char **argv);
630 static int builtin_jobs(char **argv);
631 #endif
632 #if ENABLE_HUSH_HELP
633 static int builtin_help(char **argv);
634 #endif
635 static int builtin_pwd(char **argv);
636 static int builtin_read(char **argv);
637 static int builtin_test(char **argv);
638 static int builtin_set(char **argv);
639 static int builtin_shift(char **argv);
640 static int builtin_source(char **argv);
641 static int builtin_umask(char **argv);
642 static int builtin_unset(char **argv);
643 //static int builtin_not_written(char **argv);
644
645 /* Table of built-in functions.  They can be forked or not, depending on
646  * context: within pipes, they fork.  As simple commands, they do not.
647  * When used in non-forking context, they can change global variables
648  * in the parent shell process.  If forked, of course they cannot.
649  * For example, 'unset foo | whatever' will parse and run, but foo will
650  * still be set at the end. */
651 struct built_in_command {
652         const char *cmd;                /* name */
653         int (*function) (char **argv);  /* function ptr */
654 #if ENABLE_HUSH_HELP
655         const char *descr;              /* description */
656 #define BLTIN(cmd, func, help) { cmd, func, help }
657 #else
658 #define BLTIN(cmd, func, help) { cmd, func }
659 #endif
660 };
661
662 /* For now, echo and test are unconditionally enabled.
663  * Maybe make it configurable? */
664 static const struct built_in_command bltins[] = {
665         BLTIN("["     , builtin_test, "Test condition"),
666         BLTIN("[["    , builtin_test, "Test condition"),
667 #if ENABLE_HUSH_JOB
668         BLTIN("bg"    , builtin_fg_bg, "Resume a job in the background"),
669 #endif
670 //      BLTIN("break" , builtin_not_written, "Exit for, while or until loop"),
671         BLTIN("cd"    , builtin_cd, "Change working directory"),
672 //      BLTIN("continue", builtin_not_written, "Continue for, while or until loop"),
673         BLTIN("echo"  , builtin_echo, "Write strings to stdout"),
674         BLTIN("eval"  , builtin_eval, "Construct and run shell command"),
675         BLTIN("exec"  , builtin_exec, "Exec command, replacing this shell with the exec'd process"),
676         BLTIN("exit"  , builtin_exit, "Exit from shell"),
677         BLTIN("export", builtin_export, "Set environment variable"),
678 #if ENABLE_HUSH_JOB
679         BLTIN("fg"    , builtin_fg_bg, "Bring job into the foreground"),
680         BLTIN("jobs"  , builtin_jobs, "Lists the active jobs"),
681 #endif
682 // TODO: remove pwd? we have it as an applet...
683         BLTIN("pwd"   , builtin_pwd, "Print current directory"),
684         BLTIN("read"  , builtin_read, "Input environment variable"),
685 //      BLTIN("return", builtin_not_written, "Return from a function"),
686         BLTIN("set"   , builtin_set, "Set/unset shell local variables"),
687         BLTIN("shift" , builtin_shift, "Shift positional parameters"),
688 //      BLTIN("trap"  , builtin_not_written, "Trap signals"),
689         BLTIN("test"  , builtin_test, "Test condition"),
690 //      BLTIN("ulimit", builtin_not_written, "Controls resource limits"),
691         BLTIN("umask" , builtin_umask, "Sets file creation mask"),
692         BLTIN("unset" , builtin_unset, "Unset environment variable"),
693         BLTIN("."     , builtin_source, "Source-in and run commands in a file"),
694 #if ENABLE_HUSH_HELP
695         BLTIN("help"  , builtin_help, "List shell built-in commands"),
696 #endif
697         BLTIN(NULL, NULL, NULL)
698 };
699
700 #if ENABLE_HUSH_JOB
701
702 /* move to libbb? */
703 static void signal_SA_RESTART(int sig, void (*handler)(int))
704 {
705         struct sigaction sa;
706         sa.sa_handler = handler;
707         sa.sa_flags = SA_RESTART;
708         sigemptyset(&sa.sa_mask);
709         sigaction(sig, &sa, NULL);
710 }
711
712 /* Signals are grouped, we handle them in batches */
713 static void set_fatal_sighandler(void (*handler)(int))
714 {
715         bb_signals(0
716                 + (1 << SIGILL)
717                 + (1 << SIGTRAP)
718                 + (1 << SIGABRT)
719                 + (1 << SIGFPE)
720                 + (1 << SIGBUS)
721                 + (1 << SIGSEGV)
722         /* bash 3.2 seems to handle these just like 'fatal' ones */
723                 + (1 << SIGHUP)
724                 + (1 << SIGPIPE)
725                 + (1 << SIGALRM)
726                 , handler);
727 }
728 static void set_jobctrl_sighandler(void (*handler)(int))
729 {
730         bb_signals(0
731                 + (1 << SIGTSTP)
732                 + (1 << SIGTTIN)
733                 + (1 << SIGTTOU)
734                 , handler);
735 }
736 static void set_misc_sighandler(void (*handler)(int))
737 {
738         bb_signals(0
739                 + (1 << SIGINT)
740                 + (1 << SIGQUIT)
741                 + (1 << SIGTERM)
742                 , handler);
743 }
744 /* SIGCHLD is special and handled separately */
745
746 static void set_every_sighandler(void (*handler)(int))
747 {
748         set_fatal_sighandler(handler);
749         set_jobctrl_sighandler(handler);
750         set_misc_sighandler(handler);
751         signal(SIGCHLD, handler);
752 }
753
754 static void handler_ctrl_c(int sig)
755 {
756         debug_printf_jobs("got sig %d\n", sig);
757 // as usual we can have all kinds of nasty problems with leaked malloc data here
758         siglongjmp(toplevel_jb, 1);
759 }
760
761 static void handler_ctrl_z(int sig)
762 {
763         pid_t pid;
764
765         debug_printf_jobs("got tty sig %d in pid %d\n", sig, getpid());
766         pid = fork();
767         if (pid < 0) /* can't fork. Pretend there was no ctrl-Z */
768                 return;
769         ctrl_z_flag = 1;
770         if (!pid) { /* child */
771                 if (ENABLE_HUSH_JOB)
772                         die_sleep = 0; /* let nofork's xfuncs die */
773                 setpgrp();
774                 debug_printf_jobs("set pgrp for child %d ok\n", getpid());
775                 set_every_sighandler(SIG_DFL);
776                 raise(SIGTSTP); /* resend TSTP so that child will be stopped */
777                 debug_printf_jobs("returning in child\n");
778                 /* return to nofork, it will eventually exit now,
779                  * not return back to shell */
780                 return;
781         }
782         /* parent */
783         /* finish filling up pipe info */
784         toplevel_list->pgrp = pid; /* child is in its own pgrp */
785         toplevel_list->progs[0].pid = pid;
786         /* parent needs to longjmp out of running nofork.
787          * we will "return" exitcode 0, with child put in background */
788 // as usual we can have all kinds of nasty problems with leaked malloc data here
789         debug_printf_jobs("siglongjmp in parent\n");
790         siglongjmp(toplevel_jb, 1);
791 }
792
793 /* Restores tty foreground process group, and exits.
794  * May be called as signal handler for fatal signal
795  * (will faithfully resend signal to itself, producing correct exit state)
796  * or called directly with -EXITCODE.
797  * We also call it if xfunc is exiting. */
798 static void sigexit(int sig) ATTRIBUTE_NORETURN;
799 static void sigexit(int sig)
800 {
801         sigset_t block_all;
802
803         /* Disable all signals: job control, SIGPIPE, etc. */
804         sigfillset(&block_all);
805         sigprocmask(SIG_SETMASK, &block_all, NULL);
806
807         if (interactive_fd)
808                 tcsetpgrp(interactive_fd, saved_tty_pgrp);
809
810         /* Not a signal, just exit */
811         if (sig <= 0)
812                 _exit(- sig);
813
814         kill_myself_with_sig(sig); /* does not return */
815 }
816
817 /* Restores tty foreground process group, and exits. */
818 static void hush_exit(int exitcode) ATTRIBUTE_NORETURN;
819 static void hush_exit(int exitcode)
820 {
821         fflush(NULL); /* flush all streams */
822         sigexit(- (exitcode & 0xff));
823 }
824
825 #else /* !JOB */
826
827 #define set_fatal_sighandler(handler)   ((void)0)
828 #define set_jobctrl_sighandler(handler) ((void)0)
829 #define set_misc_sighandler(handler)    ((void)0)
830 #define hush_exit(e)                    exit(e)
831
832 #endif /* JOB */
833
834
835 static const char *set_cwd(void)
836 {
837         if (cwd == bb_msg_unknown)
838                 cwd = NULL;     /* xrealloc_getcwd_or_warn(arg) calls free(arg)! */
839         cwd = xrealloc_getcwd_or_warn((char *)cwd);
840         if (!cwd)
841                 cwd = bb_msg_unknown;
842         return cwd;
843 }
844
845
846 /* built-in 'test' handler */
847 static int builtin_test(char **argv)
848 {
849         int argc = 0;
850         while (*argv) {
851                 argc++;
852                 argv++;
853         }
854         return test_main(argc, argv - argc);
855 }
856
857 /* built-in 'test' handler */
858 static int builtin_echo(char **argv)
859 {
860         int argc = 0;
861         while (*argv) {
862                 argc++;
863                 argv++;
864         }
865         return echo_main(argc, argv - argc);
866 }
867
868 /* built-in 'eval' handler */
869 static int builtin_eval(char **argv)
870 {
871         int rcode = EXIT_SUCCESS;
872
873         if (argv[1]) {
874                 char *str = expand_strvec_to_string(argv + 1);
875                 parse_and_run_string(str, PARSEFLAG_EXIT_FROM_LOOP |
876                                         PARSEFLAG_SEMICOLON);
877                 free(str);
878                 rcode = last_return_code;
879         }
880         return rcode;
881 }
882
883 /* built-in 'cd <path>' handler */
884 static int builtin_cd(char **argv)
885 {
886         const char *newdir;
887         if (argv[1] == NULL) {
888                 // bash does nothing (exitcode 0) if HOME is ""; if it's unset,
889                 // bash says "bash: cd: HOME not set" and does nothing (exitcode 1)
890                 newdir = getenv("HOME") ? : "/";
891         } else
892                 newdir = argv[1];
893         if (chdir(newdir)) {
894                 printf("cd: %s: %s\n", newdir, strerror(errno));
895                 return EXIT_FAILURE;
896         }
897         set_cwd();
898         return EXIT_SUCCESS;
899 }
900
901 /* built-in 'exec' handler */
902 static int builtin_exec(char **argv)
903 {
904         if (argv[1] == NULL)
905                 return EXIT_SUCCESS;   /* Really? */
906         pseudo_exec_argv(argv + 1);
907         /* never returns */
908 }
909
910 /* built-in 'exit' handler */
911 static int builtin_exit(char **argv)
912 {
913 // TODO: bash does it ONLY on top-level sh exit (+interacive only?)
914         //puts("exit"); /* bash does it */
915 // TODO: warn if we have background jobs: "There are stopped jobs"
916 // On second consecutive 'exit', exit anyway.
917
918         if (argv[1] == NULL)
919                 hush_exit(last_return_code);
920         /* mimic bash: exit 123abc == exit 255 + error msg */
921         xfunc_error_retval = 255;
922         /* bash: exit -2 == exit 254, no error msg */
923         hush_exit(xatoi(argv[1]) & 0xff);
924 }
925
926 /* built-in 'export VAR=value' handler */
927 static int builtin_export(char **argv)
928 {
929         const char *value;
930         char *name = argv[1];
931
932         if (name == NULL) {
933                 // TODO:
934                 // ash emits: export VAR='VAL'
935                 // bash: declare -x VAR="VAL"
936                 // (both also escape as needed (quotes, $, etc))
937                 char **e = environ;
938                 if (e)
939                         while (*e)
940                                 puts(*e++);
941                 return EXIT_SUCCESS;
942         }
943
944         value = strchr(name, '=');
945         if (!value) {
946                 /* They are exporting something without a =VALUE */
947                 struct variable *var;
948
949                 var = get_local_var(name);
950                 if (var) {
951                         var->flg_export = 1;
952                         putenv(var->varstr);
953                 }
954                 /* bash does not return an error when trying to export
955                  * an undefined variable.  Do likewise. */
956                 return EXIT_SUCCESS;
957         }
958
959         set_local_var(xstrdup(name), 1);
960         return EXIT_SUCCESS;
961 }
962
963 #if ENABLE_HUSH_JOB
964 /* built-in 'fg' and 'bg' handler */
965 static int builtin_fg_bg(char **argv)
966 {
967         int i, jobnum;
968         struct pipe *pi;
969
970         if (!interactive_fd)
971                 return EXIT_FAILURE;
972         /* If they gave us no args, assume they want the last backgrounded task */
973         if (!argv[1]) {
974                 for (pi = job_list; pi; pi = pi->next) {
975                         if (pi->jobid == last_jobid) {
976                                 goto found;
977                         }
978                 }
979                 bb_error_msg("%s: no current job", argv[0]);
980                 return EXIT_FAILURE;
981         }
982         if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
983                 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
984                 return EXIT_FAILURE;
985         }
986         for (pi = job_list; pi; pi = pi->next) {
987                 if (pi->jobid == jobnum) {
988                         goto found;
989                 }
990         }
991         bb_error_msg("%s: %d: no such job", argv[0], jobnum);
992         return EXIT_FAILURE;
993  found:
994         // TODO: bash prints a string representation
995         // of job being foregrounded (like "sleep 1 | cat")
996         if (*argv[0] == 'f') {
997                 /* Put the job into the foreground.  */
998                 tcsetpgrp(interactive_fd, pi->pgrp);
999         }
1000
1001         /* Restart the processes in the job */
1002         debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_progs, pi->pgrp);
1003         for (i = 0; i < pi->num_progs; i++) {
1004                 debug_printf_jobs("reviving pid %d\n", pi->progs[i].pid);
1005                 pi->progs[i].is_stopped = 0;
1006         }
1007         pi->stopped_progs = 0;
1008
1009         i = kill(- pi->pgrp, SIGCONT);
1010         if (i < 0) {
1011                 if (errno == ESRCH) {
1012                         delete_finished_bg_job(pi);
1013                         return EXIT_SUCCESS;
1014                 } else {
1015                         bb_perror_msg("kill (SIGCONT)");
1016                 }
1017         }
1018
1019         if (*argv[0] == 'f') {
1020                 remove_bg_job(pi);
1021                 return checkjobs_and_fg_shell(pi);
1022         }
1023         return EXIT_SUCCESS;
1024 }
1025 #endif
1026
1027 /* built-in 'help' handler */
1028 #if ENABLE_HUSH_HELP
1029 static int builtin_help(char **argv ATTRIBUTE_UNUSED)
1030 {
1031         const struct built_in_command *x;
1032
1033         printf("\nBuilt-in commands:\n");
1034         printf("-------------------\n");
1035         for (x = bltins; x->cmd; x++) {
1036                 printf("%s\t%s\n", x->cmd, x->descr);
1037         }
1038         printf("\n\n");
1039         return EXIT_SUCCESS;
1040 }
1041 #endif
1042
1043 #if ENABLE_HUSH_JOB
1044 /* built-in 'jobs' handler */
1045 static int builtin_jobs(char **argv ATTRIBUTE_UNUSED)
1046 {
1047         struct pipe *job;
1048         const char *status_string;
1049
1050         for (job = job_list; job; job = job->next) {
1051                 if (job->running_progs == job->stopped_progs)
1052                         status_string = "Stopped";
1053                 else
1054                         status_string = "Running";
1055
1056                 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
1057         }
1058         return EXIT_SUCCESS;
1059 }
1060 #endif
1061
1062 /* built-in 'pwd' handler */
1063 static int builtin_pwd(char **argv ATTRIBUTE_UNUSED)
1064 {
1065         puts(set_cwd());
1066         return EXIT_SUCCESS;
1067 }
1068
1069 /* built-in 'read VAR' handler */
1070 static int builtin_read(char **argv)
1071 {
1072         char *string;
1073         const char *name = argv[1] ? argv[1] : "REPLY";
1074
1075         string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name));
1076         return set_local_var(string, 0);
1077 }
1078
1079 /* built-in 'set [VAR=value]' handler */
1080 static int builtin_set(char **argv)
1081 {
1082         char *temp = argv[1];
1083         struct variable *e;
1084
1085         if (temp == NULL)
1086                 for (e = top_var; e; e = e->next)
1087                         puts(e->varstr);
1088         else
1089                 set_local_var(xstrdup(temp), 0);
1090
1091         return EXIT_SUCCESS;
1092 }
1093
1094
1095 /* Built-in 'shift' handler */
1096 static int builtin_shift(char **argv)
1097 {
1098         int n = 1;
1099         if (argv[1]) {
1100                 n = atoi(argv[1]);
1101         }
1102         if (n >= 0 && n < global_argc) {
1103                 global_argv[n] = global_argv[0];
1104                 global_argc -= n;
1105                 global_argv += n;
1106                 return EXIT_SUCCESS;
1107         }
1108         return EXIT_FAILURE;
1109 }
1110
1111 /* Built-in '.' handler (read-in and execute commands from file) */
1112 static int builtin_source(char **argv)
1113 {
1114         FILE *input;
1115         int status;
1116
1117         if (argv[1] == NULL)
1118                 return EXIT_FAILURE;
1119
1120         /* XXX search through $PATH is missing */
1121         input = fopen(argv[1], "r");
1122         if (!input) {
1123                 bb_error_msg("cannot open '%s'", argv[1]);
1124                 return EXIT_FAILURE;
1125         }
1126         close_on_exec_on(fileno(input));
1127
1128         /* Now run the file */
1129         /* XXX argv and argc are broken; need to save old global_argv
1130          * (pointer only is OK!) on this stack frame,
1131          * set global_argv=argv+1, recurse, and restore. */
1132         status = parse_and_run_file(input);
1133         fclose(input);
1134         return status;
1135 }
1136
1137 static int builtin_umask(char **argv)
1138 {
1139         mode_t new_umask;
1140         const char *arg = argv[1];
1141         char *end;
1142         if (arg) {
1143                 new_umask = strtoul(arg, &end, 8);
1144                 if (*end != '\0' || end == arg) {
1145                         return EXIT_FAILURE;
1146                 }
1147         } else {
1148                 new_umask = umask(0);
1149                 printf("%.3o\n", (unsigned) new_umask);
1150         }
1151         umask(new_umask);
1152         return EXIT_SUCCESS;
1153 }
1154
1155 /* built-in 'unset VAR' handler */
1156 static int builtin_unset(char **argv)
1157 {
1158         /* bash always returns true */
1159         unset_local_var(argv[1]);
1160         return EXIT_SUCCESS;
1161 }
1162
1163 //static int builtin_not_written(char **argv)
1164 //{
1165 //      printf("builtin_%s not written\n", argv[0]);
1166 //      return EXIT_FAILURE;
1167 //}
1168
1169 static int b_check_space(o_string *o, int len)
1170 {
1171         /* It would be easy to drop a more restrictive policy
1172          * in here, such as setting a maximum string length */
1173         if (o->length + len > o->maxlen) {
1174                 /* assert(data == NULL || o->maxlen != 0); */
1175                 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1176                 o->data = xrealloc(o->data, 1 + o->maxlen);
1177         }
1178         return o->data == NULL;
1179 }
1180
1181 static int b_addchr(o_string *o, int ch)
1182 {
1183         debug_printf("b_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1184         if (b_check_space(o, 1))
1185                 return B_NOSPAC;
1186         o->data[o->length] = ch;
1187         o->length++;
1188         o->data[o->length] = '\0';
1189         return 0;
1190 }
1191
1192 static void b_reset(o_string *o)
1193 {
1194         o->length = 0;
1195         o->nonnull = 0;
1196         if (o->data)
1197                 o->data[0] = '\0';
1198 }
1199
1200 static void b_free(o_string *o)
1201 {
1202         free(o->data);
1203         memset(o, 0, sizeof(*o));
1204 }
1205
1206 /* My analysis of quoting semantics tells me that state information
1207  * is associated with a destination, not a source.
1208  */
1209 static int b_addqchr(o_string *o, int ch, int quote)
1210 {
1211         if (quote && strchr("*?[\\", ch)) {
1212                 int rc;
1213                 rc = b_addchr(o, '\\');
1214                 if (rc)
1215                         return rc;
1216         }
1217         return b_addchr(o, ch);
1218 }
1219
1220 static int static_get(struct in_str *i)
1221 {
1222         int ch = *i->p++;
1223         if (ch == '\0') return EOF;
1224         return ch;
1225 }
1226
1227 static int static_peek(struct in_str *i)
1228 {
1229         return *i->p;
1230 }
1231
1232 #if ENABLE_HUSH_INTERACTIVE
1233 #if ENABLE_FEATURE_EDITING
1234 static void cmdedit_set_initial_prompt(void)
1235 {
1236 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1237         PS1 = NULL;
1238 #else
1239         PS1 = getenv("PS1");
1240         if (PS1 == NULL)
1241                 PS1 = "\\w \\$ ";
1242 #endif
1243 }
1244 #endif /* EDITING */
1245
1246 static const char* setup_prompt_string(int promptmode)
1247 {
1248         const char *prompt_str;
1249         debug_printf("setup_prompt_string %d ", promptmode);
1250 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1251         /* Set up the prompt */
1252         if (promptmode == 0) { /* PS1 */
1253                 free((char*)PS1);
1254                 PS1 = xasprintf("%s %c ", cwd, (geteuid() != 0) ? '$' : '#');
1255                 prompt_str = PS1;
1256         } else {
1257                 prompt_str = PS2;
1258         }
1259 #else
1260         prompt_str = (promptmode == 0) ? PS1 : PS2;
1261 #endif
1262         debug_printf("result '%s'\n", prompt_str);
1263         return prompt_str;
1264 }
1265
1266 static void get_user_input(struct in_str *i)
1267 {
1268         int r;
1269         const char *prompt_str;
1270
1271         prompt_str = setup_prompt_string(i->promptmode);
1272 #if ENABLE_FEATURE_EDITING
1273         /* Enable command line editing only while a command line
1274          * is actually being read */
1275         do {
1276                 r = read_line_input(prompt_str, user_input_buf, BUFSIZ-1, line_input_state);
1277         } while (r == 0); /* repeat if Ctrl-C */
1278         i->eof_flag = (r < 0);
1279         if (i->eof_flag) { /* EOF/error detected */
1280                 user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1281                 user_input_buf[1] = '\0';
1282         }
1283 #else
1284         fputs(prompt_str, stdout);
1285         fflush(stdout);
1286         user_input_buf[0] = r = fgetc(i->file);
1287         /*user_input_buf[1] = '\0'; - already is and never changed */
1288         i->eof_flag = (r == EOF);
1289 #endif
1290         i->p = user_input_buf;
1291 }
1292 #endif  /* INTERACTIVE */
1293
1294 /* This is the magic location that prints prompts
1295  * and gets data back from the user */
1296 static int file_get(struct in_str *i)
1297 {
1298         int ch;
1299
1300         /* If there is data waiting, eat it up */
1301         if (i->p && *i->p) {
1302 #if ENABLE_HUSH_INTERACTIVE
1303  take_cached:
1304 #endif
1305                 ch = *i->p++;
1306                 if (i->eof_flag && !*i->p)
1307                         ch = EOF;
1308         } else {
1309                 /* need to double check i->file because we might be doing something
1310                  * more complicated by now, like sourcing or substituting. */
1311 #if ENABLE_HUSH_INTERACTIVE
1312                 if (interactive_fd && i->promptme && i->file == stdin) {
1313                         do {
1314                                 get_user_input(i);
1315                         } while (!*i->p); /* need non-empty line */
1316                         i->promptmode = 1; /* PS2 */
1317                         i->promptme = 0;
1318                         goto take_cached;
1319                 }
1320 #endif
1321                 ch = fgetc(i->file);
1322         }
1323         debug_printf("file_get: got a '%c' %d\n", ch, ch);
1324 #if ENABLE_HUSH_INTERACTIVE
1325         if (ch == '\n')
1326                 i->promptme = 1;
1327 #endif
1328         return ch;
1329 }
1330
1331 /* All the callers guarantee this routine will never be
1332  * used right after a newline, so prompting is not needed.
1333  */
1334 static int file_peek(struct in_str *i)
1335 {
1336         int ch;
1337         if (i->p && *i->p) {
1338                 if (i->eof_flag && !i->p[1])
1339                         return EOF;
1340                 return *i->p;
1341         }
1342         ch = fgetc(i->file);
1343         i->eof_flag = (ch == EOF);
1344         i->peek_buf[0] = ch;
1345         i->peek_buf[1] = '\0';
1346         i->p = i->peek_buf;
1347         debug_printf("file_peek: got a '%c' %d\n", *i->p, *i->p);
1348         return ch;
1349 }
1350
1351 static void setup_file_in_str(struct in_str *i, FILE *f)
1352 {
1353         i->peek = file_peek;
1354         i->get = file_get;
1355 #if ENABLE_HUSH_INTERACTIVE
1356         i->promptme = 1;
1357         i->promptmode = 0; /* PS1 */
1358 #endif
1359         i->file = f;
1360         i->p = NULL;
1361 }
1362
1363 static void setup_string_in_str(struct in_str *i, const char *s)
1364 {
1365         i->peek = static_peek;
1366         i->get = static_get;
1367 #if ENABLE_HUSH_INTERACTIVE
1368         i->promptme = 1;
1369         i->promptmode = 0; /* PS1 */
1370 #endif
1371         i->p = s;
1372         i->eof_flag = 0;
1373 }
1374
1375 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
1376  * and stderr if they are redirected. */
1377 static int setup_redirects(struct child_prog *prog, int squirrel[])
1378 {
1379         int openfd, mode;
1380         struct redir_struct *redir;
1381
1382         for (redir = prog->redirects; redir; redir = redir->next) {
1383                 if (redir->dup == -1 && redir->glob_word == NULL) {
1384                         /* something went wrong in the parse.  Pretend it didn't happen */
1385                         continue;
1386                 }
1387                 if (redir->dup == -1) {
1388                         char *p;
1389                         mode = redir_table[redir->type].mode;
1390                         p = expand_string_to_string(redir->glob_word[0]);
1391                         openfd = open_or_warn(p, mode);
1392                         free(p);
1393                         if (openfd < 0) {
1394                         /* this could get lost if stderr has been redirected, but
1395                            bash and ash both lose it as well (though zsh doesn't!) */
1396                                 return 1;
1397                         }
1398                 } else {
1399                         openfd = redir->dup;
1400                 }
1401
1402                 if (openfd != redir->fd) {
1403                         if (squirrel && redir->fd < 3) {
1404                                 squirrel[redir->fd] = dup(redir->fd);
1405                         }
1406                         if (openfd == -3) {
1407                                 //close(openfd); // close(-3) ??!
1408                         } else {
1409                                 dup2(openfd, redir->fd);
1410                                 if (redir->dup == -1)
1411                                         close(openfd);
1412                         }
1413                 }
1414         }
1415         return 0;
1416 }
1417
1418 static void restore_redirects(int squirrel[])
1419 {
1420         int i, fd;
1421         for (i = 0; i < 3; i++) {
1422                 fd = squirrel[i];
1423                 if (fd != -1) {
1424                         /* We simply die on error */
1425                         xmove_fd(fd, i);
1426                 }
1427         }
1428 }
1429
1430 /* Called after [v]fork() in run_pipe(), or from builtin_exec().
1431  * Never returns.
1432  * XXX no exit() here.  If you don't exec, use _exit instead.
1433  * The at_exit handlers apparently confuse the calling process,
1434  * in particular stdin handling.  Not sure why? -- because of vfork! (vda) */
1435 static void pseudo_exec_argv(char **argv)
1436 {
1437         int i, rcode;
1438         char *p;
1439         const struct built_in_command *x;
1440
1441         for (i = 0; is_assignment(argv[i]); i++) {
1442                 debug_printf_exec("pid %d environment modification: %s\n",
1443                                 getpid(), argv[i]);
1444 // FIXME: vfork case??
1445                 p = expand_string_to_string(argv[i]);
1446                 putenv(p);
1447         }
1448         argv += i;
1449         /* If a variable is assigned in a forest, and nobody listens,
1450          * was it ever really set?
1451          */
1452         if (!argv[0])
1453                 _exit(EXIT_SUCCESS);
1454
1455         argv = expand_strvec_to_strvec(argv);
1456
1457         /*
1458          * Check if the command matches any of the builtins.
1459          * Depending on context, this might be redundant.  But it's
1460          * easier to waste a few CPU cycles than it is to figure out
1461          * if this is one of those cases.
1462          */
1463         for (x = bltins; x->cmd; x++) {
1464                 if (strcmp(argv[0], x->cmd) == 0) {
1465                         debug_printf_exec("running builtin '%s'\n", argv[0]);
1466                         rcode = x->function(argv);
1467                         fflush(stdout);
1468                         _exit(rcode);
1469                 }
1470         }
1471
1472         /* Check if the command matches any busybox applets */
1473 #if ENABLE_FEATURE_SH_STANDALONE
1474         if (strchr(argv[0], '/') == NULL) {
1475                 int a = find_applet_by_name(argv[0]);
1476                 if (a >= 0) {
1477                         if (APPLET_IS_NOEXEC(a)) {
1478                                 debug_printf_exec("running applet '%s'\n", argv[0]);
1479 // is it ok that run_applet_no_and_exit() does exit(), not _exit()?
1480                                 run_applet_no_and_exit(a, argv);
1481                         }
1482                         /* re-exec ourselves with the new arguments */
1483                         debug_printf_exec("re-execing applet '%s'\n", argv[0]);
1484                         execvp(bb_busybox_exec_path, argv);
1485                         /* If they called chroot or otherwise made the binary no longer
1486                          * executable, fall through */
1487                 }
1488         }
1489 #endif
1490
1491         debug_printf_exec("execing '%s'\n", argv[0]);
1492         execvp(argv[0], argv);
1493         bb_perror_msg("cannot exec '%s'", argv[0]);
1494         _exit(1);
1495 }
1496
1497 /* Called after [v]fork() in run_pipe()
1498  */
1499 static void pseudo_exec(struct child_prog *child)
1500 {
1501 // FIXME: buggy wrt NOMMU! Must not modify any global data
1502 // until it does exec/_exit, but currently it does
1503 // (puts malloc'ed stuff into environment)
1504         if (child->argv)
1505                 pseudo_exec_argv(child->argv);
1506
1507         if (child->group) {
1508 #if !BB_MMU
1509                 bb_error_msg_and_die("nested lists are not supported on NOMMU");
1510 #else
1511                 int rcode;
1512
1513 #if ENABLE_HUSH_INTERACTIVE
1514 // run_list_level now takes care of it?
1515 //              debug_printf_exec("pseudo_exec: setting interactive_fd=0\n");
1516 //              interactive_fd = 0;    /* crucial!!!! */
1517 #endif
1518                 debug_printf_exec("pseudo_exec: run_list\n");
1519                 rcode = run_list(child->group);
1520                 /* OK to leak memory by not calling free_pipe_list,
1521                  * since this process is about to exit */
1522                 _exit(rcode);
1523 #endif
1524         }
1525
1526         /* Can happen.  See what bash does with ">foo" by itself. */
1527         debug_printf("trying to pseudo_exec null command\n");
1528         _exit(EXIT_SUCCESS);
1529 }
1530
1531 #if ENABLE_HUSH_JOB
1532 static const char *get_cmdtext(struct pipe *pi)
1533 {
1534         char **argv;
1535         char *p;
1536         int len;
1537
1538         /* This is subtle. ->cmdtext is created only on first backgrounding.
1539          * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
1540          * On subsequent bg argv is trashed, but we won't use it */
1541         if (pi->cmdtext)
1542                 return pi->cmdtext;
1543         argv = pi->progs[0].argv;
1544         if (!argv || !argv[0])
1545                 return (pi->cmdtext = xzalloc(1));
1546
1547         len = 0;
1548         do len += strlen(*argv) + 1; while (*++argv);
1549         pi->cmdtext = p = xmalloc(len);
1550         argv = pi->progs[0].argv;
1551         do {
1552                 len = strlen(*argv);
1553                 memcpy(p, *argv, len);
1554                 p += len;
1555                 *p++ = ' ';
1556         } while (*++argv);
1557         p[-1] = '\0';
1558         return pi->cmdtext;
1559 }
1560
1561 static void insert_bg_job(struct pipe *pi)
1562 {
1563         struct pipe *thejob;
1564         int i;
1565
1566         /* Linear search for the ID of the job to use */
1567         pi->jobid = 1;
1568         for (thejob = job_list; thejob; thejob = thejob->next)
1569                 if (thejob->jobid >= pi->jobid)
1570                         pi->jobid = thejob->jobid + 1;
1571
1572         /* Add thejob to the list of running jobs */
1573         if (!job_list) {
1574                 thejob = job_list = xmalloc(sizeof(*thejob));
1575         } else {
1576                 for (thejob = job_list; thejob->next; thejob = thejob->next)
1577                         continue;
1578                 thejob->next = xmalloc(sizeof(*thejob));
1579                 thejob = thejob->next;
1580         }
1581
1582         /* Physically copy the struct job */
1583         memcpy(thejob, pi, sizeof(struct pipe));
1584         thejob->progs = xzalloc(sizeof(pi->progs[0]) * pi->num_progs);
1585         /* We cannot copy entire pi->progs[] vector! Double free()s will happen */
1586         for (i = 0; i < pi->num_progs; i++) {
1587 // TODO: do we really need to have so many fields which are just dead weight
1588 // at execution stage?
1589                 thejob->progs[i].pid = pi->progs[i].pid;
1590                 /* all other fields are not used and stay zero */
1591         }
1592         thejob->next = NULL;
1593         thejob->cmdtext = xstrdup(get_cmdtext(pi));
1594
1595         /* We don't wait for background thejobs to return -- append it
1596            to the list of backgrounded thejobs and leave it alone */
1597         printf("[%d] %d %s\n", thejob->jobid, thejob->progs[0].pid, thejob->cmdtext);
1598         last_bg_pid = thejob->progs[0].pid;
1599         last_jobid = thejob->jobid;
1600 }
1601
1602 static void remove_bg_job(struct pipe *pi)
1603 {
1604         struct pipe *prev_pipe;
1605
1606         if (pi == job_list) {
1607                 job_list = pi->next;
1608         } else {
1609                 prev_pipe = job_list;
1610                 while (prev_pipe->next != pi)
1611                         prev_pipe = prev_pipe->next;
1612                 prev_pipe->next = pi->next;
1613         }
1614         if (job_list)
1615                 last_jobid = job_list->jobid;
1616         else
1617                 last_jobid = 0;
1618 }
1619
1620 /* remove a backgrounded job */
1621 static void delete_finished_bg_job(struct pipe *pi)
1622 {
1623         remove_bg_job(pi);
1624         pi->stopped_progs = 0;
1625         free_pipe(pi, 0);
1626         free(pi);
1627 }
1628 #endif /* JOB */
1629
1630 /* Checks to see if any processes have exited -- if they
1631    have, figure out why and see if a job has completed */
1632 static int checkjobs(struct pipe* fg_pipe)
1633 {
1634         int attributes;
1635         int status;
1636 #if ENABLE_HUSH_JOB
1637         int prognum = 0;
1638         struct pipe *pi;
1639 #endif
1640         pid_t childpid;
1641         int rcode = 0;
1642
1643         attributes = WUNTRACED;
1644         if (fg_pipe == NULL) {
1645                 attributes |= WNOHANG;
1646         }
1647
1648 /* Do we do this right?
1649  * bash-3.00# sleep 20 | false
1650  * <ctrl-Z pressed>
1651  * [3]+  Stopped          sleep 20 | false
1652  * bash-3.00# echo $?
1653  * 1   <========== bg pipe is not fully done, but exitcode is already known!
1654  */
1655
1656 //FIXME: non-interactive bash does not continue even if all processes in fg pipe
1657 //are stopped. Testcase: "cat | cat" in a script (not on command line)
1658 // + killall -STOP cat
1659
1660  wait_more:
1661 // TODO: safe_waitpid?
1662         while ((childpid = waitpid(-1, &status, attributes)) > 0) {
1663                 const int dead = WIFEXITED(status) || WIFSIGNALED(status);
1664
1665 #ifdef DEBUG_SHELL_JOBS
1666                 if (WIFSTOPPED(status))
1667                         debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
1668                                         childpid, WSTOPSIG(status), WEXITSTATUS(status));
1669                 if (WIFSIGNALED(status))
1670                         debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
1671                                         childpid, WTERMSIG(status), WEXITSTATUS(status));
1672                 if (WIFEXITED(status))
1673                         debug_printf_jobs("pid %d exited, exitcode %d\n",
1674                                         childpid, WEXITSTATUS(status));
1675 #endif
1676                 /* Were we asked to wait for fg pipe? */
1677                 if (fg_pipe) {
1678                         int i;
1679                         for (i = 0; i < fg_pipe->num_progs; i++) {
1680                                 debug_printf_jobs("check pid %d\n", fg_pipe->progs[i].pid);
1681                                 if (fg_pipe->progs[i].pid == childpid) {
1682                                         /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
1683                                         if (dead) {
1684                                                 fg_pipe->progs[i].pid = 0;
1685                                                 fg_pipe->running_progs--;
1686                                                 if (i == fg_pipe->num_progs - 1)
1687                                                         /* last process gives overall exitstatus */
1688                                                         rcode = WEXITSTATUS(status);
1689                                         } else {
1690                                                 fg_pipe->progs[i].is_stopped = 1;
1691                                                 fg_pipe->stopped_progs++;
1692                                         }
1693                                         debug_printf_jobs("fg_pipe: running_progs %d stopped_progs %d\n",
1694                                                         fg_pipe->running_progs, fg_pipe->stopped_progs);
1695                                         if (fg_pipe->running_progs - fg_pipe->stopped_progs <= 0) {
1696                                                 /* All processes in fg pipe have exited/stopped */
1697 #if ENABLE_HUSH_JOB
1698                                                 if (fg_pipe->running_progs)
1699                                                         insert_bg_job(fg_pipe);
1700 #endif
1701                                                 return rcode;
1702                                         }
1703                                         /* There are still running processes in the fg pipe */
1704                                         goto wait_more;
1705                                 }
1706                         }
1707                         /* fall through to searching process in bg pipes */
1708                 }
1709
1710 #if ENABLE_HUSH_JOB
1711                 /* We asked to wait for bg or orphaned children */
1712                 /* No need to remember exitcode in this case */
1713                 for (pi = job_list; pi; pi = pi->next) {
1714                         prognum = 0;
1715                         while (prognum < pi->num_progs) {
1716                                 if (pi->progs[prognum].pid == childpid)
1717                                         goto found_pi_and_prognum;
1718                                 prognum++;
1719                         }
1720                 }
1721 #endif
1722
1723                 /* Happens when shell is used as init process (init=/bin/sh) */
1724                 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
1725                 goto wait_more;
1726
1727 #if ENABLE_HUSH_JOB
1728  found_pi_and_prognum:
1729                 if (dead) {
1730                         /* child exited */
1731                         pi->progs[prognum].pid = 0;
1732                         pi->running_progs--;
1733                         if (!pi->running_progs) {
1734                                 printf(JOB_STATUS_FORMAT, pi->jobid,
1735                                                         "Done", pi->cmdtext);
1736                                 delete_finished_bg_job(pi);
1737                         }
1738                 } else {
1739                         /* child stopped */
1740                         pi->stopped_progs++;
1741                         pi->progs[prognum].is_stopped = 1;
1742                 }
1743 #endif
1744         }
1745
1746         /* wait found no children or failed */
1747
1748         if (childpid && errno != ECHILD)
1749                 bb_perror_msg("waitpid");
1750         return rcode;
1751 }
1752
1753 #if ENABLE_HUSH_JOB
1754 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
1755 {
1756         pid_t p;
1757         int rcode = checkjobs(fg_pipe);
1758         /* Job finished, move the shell to the foreground */
1759         p = getpgid(0); /* pgid of our process */
1760         debug_printf_jobs("fg'ing ourself: getpgid(0)=%d\n", (int)p);
1761         if (tcsetpgrp(interactive_fd, p) && errno != ENOTTY)
1762                 bb_perror_msg("tcsetpgrp-4a");
1763         return rcode;
1764 }
1765 #endif
1766
1767 /* run_pipe() starts all the jobs, but doesn't wait for anything
1768  * to finish.  See checkjobs().
1769  *
1770  * return code is normally -1, when the caller has to wait for children
1771  * to finish to determine the exit status of the pipe.  If the pipe
1772  * is a simple builtin command, however, the action is done by the
1773  * time run_pipe returns, and the exit code is provided as the
1774  * return value.
1775  *
1776  * The input of the pipe is always stdin, the output is always
1777  * stdout.  The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
1778  * because it tries to avoid running the command substitution in
1779  * subshell, when that is in fact necessary.  The subshell process
1780  * now has its stdout directed to the input of the appropriate pipe,
1781  * so this routine is noticeably simpler.
1782  *
1783  * Returns -1 only if started some children. IOW: we have to
1784  * mask out retvals of builtins etc with 0xff!
1785  */
1786 static int run_pipe(struct pipe *pi)
1787 {
1788         int i;
1789         int nextin;
1790         int pipefds[2];         /* pipefds[0] is for reading */
1791         struct child_prog *child;
1792         const struct built_in_command *x;
1793         char *p;
1794         /* it is not always needed, but we aim to smaller code */
1795         int squirrel[] = { -1, -1, -1 };
1796         int rcode;
1797         const int single_fg = (pi->num_progs == 1 && pi->followup != PIPE_BG);
1798
1799         debug_printf_exec("run_pipe start: single_fg=%d\n", single_fg);
1800
1801 #if ENABLE_HUSH_JOB
1802         pi->pgrp = -1;
1803 #endif
1804         pi->running_progs = 1;
1805         pi->stopped_progs = 0;
1806
1807         /* Check if this is a simple builtin (not part of a pipe).
1808          * Builtins within pipes have to fork anyway, and are handled in
1809          * pseudo_exec.  "echo foo | read bar" doesn't work on bash, either.
1810          */
1811         child = &(pi->progs[0]);
1812         if (single_fg && child->group && child->subshell == 0) {
1813                 debug_printf("non-subshell grouping\n");
1814                 setup_redirects(child, squirrel);
1815                 debug_printf_exec(": run_list\n");
1816                 rcode = run_list(child->group) & 0xff;
1817                 restore_redirects(squirrel);
1818                 debug_printf_exec("run_pipe return %d\n", rcode);
1819                 return rcode;
1820         }
1821
1822         if (single_fg && child->argv != NULL) {
1823                 char **argv_expanded;
1824                 char **argv = child->argv;
1825
1826                 for (i = 0; is_assignment(argv[i]); i++)
1827                         continue;
1828                 if (i != 0 && argv[i] == NULL) {
1829                         /* assignments, but no command: set the local environment */
1830                         for (i = 0; argv[i] != NULL; i++) {
1831                                 debug_printf("local environment set: %s\n", argv[i]);
1832                                 p = expand_string_to_string(argv[i]);
1833                                 set_local_var(p, 0);
1834                         }
1835                         return EXIT_SUCCESS;   /* don't worry about errors in set_local_var() yet */
1836                 }
1837                 for (i = 0; is_assignment(argv[i]); i++) {
1838                         p = expand_string_to_string(argv[i]);
1839                         //sp: child->sp--;
1840                         putenv(p);
1841                 }
1842                 for (x = bltins; x->cmd; x++) {
1843                         if (strcmp(argv[i], x->cmd) == 0) {
1844                                 if (x->function == builtin_exec && argv[i+1] == NULL) {
1845                                         debug_printf("magic exec\n");
1846                                         setup_redirects(child, NULL);
1847                                         return EXIT_SUCCESS;
1848                                 }
1849                                 debug_printf("builtin inline %s\n", argv[0]);
1850                                 /* XXX setup_redirects acts on file descriptors, not FILEs.
1851                                  * This is perfect for work that comes after exec().
1852                                  * Is it really safe for inline use?  Experimentally,
1853                                  * things seem to work with glibc. */
1854                                 setup_redirects(child, squirrel);
1855                                 debug_printf_exec(": builtin '%s' '%s'...\n", x->cmd, argv[i+1]);
1856                                 //sp: if (child->sp) /* btw we can do it unconditionally... */
1857                                 argv_expanded = expand_strvec_to_strvec(argv + i);
1858                                 rcode = x->function(argv_expanded) & 0xff;
1859                                 free(argv_expanded);
1860                                 restore_redirects(squirrel);
1861                                 debug_printf_exec("run_pipe return %d\n", rcode);
1862                                 return rcode;
1863                         }
1864                 }
1865 #if ENABLE_FEATURE_SH_STANDALONE
1866                 {
1867                         int a = find_applet_by_name(argv[i]);
1868                         if (a >= 0 && APPLET_IS_NOFORK(a)) {
1869                                 setup_redirects(child, squirrel);
1870                                 save_nofork_data(&nofork_save);
1871                                 argv_expanded = argv + i;
1872                                 //sp: if (child->sp)
1873                                 argv_expanded = expand_strvec_to_strvec(argv + i);
1874                                 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n", argv_expanded[0], argv_expanded[1]);
1875                                 rcode = run_nofork_applet_prime(&nofork_save, a, argv_expanded) & 0xff;
1876                                 free(argv_expanded);
1877                                 restore_redirects(squirrel);
1878                                 debug_printf_exec("run_pipe return %d\n", rcode);
1879                                 return rcode;
1880                         }
1881                 }
1882 #endif
1883         }
1884
1885         /* Disable job control signals for shell (parent) and
1886          * for initial child code after fork */
1887         set_jobctrl_sighandler(SIG_IGN);
1888
1889         /* Going to fork a child per each pipe member */
1890         pi->running_progs = 0;
1891         nextin = 0;
1892
1893         for (i = 0; i < pi->num_progs; i++) {
1894                 child = &(pi->progs[i]);
1895                 if (child->argv)
1896                         debug_printf_exec(": pipe member '%s' '%s'...\n", child->argv[0], child->argv[1]);
1897                 else
1898                         debug_printf_exec(": pipe member with no argv\n");
1899
1900                 /* pipes are inserted between pairs of commands */
1901                 pipefds[0] = 0;
1902                 pipefds[1] = 1;
1903                 if ((i + 1) < pi->num_progs)
1904                         xpipe(pipefds);
1905
1906                 child->pid = BB_MMU ? fork() : vfork();
1907                 if (!child->pid) { /* child */
1908                         if (ENABLE_HUSH_JOB)
1909                                 die_sleep = 0; /* let nofork's xfuncs die */
1910 #if ENABLE_HUSH_JOB
1911                         /* Every child adds itself to new process group
1912                          * with pgid == pid_of_first_child_in_pipe */
1913                         if (run_list_level == 1 && interactive_fd) {
1914                                 pid_t pgrp;
1915                                 /* Don't do pgrp restore anymore on fatal signals */
1916                                 set_fatal_sighandler(SIG_DFL);
1917                                 pgrp = pi->pgrp;
1918                                 if (pgrp < 0) /* true for 1st process only */
1919                                         pgrp = getpid();
1920                                 if (setpgid(0, pgrp) == 0 && pi->followup != PIPE_BG) {
1921                                         /* We do it in *every* child, not just first,
1922                                          * to avoid races */
1923                                         tcsetpgrp(interactive_fd, pgrp);
1924                                 }
1925                         }
1926 #endif
1927                         xmove_fd(nextin, 0);
1928                         xmove_fd(pipefds[1], 1); /* write end */
1929                         if (pipefds[0] > 1)
1930                                 close(pipefds[0]); /* read end */
1931                         /* Like bash, explicit redirects override pipes,
1932                          * and the pipe fd is available for dup'ing. */
1933                         setup_redirects(child, NULL);
1934
1935                         /* Restore default handlers just prior to exec */
1936                         set_jobctrl_sighandler(SIG_DFL);
1937                         set_misc_sighandler(SIG_DFL);
1938                         signal(SIGCHLD, SIG_DFL);
1939                         pseudo_exec(child); /* does not return */
1940                 }
1941
1942                 if (child->pid < 0) { /* [v]fork failed */
1943                         /* Clearly indicate, was it fork or vfork */
1944                         bb_perror_msg(BB_MMU ? "fork" : "vfork");
1945                 } else {
1946                         pi->running_progs++;
1947 #if ENABLE_HUSH_JOB
1948                         /* Second and next children need to know pid of first one */
1949                         if (pi->pgrp < 0)
1950                                 pi->pgrp = child->pid;
1951 #endif
1952                 }
1953
1954                 if (i)
1955                         close(nextin);
1956                 if ((i + 1) < pi->num_progs)
1957                         close(pipefds[1]); /* write end */
1958                 /* Pass read (output) pipe end to next iteration */
1959                 nextin = pipefds[0];
1960         }
1961
1962         if (!pi->running_progs) {
1963                 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
1964                 return 1;
1965         }
1966
1967         debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->running_progs);
1968         return -1;
1969 }
1970
1971 #ifndef debug_print_tree
1972 static void debug_print_tree(struct pipe *pi, int lvl)
1973 {
1974         static const char *PIPE[] = {
1975                 [PIPE_SEQ] = "SEQ",
1976                 [PIPE_AND] = "AND",
1977                 [PIPE_OR ] = "OR" ,
1978                 [PIPE_BG ] = "BG" ,
1979         };
1980         static const char *RES[] = {
1981                 [RES_NONE ] = "NONE" ,
1982 #if ENABLE_HUSH_IF
1983                 [RES_IF   ] = "IF"   ,
1984                 [RES_THEN ] = "THEN" ,
1985                 [RES_ELIF ] = "ELIF" ,
1986                 [RES_ELSE ] = "ELSE" ,
1987                 [RES_FI   ] = "FI"   ,
1988 #endif
1989 #if ENABLE_HUSH_LOOPS
1990                 [RES_FOR  ] = "FOR"  ,
1991                 [RES_WHILE] = "WHILE",
1992                 [RES_UNTIL] = "UNTIL",
1993                 [RES_DO   ] = "DO"   ,
1994                 [RES_DONE ] = "DONE" ,
1995                 [RES_IN   ] = "IN"   ,
1996 #endif
1997                 [RES_XXXX ] = "XXXX" ,
1998                 [RES_SNTX ] = "SNTX" ,
1999         };
2000
2001         int pin, prn;
2002
2003         pin = 0;
2004         while (pi) {
2005                 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
2006                                 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
2007                 prn = 0;
2008                 while (prn < pi->num_progs) {
2009                         struct child_prog *child = &pi->progs[prn];
2010                         char **argv = child->argv;
2011
2012                         fprintf(stderr, "%*s prog %d", lvl*2, "", prn);
2013                         if (child->group) {
2014                                 fprintf(stderr, " group %s: (argv=%p)\n",
2015                                                 (child->subshell ? "()" : "{}"),
2016                                                 argv);
2017                                 debug_print_tree(child->group, lvl+1);
2018                                 prn++;
2019                                 continue;
2020                         }
2021                         if (argv) while (*argv) {
2022                                 fprintf(stderr, " '%s'", *argv);
2023                                 argv++;
2024                         }
2025                         fprintf(stderr, "\n");
2026                         prn++;
2027                 }
2028                 pi = pi->next;
2029                 pin++;
2030         }
2031 }
2032 #endif
2033
2034 /* NB: called by pseudo_exec, and therefore must not modify any
2035  * global data until exec/_exit (we can be a child after vfork!) */
2036 static int run_list(struct pipe *pi)
2037 {
2038         struct pipe *rpipe;
2039 #if ENABLE_HUSH_LOOPS
2040         char *for_varname = NULL;
2041         char **for_lcur = NULL;
2042         char **for_list = NULL;
2043         int flag_rep = 0;
2044 #endif
2045         int flag_skip = 1;
2046         int rcode = 0; /* probably for gcc only */
2047         int flag_restore = 0;
2048 #if ENABLE_HUSH_IF
2049         int if_code = 0, next_if_code = 0;  /* need double-buffer to handle elif */
2050 #else
2051         enum { if_code = 0, next_if_code = 0 };
2052 #endif
2053         reserved_style rword;
2054         reserved_style skip_more_for_this_rword = RES_XXXX;
2055
2056         debug_printf_exec("run_list start lvl %d\n", run_list_level + 1);
2057
2058 #if ENABLE_HUSH_LOOPS
2059         /* check syntax for "for" */
2060         for (rpipe = pi; rpipe; rpipe = rpipe->next) {
2061                 if ((rpipe->res_word == RES_IN || rpipe->res_word == RES_FOR)
2062                  && (rpipe->next == NULL)
2063                 ) {
2064                         syntax("malformed for"); /* no IN or no commands after IN */
2065                         debug_printf_exec("run_list lvl %d return 1\n", run_list_level);
2066                         return 1;
2067                 }
2068                 if ((rpipe->res_word == RES_IN && rpipe->next->res_word == RES_IN && rpipe->next->progs[0].argv != NULL)
2069                  || (rpipe->res_word == RES_FOR && rpipe->next->res_word != RES_IN)
2070                 ) {
2071                         /* TODO: what is tested in the first condition? */
2072                         syntax("malformed for"); /* 2nd condition: not followed by IN */
2073                         debug_printf_exec("run_list lvl %d return 1\n", run_list_level);
2074                         return 1;
2075                 }
2076         }
2077 #else
2078         rpipe = NULL;
2079 #endif
2080
2081 #if ENABLE_HUSH_JOB
2082         /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
2083          * We are saving state before entering outermost list ("while...done")
2084          * so that ctrl-Z will correctly background _entire_ outermost list,
2085          * not just a part of it (like "sleep 1 | exit 2") */
2086         if (++run_list_level == 1 && interactive_fd) {
2087                 if (sigsetjmp(toplevel_jb, 1)) {
2088                         /* ctrl-Z forked and we are parent; or ctrl-C.
2089                          * Sighandler has longjmped us here */
2090                         signal(SIGINT, SIG_IGN);
2091                         signal(SIGTSTP, SIG_IGN);
2092                         /* Restore level (we can be coming from deep inside
2093                          * nested levels) */
2094                         run_list_level = 1;
2095 #if ENABLE_FEATURE_SH_STANDALONE
2096                         if (nofork_save.saved) { /* if save area is valid */
2097                                 debug_printf_jobs("exiting nofork early\n");
2098                                 restore_nofork_data(&nofork_save);
2099                         }
2100 #endif
2101                         if (ctrl_z_flag) {
2102                                 /* ctrl-Z has forked and stored pid of the child in pi->pid.
2103                                  * Remember this child as background job */
2104                                 insert_bg_job(pi);
2105                         } else {
2106                                 /* ctrl-C. We just stop doing whatever we were doing */
2107                                 bb_putchar('\n');
2108                         }
2109                         rcode = 0;
2110                         goto ret;
2111                 }
2112                 /* ctrl-Z handler will store pid etc in pi */
2113                 toplevel_list = pi;
2114                 ctrl_z_flag = 0;
2115 #if ENABLE_FEATURE_SH_STANDALONE
2116                 nofork_save.saved = 0; /* in case we will run a nofork later */
2117 #endif
2118                 signal_SA_RESTART(SIGTSTP, handler_ctrl_z);
2119                 signal(SIGINT, handler_ctrl_c);
2120         }
2121 #endif /* JOB */
2122
2123         for (; pi; pi = flag_restore ? rpipe : pi->next) {
2124 //why?          int save_num_progs;
2125                 rword = pi->res_word;
2126 #if ENABLE_HUSH_LOOPS
2127                 if (rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR) {
2128                         flag_restore = 0;
2129                         if (!rpipe) {
2130                                 flag_rep = 0;
2131                                 rpipe = pi;
2132                         }
2133                 }
2134 #endif
2135                 debug_printf_exec(": rword=%d if_code=%d next_if_code=%d skip_more=%d\n",
2136                                 rword, if_code, next_if_code, skip_more_for_this_rword);
2137                 if (rword == skip_more_for_this_rword && flag_skip) {
2138                         if (pi->followup == PIPE_SEQ)
2139                                 flag_skip = 0;
2140                         continue;
2141                 }
2142                 flag_skip = 1;
2143                 skip_more_for_this_rword = RES_XXXX;
2144 #if ENABLE_HUSH_IF
2145                 if (rword == RES_THEN || rword == RES_ELSE)
2146                         if_code = next_if_code;
2147                 if (rword == RES_THEN && if_code)
2148                         continue;
2149                 if (rword == RES_ELSE && !if_code)
2150                         continue;
2151                 if (rword == RES_ELIF && !if_code)
2152                         break;
2153 #endif
2154 #if ENABLE_HUSH_LOOPS
2155                 if (rword == RES_FOR && pi->num_progs) {
2156                         if (!for_lcur) {
2157                                 /* first loop through for */
2158                                 /* if no variable values after "in" we skip "for" */
2159                                 if (!pi->next->progs->argv)
2160                                         continue;
2161                                 /* create list of variable values */
2162                                 for_list = expand_strvec_to_strvec(pi->next->progs->argv);
2163                                 for_lcur = for_list;
2164                                 for_varname = pi->progs->argv[0];
2165                                 pi->progs->argv[0] = NULL;
2166                                 flag_rep = 1;
2167                         }
2168                         free(pi->progs->argv[0]);
2169                         if (!*for_lcur) {
2170                                 /* for loop is over, clean up */
2171                                 free(for_list);
2172                                 for_lcur = NULL;
2173                                 flag_rep = 0;
2174                                 pi->progs->argv[0] = for_varname;
2175                                 continue;
2176                         }
2177                         /* insert next value from for_lcur */
2178                         /* vda: does it need escaping? */
2179                         pi->progs->argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
2180                 }
2181                 if (rword == RES_IN)
2182                         continue;
2183                 if (rword == RES_DO) {
2184                         if (!flag_rep)
2185                                 continue;
2186                 }
2187                 if (rword == RES_DONE) {
2188                         if (flag_rep) {
2189                                 flag_restore = 1;
2190                         } else {
2191                                 rpipe = NULL;
2192                         }
2193                 }
2194 #endif
2195                 if (pi->num_progs == 0)
2196                         continue;
2197 //why?          save_num_progs = pi->num_progs;
2198                 debug_printf_exec(": run_pipe with %d members\n", pi->num_progs);
2199                 rcode = run_pipe(pi);
2200                 if (rcode != -1) {
2201                         /* We only ran a builtin: rcode was set by the return value
2202                          * of run_pipe(), and we don't need to wait for anything. */
2203                 } else if (pi->followup == PIPE_BG) {
2204                         /* What does bash do with attempts to background builtins? */
2205                         /* Even bash 3.2 doesn't do that well with nested bg:
2206                          * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
2207                          * I'm NOT treating inner &'s as jobs */
2208 #if ENABLE_HUSH_JOB
2209                         if (run_list_level == 1)
2210                                 insert_bg_job(pi);
2211 #endif
2212                         rcode = EXIT_SUCCESS;
2213                 } else {
2214 #if ENABLE_HUSH_JOB
2215                         if (run_list_level == 1 && interactive_fd) {
2216                                 /* waits for completion, then fg's main shell */
2217                                 rcode = checkjobs_and_fg_shell(pi);
2218                         } else
2219 #endif
2220                         {
2221                                 /* this one just waits for completion */
2222                                 rcode = checkjobs(pi);
2223                         }
2224                         debug_printf_exec(": checkjobs returned %d\n", rcode);
2225                 }
2226                 debug_printf_exec(": setting last_return_code=%d\n", rcode);
2227                 last_return_code = rcode;
2228 //why?          pi->num_progs = save_num_progs;
2229 #if ENABLE_HUSH_IF
2230                 if (rword == RES_IF || rword == RES_ELIF)
2231                         next_if_code = rcode;  /* can be overwritten a number of times */
2232 #endif
2233 #if ENABLE_HUSH_LOOPS
2234                 if (rword == RES_WHILE)
2235                         flag_rep = !last_return_code;
2236                 if (rword == RES_UNTIL)
2237                         flag_rep = last_return_code;
2238 #endif
2239                 if ((rcode == EXIT_SUCCESS && pi->followup == PIPE_OR)
2240                  || (rcode != EXIT_SUCCESS && pi->followup == PIPE_AND)
2241                 ) {
2242                         skip_more_for_this_rword = rword;
2243                 }
2244                 checkjobs(NULL);
2245         }
2246
2247 #if ENABLE_HUSH_JOB
2248         if (ctrl_z_flag) {
2249                 /* ctrl-Z forked somewhere in the past, we are the child,
2250                  * and now we completed running the list. Exit. */
2251                 exit(rcode);
2252         }
2253  ret:
2254         if (!--run_list_level && interactive_fd) {
2255                 signal(SIGTSTP, SIG_IGN);
2256                 signal(SIGINT, SIG_IGN);
2257         }
2258 #endif
2259         debug_printf_exec("run_list lvl %d return %d\n", run_list_level + 1, rcode);
2260         return rcode;
2261 }
2262
2263 /* return code is the exit status of the pipe */
2264 static int free_pipe(struct pipe *pi, int indent)
2265 {
2266         char **p;
2267         struct child_prog *child;
2268         struct redir_struct *r, *rnext;
2269         int a, i, ret_code = 0;
2270
2271         if (pi->stopped_progs > 0)
2272                 return ret_code;
2273         debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
2274         for (i = 0; i < pi->num_progs; i++) {
2275                 child = &pi->progs[i];
2276                 debug_printf_clean("%s  command %d:\n", indenter(indent), i);
2277                 if (child->argv) {
2278                         for (a = 0, p = child->argv; *p; a++, p++) {
2279                                 debug_printf_clean("%s   argv[%d] = %s\n", indenter(indent), a, *p);
2280                         }
2281                         free_strings(child->argv);
2282                         child->argv = NULL;
2283                 } else if (child->group) {
2284                         debug_printf_clean("%s   begin group (subshell:%d)\n", indenter(indent), child->subshell);
2285                         ret_code = free_pipe_list(child->group, indent+3);
2286                         debug_printf_clean("%s   end group\n", indenter(indent));
2287                 } else {
2288                         debug_printf_clean("%s   (nil)\n", indenter(indent));
2289                 }
2290                 for (r = child->redirects; r; r = rnext) {
2291                         debug_printf_clean("%s   redirect %d%s", indenter(indent), r->fd, redir_table[r->type].descrip);
2292                         if (r->dup == -1) {
2293                                 /* guard against the case >$FOO, where foo is unset or blank */
2294                                 if (r->glob_word) {
2295                                         debug_printf_clean(" %s\n", r->glob_word[0]);
2296                                         free_strings(r->glob_word);
2297                                         r->glob_word = NULL;
2298                                 }
2299                         } else {
2300                                 debug_printf_clean("&%d\n", r->dup);
2301                         }
2302                         rnext = r->next;
2303                         free(r);
2304                 }
2305                 child->redirects = NULL;
2306         }
2307         free(pi->progs);   /* children are an array, they get freed all at once */
2308         pi->progs = NULL;
2309 #if ENABLE_HUSH_JOB
2310         free(pi->cmdtext);
2311         pi->cmdtext = NULL;
2312 #endif
2313         return ret_code;
2314 }
2315
2316 static int free_pipe_list(struct pipe *head, int indent)
2317 {
2318         int rcode = 0;   /* if list has no members */
2319         struct pipe *pi, *next;
2320
2321         for (pi = head; pi; pi = next) {
2322                 debug_printf_clean("%s pipe reserved mode %d\n", indenter(indent), pi->res_word);
2323                 rcode = free_pipe(pi, indent);
2324                 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
2325                 next = pi->next;
2326                 /*pi->next = NULL;*/
2327                 free(pi);
2328         }
2329         return rcode;
2330 }
2331
2332 /* Select which version we will use */
2333 static int run_and_free_list(struct pipe *pi)
2334 {
2335         int rcode = 0;
2336         debug_printf_exec("run_and_free_list entered\n");
2337         if (!fake_mode) {
2338                 debug_printf_exec(": run_list with %d members\n", pi->num_progs);
2339                 rcode = run_list(pi);
2340         }
2341         /* free_pipe_list has the side effect of clearing memory.
2342          * In the long run that function can be merged with run_list,
2343          * but doing that now would hobble the debugging effort. */
2344         free_pipe_list(pi, /* indent: */ 0);
2345         debug_printf_exec("run_nad_free_list return %d\n", rcode);
2346         return rcode;
2347 }
2348
2349 /* Whoever decided to muck with glob internal data is AN IDIOT! */
2350 /* uclibc happily changed the way it works (and it has rights to do so!),
2351    all hell broke loose (SEGVs) */
2352
2353 /* The API for glob is arguably broken.  This routine pushes a non-matching
2354  * string into the output structure, removing non-backslashed backslashes.
2355  * If someone can prove me wrong, by performing this function within the
2356  * original glob(3) api, feel free to rewrite this routine into oblivion.
2357  * XXX broken if the last character is '\\', check that before calling.
2358  */
2359 static char **globhack(const char *src, char **strings)
2360 {
2361         int cnt;
2362         const char *s;
2363         char *v, *dest;
2364
2365         for (cnt = 1, s = src; s && *s; s++) {
2366                 if (*s == '\\') s++;
2367                 cnt++;
2368         }
2369         v = dest = xmalloc(cnt);
2370         for (s = src; s && *s; s++, dest++) {
2371                 if (*s == '\\') s++;
2372                 *dest = *s;
2373         }
2374         *dest = '\0';
2375
2376         return add_string_to_strings(strings, v);
2377 }
2378
2379 /* XXX broken if the last character is '\\', check that before calling */
2380 static int glob_needed(const char *s)
2381 {
2382         for (; *s; s++) {
2383                 if (*s == '\\')
2384                         s++;
2385                 if (strchr("*[?", *s))
2386                         return 1;
2387         }
2388         return 0;
2389 }
2390
2391 static int xglob(o_string *dest, char ***pglob)
2392 {
2393         /* short-circuit for null word */
2394         /* we can code this better when the debug_printf's are gone */
2395         if (dest->length == 0) {
2396                 if (dest->nonnull) {
2397                         /* bash man page calls this an "explicit" null */
2398                         *pglob = globhack(dest->data, *pglob);
2399                 }
2400                 return 0;
2401         }
2402
2403         if (glob_needed(dest->data)) {
2404                 glob_t globdata;
2405                 int gr;
2406
2407                 memset(&globdata, 0, sizeof(globdata));
2408                 gr = glob(dest->data, 0, NULL, &globdata);
2409                 debug_printf("glob returned %d\n", gr);
2410                 if (gr == GLOB_NOSPACE)
2411                         bb_error_msg_and_die("out of memory during glob");
2412                 if (gr == GLOB_NOMATCH) {
2413                         debug_printf("globhack returned %d\n", gr);
2414                         /* quote removal, or more accurately, backslash removal */
2415                         *pglob = globhack(dest->data, *pglob);
2416                         globfree(&globdata);
2417                         return 0;
2418                 }
2419                 if (gr != 0) { /* GLOB_ABORTED ? */
2420                         bb_error_msg("glob(3) error %d", gr);
2421                 }
2422                 if (globdata.gl_pathv && globdata.gl_pathv[0])
2423                         *pglob = add_strings_to_strings(1, *pglob, globdata.gl_pathv);
2424                 globfree(&globdata);
2425                 return gr;
2426         }
2427
2428         *pglob = globhack(dest->data, *pglob);
2429         return 0;
2430 }
2431
2432 /* expand_strvec_to_strvec() takes a list of strings, expands
2433  * all variable references within and returns a pointer to
2434  * a list of expanded strings, possibly with larger number
2435  * of strings. (Think VAR="a b"; echo $VAR).
2436  * This new list is allocated as a single malloc block.
2437  * NULL-terminated list of char* pointers is at the beginning of it,
2438  * followed by strings themself.
2439  * Caller can deallocate entire list by single free(list). */
2440
2441 /* Helpers first:
2442  * count_XXX estimates size of the block we need. It's okay
2443  * to over-estimate sizes a bit, if it makes code simpler */
2444 static int count_ifs(const char *str)
2445 {
2446         int cnt = 0;
2447         debug_printf_expand("count_ifs('%s') ifs='%s'", str, ifs);
2448         while (1) {
2449                 str += strcspn(str, ifs);
2450                 if (!*str) break;
2451                 str++; /* str += strspn(str, ifs); */
2452                 cnt++; /* cnt += strspn(str, ifs); - but this code is larger */
2453         }
2454         debug_printf_expand(" return %d\n", cnt);
2455         return cnt;
2456 }
2457
2458 static void count_var_expansion_space(int *countp, int *lenp, char *arg)
2459 {
2460         char first_ch;
2461         int i;
2462         int len = *lenp;
2463         int count = *countp;
2464         const char *val;
2465         char *p;
2466
2467         while ((p = strchr(arg, SPECIAL_VAR_SYMBOL))) {
2468                 len += p - arg;
2469                 arg = ++p;
2470                 p = strchr(p, SPECIAL_VAR_SYMBOL);
2471                 first_ch = arg[0];
2472
2473                 switch (first_ch & 0x7f) {
2474                 /* high bit in 1st_ch indicates that var is double-quoted */
2475                 case '$': /* pid */
2476                 case '!': /* bg pid */
2477                 case '?': /* exitcode */
2478                 case '#': /* argc */
2479                         len += sizeof(int)*3 + 1; /* enough for int */
2480                         break;
2481                 case '*':
2482                 case '@':
2483                         for (i = 1; global_argv[i]; i++) {
2484                                 len += strlen(global_argv[i]) + 1;
2485                                 count++;
2486                                 if (!(first_ch & 0x80))
2487                                         count += count_ifs(global_argv[i]);
2488                         }
2489                         break;
2490                 default:
2491                         *p = '\0';
2492                         arg[0] = first_ch & 0x7f;
2493                         if (isdigit(arg[0])) {
2494                                 i = xatoi_u(arg);
2495                                 val = NULL;
2496                                 if (i < global_argc)
2497                                         val = global_argv[i];
2498                         } else
2499                                 val = lookup_param(arg);
2500                         arg[0] = first_ch;
2501                         *p = SPECIAL_VAR_SYMBOL;
2502
2503                         if (val) {
2504                                 len += strlen(val) + 1;
2505                                 if (!(first_ch & 0x80))
2506                                         count += count_ifs(val);
2507                         }
2508                 }
2509                 arg = ++p;
2510         }
2511
2512         len += strlen(arg) + 1;
2513         count++;
2514         *lenp = len;
2515         *countp = count;
2516 }
2517
2518 /* Store given string, finalizing the word and starting new one whenever
2519  * we encounter ifs char(s). This is used for expanding variable values.
2520  * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
2521 static int expand_on_ifs(char **list, int n, char **posp, const char *str)
2522 {
2523         char *pos = *posp;
2524         while (1) {
2525                 int word_len = strcspn(str, ifs);
2526                 if (word_len) {
2527                         memcpy(pos, str, word_len); /* store non-ifs chars */
2528                         pos += word_len;
2529                         str += word_len;
2530                 }
2531                 if (!*str)  /* EOL - do not finalize word */
2532                         break;
2533                 *pos++ = '\0';
2534                 if (n) debug_printf_expand("expand_on_ifs finalized list[%d]=%p '%s' "
2535                         "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2536                         strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2537                 list[n++] = pos;
2538                 str += strspn(str, ifs); /* skip ifs chars */
2539         }
2540         *posp = pos;
2541         return n;
2542 }
2543
2544 /* Expand all variable references in given string, adding words to list[]
2545  * at n, n+1,... positions. Return updated n (so that list[n] is next one
2546  * to be filled). This routine is extremely tricky: has to deal with
2547  * variables/parameters with whitespace, $* and $@, and constructs like
2548  * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
2549 /* NB: another bug is that we cannot detect empty strings yet:
2550  * "" or $empty"" expands to zero words, has to expand to empty word */
2551 static int expand_vars_to_list(char **list, int n, char **posp, char *arg, char or_mask)
2552 {
2553         /* or_mask is either 0 (normal case) or 0x80
2554          * (expansion of right-hand side of assignment == 1-element expand) */
2555
2556         char first_ch, ored_ch;
2557         int i;
2558         const char *val;
2559         char *p;
2560         char *pos = *posp;
2561
2562         ored_ch = 0;
2563
2564         if (n) debug_printf_expand("expand_vars_to_list finalized list[%d]=%p '%s' "
2565                 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2566                 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2567         list[n++] = pos;
2568
2569         while ((p = strchr(arg, SPECIAL_VAR_SYMBOL))) {
2570                 memcpy(pos, arg, p - arg);
2571                 pos += (p - arg);
2572                 arg = ++p;
2573                 p = strchr(p, SPECIAL_VAR_SYMBOL);
2574
2575                 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
2576                 ored_ch |= first_ch;
2577                 val = NULL;
2578                 switch (first_ch & 0x7f) {
2579                 /* Highest bit in first_ch indicates that var is double-quoted */
2580                 case '$': /* pid */
2581                         /* FIXME: (echo $$) should still print pid of main shell */
2582                         val = utoa(getpid()); /* rootpid? */
2583                         break;
2584                 case '!': /* bg pid */
2585                         val = last_bg_pid ? utoa(last_bg_pid) : (char*)"";
2586                         break;
2587                 case '?': /* exitcode */
2588                         val = utoa(last_return_code);
2589                         break;
2590                 case '#': /* argc */
2591                         val = utoa(global_argc ? global_argc-1 : 0);
2592                         break;
2593                 case '*':
2594                 case '@':
2595                         i = 1;
2596                         if (!global_argv[i])
2597                                 break;
2598                         if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
2599                                 while (global_argv[i]) {
2600                                         n = expand_on_ifs(list, n, &pos, global_argv[i]);
2601                                         debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, global_argc-1);
2602                                         if (global_argv[i++][0] && global_argv[i]) {
2603                                                 /* this argv[] is not empty and not last:
2604                                                  * put terminating NUL, start new word */
2605                                                 *pos++ = '\0';
2606                                                 if (n) debug_printf_expand("expand_vars_to_list 2 finalized list[%d]=%p '%s' "
2607                                                         "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2608                                                         strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2609                                                 list[n++] = pos;
2610                                         }
2611                                 }
2612                         } else
2613                         /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2614                          * and in this case should treat it like '$*' - see 'else...' below */
2615                         if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
2616                                 while (1) {
2617                                         strcpy(pos, global_argv[i]);
2618                                         pos += strlen(global_argv[i]);
2619                                         if (++i >= global_argc)
2620                                                 break;
2621                                         *pos++ = '\0';
2622                                         if (n) debug_printf_expand("expand_vars_to_list 3 finalized list[%d]=%p '%s' "
2623                                                 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2624                                                         strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2625                                         list[n++] = pos;
2626                                 }
2627                         } else { /* quoted $*: add as one word */
2628                                 while (1) {
2629                                         strcpy(pos, global_argv[i]);
2630                                         pos += strlen(global_argv[i]);
2631                                         if (!global_argv[++i])
2632                                                 break;
2633                                         if (ifs[0])
2634                                                 *pos++ = ifs[0];
2635                                 }
2636                         }
2637                         break;
2638                 default:
2639                         *p = '\0';
2640                         arg[0] = first_ch & 0x7f;
2641                         if (isdigit(arg[0])) {
2642                                 i = xatoi_u(arg);
2643                                 val = NULL;
2644                                 if (i < global_argc)
2645                                         val = global_argv[i];
2646                         } else
2647                                 val = lookup_param(arg);
2648                         arg[0] = first_ch;
2649                         *p = SPECIAL_VAR_SYMBOL;
2650                         if (!(first_ch & 0x80)) { /* unquoted $VAR */
2651                                 if (val) {
2652                                         n = expand_on_ifs(list, n, &pos, val);
2653                                         val = NULL;
2654                                 }
2655                         } /* else: quoted $VAR, val will be appended at pos */
2656                 }
2657                 if (val) {
2658                         strcpy(pos, val);
2659                         pos += strlen(val);
2660                 }
2661                 arg = ++p;
2662         }
2663         debug_printf_expand("expand_vars_to_list adding tail '%s' at %p\n", arg, pos);
2664         strcpy(pos, arg);
2665         pos += strlen(arg) + 1;
2666         if (pos == list[n-1] + 1) { /* expansion is empty */
2667                 if (!(ored_ch & 0x80)) { /* all vars were not quoted... */
2668                         debug_printf_expand("expand_vars_to_list list[%d] empty, going back\n", n);
2669                         pos--;
2670                         n--;
2671                 }
2672         }
2673
2674         *posp = pos;
2675         return n;
2676 }
2677
2678 static char **expand_variables(char **argv, char or_mask)
2679 {
2680         int n;
2681         int count = 1;
2682         int len = 0;
2683         char *pos, **v, **list;
2684
2685         v = argv;
2686         if (!*v) debug_printf_expand("count_var_expansion_space: "
2687                         "argv[0]=NULL count=%d len=%d alloc_space=%d\n",
2688                         count, len, sizeof(char*) * count + len);
2689         while (*v) {
2690                 count_var_expansion_space(&count, &len, *v);
2691                 debug_printf_expand("count_var_expansion_space: "
2692                         "'%s' count=%d len=%d alloc_space=%d\n",
2693                         *v, count, len, sizeof(char*) * count + len);
2694                 v++;
2695         }
2696         len += sizeof(char*) * count; /* total to alloc */
2697         list = xmalloc(len);
2698         pos = (char*)(list + count);
2699         debug_printf_expand("list=%p, list[0] should be %p\n", list, pos);
2700         n = 0;
2701         v = argv;
2702         while (*v)
2703                 n = expand_vars_to_list(list, n, &pos, *v++, or_mask);
2704
2705         if (n) debug_printf_expand("finalized list[%d]=%p '%s' "
2706                 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2707                 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2708         list[n] = NULL;
2709
2710 #ifdef DEBUG_EXPAND
2711         {
2712                 int m = 0;
2713                 while (m <= n) {
2714                         debug_printf_expand("list[%d]=%p '%s'\n", m, list[m], list[m]);
2715                         m++;
2716                 }
2717                 debug_printf_expand("used_space=%d\n", pos - (char*)list);
2718         }
2719 #endif
2720         if (ENABLE_HUSH_DEBUG)
2721                 if (pos - (char*)list > len)
2722                         bb_error_msg_and_die("BUG in varexp");
2723         return list;
2724 }
2725
2726 static char **expand_strvec_to_strvec(char **argv)
2727 {
2728         return expand_variables(argv, 0);
2729 }
2730
2731 static char *expand_string_to_string(const char *str)
2732 {
2733         char *argv[2], **list;
2734
2735         argv[0] = (char*)str;
2736         argv[1] = NULL;
2737         list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
2738         if (ENABLE_HUSH_DEBUG)
2739                 if (!list[0] || list[1])
2740                         bb_error_msg_and_die("BUG in varexp2");
2741         /* actually, just move string 2*sizeof(char*) bytes back */
2742         strcpy((char*)list, list[0]);
2743         debug_printf_expand("string_to_string='%s'\n", (char*)list);
2744         return (char*)list;
2745 }
2746
2747 static char* expand_strvec_to_string(char **argv)
2748 {
2749         char **list;
2750
2751         list = expand_variables(argv, 0x80);
2752         /* Convert all NULs to spaces */
2753         if (list[0]) {
2754                 int n = 1;
2755                 while (list[n]) {
2756                         if (ENABLE_HUSH_DEBUG)
2757                                 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2758                                         bb_error_msg_and_die("BUG in varexp3");
2759                         list[n][-1] = ' '; /* TODO: or to ifs[0]? */
2760                         n++;
2761                 }
2762         }
2763         strcpy((char*)list, list[0]);
2764         debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2765         return (char*)list;
2766 }
2767
2768 /* This is used to get/check local shell variables */
2769 static struct variable *get_local_var(const char *name)
2770 {
2771         struct variable *cur;
2772         int len;
2773
2774         if (!name)
2775                 return NULL;
2776         len = strlen(name);
2777         for (cur = top_var; cur; cur = cur->next) {
2778                 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
2779                         return cur;
2780         }
2781         return NULL;
2782 }
2783
2784 /* str holds "NAME=VAL" and is expected to be malloced.
2785  * We take ownership of it. */
2786 static int set_local_var(char *str, int flg_export)
2787 {
2788         struct variable *cur;
2789         char *value;
2790         int name_len;
2791
2792         value = strchr(str, '=');
2793         if (!value) { /* not expected to ever happen? */
2794                 free(str);
2795                 return -1;
2796         }
2797
2798         name_len = value - str + 1; /* including '=' */
2799         cur = top_var; /* cannot be NULL (we have HUSH_VERSION and it's RO) */
2800         while (1) {
2801                 if (strncmp(cur->varstr, str, name_len) != 0) {
2802                         if (!cur->next) {
2803                                 /* Bail out. Note that now cur points
2804                                  * to last var in linked list */
2805                                 break;
2806                         }
2807                         cur = cur->next;
2808                         continue;
2809                 }
2810                 /* We found an existing var with this name */
2811                 *value = '\0';
2812                 if (cur->flg_read_only) {
2813                         bb_error_msg("%s: readonly variable", str);
2814                         free(str);
2815                         return -1;
2816                 }
2817                 unsetenv(str); /* just in case */
2818                 *value = '=';
2819                 if (strcmp(cur->varstr, str) == 0) {
2820  free_and_exp:
2821                         free(str);
2822                         goto exp;
2823                 }
2824                 if (cur->max_len >= strlen(str)) {
2825                         /* This one is from startup env, reuse space */
2826                         strcpy(cur->varstr, str);
2827                         goto free_and_exp;
2828                 }
2829                 /* max_len == 0 signifies "malloced" var, which we can
2830                  * (and has to) free */
2831                 if (!cur->max_len)
2832                         free(cur->varstr);
2833                 cur->max_len = 0;
2834                 goto set_str_and_exp;
2835         }
2836
2837         /* Not found - create next variable struct */
2838         cur->next = xzalloc(sizeof(*cur));
2839         cur = cur->next;
2840
2841  set_str_and_exp:
2842         cur->varstr = str;
2843  exp:
2844         if (flg_export)
2845                 cur->flg_export = 1;
2846         if (cur->flg_export)
2847                 return putenv(cur->varstr);
2848         return 0;
2849 }
2850
2851 static void unset_local_var(const char *name)
2852 {
2853         struct variable *cur;
2854         struct variable *prev = prev; /* for gcc */
2855         int name_len;
2856
2857         if (!name)
2858                 return;
2859         name_len = strlen(name);
2860         cur = top_var;
2861         while (cur) {
2862                 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
2863                         if (cur->flg_read_only) {
2864                                 bb_error_msg("%s: readonly variable", name);
2865                                 return;
2866                         }
2867                 /* prev is ok to use here because 1st variable, HUSH_VERSION,
2868                  * is ro, and we cannot reach this code on the 1st pass */
2869                         prev->next = cur->next;
2870                         unsetenv(cur->varstr);
2871                         if (!cur->max_len)
2872                                 free(cur->varstr);
2873                         free(cur);
2874                         return;
2875                 }
2876                 prev = cur;
2877                 cur = cur->next;
2878         }
2879 }
2880
2881 static int is_assignment(const char *s)
2882 {
2883         if (!s || !isalpha(*s))
2884                 return 0;
2885         s++;
2886         while (isalnum(*s) || *s == '_')
2887                 s++;
2888         return *s == '=';
2889 }
2890
2891 /* the src parameter allows us to peek forward to a possible &n syntax
2892  * for file descriptor duplication, e.g., "2>&1".
2893  * Return code is 0 normally, 1 if a syntax error is detected in src.
2894  * Resource errors (in xmalloc) cause the process to exit */
2895 static int setup_redirect(struct p_context *ctx, int fd, redir_type style,
2896         struct in_str *input)
2897 {
2898         struct child_prog *child = ctx->child;
2899         struct redir_struct *redir = child->redirects;
2900         struct redir_struct *last_redir = NULL;
2901
2902         /* Create a new redir_struct and drop it onto the end of the linked list */
2903         while (redir) {
2904                 last_redir = redir;
2905                 redir = redir->next;
2906         }
2907         redir = xzalloc(sizeof(struct redir_struct));
2908         /* redir->next = NULL; */
2909         /* redir->glob_word = NULL; */
2910         if (last_redir) {
2911                 last_redir->next = redir;
2912         } else {
2913                 child->redirects = redir;
2914         }
2915
2916         redir->type = style;
2917         redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
2918
2919         debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
2920
2921         /* Check for a '2>&1' type redirect */
2922         redir->dup = redirect_dup_num(input);
2923         if (redir->dup == -2) return 1;  /* syntax error */
2924         if (redir->dup != -1) {
2925                 /* Erik had a check here that the file descriptor in question
2926                  * is legit; I postpone that to "run time"
2927                  * A "-" representation of "close me" shows up as a -3 here */
2928                 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
2929         } else {
2930                 /* We do _not_ try to open the file that src points to,
2931                  * since we need to return and let src be expanded first.
2932                  * Set ctx->pending_redirect, so we know what to do at the
2933                  * end of the next parsed word. */
2934                 ctx->pending_redirect = redir;
2935         }
2936         return 0;
2937 }
2938
2939 static struct pipe *new_pipe(void)
2940 {
2941         struct pipe *pi;
2942         pi = xzalloc(sizeof(struct pipe));
2943         /*pi->num_progs = 0;*/
2944         /*pi->progs = NULL;*/
2945         /*pi->next = NULL;*/
2946         /*pi->followup = 0;  invalid */
2947         if (RES_NONE)
2948                 pi->res_word = RES_NONE;
2949         return pi;
2950 }
2951
2952 static void initialize_context(struct p_context *ctx)
2953 {
2954         ctx->child = NULL;
2955         ctx->pipe = ctx->list_head = new_pipe();
2956         ctx->pending_redirect = NULL;
2957         ctx->res_w = RES_NONE;
2958         //only ctx->parse_type is not touched... is this intentional?
2959         ctx->old_flag = 0;
2960         ctx->stack = NULL;
2961         done_command(ctx);   /* creates the memory for working child */
2962 }
2963
2964 /* normal return is 0
2965  * if a reserved word is found, and processed, return 1
2966  * should handle if, then, elif, else, fi, for, while, until, do, done.
2967  * case, function, and select are obnoxious, save those for later.
2968  */
2969 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS
2970 static int reserved_word(o_string *dest, struct p_context *ctx)
2971 {
2972         struct reserved_combo {
2973                 char literal[7];
2974                 unsigned char code;
2975                 int flag;
2976         };
2977         /* Mostly a list of accepted follow-up reserved words.
2978          * FLAG_END means we are done with the sequence, and are ready
2979          * to turn the compound list into a command.
2980          * FLAG_START means the word must start a new compound list.
2981          */
2982         static const struct reserved_combo reserved_list[] = {
2983 #if ENABLE_HUSH_IF
2984                 { "if",    RES_IF,    FLAG_THEN | FLAG_START },
2985                 { "then",  RES_THEN,  FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2986                 { "elif",  RES_ELIF,  FLAG_THEN },
2987                 { "else",  RES_ELSE,  FLAG_FI   },
2988                 { "fi",    RES_FI,    FLAG_END  },
2989 #endif
2990 #if ENABLE_HUSH_LOOPS
2991                 { "for",   RES_FOR,   FLAG_IN   | FLAG_START },
2992                 { "while", RES_WHILE, FLAG_DO   | FLAG_START },
2993                 { "until", RES_UNTIL, FLAG_DO   | FLAG_START },
2994                 { "in",    RES_IN,    FLAG_DO   },
2995                 { "do",    RES_DO,    FLAG_DONE },
2996                 { "done",  RES_DONE,  FLAG_END  }
2997 #endif
2998         };
2999
3000         const struct reserved_combo *r;
3001
3002         for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3003                 if (strcmp(dest->data, r->literal) != 0)
3004                         continue;
3005                 debug_printf("found reserved word %s, code %d\n", r->literal, r->code);
3006                 if (r->flag & FLAG_START) {
3007                         struct p_context *new;
3008                         debug_printf("push stack\n");
3009 #if ENABLE_HUSH_LOOPS
3010                         if (ctx->res_w == RES_IN || ctx->res_w == RES_FOR) {
3011                                 syntax("malformed for"); /* example: 'for if' */
3012                                 ctx->res_w = RES_SNTX;
3013                                 b_reset(dest);
3014                                 return 1;
3015                         }
3016 #endif
3017                         new = xmalloc(sizeof(*new));
3018                         *new = *ctx;   /* physical copy */
3019                         initialize_context(ctx);
3020                         ctx->stack = new;
3021                 } else if (ctx->res_w == RES_NONE || !(ctx->old_flag & (1 << r->code))) {
3022                         syntax(NULL);
3023                         ctx->res_w = RES_SNTX;
3024                         b_reset(dest);
3025                         return 1;
3026                 }
3027                 ctx->res_w = r->code;
3028                 ctx->old_flag = r->flag;
3029                 if (ctx->old_flag & FLAG_END) {
3030                         struct p_context *old;
3031                         debug_printf("pop stack\n");
3032                         done_pipe(ctx, PIPE_SEQ);
3033                         old = ctx->stack;
3034                         old->child->group = ctx->list_head;
3035                         old->child->subshell = 0;
3036                         *ctx = *old;   /* physical copy */
3037                         free(old);
3038                 }
3039                 b_reset(dest);
3040                 return 1;
3041         }
3042         return 0;
3043 }
3044 #else
3045 #define reserved_word(dest, ctx) ((int)0)
3046 #endif
3047
3048 /* Normal return is 0.
3049  * Syntax or xglob errors return 1. */
3050 static int done_word(o_string *dest, struct p_context *ctx)
3051 {
3052         struct child_prog *child = ctx->child;
3053         char ***glob_target;
3054         int gr;
3055
3056         debug_printf_parse("done_word entered: '%s' %p\n", dest->data, child);
3057         if (dest->length == 0 && !dest->nonnull) {
3058                 debug_printf_parse("done_word return 0: true null, ignored\n");
3059                 return 0;
3060         }
3061         if (ctx->pending_redirect) {
3062                 glob_target = &ctx->pending_redirect->glob_word;
3063         } else {
3064                 if (child->group) {
3065                         syntax(NULL);
3066                         debug_printf_parse("done_word return 1: syntax error, groups and arglists don't mix\n");
3067                         return 1;
3068                 }
3069                 if (!child->argv && (ctx->parse_type & PARSEFLAG_SEMICOLON)) {
3070                         debug_printf_parse(": checking '%s' for reserved-ness\n", dest->data);
3071                         if (reserved_word(dest, ctx)) {
3072                                 debug_printf_parse("done_word return %d\n", (ctx->res_w == RES_SNTX));
3073                                 return (ctx->res_w == RES_SNTX);
3074                         }
3075                 }
3076                 glob_target = &child->argv;
3077         }
3078         gr = xglob(dest, glob_target);
3079         if (gr != 0) {
3080                 debug_printf_parse("done_word return 1: xglob returned %d\n", gr);
3081                 return 1;
3082         }
3083
3084         b_reset(dest);
3085         if (ctx->pending_redirect) {
3086                 /* NB: don't free_strings(ctx->pending_redirect->glob_word) here */
3087                 if (ctx->pending_redirect->glob_word
3088                  && ctx->pending_redirect->glob_word[0]
3089                  && ctx->pending_redirect->glob_word[1]
3090                 ) {
3091                         /* more than one word resulted from globbing redir */
3092                         ctx->pending_redirect = NULL;
3093                         bb_error_msg("ambiguous redirect");
3094                         debug_printf_parse("done_word return 1: ambiguous redirect\n");
3095                         return 1;
3096                 }
3097                 ctx->pending_redirect = NULL;
3098         }
3099 #if ENABLE_HUSH_LOOPS
3100         if (ctx->res_w == RES_FOR) {
3101                 done_word(dest, ctx);
3102                 done_pipe(ctx, PIPE_SEQ);
3103         }
3104 #endif
3105         debug_printf_parse("done_word return 0\n");
3106         return 0;
3107 }
3108
3109 /* The only possible error here is out of memory, in which case
3110  * xmalloc exits. */
3111 static int done_command(struct p_context *ctx)
3112 {
3113         /* The child is really already in the pipe structure, so
3114          * advance the pipe counter and make a new, null child. */
3115         struct pipe *pi = ctx->pipe;
3116         struct child_prog *child = ctx->child;
3117
3118         if (child) {
3119                 if (child->group == NULL
3120                  && child->argv == NULL
3121                  && child->redirects == NULL
3122                 ) {
3123                         debug_printf_parse("done_command: skipping null cmd, num_progs=%d\n", pi->num_progs);
3124                         return pi->num_progs;
3125                 }
3126                 pi->num_progs++;
3127                 debug_printf_parse("done_command: ++num_progs=%d\n", pi->num_progs);
3128         } else {
3129                 debug_printf_parse("done_command: initializing, num_progs=%d\n", pi->num_progs);
3130         }
3131
3132         /* Only real trickiness here is that the uncommitted
3133          * child structure is not counted in pi->num_progs. */
3134         pi->progs = xrealloc(pi->progs, sizeof(*pi->progs) * (pi->num_progs+1));
3135         child = &pi->progs[pi->num_progs];
3136
3137         memset(child, 0, sizeof(*child));
3138         /*child->redirects = NULL;*/
3139         /*child->argv = NULL;*/
3140         /*child->is_stopped = 0;*/
3141         /*child->group = NULL;*/
3142         child->family = pi;
3143         //sp: /*child->sp = 0;*/
3144         //pt: child->parse_type = ctx->parse_type;
3145
3146         ctx->child = child;
3147         /* but ctx->pipe and ctx->list_head remain unchanged */
3148
3149         return pi->num_progs; /* used only for 0/nonzero check */
3150 }
3151
3152 static int done_pipe(struct p_context *ctx, pipe_style type)
3153 {
3154         struct pipe *new_p;
3155         int not_null;
3156
3157         debug_printf_parse("done_pipe entered, followup %d\n", type);
3158         not_null = done_command(ctx);  /* implicit closure of previous command */
3159         ctx->pipe->followup = type;
3160         ctx->pipe->res_word = ctx->res_w;
3161         /* Without this check, even just <enter> on command line generates
3162          * tree of three NOPs (!). Which is harmless but annoying.
3163          * IOW: it is safe to do it unconditionally. */
3164         if (not_null) {
3165                 new_p = new_pipe();
3166                 ctx->pipe->next = new_p;
3167                 ctx->pipe = new_p;
3168                 ctx->child = NULL;
3169                 done_command(ctx);  /* set up new pipe to accept commands */
3170         }
3171         debug_printf_parse("done_pipe return 0\n");
3172         return 0;
3173 }
3174
3175 /* peek ahead in the in_str to find out if we have a "&n" construct,
3176  * as in "2>&1", that represents duplicating a file descriptor.
3177  * returns either -2 (syntax error), -1 (no &), or the number found.
3178  */
3179 static int redirect_dup_num(struct in_str *input)
3180 {
3181         int ch, d = 0, ok = 0;
3182         ch = b_peek(input);
3183         if (ch != '&') return -1;
3184
3185         b_getch(input);  /* get the & */
3186         ch = b_peek(input);
3187         if (ch == '-') {
3188                 b_getch(input);
3189                 return -3;  /* "-" represents "close me" */
3190         }
3191         while (isdigit(ch)) {
3192                 d = d*10 + (ch-'0');
3193                 ok = 1;
3194                 b_getch(input);
3195                 ch = b_peek(input);
3196         }
3197         if (ok) return d;
3198
3199         bb_error_msg("ambiguous redirect");
3200         return -2;
3201 }
3202
3203 /* If a redirect is immediately preceded by a number, that number is
3204  * supposed to tell which file descriptor to redirect.  This routine
3205  * looks for such preceding numbers.  In an ideal world this routine
3206  * needs to handle all the following classes of redirects...
3207  *     echo 2>foo     # redirects fd  2 to file "foo", nothing passed to echo
3208  *     echo 49>foo    # redirects fd 49 to file "foo", nothing passed to echo
3209  *     echo -2>foo    # redirects fd  1 to file "foo",    "-2" passed to echo
3210  *     echo 49x>foo   # redirects fd  1 to file "foo",   "49x" passed to echo
3211  * A -1 output from this program means no valid number was found, so the
3212  * caller should use the appropriate default for this redirection.
3213  */
3214 static int redirect_opt_num(o_string *o)
3215 {
3216         int num;
3217
3218         if (o->length == 0)
3219                 return -1;
3220         for (num = 0; num < o->length; num++) {
3221                 if (!isdigit(*(o->data + num))) {
3222                         return -1;
3223                 }
3224         }
3225         /* reuse num (and save an int) */
3226         num = atoi(o->data);
3227         b_reset(o);
3228         return num;
3229 }
3230
3231 #if ENABLE_HUSH_TICK
3232 /* NB: currently disabled on NOMMU */
3233 static FILE *generate_stream_from_list(struct pipe *head)
3234 {
3235         FILE *pf;
3236         int pid, channel[2];
3237
3238         xpipe(channel);
3239 /* *** NOMMU WARNING *** */
3240 /* By using vfork here, we suspend parent till child exits or execs.
3241  * If child will not do it before it fills the pipe, it can block forever
3242  * in write(STDOUT_FILENO), and parent (shell) will be also stuck.
3243  */
3244         pid = BB_MMU ? fork() : vfork();
3245         if (pid < 0)
3246                 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
3247         if (pid == 0) { /* child */
3248                 if (ENABLE_HUSH_JOB)
3249                         die_sleep = 0; /* let nofork's xfuncs die */
3250                 close(channel[0]); /* NB: close _first_, then move fd! */
3251                 xmove_fd(channel[1], 1);
3252                 /* Prevent it from trying to handle ctrl-z etc */
3253 #if ENABLE_HUSH_JOB
3254                 run_list_level = 1;
3255 #endif
3256                 /* Process substitution is not considered to be usual
3257                  * 'command execution'.
3258                  * SUSv3 says ctrl-Z should be ignored, ctrl-C should not. */
3259                 /* Not needed, we are relying on it being disabled
3260                  * everywhere outside actual command execution. */
3261                 /*set_jobctrl_sighandler(SIG_IGN);*/
3262                 set_misc_sighandler(SIG_DFL);
3263                 /* Freeing 'head' here would break NOMMU. */
3264                 _exit(run_list(head));
3265         }
3266         close(channel[1]);
3267         pf = fdopen(channel[0], "r");
3268         return pf;
3269         /* 'head' is freed by the caller */
3270 }
3271
3272 /* Return code is exit status of the process that is run. */
3273 static int process_command_subs(o_string *dest, struct p_context *ctx,
3274         struct in_str *input, const char *subst_end)
3275 {
3276         int retcode, ch, eol_cnt;
3277         o_string result = NULL_O_STRING;
3278         struct p_context inner;
3279         FILE *p;
3280         struct in_str pipe_str;
3281
3282         initialize_context(&inner);
3283
3284         /* recursion to generate command */
3285         retcode = parse_stream(&result, &inner, input, subst_end);
3286         if (retcode != 0)
3287                 return retcode;  /* syntax error or EOF */
3288         done_word(&result, &inner);
3289         done_pipe(&inner, PIPE_SEQ);
3290         b_free(&result);
3291
3292         p = generate_stream_from_list(inner.list_head);
3293         if (p == NULL)
3294                 return 1;
3295         close_on_exec_on(fileno(p));
3296         setup_file_in_str(&pipe_str, p);
3297
3298         /* now send results of command back into original context */
3299         eol_cnt = 0;
3300         while ((ch = b_getch(&pipe_str)) != EOF) {
3301                 if (ch == '\n') {
3302                         eol_cnt++;
3303                         continue;
3304                 }
3305                 while (eol_cnt) {
3306                         b_addqchr(dest, '\n', dest->o_quote);
3307                         eol_cnt--;
3308                 }
3309                 b_addqchr(dest, ch, dest->o_quote);
3310         }
3311
3312         debug_printf("done reading from pipe, pclose()ing\n");
3313         /* This is the step that wait()s for the child.  Should be pretty
3314          * safe, since we just read an EOF from its stdout.  We could try
3315          * to do better, by using wait(), and keeping track of background jobs
3316          * at the same time.  That would be a lot of work, and contrary
3317          * to the KISS philosophy of this program. */
3318         retcode = fclose(p);
3319         free_pipe_list(inner.list_head, /* indent: */ 0);
3320         debug_printf("closed FILE from child, retcode=%d\n", retcode);
3321         return retcode;
3322 }
3323 #endif
3324
3325 static int parse_group(o_string *dest, struct p_context *ctx,
3326         struct in_str *input, int ch)
3327 {
3328         int rcode;
3329         const char *endch = NULL;
3330         struct p_context sub;
3331         struct child_prog *child = ctx->child;
3332
3333         debug_printf_parse("parse_group entered\n");
3334         if (child->argv) {
3335                 syntax(NULL);
3336                 debug_printf_parse("parse_group return 1: syntax error, groups and arglists don't mix\n");
3337                 return 1;
3338         }
3339         initialize_context(&sub);
3340         endch = "}";
3341         if (ch == '(') {
3342                 endch = ")";
3343                 child->subshell = 1;
3344         }
3345         rcode = parse_stream(dest, &sub, input, endch);
3346 //vda: err chk?
3347         done_word(dest, &sub); /* finish off the final word in the subcontext */
3348         done_pipe(&sub, PIPE_SEQ);  /* and the final command there, too */
3349         child->group = sub.list_head;
3350
3351         debug_printf_parse("parse_group return %d\n", rcode);
3352         return rcode;
3353         /* child remains "open", available for possible redirects */
3354 }
3355
3356 /* Basically useful version until someone wants to get fancier,
3357  * see the bash man page under "Parameter Expansion" */
3358 static const char *lookup_param(const char *src)
3359 {
3360         struct variable *var = get_local_var(src);
3361         if (var)
3362                 return strchr(var->varstr, '=') + 1;
3363         return NULL;
3364 }
3365
3366 /* return code: 0 for OK, 1 for syntax error */
3367 static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input)
3368 {
3369         int ch = b_peek(input);  /* first character after the $ */
3370         unsigned char quote_mask = dest->o_quote ? 0x80 : 0;
3371
3372         debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
3373         if (isalpha(ch)) {
3374                 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3375                 //sp: ctx->child->sp++;
3376                 while (1) {
3377                         debug_printf_parse(": '%c'\n", ch);
3378                         b_getch(input);
3379                         b_addchr(dest, ch | quote_mask);
3380                         quote_mask = 0;
3381                         ch = b_peek(input);
3382                         if (!isalnum(ch) && ch != '_')
3383                                 break;
3384                 }
3385                 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3386         } else if (isdigit(ch)) {
3387  make_one_char_var:
3388                 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3389                 //sp: ctx->child->sp++;
3390                 debug_printf_parse(": '%c'\n", ch);
3391                 b_getch(input);
3392                 b_addchr(dest, ch | quote_mask);
3393                 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3394         } else switch (ch) {
3395                 case '$': /* pid */
3396                 case '!': /* last bg pid */
3397                 case '?': /* last exit code */
3398                 case '#': /* number of args */
3399                 case '*': /* args */
3400                 case '@': /* args */
3401                         goto make_one_char_var;
3402                 case '{':
3403                         b_addchr(dest, SPECIAL_VAR_SYMBOL);
3404                         //sp: ctx->child->sp++;
3405                         b_getch(input);
3406                         /* XXX maybe someone will try to escape the '}' */
3407                         while (1) {
3408                                 ch = b_getch(input);
3409                                 if (ch == '}')
3410                                         break;
3411                                 if (!isalnum(ch) && ch != '_') {
3412                                         syntax("unterminated ${name}");
3413                                         debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
3414                                         return 1;
3415                                 }
3416                                 debug_printf_parse(": '%c'\n", ch);
3417                                 b_addchr(dest, ch | quote_mask);
3418                                 quote_mask = 0;
3419                         }
3420                         b_addchr(dest, SPECIAL_VAR_SYMBOL);
3421                         break;
3422 #if ENABLE_HUSH_TICK
3423                 case '(':
3424                         b_getch(input);
3425                         process_command_subs(dest, ctx, input, ")");
3426                         break;
3427 #endif
3428                 case '-':
3429                 case '_':
3430                         /* still unhandled, but should be eventually */
3431                         bb_error_msg("unhandled syntax: $%c", ch);
3432                         return 1;
3433                         break;
3434                 default:
3435                         b_addqchr(dest, '$', dest->o_quote);
3436         }
3437         debug_printf_parse("handle_dollar return 0\n");
3438         return 0;
3439 }
3440
3441 /* return code is 0 for normal exit, 1 for syntax error */
3442 static int parse_stream(o_string *dest, struct p_context *ctx,
3443         struct in_str *input, const char *end_trigger)
3444 {
3445         int ch, m;
3446         int redir_fd;
3447         redir_type redir_style;
3448         int next;
3449
3450         /* Only double-quote state is handled in the state variable dest->o_quote.
3451          * A single-quote triggers a bypass of the main loop until its mate is
3452          * found.  When recursing, quote state is passed in via dest->o_quote. */
3453
3454         debug_printf_parse("parse_stream entered, end_trigger='%s'\n", end_trigger);
3455
3456         while (1) {
3457                 m = CHAR_IFS;
3458                 next = '\0';
3459                 ch = b_getch(input);
3460                 if (ch != EOF) {
3461                         m = charmap[ch];
3462                         if (ch != '\n')
3463                                 next = b_peek(input);
3464                 }
3465                 debug_printf_parse(": ch=%c (%d) m=%d quote=%d\n",
3466                                                 ch, ch, m, dest->o_quote);
3467                 if (m == CHAR_ORDINARY
3468                  || (m != CHAR_SPECIAL && dest->o_quote)
3469                 ) {
3470                         if (ch == EOF) {
3471                                 syntax("unterminated \"");
3472                                 debug_printf_parse("parse_stream return 1: unterminated \"\n");
3473                                 return 1;
3474                         }
3475                         b_addqchr(dest, ch, dest->o_quote);
3476                         continue;
3477                 }
3478                 if (m == CHAR_IFS) {
3479                         if (done_word(dest, ctx)) {
3480                                 debug_printf_parse("parse_stream return 1: done_word!=0\n");
3481                                 return 1;
3482                         }
3483                         if (ch == EOF)
3484                                 break;
3485                         /* If we aren't performing a substitution, treat
3486                          * a newline as a command separator.
3487                          * [why we don't handle it exactly like ';'? --vda] */
3488                         if (end_trigger && ch == '\n') {
3489                                 done_pipe(ctx, PIPE_SEQ);
3490                         }
3491                 }
3492                 if ((end_trigger && strchr(end_trigger, ch))
3493                  && !dest->o_quote && ctx->res_w == RES_NONE
3494                 ) {
3495                         debug_printf_parse("parse_stream return 0: end_trigger char found\n");
3496                         return 0;
3497                 }
3498                 if (m == CHAR_IFS)
3499                         continue;
3500                 switch (ch) {
3501                 case '#':
3502                         if (dest->length == 0 && !dest->o_quote) {
3503                                 while (1) {
3504                                         ch = b_peek(input);
3505                                         if (ch == EOF || ch == '\n')
3506                                                 break;
3507                                         b_getch(input);
3508                                 }
3509                         } else {
3510                                 b_addqchr(dest, ch, dest->o_quote);
3511                         }
3512                         break;
3513                 case '\\':
3514                         if (next == EOF) {
3515                                 syntax("\\<eof>");
3516                                 debug_printf_parse("parse_stream return 1: \\<eof>\n");
3517                                 return 1;
3518                         }
3519                         b_addqchr(dest, '\\', dest->o_quote);
3520                         b_addqchr(dest, b_getch(input), dest->o_quote);
3521                         break;
3522                 case '$':
3523                         if (handle_dollar(dest, ctx, input) != 0) {
3524                                 debug_printf_parse("parse_stream return 1: handle_dollar returned non-0\n");
3525                                 return 1;
3526                         }
3527                         break;
3528                 case '\'':
3529                         dest->nonnull = 1;
3530                         while (1) {
3531                                 ch = b_getch(input);
3532                                 if (ch == EOF || ch == '\'')
3533                                         break;
3534                                 b_addchr(dest, ch);
3535                         }
3536                         if (ch == EOF) {
3537                                 syntax("unterminated '");
3538                                 debug_printf_parse("parse_stream return 1: unterminated '\n");
3539                                 return 1;
3540                         }
3541                         break;
3542                 case '"':
3543                         dest->nonnull = 1;
3544                         dest->o_quote ^= 1; /* invert */
3545                         break;
3546 #if ENABLE_HUSH_TICK
3547                 case '`':
3548                         process_command_subs(dest, ctx, input, "`");
3549                         break;
3550 #endif
3551                 case '>':
3552                         redir_fd = redirect_opt_num(dest);
3553                         done_word(dest, ctx);
3554                         redir_style = REDIRECT_OVERWRITE;
3555                         if (next == '>') {
3556                                 redir_style = REDIRECT_APPEND;
3557                                 b_getch(input);
3558                         }
3559 #if 0
3560                         else if (next == '(') {
3561                                 syntax(">(process) not supported");
3562                                 debug_printf_parse("parse_stream return 1: >(process) not supported\n");
3563                                 return 1;
3564                         }
3565 #endif
3566                         setup_redirect(ctx, redir_fd, redir_style, input);
3567                         break;
3568                 case '<':
3569                         redir_fd = redirect_opt_num(dest);
3570                         done_word(dest, ctx);
3571                         redir_style = REDIRECT_INPUT;
3572                         if (next == '<') {
3573                                 redir_style = REDIRECT_HEREIS;
3574                                 b_getch(input);
3575                         } else if (next == '>') {
3576                                 redir_style = REDIRECT_IO;
3577                                 b_getch(input);
3578                         }
3579 #if 0
3580                         else if (next == '(') {
3581                                 syntax("<(process) not supported");
3582                                 debug_printf_parse("parse_stream return 1: <(process) not supported\n");
3583                                 return 1;
3584                         }
3585 #endif
3586                         setup_redirect(ctx, redir_fd, redir_style, input);
3587                         break;
3588                 case ';':
3589                         done_word(dest, ctx);
3590                         done_pipe(ctx, PIPE_SEQ);
3591                         break;
3592                 case '&':
3593                         done_word(dest, ctx);
3594                         if (next == '&') {
3595                                 b_getch(input);
3596                                 done_pipe(ctx, PIPE_AND);
3597                         } else {
3598                                 done_pipe(ctx, PIPE_BG);
3599                         }
3600                         break;
3601                 case '|':
3602                         done_word(dest, ctx);
3603                         if (next == '|') {
3604                                 b_getch(input);
3605                                 done_pipe(ctx, PIPE_OR);
3606                         } else {
3607                                 /* we could pick up a file descriptor choice here
3608                                  * with redirect_opt_num(), but bash doesn't do it.
3609                                  * "echo foo 2| cat" yields "foo 2". */
3610                                 done_command(ctx);
3611                         }
3612                         break;
3613                 case '(':
3614                 case '{':
3615                         if (parse_group(dest, ctx, input, ch) != 0) {
3616                                 debug_printf_parse("parse_stream return 1: parse_group returned non-0\n");
3617                                 return 1;
3618                         }
3619                         break;
3620                 case ')':
3621                 case '}':
3622                         syntax("unexpected }");   /* Proper use of this character is caught by end_trigger */
3623                         debug_printf_parse("parse_stream return 1: unexpected '}'\n");
3624                         return 1;
3625                 default:
3626                         if (ENABLE_HUSH_DEBUG)
3627                                 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
3628                 }
3629         }
3630         /* Complain if quote?  No, maybe we just finished a command substitution
3631          * that was quoted.  Example:
3632          * $ echo "`cat foo` plus more"
3633          * and we just got the EOF generated by the subshell that ran "cat foo"
3634          * The only real complaint is if we got an EOF when end_trigger != NULL,
3635          * that is, we were really supposed to get end_trigger, and never got
3636          * one before the EOF.  Can't use the standard "syntax error" return code,
3637          * so that parse_stream_outer can distinguish the EOF and exit smoothly. */
3638         debug_printf_parse("parse_stream return %d\n", -(end_trigger != NULL));
3639         if (end_trigger)
3640                 return -1;
3641         return 0;
3642 }
3643
3644 static void set_in_charmap(const char *set, int code)
3645 {
3646         while (*set)
3647                 charmap[(unsigned char)*set++] = code;
3648 }
3649
3650 static void update_charmap(void)
3651 {
3652         /* char *ifs and char charmap[256] are both globals. */
3653         ifs = getenv("IFS");
3654         if (ifs == NULL)
3655                 ifs = " \t\n";
3656         /* Precompute a list of 'flow through' behavior so it can be treated
3657          * quickly up front.  Computation is necessary because of IFS.
3658          * Special case handling of IFS == " \t\n" is not implemented.
3659          * The charmap[] array only really needs two bits each,
3660          * and on most machines that would be faster (reduced L1 cache use).
3661          */
3662         memset(charmap, CHAR_ORDINARY, sizeof(charmap));
3663 #if ENABLE_HUSH_TICK
3664         set_in_charmap("\\$\"`", CHAR_SPECIAL);
3665 #else
3666         set_in_charmap("\\$\"", CHAR_SPECIAL);
3667 #endif
3668         set_in_charmap("<>;&|(){}#'", CHAR_ORDINARY_IF_QUOTED);
3669         set_in_charmap(ifs, CHAR_IFS);  /* are ordinary if quoted */
3670 }
3671
3672 /* most recursion does not come through here, the exception is
3673  * from builtin_source() and builtin_eval() */
3674 static int parse_and_run_stream(struct in_str *inp, int parse_flag)
3675 {
3676         struct p_context ctx;
3677         o_string temp = NULL_O_STRING;
3678         int rcode;
3679         do {
3680                 ctx.parse_type = parse_flag;
3681                 initialize_context(&ctx);
3682                 update_charmap();
3683                 if (!(parse_flag & PARSEFLAG_SEMICOLON) || (parse_flag & PARSEFLAG_REPARSING))
3684                         set_in_charmap(";$&|", CHAR_ORDINARY);
3685 #if ENABLE_HUSH_INTERACTIVE
3686                 inp->promptmode = 0; /* PS1 */
3687 #endif
3688                 /* We will stop & execute after each ';' or '\n'.
3689                  * Example: "sleep 9999; echo TEST" + ctrl-C:
3690                  * TEST should be printed */
3691                 rcode = parse_stream(&temp, &ctx, inp, ";\n");
3692                 if (rcode != 1 && ctx.old_flag != 0) {
3693                         syntax(NULL);
3694                 }
3695                 if (rcode != 1 && ctx.old_flag == 0) {
3696                         done_word(&temp, &ctx);
3697                         done_pipe(&ctx, PIPE_SEQ);
3698                         debug_print_tree(ctx.list_head, 0);
3699                         debug_printf_exec("parse_stream_outer: run_and_free_list\n");
3700                         run_and_free_list(ctx.list_head);
3701                 } else {
3702                         if (ctx.old_flag != 0) {
3703                                 free(ctx.stack);
3704                                 b_reset(&temp);
3705                         }
3706                         temp.nonnull = 0;
3707                         temp.o_quote = 0;
3708                         inp->p = NULL;
3709                         free_pipe_list(ctx.list_head, /* indent: */ 0);
3710                 }
3711                 b_free(&temp);
3712         } while (rcode != -1 && !(parse_flag & PARSEFLAG_EXIT_FROM_LOOP));   /* loop on syntax errors, return on EOF */
3713         return 0;
3714 }
3715
3716 static int parse_and_run_string(const char *s, int parse_flag)
3717 {
3718         struct in_str input;
3719         setup_string_in_str(&input, s);
3720         return parse_and_run_stream(&input, parse_flag);
3721 }
3722
3723 static int parse_and_run_file(FILE *f)
3724 {
3725         int rcode;
3726         struct in_str input;
3727         setup_file_in_str(&input, f);
3728         rcode = parse_and_run_stream(&input, PARSEFLAG_SEMICOLON);
3729         return rcode;
3730 }
3731
3732 #if ENABLE_HUSH_JOB
3733 /* Make sure we have a controlling tty.  If we get started under a job
3734  * aware app (like bash for example), make sure we are now in charge so
3735  * we don't fight over who gets the foreground */
3736 static void setup_job_control(void)
3737 {
3738         pid_t shell_pgrp;
3739
3740         saved_task_pgrp = shell_pgrp = getpgrp();
3741         debug_printf_jobs("saved_task_pgrp=%d\n", saved_task_pgrp);
3742         close_on_exec_on(interactive_fd);
3743
3744         /* If we were ran as 'hush &',
3745          * sleep until we are in the foreground.  */
3746         while (tcgetpgrp(interactive_fd) != shell_pgrp) {
3747                 /* Send TTIN to ourself (should stop us) */
3748                 kill(- shell_pgrp, SIGTTIN);
3749                 shell_pgrp = getpgrp();
3750         }
3751
3752         /* Ignore job-control and misc signals.  */
3753         set_jobctrl_sighandler(SIG_IGN);
3754         set_misc_sighandler(SIG_IGN);
3755 //huh?  signal(SIGCHLD, SIG_IGN);
3756
3757         /* We _must_ restore tty pgrp on fatal signals */
3758         set_fatal_sighandler(sigexit);
3759
3760         /* Put ourselves in our own process group.  */
3761         setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
3762         /* Grab control of the terminal.  */
3763         tcsetpgrp(interactive_fd, getpid());
3764 }
3765 #endif
3766
3767 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
3768 int hush_main(int argc, char **argv)
3769 {
3770         static const char version_str[] ALIGN1 = "HUSH_VERSION="HUSH_VER_STR;
3771         static const struct variable const_shell_ver = {
3772                 .next = NULL,
3773                 .varstr = (char*)version_str,
3774                 .max_len = 1, /* 0 can provoke free(name) */
3775                 .flg_export = 1,
3776                 .flg_read_only = 1,
3777         };
3778
3779         int opt;
3780         FILE *input;
3781         char **e;
3782         struct variable *cur_var;
3783
3784         INIT_G();
3785
3786         /* Deal with HUSH_VERSION */
3787         shell_ver = const_shell_ver; /* copying struct here */
3788         top_var = &shell_ver;
3789         unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
3790         /* Initialize our shell local variables with the values
3791          * currently living in the environment */
3792         cur_var = top_var;
3793         e = environ;
3794         if (e) while (*e) {
3795                 char *value = strchr(*e, '=');
3796                 if (value) { /* paranoia */
3797                         cur_var->next = xzalloc(sizeof(*cur_var));
3798                         cur_var = cur_var->next;
3799                         cur_var->varstr = *e;
3800                         cur_var->max_len = strlen(*e);
3801                         cur_var->flg_export = 1;
3802                 }
3803                 e++;
3804         }
3805         putenv((char *)version_str); /* reinstate HUSH_VERSION */
3806
3807 #if ENABLE_FEATURE_EDITING
3808         line_input_state = new_line_input_t(FOR_SHELL);
3809 #endif
3810         /* XXX what should these be while sourcing /etc/profile? */
3811         global_argc = argc;
3812         global_argv = argv;
3813         /* Initialize some more globals to non-zero values */
3814         set_cwd();
3815 #if ENABLE_HUSH_INTERACTIVE
3816 #if ENABLE_FEATURE_EDITING
3817         cmdedit_set_initial_prompt();
3818 #endif
3819         PS2 = "> ";
3820 #endif
3821
3822         if (EXIT_SUCCESS) /* otherwise is already done */
3823                 last_return_code = EXIT_SUCCESS;
3824
3825         if (argv[0] && argv[0][0] == '-') {
3826                 debug_printf("sourcing /etc/profile\n");
3827                 input = fopen("/etc/profile", "r");
3828                 if (input != NULL) {
3829                         close_on_exec_on(fileno(input));
3830                         parse_and_run_file(input);
3831                         fclose(input);
3832                 }
3833         }
3834         input = stdin;
3835
3836         while ((opt = getopt(argc, argv, "c:xif")) > 0) {
3837                 switch (opt) {
3838                 case 'c':
3839                         global_argv = argv + optind;
3840                         global_argc = argc - optind;
3841                         opt = parse_and_run_string(optarg, PARSEFLAG_SEMICOLON);
3842                         goto final_return;
3843                 case 'i':
3844                         /* Well, we cannot just declare interactiveness,
3845                          * we have to have some stuff (ctty, etc) */
3846                         /* interactive_fd++; */
3847                         break;
3848                 case 'f':
3849                         fake_mode = 1;
3850                         break;
3851                 default:
3852 #ifndef BB_VER
3853                         fprintf(stderr, "Usage: sh [FILE]...\n"
3854                                         "   or: sh -c command [args]...\n\n");
3855                         exit(EXIT_FAILURE);
3856 #else
3857                         bb_show_usage();
3858 #endif
3859                 }
3860         }
3861 #if ENABLE_HUSH_JOB
3862         /* A shell is interactive if the '-i' flag was given, or if all of
3863          * the following conditions are met:
3864          *    no -c command
3865          *    no arguments remaining or the -s flag given
3866          *    standard input is a terminal
3867          *    standard output is a terminal
3868          *    Refer to Posix.2, the description of the 'sh' utility. */
3869         if (argv[optind] == NULL && input == stdin
3870          && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3871         ) {
3872                 saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
3873                 debug_printf("saved_tty_pgrp=%d\n", saved_tty_pgrp);
3874                 if (saved_tty_pgrp >= 0) {
3875                         /* try to dup to high fd#, >= 255 */
3876                         interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3877                         if (interactive_fd < 0) {
3878                                 /* try to dup to any fd */
3879                                 interactive_fd = dup(STDIN_FILENO);
3880                                 if (interactive_fd < 0)
3881                                         /* give up */
3882                                         interactive_fd = 0;
3883                         }
3884                         // TODO: track & disallow any attempts of user
3885                         // to (inadvertently) close/redirect it
3886                 }
3887         }
3888         debug_printf("interactive_fd=%d\n", interactive_fd);
3889         if (interactive_fd) {
3890                 fcntl(interactive_fd, F_SETFD, FD_CLOEXEC);
3891                 /* Looks like they want an interactive shell */
3892                 setup_job_control();
3893                 /* -1 is special - makes xfuncs longjmp, not exit
3894                  * (we reset die_sleep = 0 whereever we [v]fork) */
3895                 die_sleep = -1;
3896                 if (setjmp(die_jmp)) {
3897                         /* xfunc has failed! die die die */
3898                         hush_exit(xfunc_error_retval);
3899                 }
3900 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
3901                 printf("\n\n%s hush - the humble shell v"HUSH_VER_STR"\n", bb_banner);
3902                 printf("Enter 'help' for a list of built-in commands.\n\n");
3903 #endif
3904         }
3905 #elif ENABLE_HUSH_INTERACTIVE
3906 /* no job control compiled, only prompt/line editing */
3907         if (argv[optind] == NULL && input == stdin
3908          && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3909         ) {
3910                 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3911                 if (interactive_fd < 0) {
3912                         /* try to dup to any fd */
3913                         interactive_fd = dup(STDIN_FILENO);
3914                         if (interactive_fd < 0)
3915                                 /* give up */
3916                                 interactive_fd = 0;
3917                 }
3918                 if (interactive_fd)
3919                         fcntl(interactive_fd, F_SETFD, FD_CLOEXEC);
3920         }
3921 #endif
3922
3923         if (argv[optind] == NULL) {
3924                 opt = parse_and_run_file(stdin);
3925         } else {
3926                 debug_printf("\nrunning script '%s'\n", argv[optind]);
3927                 global_argv = argv + optind;
3928                 global_argc = argc - optind;
3929                 input = xfopen(argv[optind], "r");
3930                 fcntl(fileno(input), F_SETFD, FD_CLOEXEC);
3931                 opt = parse_and_run_file(input);
3932         }
3933
3934  final_return:
3935
3936 #if ENABLE_FEATURE_CLEAN_UP
3937         fclose(input);
3938         if (cwd != bb_msg_unknown)
3939                 free((char*)cwd);
3940         cur_var = top_var->next;
3941         while (cur_var) {
3942                 struct variable *tmp = cur_var;
3943                 if (!cur_var->max_len)
3944                         free(cur_var->varstr);
3945                 cur_var = cur_var->next;
3946                 free(tmp);
3947         }
3948 #endif
3949         hush_exit(opt ? opt : last_return_code);
3950 }
3951
3952
3953 #if ENABLE_LASH
3954 int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
3955 int lash_main(int argc, char **argv)
3956 {
3957         //bb_error_msg("lash is deprecated, please use hush instead");
3958         return hush_main(argc, argv);
3959 }
3960 #endif