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