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