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