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