Use BUFSIZ for the_command to match size used in cmdedit
[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.
13  *      The execution engine, the builtins, and much of the underlying
14  *      support has been adapted from busybox-0.49pre's lash,
15  *      which is Copyright (C) 2000 by Lineo, Inc., and
16  *      written by Erik Andersen <andersen@lineo.com>, <andersee@debian.org>.
17  *      That, in turn, is based in part on ladsh.c, by Michael K. Johnson and
18  *      Erik W. Troan, which they placed in the public domain.  I don't know
19  *      how much of the Johnson/Troan code has survived the repeated rewrites.
20  * Other credits:
21  *      simple_itoa() was lifted from boa-0.93.15
22  *      b_addchr() derived from similar w_addchar function in glibc-2.2
23  *      setup_redirect(), redirect_opt_num(), and big chunks of main()
24  *        and many builtins derived from contributions by Erik Andersen
25  *      miscellaneous bugfixes from Matt Kraai
26  *
27  * There are two big (and related) architecture differences between
28  * this parser and the lash parser.  One is that this version is
29  * actually designed from the ground up to understand nearly all
30  * of the Bourne grammar.  The second, consequential change is that
31  * the parser and input reader have been turned inside out.  Now,
32  * the parser is in control, and asks for input as needed.  The old
33  * way had the input reader in control, and it asked for parsing to
34  * take place as needed.  The new way makes it much easier to properly
35  * handle the recursion implicit in the various substitutions, especially
36  * across continuation lines.
37  *
38  * Bash grammar not implemented: (how many of these were in original sh?)
39  *      $@ (those sure look like weird quoting rules)
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  *      Arithmetic Expansion
47  *      <(list) and >(list) Process Substitution
48  *      reserved words: if, then, elif, else, fi, while, until, for,
49  *                      do, done, case
50  *      Here Documents ( << word )
51  *      Functions
52  * Major bugs:
53  *      job handling woefully incomplete and buggy
54  *      reserved word execution woefully incomplete and buggy
55  *      incomplete reserved word sequence doesn't request more lines of input
56  * to-do:
57  *      port selected bugfixes from post-0.49 busybox lash
58  *      finish implementing reserved words
59  *      handle children going into background
60  *      clean up recognition of null pipes
61  *      have builtin_exec set flag to avoid restore_redirects
62  *      figure out if "echo foo}" is fixable
63  *      check setting of global_argc and global_argv
64  *      control-C handling, probably with longjmp
65  *      VAR=value prefix for simple commands
66  *      follow IFS rules more precisely, including update semantics
67  *      write builtin_eval, builtin_ulimit, builtin_umask
68  *      figure out what to do with backslash-newline
69  *      explain why we use signal instead of sigaction
70  *      propagate syntax errors, die on resource errors?
71  *      continuation lines, both explicit and implicit - done?
72  *      memory leak finding and plugging - done?
73  *      more testing, especially quoting rules and redirection
74  *      maybe change map[] to use 2-bit entries
75  *      (eventually) remove all the printf's
76  *      more integration with BusyBox: prompts, cmdedit, applets
77  *
78  * This program is free software; you can redistribute it and/or modify
79  * it under the terms of the GNU General Public License as published by
80  * the Free Software Foundation; either version 2 of the License, or
81  * (at your option) any later version.
82  *
83  * This program is distributed in the hope that it will be useful,
84  * but WITHOUT ANY WARRANTY; without even the implied warranty of
85  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
86  * General Public License for more details.
87  *
88  * You should have received a copy of the GNU General Public License
89  * along with this program; if not, write to the Free Software
90  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
91  */
92 #include <ctype.h>     /* isalpha, isdigit */
93 #include <unistd.h>    /* getpid */
94 #include <stdlib.h>    /* getenv, atoi */
95 #include <string.h>    /* strchr */
96 #include <stdio.h>     /* popen etc. */
97 #include <glob.h>      /* glob, of course */
98 #include <stdarg.h>    /* va_list */
99 #include <errno.h>
100 #include <fcntl.h>
101 #include <getopt.h>    /* should be pretty obvious */
102
103 #include <sys/types.h>
104 #include <sys/wait.h>
105 #include <signal.h>
106
107 /* #include <dmalloc.h> */
108 /* #define DEBUG_SHELL */
109
110 #ifdef BB_VER
111 #include "busybox.h"
112 #include "cmdedit.h"
113 #else
114 #define applet_name "hush"
115 #include "standalone.h"
116 #define shell_main main
117 #define BB_FEATURE_SH_SIMPLE_PROMPT
118 #endif
119
120 typedef enum {
121         REDIRECT_INPUT     = 1,
122         REDIRECT_OVERWRITE = 2,
123         REDIRECT_APPEND    = 3,
124         REDIRECT_HEREIS    = 4,
125         REDIRECT_IO        = 5
126 } redir_type;
127
128 /* The descrip member of this structure is only used to make debugging
129  * output pretty */
130 struct {int mode; int default_fd; char *descrip;} redir_table[] = {
131         { 0,                         0, "()" },
132         { O_RDONLY,                  0, "<"  },
133         { O_CREAT|O_TRUNC|O_WRONLY,  1, ">"  },
134         { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
135         { O_RDONLY,                 -1, "<<" },
136         { O_RDWR,                    1, "<>" }
137 };
138
139 typedef enum {
140         PIPE_SEQ = 1,
141         PIPE_AND = 2,
142         PIPE_OR  = 3,
143         PIPE_BG  = 4,
144 } pipe_style;
145
146 /* might eventually control execution */
147 typedef enum {
148         RES_NONE  = 0,
149         RES_IF    = 1,
150         RES_THEN  = 2,
151         RES_ELIF  = 3,
152         RES_ELSE  = 4,
153         RES_FI    = 5,
154         RES_FOR   = 6,
155         RES_WHILE = 7,
156         RES_UNTIL = 8,
157         RES_DO    = 9,
158         RES_DONE  = 10,
159         RES_XXXX  = 11,
160         RES_SNTX  = 12
161 } reserved_style;
162 #define FLAG_END   (1<<RES_NONE)
163 #define FLAG_IF    (1<<RES_IF)
164 #define FLAG_THEN  (1<<RES_THEN)
165 #define FLAG_ELIF  (1<<RES_ELIF)
166 #define FLAG_ELSE  (1<<RES_ELSE)
167 #define FLAG_FI    (1<<RES_FI)
168 #define FLAG_FOR   (1<<RES_FOR)
169 #define FLAG_WHILE (1<<RES_WHILE)
170 #define FLAG_UNTIL (1<<RES_UNTIL)
171 #define FLAG_DO    (1<<RES_DO)
172 #define FLAG_DONE  (1<<RES_DONE)
173 #define FLAG_START (1<<RES_XXXX)
174
175 /* This holds pointers to the various results of parsing */
176 struct p_context {
177         struct child_prog *child;
178         struct pipe *list_head;
179         struct pipe *pipe;
180         struct redir_struct *pending_redirect;
181         reserved_style w;
182         int old_flag;                           /* for figuring out valid reserved words */
183         struct p_context *stack;
184         /* How about quoting status? */
185 };
186
187 struct redir_struct {
188         redir_type type;                        /* type of redirection */
189         int fd;                                         /* file descriptor being redirected */
190         int dup;                                        /* -1, or file descriptor being duplicated */
191         struct redir_struct *next;      /* pointer to the next redirect in the list */ 
192         glob_t word;                            /* *word.gl_pathv is the filename */
193 };
194
195 struct child_prog {
196         pid_t pid;                                      /* 0 if exited */
197         char **argv;                            /* program name and arguments */
198         struct pipe *group;                     /* if non-NULL, first in group or subshell */
199         int subshell;                           /* flag, non-zero if group must be forked */
200         struct redir_struct *redirects; /* I/O redirections */
201         glob_t glob_result;                     /* result of parameter globbing */
202         int is_stopped;                         /* is the program currently running? */
203         struct pipe *family;            /* pointer back to the child's parent pipe */
204 };
205
206 struct pipe {
207         int jobid;                                      /* job number */
208         int num_progs;                          /* total number of programs in job */
209         int running_progs;                      /* number of programs running */
210         char *text;                                     /* name of job */
211         char *cmdbuf;                           /* buffer various argv's point into */
212         pid_t pgrp;                                     /* process group ID for the job */
213         struct child_prog *progs;       /* array of commands in pipe */
214         struct pipe *next;                      /* to track background commands */
215         int stopped_progs;                      /* number of programs alive, but stopped */
216         int job_context;                        /* bitmask defining current context */
217         pipe_style followup;            /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
218         reserved_style r_mode;          /* supports if, for, while, until */
219         struct jobset *job_list;
220 };
221
222 struct jobset {
223         struct pipe *head;                      /* head of list of running jobs */
224         struct pipe *fg;                        /* current foreground job */
225 };
226
227 struct close_me {
228         int fd;
229         struct close_me *next;
230 };
231
232 /* globals, connect us to the outside world
233  * the first three support $?, $#, and $1 */
234 char **global_argv;
235 unsigned int global_argc;
236 unsigned int last_return_code;
237 extern char **environ; /* This is in <unistd.h>, but protected with __USE_GNU */
238  
239 /* Variables we export */
240 unsigned int shell_context;  /* Used in cmdedit.c to reset the
241                               * context when someone hits ^C */
242
243 /* "globals" within this file */
244 static char *ifs=NULL;
245 static char map[256];
246 static int fake_mode=0;
247 static int interactive=0;
248 static struct close_me *close_me_head = NULL;
249 static char *cwd;
250 /* static struct jobset job_list = { NULL, NULL }; */
251 static unsigned int last_bg_pid=0;
252 static char *PS1;
253 static char *PS2 = "> ";
254
255 #define B_CHUNK (100)
256 #define B_NOSPAC 1
257 #define MAX_LINE 256       /* for cwd */
258 #define MAX_READ 256       /* for builtin_read */
259
260 typedef struct {
261         char *data;
262         int length;
263         int maxlen;
264         int quote;
265         int nonnull;
266 } o_string;
267 #define NULL_O_STRING {NULL,0,0,0,0}
268 /* used for initialization:
269         o_string foo = NULL_O_STRING; */
270
271 /* I can almost use ordinary FILE *.  Is open_memstream() universally
272  * available?  Where is it documented? */
273 struct in_str {
274         const char *p;
275         int __promptme;
276         int promptmode;
277         FILE *file;
278         int (*get) (struct in_str *);
279         int (*peek) (struct in_str *);
280 };
281 #define b_getch(input) ((input)->get(input))
282 #define b_peek(input) ((input)->peek(input))
283
284 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
285
286 struct built_in_command {
287         char *cmd;                                      /* name */
288         char *descr;                            /* description */
289         int (*function) (struct child_prog *);  /* function ptr */
290 };
291
292 /* belongs in busybox.h */
293 static inline int max(int a, int b) {
294         return (a>b)?a:b;
295 }
296
297 /* This should be in utility.c */
298 #ifdef DEBUG_SHELL
299 static void debug_printf(const char *format, ...)
300 {
301         va_list args;
302         va_start(args, format);
303         vfprintf(stderr, format, args);
304         va_end(args);
305 }
306 #else
307 static void debug_printf(const char *format, ...) { }
308 #endif
309 #define final_printf debug_printf
310
311 void __syntax(char *file, int line) {
312         fprintf(stderr,"syntax error %s:%d\n",file,line);
313 }
314 #define syntax() __syntax(__FILE__, __LINE__)
315
316 /* Index of subroutines: */
317 /*   function prototypes for builtins */
318 static int builtin_cd(struct child_prog *child);
319 static int builtin_env(struct child_prog *child);
320 static int builtin_exec(struct child_prog *child);
321 static int builtin_exit(struct child_prog *child);
322 static int builtin_export(struct child_prog *child);
323 static int builtin_fg_bg(struct child_prog *child);
324 static int builtin_help(struct child_prog *child);
325 static int builtin_jobs(struct child_prog *child);
326 static int builtin_pwd(struct child_prog *child);
327 static int builtin_read(struct child_prog *child);
328 static int builtin_shift(struct child_prog *child);
329 static int builtin_source(struct child_prog *child);
330 static int builtin_ulimit(struct child_prog *child);
331 static int builtin_umask(struct child_prog *child);
332 static int builtin_unset(struct child_prog *child);
333 /*   o_string manipulation: */
334 static int b_check_space(o_string *o, int len);
335 static int b_addchr(o_string *o, int ch);
336 static void b_reset(o_string *o);
337 static int b_addqchr(o_string *o, int ch, int quote);
338 static int b_adduint(o_string *o, unsigned int i);
339 /*  in_str manipulations: */
340 static int static_get(struct in_str *i);
341 static int static_peek(struct in_str *i);
342 static int file_get(struct in_str *i);
343 static int file_peek(struct in_str *i);
344 static void setup_file_in_str(struct in_str *i, FILE *f);
345 static void setup_string_in_str(struct in_str *i, const char *s);
346 /*  close_me manipulations: */
347 static void mark_open(int fd);
348 static void mark_closed(int fd);
349 static void close_all();
350 /*  "run" the final data structures: */
351 static char *indenter(int i);
352 static int run_list_test(struct pipe *head, int indent);
353 static int run_pipe_test(struct pipe *pi, int indent);
354 /*  really run the final data structures: */
355 static int setup_redirects(struct child_prog *prog, int squirrel[]);
356 static int pipe_wait(struct pipe *pi);
357 static int run_list_real(struct pipe *pi);
358 static void pseudo_exec(struct child_prog *child) __attribute__ ((noreturn));
359 static int run_pipe_real(struct pipe *pi);
360 /*   extended glob support: */
361 static int globhack(const char *src, int flags, glob_t *pglob);
362 static int glob_needed(const char *s);
363 static int xglob(o_string *dest, int flags, glob_t *pglob);
364 /*   data structure manipulation: */
365 static int setup_redirect(struct p_context *ctx, int fd, redir_type style, struct in_str *input);
366 static void initialize_context(struct p_context *ctx);
367 static int done_word(o_string *dest, struct p_context *ctx);
368 static int done_command(struct p_context *ctx);
369 static int done_pipe(struct p_context *ctx, pipe_style type);
370 /*   primary string parsing: */
371 static int redirect_dup_num(struct in_str *input);
372 static int redirect_opt_num(o_string *o);
373 static int process_command_subs(o_string *dest, struct p_context *ctx, struct in_str *input, int subst_end);
374 static int parse_group(o_string *dest, struct p_context *ctx, struct in_str *input, int ch);
375 static void lookup_param(o_string *dest, struct p_context *ctx, o_string *src);
376 static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input);
377 static int parse_string(o_string *dest, struct p_context *ctx, const char *src);
378 static int parse_stream(o_string *dest, struct p_context *ctx, struct in_str *input0, int end_trigger);
379 /*   setup: */
380 static int parse_stream_outer(struct in_str *inp);
381 static int parse_string_outer(const char *s);
382 static int parse_file_outer(FILE *f);
383
384 /* Table of built-in functions.  They can be forked or not, depending on
385  * context: within pipes, they fork.  As simple commands, they do not.
386  * When used in non-forking context, they can change global variables
387  * in the parent shell process.  If forked, of course they can not.
388  * For example, 'unset foo | whatever' will parse and run, but foo will
389  * still be set at the end. */
390 static struct built_in_command bltins[] = {
391         {"bg", "Resume a job in the background", builtin_fg_bg},
392         {"cd", "Change working directory", builtin_cd},
393         {"env", "Print all environment variables", builtin_env},
394         {"exec", "Exec command, replacing this shell with the exec'd process", builtin_exec},
395         {"exit", "Exit from shell()", builtin_exit},
396         {"export", "Set environment variable", builtin_export},
397         {"fg", "Bring job into the foreground", builtin_fg_bg},
398         {"jobs", "Lists the active jobs", builtin_jobs},
399         {"pwd", "Print current directory", builtin_pwd},
400         {"read", "Input environment variable", builtin_read},
401         {"shift", "Shift positional parameters", builtin_shift},
402         {"ulimit","Controls resource limits", builtin_ulimit},
403         {"umask","Sets file creation mask", builtin_umask},
404         {"unset", "Unset environment variable", builtin_unset},
405         {".", "Source-in and run commands in a file", builtin_source},
406         {"help", "List shell built-in commands", builtin_help},
407         {NULL, NULL, NULL}
408 };
409
410 /* built-in 'cd <path>' handler */
411 static int builtin_cd(struct child_prog *child)
412 {
413         char *newdir;
414         if (child->argv[1] == NULL)
415                 newdir = getenv("HOME");
416         else
417                 newdir = child->argv[1];
418         if (chdir(newdir)) {
419                 printf("cd: %s: %s\n", newdir, strerror(errno));
420                 return EXIT_FAILURE;
421         }
422         getcwd(cwd, sizeof(char)*MAX_LINE);
423         return EXIT_SUCCESS;
424 }
425
426 /* built-in 'env' handler */
427 static int builtin_env(struct child_prog *dummy)
428 {
429         char **e = environ;
430         if (e == NULL) return EXIT_FAILURE;
431         for (; *e; e++) {
432                 puts(*e);
433         }
434         return EXIT_SUCCESS;
435 }
436
437 /* built-in 'exec' handler */
438 static int builtin_exec(struct child_prog *child)
439 {
440         if (child->argv[1] == NULL)
441                 return EXIT_SUCCESS;   /* Really? */
442         child->argv++;
443         pseudo_exec(child);
444         /* never returns */
445 }
446
447 /* built-in 'exit' handler */
448 static int builtin_exit(struct child_prog *child)
449 {
450         if (child->argv[1] == NULL)
451                 exit(EXIT_SUCCESS);
452         exit (atoi(child->argv[1]));
453 }
454
455 /* built-in 'export VAR=value' handler */
456 static int builtin_export(struct child_prog *child)
457 {
458         int res;
459
460         if (child->argv[1] == NULL) {
461                 return (builtin_env(child));
462         }
463         res = putenv(child->argv[1]);
464         if (res)
465                 fprintf(stderr, "export: %s\n", strerror(errno));
466         return (res);
467 }
468
469 /* built-in 'fg' and 'bg' handler */
470 static int builtin_fg_bg(struct child_prog *child)
471 {
472         int i, jobNum;
473         struct pipe *job=NULL;
474         
475         if (!child->argv[1] || child->argv[2]) {
476                 error_msg("%s: exactly one argument is expected\n",
477                                 child->argv[0]);
478                 return EXIT_FAILURE;
479         }
480
481         if (sscanf(child->argv[1], "%%%d", &jobNum) != 1) {
482                 error_msg("%s: bad argument '%s'\n",
483                                 child->argv[0], child->argv[1]);
484                 return EXIT_FAILURE;
485         }
486
487         for (job = child->family->job_list->head; job; job = job->next) {
488                 if (job->jobid == jobNum) {
489                         break;
490                 }
491         }
492
493         if (!job) {
494                 error_msg("%s: unknown job %d\n",
495                                 child->argv[0], jobNum);
496                 return EXIT_FAILURE;
497         }
498
499         if (*child->argv[0] == 'f') {
500                 /* Make this job the foreground job */
501                 /* suppress messages when run from /linuxrc mag@sysgo.de */
502                 if (tcsetpgrp(0, job->pgrp) && errno != ENOTTY)
503                         perror_msg("tcsetpgrp"); 
504                 child->family->job_list->fg = job;
505         }
506
507         /* Restart the processes in the job */
508         for (i = 0; i < job->num_progs; i++)
509                 job->progs[i].is_stopped = 0;
510
511         kill(-job->pgrp, SIGCONT);
512
513         job->stopped_progs = 0;
514         return EXIT_SUCCESS;
515 }
516
517 /* built-in 'help' handler */
518 static int builtin_help(struct child_prog *dummy)
519 {
520         struct built_in_command *x;
521
522         printf("\nBuilt-in commands:\n");
523         printf("-------------------\n");
524         for (x = bltins; x->cmd; x++) {
525                 if (x->descr==NULL)
526                         continue;
527                 printf("%s\t%s\n", x->cmd, x->descr);
528         }
529         printf("\n\n");
530         return EXIT_SUCCESS;
531 }
532
533 /* built-in 'jobs' handler */
534 static int builtin_jobs(struct child_prog *child)
535 {
536         struct pipe *job;
537         char *status_string;
538
539         for (job = child->family->job_list->head; job; job = job->next) {
540                 if (job->running_progs == job->stopped_progs)
541                         status_string = "Stopped";
542                 else
543                         status_string = "Running";
544                 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->text);
545         }
546         return EXIT_SUCCESS;
547 }
548
549
550 /* built-in 'pwd' handler */
551 static int builtin_pwd(struct child_prog *dummy)
552 {
553         getcwd(cwd, MAX_LINE);
554         puts(cwd);
555         return EXIT_SUCCESS;
556 }
557
558 /* built-in 'read VAR' handler */
559 static int builtin_read(struct child_prog *child)
560 {
561         int res = 0, len, newlen;
562         char *s;
563         char string[MAX_READ];
564
565         if (child->argv[1]) {
566                 /* argument (VAR) given: put "VAR=" into buffer */
567                 strcpy(string, child->argv[1]);
568                 len = strlen(string);
569                 string[len++] = '=';
570                 string[len]   = '\0';
571                 /* XXX would it be better to go through in_str? */
572                 fgets(&string[len], sizeof(string) - len, stdin);       /* read string */
573                 newlen = strlen(string);
574                 if(newlen > len)
575                         string[--newlen] = '\0';        /* chomp trailing newline */
576                 /*
577                 ** string should now contain "VAR=<value>"
578                 ** copy it (putenv() won't do that, so we must make sure
579                 ** the string resides in a static buffer!)
580                 */
581                 res = -1;
582                 if((s = strdup(string)))
583                         res = putenv(s);
584                 if (res)
585                         fprintf(stderr, "read: %s\n", strerror(errno));
586         }
587         else
588                 fgets(string, sizeof(string), stdin);
589
590         return (res);
591 }
592
593 /* Built-in 'shift' handler */
594 static int builtin_shift(struct child_prog *child)
595 {
596         int n=1;
597         if (child->argv[1]) {
598                 n=atoi(child->argv[1]);
599         }
600         if (n>=0 && n<global_argc) {
601                 /* XXX This probably breaks $0 */
602                 global_argc -= n;
603                 global_argv += n;
604                 return EXIT_SUCCESS;
605         } else {
606                 return EXIT_FAILURE;
607         }
608 }
609
610 /* Built-in '.' handler (read-in and execute commands from file) */
611 static int builtin_source(struct child_prog *child)
612 {
613         FILE *input;
614         int status;
615
616         if (child->argv[1] == NULL)
617                 return EXIT_FAILURE;
618
619         /* XXX search through $PATH is missing */
620         input = fopen(child->argv[1], "r");
621         if (!input) {
622                 fprintf(stderr, "Couldn't open file '%s'\n", child->argv[1]);
623                 return EXIT_FAILURE;
624         }
625
626         /* Now run the file */
627         /* XXX argv and argc are broken; need to save old global_argv
628          * (pointer only is OK!) on this stack frame,
629          * set global_argv=child->argv+1, recurse, and restore. */
630         mark_open(fileno(input));
631         status = parse_file_outer(input);
632         mark_closed(fileno(input));
633         fclose(input);
634         return (status);
635 }
636
637 static int builtin_ulimit(struct child_prog *child)
638 {
639         printf("builtin_ulimit not written\n");
640         return EXIT_FAILURE;
641 }
642
643 static int builtin_umask(struct child_prog *child)
644 {
645         printf("builtin_umask not written\n");
646         return EXIT_FAILURE;
647 }
648
649 /* built-in 'unset VAR' handler */
650 static int builtin_unset(struct child_prog *child)
651 {
652         if (child->argv[1] == NULL) {
653                 fprintf(stderr, "unset: parameter required.\n");
654                 return EXIT_FAILURE;
655         }
656         unsetenv(child->argv[1]);
657         return EXIT_SUCCESS;
658 }
659
660 static int b_check_space(o_string *o, int len)
661 {
662         /* It would be easy to drop a more restrictive policy
663          * in here, such as setting a maximum string length */
664         if (o->length + len > o->maxlen) {
665                 char *old_data = o->data;
666                 /* assert (data == NULL || o->maxlen != 0); */
667                 o->maxlen += max(2*len, B_CHUNK);
668                 o->data = realloc(o->data, 1 + o->maxlen);
669                 if (o->data == NULL) {
670                         free(old_data);
671                 }
672         }
673         return o->data == NULL;
674 }
675
676 static int b_addchr(o_string *o, int ch)
677 {
678         debug_printf("b_addchr: %c %d %p\n", ch, o->length, o);
679         if (b_check_space(o, 1)) return B_NOSPAC;
680         o->data[o->length] = ch;
681         o->length++;
682         o->data[o->length] = '\0';
683         return 0;
684 }
685
686 static void b_reset(o_string *o)
687 {
688         o->length = 0;
689         o->nonnull = 0;
690         if (o->data != NULL) *o->data = '\0';
691 }
692
693 static void b_free(o_string *o)
694 {
695         b_reset(o);
696         if (o->data != NULL) free(o->data);
697         o->data = NULL;
698         o->maxlen = 0;
699 }
700
701 /* My analysis of quoting semantics tells me that state information
702  * is associated with a destination, not a source.
703  */
704 static int b_addqchr(o_string *o, int ch, int quote)
705 {
706         if (quote && strchr("*?[\\",ch)) {
707                 int rc;
708                 rc = b_addchr(o, '\\');
709                 if (rc) return rc;
710         }
711         return b_addchr(o, ch);
712 }
713
714 /* belongs in utility.c */
715 char *simple_itoa(unsigned int i)
716 {
717         /* 21 digits plus null terminator, good for 64-bit or smaller ints */
718         static char local[22];
719         char *p = &local[21];
720         *p-- = '\0';
721         do {
722                 *p-- = '0' + i % 10;
723                 i /= 10;
724         } while (i > 0);
725         return p + 1;
726 }
727
728 static int b_adduint(o_string *o, unsigned int i)
729 {
730         int r;
731         char *p = simple_itoa(i);
732         /* no escape checking necessary */
733         do r=b_addchr(o, *p++); while (r==0 && *p);
734         return r;
735 }
736
737 static int static_get(struct in_str *i)
738 {
739         int ch=*i->p++;
740         if (ch=='\0') return EOF;
741         return ch;
742 }
743
744 static int static_peek(struct in_str *i)
745 {
746         return *i->p;
747 }
748
749 static inline void cmdedit_set_initial_prompt(void)
750 {
751 #ifdef BB_FEATURE_SH_SIMPLE_PROMPT
752         PS1 = NULL;
753 #else
754         PS1 = getenv("PS1");
755         if(PS1==0)
756                 PS1 = "\\w \\$ ";
757 #endif  
758 }
759
760 static inline void setup_prompt_string(int promptmode, char **prompt_str)
761 {
762         debug_printf("setup_prompt_string %d ",promptmode);
763 #ifdef BB_FEATURE_SH_SIMPLE_PROMPT
764         /* Set up the prompt */
765         if (promptmode == 1) {
766                 if (PS1)
767                         free(PS1);
768                 PS1=xmalloc(strlen(cwd)+4);
769                 sprintf(PS1, "%s %s", cwd, ( geteuid() != 0 ) ?  "$ ":"# ");
770                 *prompt_str = PS1;
771         } else {
772                 *prompt_str = PS2;
773         }
774 #else
775         *prompt_str = (promptmode==0)? PS1 : PS2;
776 #endif
777         debug_printf("result %s\n",*prompt_str);
778 }
779
780 static void get_user_input(struct in_str *i)
781 {
782         char *prompt_str;
783         static char the_command[BUFSIZ];
784
785         setup_prompt_string(i->promptmode, &prompt_str);
786 #ifdef BB_FEATURE_COMMAND_EDITING
787         /*
788          ** enable command line editing only while a command line
789          ** is actually being read; otherwise, we'll end up bequeathing
790          ** atexit() handlers and other unwanted stuff to our
791          ** child processes (rob@sysgo.de)
792          */
793         cmdedit_read_input(prompt_str, the_command);
794         cmdedit_terminate();
795 #else
796         fputs(prompt_str, stdout);
797         fflush(stdout);
798         the_command[0]=fgetc(i->file);
799         the_command[1]='\0';
800 #endif
801         i->p = the_command;
802 }
803
804 /* This is the magic location that prints prompts 
805  * and gets data back from the user */
806 static int file_get(struct in_str *i)
807 {
808         int ch;
809
810         ch = 0;
811         /* If there is data waiting, eat it up */
812         if (i->p && *i->p) {
813                 ch=*i->p++;
814         } else {
815                 /* need to double check i->file because we might be doing something
816                  * more complicated by now, like sourcing or substituting. */
817                 if (i->__promptme && interactive && i->file == stdin) {
818                         get_user_input(i);
819                         i->promptmode=2;
820                 }
821                 i->__promptme = 0;
822
823                 if (i->p && *i->p) {
824                         ch=*i->p++;
825                 }
826                 debug_printf("b_getch: got a %d\n", ch);
827         }
828         if (ch == '\n') i->__promptme=1;
829         return ch;
830 }
831
832 /* All the callers guarantee this routine will never be
833  * used right after a newline, so prompting is not needed.
834  */
835 static int file_peek(struct in_str *i)
836 {
837         if (i->p && *i->p) {
838                 return *i->p;
839         } else {
840                 static char buffer;
841                 buffer = fgetc(i->file);
842                 i->p = &buffer;
843                 debug_printf("b_peek: got a %d\n", *i->p);
844                 return *i->p; 
845         }
846 }
847
848 static void setup_file_in_str(struct in_str *i, FILE *f)
849 {
850         i->peek = file_peek;
851         i->get = file_get;
852         i->__promptme=1;
853         i->promptmode=1;
854         i->file = f;
855         i->p = NULL;
856 }
857
858 static void setup_string_in_str(struct in_str *i, const char *s)
859 {
860         i->peek = static_peek;
861         i->get = static_get;
862         i->__promptme=1;
863         i->promptmode=1;
864         i->p = s;
865 }
866
867 static void mark_open(int fd)
868 {
869         struct close_me *new = xmalloc(sizeof(struct close_me));
870         new->fd = fd;
871         new->next = close_me_head;
872         close_me_head = new;
873 }
874
875 static void mark_closed(int fd)
876 {
877         struct close_me *tmp;
878         if (close_me_head == NULL || close_me_head->fd != fd)
879                 error_msg_and_die("corrupt close_me");
880         tmp = close_me_head;
881         close_me_head = close_me_head->next;
882         free(tmp);
883 }
884
885 static void close_all()
886 {
887         struct close_me *c;
888         for (c=close_me_head; c; c=c->next) {
889                 close(c->fd);
890         }
891         close_me_head = NULL;
892 }
893
894 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
895  * and stderr if they are redirected. */
896 static int setup_redirects(struct child_prog *prog, int squirrel[])
897 {
898         int openfd, mode;
899         struct redir_struct *redir;
900
901         for (redir=prog->redirects; redir; redir=redir->next) {
902                 if (redir->dup == -1) {
903                         mode=redir_table[redir->type].mode;
904                         openfd = open(redir->word.gl_pathv[0], mode, 0666);
905                         if (openfd < 0) {
906                         /* this could get lost if stderr has been redirected, but
907                            bash and ash both lose it as well (though zsh doesn't!) */
908                                 fprintf(stderr,"error opening %s: %s\n", redir->word.gl_pathv[0],
909                                         strerror(errno));
910                                 return 1;
911                         }
912                 } else {
913                         openfd = redir->dup;
914                 }
915
916                 if (openfd != redir->fd) {
917                         if (squirrel && redir->fd < 3) {
918                                 squirrel[redir->fd] = dup(redir->fd);
919                         }
920                         dup2(openfd, redir->fd);
921                         close(openfd);
922                 }
923         }
924         return 0;
925 }
926
927 static void restore_redirects(int squirrel[])
928 {
929         int i, fd;
930         for (i=0; i<3; i++) {
931                 fd = squirrel[i];
932                 if (fd != -1) {
933                         /* No error checking.  I sure wouldn't know what
934                          * to do with an error if I found one! */
935                         dup2(fd, i);
936                         close(fd);
937                 }
938         }
939 }
940
941 /* XXX this definitely needs some more thought, work, and
942  * cribbing from other shells */
943 static int pipe_wait(struct pipe *pi)
944 {
945         int rcode=0, i, pid, running, status;
946         running = pi->num_progs;
947         while (running) {
948                 pid=waitpid(-1, &status, 0);
949                 if (pid < 0) perror_msg_and_die("waitpid");
950                 for (i=0; i < pi->num_progs; i++) {
951                         if (pi->progs[i].pid == pid) {
952                                 if (i==pi->num_progs-1) rcode=WEXITSTATUS(status);
953                                 pi->progs[i].pid = 0;
954                                 running--;
955                                 break;
956                         }
957                 }
958         }
959         return rcode;
960 }
961
962 /* very simple version for testing */
963 static void pseudo_exec(struct child_prog *child)
964 {
965         int rcode;
966         struct built_in_command *x;
967         if (child->argv) {
968                 /*
969                  * Check if the command matches any of the builtins.
970                  * Depending on context, this might be redundant.  But it's
971                  * easier to waste a few CPU cycles than it is to figure out
972                  * if this is one of those cases.
973                  */
974                 for (x = bltins; x->cmd; x++) {
975                         if (strcmp(child->argv[0], x->cmd) == 0 ) {
976                                 debug_printf("builtin exec %s\n", child->argv[0]);
977                                 exit(x->function(child));
978                         }
979                 }
980                 debug_printf("exec of %s\n",child->argv[0]);
981                 execvp(child->argv[0],child->argv);
982                 perror("execvp");
983                 exit(1);
984         } else if (child->group) {
985                 debug_printf("runtime nesting to group\n");
986                 interactive=0;    /* crucial!!!! */
987                 rcode = run_list_real(child->group);
988                 /* OK to leak memory by not calling run_list_test,
989                  * since this process is about to exit */
990                 exit(rcode);
991         } else {
992                 /* Can happen.  See what bash does with ">foo" by itself. */
993                 debug_printf("trying to pseudo_exec null command\n");
994                 exit(EXIT_SUCCESS);
995         }
996 }
997
998 /* run_pipe_real() starts all the jobs, but doesn't wait for anything
999  * to finish.  See pipe_wait().
1000  *
1001  * return code is normally -1, when the caller has to wait for children
1002  * to finish to determine the exit status of the pipe.  If the pipe
1003  * is a simple builtin command, however, the action is done by the
1004  * time run_pipe_real returns, and the exit code is provided as the
1005  * return value.
1006  *
1007  * The input of the pipe is always stdin, the output is always
1008  * stdout.  The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
1009  * because it tries to avoid running the command substitution in
1010  * subshell, when that is in fact necessary.  The subshell process
1011  * now has its stdout directed to the input of the appropriate pipe,
1012  * so this routine is noticeably simpler.
1013  */
1014 static int run_pipe_real(struct pipe *pi)
1015 {
1016         int i;
1017         int nextin, nextout;
1018         int pipefds[2];                         /* pipefds[0] is for reading */
1019         struct child_prog *child;
1020         struct built_in_command *x;
1021
1022         nextin = 0;
1023         pi->pgrp = 0;
1024
1025         /* Check if this is a simple builtin (not part of a pipe).
1026          * Builtins within pipes have to fork anyway, and are handled in
1027          * pseudo_exec.  "echo foo | read bar" doesn't work on bash, either.
1028          */
1029         if (pi->num_progs == 1 && pi->progs[0].argv != NULL) {
1030                 child = & (pi->progs[0]);
1031                 if (child->group && ! child->subshell) {
1032                         int squirrel[] = {-1, -1, -1};
1033                         int rcode;
1034                         debug_printf("non-subshell grouping\n");
1035                         setup_redirects(child, squirrel);
1036                         /* XXX could we merge code with following builtin case,
1037                          * by creating a pseudo builtin that calls run_list_real? */
1038                         rcode = run_list_real(child->group);
1039                         restore_redirects(squirrel);
1040                         return rcode;
1041                 }
1042                 for (x = bltins; x->cmd; x++) {
1043                         if (strcmp(child->argv[0], x->cmd) == 0 ) {
1044                                 int squirrel[] = {-1, -1, -1};
1045                                 int rcode;
1046                                 debug_printf("builtin inline %s\n", child->argv[0]);
1047                                 /* XXX setup_redirects acts on file descriptors, not FILEs.
1048                                  * This is perfect for work that comes after exec().
1049                                  * Is it really safe for inline use?  Experimentally,
1050                                  * things seem to work with glibc. */
1051                                 setup_redirects(child, squirrel);
1052                                 rcode = x->function(child);
1053                                 restore_redirects(squirrel);
1054                                 return rcode;
1055                         }
1056                 }
1057         }
1058
1059         for (i = 0; i < pi->num_progs; i++) {
1060                 child = & (pi->progs[i]);
1061
1062                 /* pipes are inserted between pairs of commands */
1063                 if ((i + 1) < pi->num_progs) {
1064                         if (pipe(pipefds)<0) perror_msg_and_die("pipe");
1065                         nextout = pipefds[1];
1066                 } else {
1067                         nextout=1;
1068                         pipefds[0] = -1;
1069                 }
1070
1071                 /* XXX test for failed fork()? */
1072                 if (!(child->pid = fork())) {
1073                         close_all();
1074
1075                         if (nextin != 0) {
1076                                 dup2(nextin, 0);
1077                                 close(nextin);
1078                         }
1079                         if (nextout != 1) {
1080                                 dup2(nextout, 1);
1081                                 close(nextout);
1082                         }
1083                         if (pipefds[0]!=-1) {
1084                                 close(pipefds[0]);  /* opposite end of our output pipe */
1085                         }
1086
1087                         /* Like bash, explicit redirects override pipes,
1088                          * and the pipe fd is available for dup'ing. */
1089                         setup_redirects(child,NULL);
1090
1091                         pseudo_exec(child);
1092                 }
1093                 if (interactive) {
1094                         /* Put our child in the process group whose leader is the
1095                          * first process in this pipe. */
1096                         if (pi->pgrp==0) {
1097                                 pi->pgrp = child->pid;
1098                         }
1099                         /* Don't check for errors.  The child may be dead already,
1100                          * in which case setpgid returns error code EACCES. */
1101                         setpgid(child->pid, pi->pgrp);
1102                 }
1103                 /* In the non-interactive case, do nothing.  Leave the children
1104                  * with the process group that they inherited from us. */
1105         
1106                 if (nextin != 0)
1107                         close(nextin);
1108                 if (nextout != 1)
1109                         close(nextout);
1110
1111                 /* If there isn't another process, nextin is garbage 
1112                    but it doesn't matter */
1113                 nextin = pipefds[0];
1114         }
1115         return -1;
1116 }
1117
1118 static int run_list_real(struct pipe *pi)
1119 {
1120         int rcode=0;
1121         int if_code=0, next_if_code=0;  /* need double-buffer to handle elif */
1122         reserved_style rmode=RES_NONE;
1123         for (;pi;pi=pi->next) {
1124                 rmode = pi->r_mode;
1125                 debug_printf("rmode=%d  if_code=%d  next_if_code=%d\n", rmode, if_code, next_if_code);
1126                 if (rmode == RES_THEN || rmode == RES_ELSE) if_code = next_if_code;
1127                 if (rmode == RES_THEN &&  if_code) continue;
1128                 if (rmode == RES_ELSE && !if_code) continue;
1129                 if (rmode == RES_ELIF && !if_code) continue;
1130                 if (pi->num_progs == 0) break;
1131                 rcode = run_pipe_real(pi);
1132                 if (rcode!=-1) {
1133                         /* We only ran a builtin: rcode was set by the return value
1134                          * of run_pipe_real(), and we don't need to wait for anything. */
1135                 } else if (pi->followup==PIPE_BG) {
1136                         /* XXX check bash's behavior with nontrivial pipes */
1137                         /* XXX compute jobid */
1138                         /* XXX what does bash do with attempts to background builtins? */
1139                         printf("[%d] %d\n", pi->jobid, pi->pgrp);
1140                         last_bg_pid = pi->pgrp;
1141                         rcode = EXIT_SUCCESS;
1142                 } else {
1143                         if (interactive) {
1144                                 /* move the new process group into the foreground */
1145                                 /* suppress messages when run from /linuxrc mag@sysgo.de */
1146                                 signal(SIGTTIN, SIG_IGN);
1147                                 signal(SIGTTOU, SIG_IGN);
1148                                 if (tcsetpgrp(0, pi->pgrp) && errno != ENOTTY)
1149                                         perror_msg("tcsetpgrp");
1150                                 rcode = pipe_wait(pi);
1151                                 if (tcsetpgrp(0, getpid()) && errno != ENOTTY)
1152                                         perror_msg("tcsetpgrp");
1153                                 signal(SIGTTIN, SIG_DFL);
1154                                 signal(SIGTTOU, SIG_DFL);
1155                         } else {
1156                                 rcode = pipe_wait(pi);
1157                         }
1158                 }
1159                 last_return_code=rcode;
1160                 if ( rmode == RES_IF || rmode == RES_ELIF )
1161                         next_if_code=rcode;  /* can be overwritten a number of times */
1162                 if ( (rcode==EXIT_SUCCESS && pi->followup==PIPE_OR) ||
1163                      (rcode!=EXIT_SUCCESS && pi->followup==PIPE_AND) )
1164                         return rcode;  /* XXX broken if list is part of if/then/else */
1165         }
1166         return rcode;
1167 }
1168
1169 /* broken, of course, but OK for testing */
1170 static char *indenter(int i)
1171 {
1172         static char blanks[]="                                    ";
1173         return &blanks[sizeof(blanks)-i-1];
1174 }
1175
1176 /* return code is the exit status of the pipe */
1177 static int run_pipe_test(struct pipe *pi, int indent)
1178 {
1179         char **p;
1180         struct child_prog *child;
1181         struct redir_struct *r, *rnext;
1182         int a, i, ret_code=0;
1183         char *ind = indenter(indent);
1184         final_printf("%s run pipe: (pid %d)\n",ind,getpid());
1185         for (i=0; i<pi->num_progs; i++) {
1186                 child = &pi->progs[i];
1187                 final_printf("%s  command %d:\n",ind,i);
1188                 if (child->argv) {
1189                         for (a=0,p=child->argv; *p; a++,p++) {
1190                                 final_printf("%s   argv[%d] = %s\n",ind,a,*p);
1191                         }
1192                         globfree(&child->glob_result);
1193                         child->argv=NULL;
1194                 } else if (child->group) {
1195                         final_printf("%s   begin group (subshell:%d)\n",ind, child->subshell);
1196                         ret_code = run_list_test(child->group,indent+3);
1197                         final_printf("%s   end group\n",ind);
1198                 } else {
1199                         final_printf("%s   (nil)\n",ind);
1200                 }
1201                 for (r=child->redirects; r; r=rnext) {
1202                         final_printf("%s   redirect %d%s", ind, r->fd, redir_table[r->type].descrip);
1203                         if (r->dup == -1) {
1204                                 final_printf(" %s\n", *r->word.gl_pathv);
1205                                 globfree(&r->word);
1206                         } else {
1207                                 final_printf("&%d\n", r->dup);
1208                         }
1209                         rnext=r->next;
1210                         free(r);
1211                 }
1212                 child->redirects=NULL;
1213         }
1214         free(pi->progs);   /* children are an array, they get freed all at once */
1215         pi->progs=NULL;
1216         return ret_code;
1217 }
1218
1219 static int run_list_test(struct pipe *head, int indent)
1220 {
1221         int rcode=0;   /* if list has no members */
1222         struct pipe *pi, *next;
1223         char *ind = indenter(indent);
1224         for (pi=head; pi; pi=next) {
1225                 if (pi->num_progs == 0) break;
1226                 final_printf("%s pipe reserved mode %d\n", ind, pi->r_mode);
1227                 rcode = run_pipe_test(pi, indent);
1228                 final_printf("%s pipe followup code %d\n", ind, pi->followup);
1229                 next=pi->next;
1230                 pi->next=NULL;
1231                 free(pi);
1232         }
1233         return rcode;   
1234 }
1235
1236 /* Select which version we will use */
1237 static int run_list(struct pipe *pi)
1238 {
1239         int rcode=0;
1240         if (fake_mode==0) {
1241                 rcode = run_list_real(pi);
1242         } 
1243         /* run_list_test has the side effect of clearing memory
1244          * In the long run that function can be merged with run_list_real,
1245          * but doing that now would hobble the debugging effort. */
1246         run_list_test(pi,0);
1247         return rcode;
1248 }
1249
1250 /* The API for glob is arguably broken.  This routine pushes a non-matching
1251  * string into the output structure, removing non-backslashed backslashes.
1252  * If someone can prove me wrong, by performing this function within the
1253  * original glob(3) api, feel free to rewrite this routine into oblivion.
1254  * Return code (0 vs. GLOB_NOSPACE) matches glob(3).
1255  * XXX broken if the last character is '\\', check that before calling.
1256  */
1257 static int globhack(const char *src, int flags, glob_t *pglob)
1258 {
1259         int cnt, pathc;
1260         const char *s;
1261         char *dest;
1262         for (cnt=1, s=src; *s; s++) {
1263                 if (*s == '\\') s++;
1264                 cnt++;
1265         }
1266         dest = malloc(cnt);
1267         if (!dest) return GLOB_NOSPACE;
1268         if (!(flags & GLOB_APPEND)) {
1269                 pglob->gl_pathv=NULL;
1270                 pglob->gl_pathc=0;
1271                 pglob->gl_offs=0;
1272                 pglob->gl_offs=0;
1273         }
1274         pathc = ++pglob->gl_pathc;
1275         pglob->gl_pathv = realloc(pglob->gl_pathv, (pathc+1)*sizeof(*pglob->gl_pathv));
1276         if (pglob->gl_pathv == NULL) return GLOB_NOSPACE;
1277         pglob->gl_pathv[pathc-1]=dest;
1278         pglob->gl_pathv[pathc]=NULL;
1279         for (s=src; *s; s++, dest++) {
1280                 if (*s == '\\') s++;
1281                 *dest = *s;
1282         }
1283         *dest='\0';
1284         return 0;
1285 }
1286
1287 /* XXX broken if the last character is '\\', check that before calling */
1288 static int glob_needed(const char *s)
1289 {
1290         for (; *s; s++) {
1291                 if (*s == '\\') s++;
1292                 if (strchr("*[?",*s)) return 1;
1293         }
1294         return 0;
1295 }
1296
1297 #if 0
1298 static void globprint(glob_t *pglob)
1299 {
1300         int i;
1301         debug_printf("glob_t at %p:\n", pglob);
1302         debug_printf("  gl_pathc=%d  gl_pathv=%p  gl_offs=%d  gl_flags=%d\n",
1303                 pglob->gl_pathc, pglob->gl_pathv, pglob->gl_offs, pglob->gl_flags);
1304         for (i=0; i<pglob->gl_pathc; i++)
1305                 debug_printf("pglob->gl_pathv[%d] = %p = %s\n", i,
1306                         pglob->gl_pathv[i], pglob->gl_pathv[i]);
1307 }
1308 #endif
1309
1310 static int xglob(o_string *dest, int flags, glob_t *pglob)
1311 {
1312         int gr;
1313
1314         /* short-circuit for null word */
1315         /* we can code this better when the debug_printf's are gone */
1316         if (dest->length == 0) {
1317                 if (dest->nonnull) {
1318                         /* bash man page calls this an "explicit" null */
1319                         gr = globhack(dest->data, flags, pglob);
1320                         debug_printf("globhack returned %d\n",gr);
1321                 } else {
1322                         return 0;
1323                 }
1324         } else if (glob_needed(dest->data)) {
1325                 gr = glob(dest->data, flags, NULL, pglob);
1326                 debug_printf("glob returned %d\n",gr);
1327                 if (gr == GLOB_NOMATCH) {
1328                         /* quote removal, or more accurately, backslash removal */
1329                         gr = globhack(dest->data, flags, pglob);
1330                         debug_printf("globhack returned %d\n",gr);
1331                 }
1332         } else {
1333                 gr = globhack(dest->data, flags, pglob);
1334                 debug_printf("globhack returned %d\n",gr);
1335         }
1336         if (gr == GLOB_NOSPACE) {
1337                 fprintf(stderr,"out of memory during glob\n");
1338                 exit(1);
1339         }
1340         if (gr != 0) { /* GLOB_ABORTED ? */
1341                 fprintf(stderr,"glob(3) error %d\n",gr);
1342         }
1343         /* globprint(glob_target); */
1344         return gr;
1345 }
1346
1347 /* the src parameter allows us to peek forward to a possible &n syntax
1348  * for file descriptor duplication, e.g., "2>&1".
1349  * Return code is 0 normally, 1 if a syntax error is detected in src.
1350  * Resource errors (in xmalloc) cause the process to exit */
1351 static int setup_redirect(struct p_context *ctx, int fd, redir_type style,
1352         struct in_str *input)
1353 {
1354         struct child_prog *child=ctx->child;
1355         struct redir_struct *redir = child->redirects;
1356         struct redir_struct *last_redir=NULL;
1357
1358         /* Create a new redir_struct and drop it onto the end of the linked list */
1359         while(redir) {
1360                 last_redir=redir;
1361                 redir=redir->next;
1362         }
1363         redir = xmalloc(sizeof(struct redir_struct));
1364         redir->next=NULL;
1365         if (last_redir) {
1366                 last_redir->next=redir;
1367         } else {
1368                 child->redirects=redir;
1369         }
1370
1371         redir->type=style;
1372         redir->fd= (fd==-1) ? redir_table[style].default_fd : fd ;
1373
1374         debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
1375
1376         /* Check for a '2>&1' type redirect */ 
1377         redir->dup = redirect_dup_num(input);
1378         if (redir->dup == -2) return 1;  /* syntax error */
1379         if (redir->dup != -1) {
1380                 /* Erik had a check here that the file descriptor in question
1381                  * is legit; I postpone that to "run time" */
1382                 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
1383         } else {
1384                 /* We do _not_ try to open the file that src points to,
1385                  * since we need to return and let src be expanded first.
1386                  * Set ctx->pending_redirect, so we know what to do at the
1387                  * end of the next parsed word.
1388                  */
1389                 ctx->pending_redirect = redir;
1390         }
1391         return 0;
1392 }
1393
1394 struct pipe *new_pipe(void) {
1395         struct pipe *pi;
1396         pi = xmalloc(sizeof(struct pipe));
1397         pi->num_progs = 0;
1398         pi->progs = NULL;
1399         pi->next = NULL;
1400         pi->followup = 0;  /* invalid */
1401         return pi;
1402 }
1403
1404 static void initialize_context(struct p_context *ctx)
1405 {
1406         ctx->pipe=NULL;
1407         ctx->pending_redirect=NULL;
1408         ctx->child=NULL;
1409         ctx->list_head=new_pipe();
1410         ctx->pipe=ctx->list_head;
1411         ctx->w=RES_NONE;
1412         ctx->stack=NULL;
1413         done_command(ctx);   /* creates the memory for working child */
1414 }
1415
1416 /* normal return is 0
1417  * if a reserved word is found, and processed, return 1
1418  * should handle if, then, elif, else, fi, for, while, until, do, done.
1419  * case, function, and select are obnoxious, save those for later.
1420  */
1421 int reserved_word(o_string *dest, struct p_context *ctx)
1422 {
1423         struct reserved_combo {
1424                 char *literal;
1425                 int code;
1426                 long flag;
1427         };
1428         /* Mostly a list of accepted follow-up reserved words.
1429          * FLAG_END means we are done with the sequence, and are ready
1430          * to turn the compound list into a command.
1431          * FLAG_START means the word must start a new compound list.
1432          */
1433         static struct reserved_combo reserved_list[] = {
1434                 { "if",    RES_IF,    FLAG_THEN | FLAG_START },
1435                 { "then",  RES_THEN,  FLAG_ELIF | FLAG_ELSE | FLAG_FI },
1436                 { "elif",  RES_ELIF,  FLAG_THEN },
1437                 { "else",  RES_ELSE,  FLAG_FI   },
1438                 { "fi",    RES_FI,    FLAG_END  },
1439                 { "for",   RES_FOR,   FLAG_DO   | FLAG_START },
1440                 { "while", RES_WHILE, FLAG_DO   | FLAG_START },
1441                 { "until", RES_UNTIL, FLAG_DO   | FLAG_START },
1442                 { "do",    RES_DO,    FLAG_DONE },
1443                 { "done",  RES_DONE,  FLAG_END  }
1444         };
1445         struct reserved_combo *r;
1446         for (r=reserved_list;
1447 #define NRES sizeof(reserved_list)/sizeof(struct reserved_combo)
1448                 r<reserved_list+NRES; r++) {
1449                 if (strcmp(dest->data, r->literal) == 0) {
1450                         debug_printf("found reserved word %s, code %d\n",r->literal,r->code);
1451                         if (r->flag & FLAG_START) {
1452                                 struct p_context *new = xmalloc(sizeof(struct p_context));
1453                                 debug_printf("push stack\n");
1454                                 *new = *ctx;   /* physical copy */
1455                                 initialize_context(ctx);
1456                                 ctx->stack=new;
1457                         } else if ( ctx->w == RES_NONE || ! (ctx->old_flag & (1<<r->code))) {
1458                                 syntax();
1459                                 ctx->w = RES_SNTX;
1460                                 b_reset (dest);
1461                                 return 1;
1462                         }
1463                         ctx->w=r->code;
1464                         ctx->old_flag = r->flag;
1465                         if (ctx->old_flag & FLAG_END) {
1466                                 struct p_context *old;
1467                                 debug_printf("pop stack\n");
1468                                 old = ctx->stack;
1469                                 old->child->group = ctx->list_head;
1470                                 *ctx = *old;   /* physical copy */
1471                                 free(old);
1472                                 ctx->w=RES_NONE;
1473                         }
1474                         b_reset (dest);
1475                         return 1;
1476                 }
1477         }
1478         return 0;
1479 }
1480
1481 /* normal return is 0.
1482  * Syntax or xglob errors return 1. */
1483 static int done_word(o_string *dest, struct p_context *ctx)
1484 {
1485         struct child_prog *child=ctx->child;
1486         glob_t *glob_target;
1487         int gr, flags = 0;
1488
1489         debug_printf("done_word: %s %p\n", dest->data, child);
1490         if (dest->length == 0 && !dest->nonnull) {
1491                 debug_printf("  true null, ignored\n");
1492                 return 0;
1493         }
1494         if (ctx->pending_redirect) {
1495                 glob_target = &ctx->pending_redirect->word;
1496         } else {
1497                 if (child->group) {
1498                         syntax();
1499                         return 1;  /* syntax error, groups and arglists don't mix */
1500                 }
1501                 if (!child->argv) {
1502                         debug_printf("checking %s for reserved-ness\n",dest->data);
1503                         if (reserved_word(dest,ctx)) return ctx->w==RES_SNTX;
1504                 }
1505                 glob_target = &child->glob_result;
1506                 if (child->argv) flags |= GLOB_APPEND;
1507         }
1508         gr = xglob(dest, flags, glob_target);
1509         if (gr != 0) return 1;
1510
1511         b_reset(dest);
1512         if (ctx->pending_redirect) {
1513                 ctx->pending_redirect=NULL;
1514                 if (glob_target->gl_pathc != 1) {
1515                         fprintf(stderr, "ambiguous redirect\n");
1516                         return 1;
1517                 }
1518         } else {
1519                 child->argv = glob_target->gl_pathv;
1520         }
1521         return 0;
1522 }
1523
1524 /* The only possible error here is out of memory, in which case
1525  * xmalloc exits. */
1526 static int done_command(struct p_context *ctx)
1527 {
1528         /* The child is really already in the pipe structure, so
1529          * advance the pipe counter and make a new, null child.
1530          * Only real trickiness here is that the uncommitted
1531          * child structure, to which ctx->child points, is not
1532          * counted in pi->num_progs. */
1533         struct pipe *pi=ctx->pipe;
1534         struct child_prog *prog=ctx->child;
1535
1536         if (prog && prog->group == NULL
1537                  && prog->argv == NULL
1538                  && prog->redirects == NULL) {
1539                 debug_printf("done_command: skipping null command\n");
1540                 return 0;
1541         } else if (prog) {
1542                 pi->num_progs++;
1543                 debug_printf("done_command: num_progs incremented to %d\n",pi->num_progs);
1544         } else {
1545                 debug_printf("done_command: initializing\n");
1546         }
1547         pi->progs = xrealloc(pi->progs, sizeof(*pi->progs) * (pi->num_progs+1));
1548
1549         prog = pi->progs + pi->num_progs;
1550         prog->redirects = NULL;
1551         prog->argv = NULL;
1552         prog->is_stopped = 0;
1553         prog->group = NULL;
1554         prog->glob_result.gl_pathv = NULL;
1555         prog->family = pi;
1556
1557         ctx->child=prog;
1558         /* but ctx->pipe and ctx->list_head remain unchanged */
1559         return 0;
1560 }
1561
1562 static int done_pipe(struct p_context *ctx, pipe_style type)
1563 {
1564         struct pipe *new_p;
1565         done_command(ctx);  /* implicit closure of previous command */
1566         debug_printf("done_pipe, type %d\n", type);
1567         ctx->pipe->followup = type;
1568         ctx->pipe->r_mode = ctx->w;
1569         new_p=new_pipe();
1570         ctx->pipe->next = new_p;
1571         ctx->pipe = new_p;
1572         ctx->child = NULL;
1573         done_command(ctx);  /* set up new pipe to accept commands */
1574         return 0;
1575 }
1576
1577 /* peek ahead in the in_str to find out if we have a "&n" construct,
1578  * as in "2>&1", that represents duplicating a file descriptor.
1579  * returns either -2 (syntax error), -1 (no &), or the number found.
1580  */
1581 static int redirect_dup_num(struct in_str *input)
1582 {
1583         int ch, d=0, ok=0;
1584         ch = b_peek(input);
1585         if (ch != '&') return -1;
1586
1587         b_getch(input);  /* get the & */
1588         while (ch=b_peek(input),isdigit(ch)) {
1589                 d = d*10+(ch-'0');
1590                 ok=1;
1591                 b_getch(input);
1592         }
1593         if (ok) return d;
1594
1595         fprintf(stderr, "ambiguous redirect\n");
1596         return -2;
1597 }
1598
1599 /* If a redirect is immediately preceded by a number, that number is
1600  * supposed to tell which file descriptor to redirect.  This routine
1601  * looks for such preceding numbers.  In an ideal world this routine
1602  * needs to handle all the following classes of redirects...
1603  *     echo 2>foo     # redirects fd  2 to file "foo", nothing passed to echo
1604  *     echo 49>foo    # redirects fd 49 to file "foo", nothing passed to echo
1605  *     echo -2>foo    # redirects fd  1 to file "foo",    "-2" passed to echo
1606  *     echo 49x>foo   # redirects fd  1 to file "foo",   "49x" passed to echo
1607  * A -1 output from this program means no valid number was found, so the
1608  * caller should use the appropriate default for this redirection.
1609  */
1610 static int redirect_opt_num(o_string *o)
1611 {
1612         int num;
1613
1614         if (o->length==0) return -1;
1615         for(num=0; num<o->length; num++) {
1616                 if (!isdigit(*(o->data+num))) {
1617                         return -1;
1618                 }
1619         }
1620         /* reuse num (and save an int) */
1621         num=atoi(o->data);
1622         b_reset(o);
1623         return num;
1624 }
1625
1626 FILE *generate_stream_from_list(struct pipe *head)
1627 {
1628         FILE *pf;
1629 #if 1
1630         int pid, channel[2];
1631         if (pipe(channel)<0) perror_msg_and_die("pipe");
1632         pid=fork();
1633         if (pid<0) {
1634                 perror_msg_and_die("fork");
1635         } else if (pid==0) {
1636                 close(channel[0]);
1637                 if (channel[1] != 1) {
1638                         dup2(channel[1],1);
1639                         close(channel[1]);
1640                 }
1641 #if 0
1642 #define SURROGATE "surrogate response"
1643                 write(1,SURROGATE,sizeof(SURROGATE));
1644                 exit(run_list(head));
1645 #else
1646                 exit(run_list_real(head));   /* leaks memory */
1647 #endif
1648         }
1649         debug_printf("forked child %d\n",pid);
1650         close(channel[1]);
1651         pf = fdopen(channel[0],"r");
1652         debug_printf("pipe on FILE *%p\n",pf);
1653 #else
1654         run_list_test(head,0);
1655         pf=popen("echo surrogate response","r");
1656         debug_printf("started fake pipe on FILE *%p\n",pf);
1657 #endif
1658         return pf;
1659 }
1660
1661 /* this version hacked for testing purposes */
1662 /* return code is exit status of the process that is run. */
1663 static int process_command_subs(o_string *dest, struct p_context *ctx, struct in_str *input, int subst_end)
1664 {
1665         int retcode;
1666         o_string result=NULL_O_STRING;
1667         struct p_context inner;
1668         FILE *p;
1669         struct in_str pipe_str;
1670         initialize_context(&inner);
1671
1672         /* recursion to generate command */
1673         retcode = parse_stream(&result, &inner, input, subst_end);
1674         if (retcode != 0) return retcode;  /* syntax error or EOF */
1675         done_word(&result, &inner);
1676         done_pipe(&inner, PIPE_SEQ);
1677         b_free(&result);
1678
1679         p=generate_stream_from_list(inner.list_head);
1680         if (p==NULL) return 1;
1681         mark_open(fileno(p));
1682         setup_file_in_str(&pipe_str, p);
1683
1684         /* now send results of command back into original context */
1685         retcode = parse_stream(dest, ctx, &pipe_str, '\0');
1686         /* XXX In case of a syntax error, should we try to kill the child?
1687          * That would be tough to do right, so just read until EOF. */
1688         if (retcode == 1) {
1689                 while (b_getch(&pipe_str)!=EOF) { /* discard */ };
1690         }
1691
1692         debug_printf("done reading from pipe, pclose()ing\n");
1693         /* This is the step that wait()s for the child.  Should be pretty
1694          * safe, since we just read an EOF from its stdout.  We could try
1695          * to better, by using wait(), and keeping track of background jobs
1696          * at the same time.  That would be a lot of work, and contrary
1697          * to the KISS philosophy of this program. */
1698         mark_closed(fileno(p));
1699         retcode=pclose(p);
1700         debug_printf("pclosed, retcode=%d\n",retcode);
1701         /* XXX this process fails to trim a single trailing newline */
1702         return retcode;
1703 }
1704
1705 static int parse_group(o_string *dest, struct p_context *ctx,
1706         struct in_str *input, int ch)
1707 {
1708         int rcode, endch=0;
1709         struct p_context sub;
1710         struct child_prog *child = ctx->child;
1711         if (child->argv) {
1712                 syntax();
1713                 return 1;  /* syntax error, groups and arglists don't mix */
1714         }
1715         initialize_context(&sub);
1716         switch(ch) {
1717                 case '(': endch=')'; child->subshell=1; break;
1718                 case '{': endch='}'; break;
1719                 default: syntax();   /* really logic error */
1720         }
1721         rcode=parse_stream(dest,&sub,input,endch);
1722         done_word(dest,&sub); /* finish off the final word in the subcontext */
1723         done_pipe(&sub, PIPE_SEQ);  /* and the final command there, too */
1724         child->group = sub.list_head;
1725         return rcode;
1726         /* child remains "open", available for possible redirects */
1727 }
1728
1729 /* basically useful version until someone wants to get fancier,
1730  * see the bash man page under "Parameter Expansion" */
1731 static void lookup_param(o_string *dest, struct p_context *ctx, o_string *src)
1732 {
1733         const char *p=NULL;
1734         if (src->data) p = getenv(src->data);
1735         if (p) parse_string(dest, ctx, p);   /* recursion */
1736         b_free(src);
1737 }
1738
1739 /* return code: 0 for OK, 1 for syntax error */
1740 static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input)
1741 {
1742         int i, advance=0;
1743         o_string alt=NULL_O_STRING;
1744         char sep[]=" ";
1745         int ch = input->peek(input);  /* first character after the $ */
1746         debug_printf("handle_dollar: ch=%c\n",ch);
1747         if (isalpha(ch)) {
1748                 while(ch=b_peek(input),isalnum(ch) || ch=='_') {
1749                         b_getch(input);
1750                         b_addchr(&alt,ch);
1751                 }
1752                 lookup_param(dest, ctx, &alt);
1753         } else if (isdigit(ch)) {
1754                 i = ch-'0';  /* XXX is $0 special? */
1755                 if (i<global_argc) {
1756                         parse_string(dest, ctx, global_argv[i]); /* recursion */
1757                 }
1758                 advance = 1;
1759         } else switch (ch) {
1760                 case '$':
1761                         b_adduint(dest,getpid());
1762                         advance = 1;
1763                         break;
1764                 case '!':
1765                         if (last_bg_pid > 0) b_adduint(dest, last_bg_pid);
1766                         advance = 1;
1767                         break;
1768                 case '?':
1769                         b_adduint(dest,last_return_code);
1770                         advance = 1;
1771                         break;
1772                 case '#':
1773                         b_adduint(dest,global_argc ? global_argc-1 : 0);
1774                         advance = 1;
1775                         break;
1776                 case '{':
1777                         b_getch(input);
1778                         /* XXX maybe someone will try to escape the '}' */
1779                         while(ch=b_getch(input),ch!=EOF && ch!='}') {
1780                                 b_addchr(&alt,ch);
1781                         }
1782                         if (ch != '}') {
1783                                 syntax();
1784                                 return 1;
1785                         }
1786                         lookup_param(dest, ctx, &alt);
1787                         break;
1788                 case '(':
1789                         process_command_subs(dest, ctx, input, ')');
1790                         break;
1791                 case '*':
1792                         sep[0]=ifs[0];
1793                         for (i=1; i<global_argc; i++) {
1794                                 parse_string(dest, ctx, global_argv[i]);
1795                                 if (i+1 < global_argc) parse_string(dest, ctx, sep);
1796                         }
1797                         break;
1798                 case '@':
1799                 case '-':
1800                 case '_':
1801                         /* still unhandled, but should be eventually */
1802                         fprintf(stderr,"unhandled syntax: $%c\n",ch);
1803                         return 1;
1804                         break;
1805                 default:
1806                         b_addqchr(dest,'$',dest->quote);
1807         }
1808         /* Eat the character if the flag was set.  If the compiler
1809          * is smart enough, we could substitute "b_getch(input);"
1810          * for all the "advance = 1;" above, and also end up with
1811          * a nice size-optimized program.  Hah!  That'll be the day.
1812          */
1813         if (advance) b_getch(input);
1814         return 0;
1815 }
1816
1817 int parse_string(o_string *dest, struct p_context *ctx, const char *src)
1818 {
1819         struct in_str foo;
1820         setup_string_in_str(&foo, src);
1821         return parse_stream(dest, ctx, &foo, '\0');
1822 }
1823
1824 /* return code is 0 for normal exit, 1 for syntax error */
1825 int parse_stream(o_string *dest, struct p_context *ctx,
1826         struct in_str *input, int end_trigger)
1827 {
1828         unsigned int ch, m;
1829         int redir_fd;
1830         redir_type redir_style;
1831         int next;
1832
1833         /* Only double-quote state is handled in the state variable dest->quote.
1834          * A single-quote triggers a bypass of the main loop until its mate is
1835          * found.  When recursing, quote state is passed in via dest->quote. */
1836
1837         debug_printf("parse_stream, end_trigger=%d\n",end_trigger);
1838         while ((ch=b_getch(input))!=EOF) {
1839                 m = map[ch];
1840                 next = (ch == '\n') ? 0 : b_peek(input);
1841                 debug_printf("parse_stream: ch=%c (%d) m=%d quote=%d\n",
1842                         ch,ch,m,dest->quote);
1843                 if (m==0 || ((m==1 || m==2) && dest->quote)) {
1844                         b_addqchr(dest, ch, dest->quote);
1845                 } else if (ch == end_trigger && !dest->quote && ctx->w==RES_NONE) {
1846                         debug_printf("leaving parse_stream\n");
1847                         return 0;
1848                 } else if (m==2 && !dest->quote) {  /* IFS */
1849                         done_word(dest, ctx);
1850                         if (ch=='\n') done_pipe(ctx,PIPE_SEQ);
1851                         if (ch == end_trigger && !dest->quote && ctx->w==RES_NONE) {
1852                                 debug_printf("leaving parse_stream (stupid duplication)\n");
1853                                 return 0;
1854                         }
1855 #if 0
1856                         if (ch=='\n') {
1857                                 /* Yahoo!  Time to run with it! */
1858                                 done_pipe(ctx,PIPE_SEQ);
1859                                 run_list(ctx->list_head);
1860                                 initialize_context(ctx);
1861                         }
1862 #endif
1863                 } else switch (ch) {
1864                 case '#':
1865                         if (dest->length == 0 && !dest->quote) {
1866                                 while(ch=b_peek(input),ch!=EOF && ch!='\n') { b_getch(input); }
1867                         } else {
1868                                 b_addqchr(dest, ch, dest->quote);
1869                         }
1870                         break;
1871                 case '\\':
1872                         if (next == EOF) {
1873                                 syntax();
1874                                 return 1;
1875                         }
1876                         b_addqchr(dest, '\\', dest->quote);
1877                         b_addqchr(dest, b_getch(input), dest->quote);
1878                         break;
1879                 case '$':
1880                         if (handle_dollar(dest, ctx, input)!=0) return 1;
1881                         break;
1882                 case '\'':
1883                         dest->nonnull = 1;
1884                         while(ch=b_getch(input),ch!=EOF && ch!='\'') {
1885                                 b_addchr(dest,ch);
1886                         }
1887                         if (ch==EOF) {
1888                                 syntax();
1889                                 return 1;
1890                         }
1891                         break;
1892                 case '"':
1893                         dest->nonnull = 1;
1894                         dest->quote = !dest->quote;
1895                         break;
1896                 case '`':
1897                         process_command_subs(dest, ctx, input, '`');
1898                         break;
1899                 case '>':
1900                         redir_fd = redirect_opt_num(dest);
1901                         done_word(dest, ctx);
1902                         redir_style=REDIRECT_OVERWRITE;
1903                         if (next == '>') {
1904                                 redir_style=REDIRECT_APPEND;
1905                                 b_getch(input);
1906                         } else if (next == '(') {
1907                                 syntax();   /* until we support >(list) Process Substitution */
1908                                 return 1;
1909                         }
1910                         setup_redirect(ctx, redir_fd, redir_style, input);
1911                         break;
1912                 case '<':
1913                         redir_fd = redirect_opt_num(dest);
1914                         done_word(dest, ctx);
1915                         redir_style=REDIRECT_INPUT;
1916                         if (next == '<') {
1917                                 redir_style=REDIRECT_HEREIS;
1918                                 b_getch(input);
1919                         } else if (next == '>') {
1920                                 redir_style=REDIRECT_IO;
1921                                 b_getch(input);
1922                         } else if (next == '(') {
1923                                 syntax();   /* until we support <(list) Process Substitution */
1924                                 return 1;
1925                         }
1926                         setup_redirect(ctx, redir_fd, redir_style, input);
1927                         break;
1928                 case ';':
1929                         done_word(dest, ctx);
1930                         done_pipe(ctx,PIPE_SEQ);
1931                         break;
1932                 case '&':
1933                         done_word(dest, ctx);
1934                         if (next=='&') {
1935                                 b_getch(input);
1936                                 done_pipe(ctx,PIPE_AND);
1937                         } else {
1938                                 done_pipe(ctx,PIPE_BG);
1939                         }
1940                         break;
1941                 case '|':
1942                         done_word(dest, ctx);
1943                         if (next=='|') {
1944                                 b_getch(input);
1945                                 done_pipe(ctx,PIPE_OR);
1946                         } else {
1947                                 /* we could pick up a file descriptor choice here
1948                                  * with redirect_opt_num(), but bash doesn't do it.
1949                                  * "echo foo 2| cat" yields "foo 2". */
1950                                 done_command(ctx);
1951                         }
1952                         break;
1953                 case '(':
1954                 case '{':
1955                         if (parse_group(dest, ctx, input, ch)!=0) return 1;
1956                         break;
1957                 case ')':
1958                 case '}':
1959                         syntax();   /* Proper use of this character caught by end_trigger */
1960                         return 1;
1961                         break;
1962                 default:
1963                         syntax();   /* this is really an internal logic error */
1964                         return 1;
1965                 }
1966         }
1967         /* complain if quote?  No, maybe we just finished a command substitution
1968          * that was quoted.  Example:
1969          * $ echo "`cat foo` plus more" 
1970          * and we just got the EOF generated by the subshell that ran "cat foo"
1971          * The only real complaint is if we got an EOF when end_trigger != '\0',
1972          * that is, we were really supposed to get end_trigger, and never got
1973          * one before the EOF.  Can't use the standard "syntax error" return code,
1974          * so that parse_stream_outer can distinguish the EOF and exit smoothly. */
1975         if (end_trigger != '\0') return -1;
1976         return 0;
1977 }
1978
1979 void mapset(const unsigned char *set, int code)
1980 {
1981         const unsigned char *s;
1982         for (s=set; *s; s++) map[*s] = code;
1983 }
1984
1985 void update_ifs_map(void)
1986 {
1987         /* char *ifs and char map[256] are both globals. */
1988         ifs = getenv("IFS");
1989         if (ifs == NULL) ifs=" \t\n";
1990         /* Precompute a list of 'flow through' behavior so it can be treated
1991          * quickly up front.  Computation is necessary because of IFS.
1992          * Special case handling of IFS == " \t\n" is not implemented.
1993          * The map[] array only really needs two bits each, and on most machines
1994          * that would be faster because of the reduced L1 cache footprint.
1995          */
1996         memset(map,0,256);        /* most characters flow through always */
1997         mapset("\\$'\"`", 3);     /* never flow through */
1998         mapset("<>;&|(){}#", 1);  /* flow through if quoted */
1999         mapset(ifs, 2);           /* also flow through if quoted */
2000 }
2001
2002 /* most recursion does not come through here, the exeception is
2003  * from builtin_source() */
2004 int parse_stream_outer(struct in_str *inp)
2005 {
2006
2007         struct p_context ctx;
2008         o_string temp=NULL_O_STRING;
2009         int rcode;
2010         do {
2011                 initialize_context(&ctx);
2012                 update_ifs_map();
2013                 inp->promptmode=1;
2014                 rcode = parse_stream(&temp, &ctx, inp, '\n');
2015                 done_word(&temp, &ctx);
2016                 done_pipe(&ctx,PIPE_SEQ);
2017                 run_list(ctx.list_head);
2018         } while (rcode != -1);   /* loop on syntax errors, return on EOF */
2019         return 0;
2020 }
2021
2022 static int parse_string_outer(const char *s)
2023 {
2024         struct in_str input;
2025         setup_string_in_str(&input, s);
2026         return parse_stream_outer(&input);
2027 }
2028
2029 static int parse_file_outer(FILE *f)
2030 {
2031         int rcode;
2032         struct in_str input;
2033         setup_file_in_str(&input, f);
2034         rcode = parse_stream_outer(&input);
2035         return rcode;
2036 }
2037
2038 int shell_main(int argc, char **argv)
2039 {
2040         int opt;
2041         FILE *input;
2042
2043         /* XXX what should these be while sourcing /etc/profile? */
2044         global_argc = argc;
2045         global_argv = argv;
2046
2047         if (argv[0] && argv[0][0] == '-') {
2048                 debug_printf("\nsourcing /etc/profile\n");
2049                 input = xfopen("/etc/profile", "r");
2050                 mark_open(fileno(input));
2051                 parse_file_outer(input);
2052                 mark_closed(fileno(input));
2053                 fclose(input);
2054         }
2055         input=stdin;
2056         
2057         /* initialize the cwd -- this is never freed...*/
2058         cwd = xgetcwd(0);
2059 #ifdef BB_FEATURE_COMMAND_EDITING
2060         cmdedit_set_initial_prompt();
2061 #else
2062         PS1 = NULL;
2063 #endif
2064         
2065         while ((opt = getopt(argc, argv, "c:xif")) > 0) {
2066                 switch (opt) {
2067                         case 'c':
2068                                 {
2069                                         global_argv = argv+optind;
2070                                         global_argc = argc-optind;
2071                                         opt = parse_string_outer(optarg);
2072                                         exit(opt);
2073                                 }
2074                                 break;
2075                         case 'i':
2076                                 interactive++;
2077                                 break;
2078                         case 'f':
2079                                 fake_mode++;
2080                                 break;
2081                         default:
2082                                 fprintf(stderr, "Usage: sh [FILE]...\n"
2083                                                 "   or: sh -c command [args]...\n\n");
2084                                 exit(EXIT_FAILURE);
2085                 }
2086         }
2087         /* A shell is interactive if the `-i' flag was given, or if all of
2088          * the following conditions are met:
2089          *        no -c command
2090          *    no arguments remaining or the -s flag given
2091          *    standard input is a terminal
2092          *    standard output is a terminal
2093          *    Refer to Posix.2, the description of the `sh' utility. */
2094         if (argv[optind]==NULL && input==stdin &&
2095                         isatty(fileno(stdin)) && isatty(fileno(stdout))) {
2096                 interactive++;
2097         }
2098         
2099         if (interactive) {
2100                 /* Looks like they want an interactive shell */
2101                 fprintf(stdout, "\nhush -- the humble shell v0.01 (testing)\n\n");
2102                 exit(parse_file_outer(stdin));
2103         }
2104         debug_printf("\ninteractive=%d\n", interactive);
2105
2106         debug_printf("\nrunning script '%s'\n", argv[optind]);
2107         global_argv = argv+optind;
2108         global_argc = argc-optind;
2109         input = xfopen(argv[optind], "r");
2110         opt = parse_file_outer(input);
2111
2112 #ifdef BB_FEATURE_CLEAN_UP
2113         fclose(input.file);
2114 #endif
2115
2116         return(opt);
2117 }