b8e4a55c26bf8914114306ccce6ffd2a1b51f112
[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                 }
1023 #endif
1024                 debug_printf("exec of %s\n",child->argv[0]);
1025                 execvp(child->argv[0],child->argv);
1026                 perror("execvp");
1027                 exit(1);
1028         } else if (child->group) {
1029                 debug_printf("runtime nesting to group\n");
1030                 interactive=0;    /* crucial!!!! */
1031                 rcode = run_list_real(child->group);
1032                 /* OK to leak memory by not calling run_list_test,
1033                  * since this process is about to exit */
1034                 exit(rcode);
1035         } else {
1036                 /* Can happen.  See what bash does with ">foo" by itself. */
1037                 debug_printf("trying to pseudo_exec null command\n");
1038                 exit(EXIT_SUCCESS);
1039         }
1040 }
1041
1042 static void insert_bg_job(struct pipe *pi)
1043 {
1044         struct pipe *thejob;
1045
1046         /* Linear search for the ID of the job to use */
1047         pi->jobid = 1;
1048         for (thejob = job_list->head; thejob; thejob = thejob->next)
1049                 if (thejob->jobid >= pi->jobid)
1050                         pi->jobid = thejob->jobid + 1;
1051
1052         /* add thejob to the list of running jobs */
1053         if (!job_list->head) {
1054                 thejob = job_list->head = xmalloc(sizeof(*thejob));
1055         } else {
1056                 for (thejob = job_list->head; thejob->next; thejob = thejob->next) /* nothing */;
1057                 thejob->next = xmalloc(sizeof(*thejob));
1058                 thejob = thejob->next;
1059         }
1060
1061         /* physically copy the struct job */
1062         memcpy(thejob, pi, sizeof(struct pipe));
1063         thejob->next = NULL;
1064         thejob->running_progs = thejob->num_progs;
1065         thejob->stopped_progs = 0;
1066
1067         /* we don't wait for background thejobs to return -- append it 
1068            to the list of backgrounded thejobs and leave it alone */
1069         printf("[%d] %d\n", pi->jobid, pi->pgrp);
1070         last_bg_pid = pi->pgrp;
1071 }
1072
1073 /* remove a backgrounded job from a jobset */
1074 static void remove_bg_job(struct pipe *pi)
1075 {
1076         struct pipe *prev_pipe;
1077
1078         free_pipe(pi);
1079         if (pi == job_list->head) {
1080                 job_list->head = pi->next;
1081         } else {
1082                 prev_pipe = job_list->head;
1083                 while (prev_pipe->next != pi)
1084                         prev_pipe = prev_pipe->next;
1085                 prev_pipe->next = pi->next;
1086         }
1087
1088         free(pi);
1089 }
1090
1091 /* free up all memory from a pipe */
1092 static void free_pipe(struct pipe *pi)
1093 {
1094         int i;
1095
1096         for (i = 0; i < pi->num_progs; i++) {
1097                 free(pi->progs[i].argv);
1098                 if (pi->progs[i].redirects)
1099                         free(pi->progs[i].redirects);
1100         }
1101         if (pi->progs)
1102                 free(pi->progs);
1103         if (pi->text)
1104                 free(pi->text);
1105         if (pi->cmdbuf)
1106                 free(pi->cmdbuf);
1107         memset(pi, 0, sizeof(struct pipe));
1108 }
1109
1110
1111 /* Checks to see if any background processes have exited -- if they 
1112    have, figure out why and see if a job has completed */
1113 static void checkjobs()
1114 {
1115         int status;
1116         int prognum = 0;
1117         struct pipe *pi;
1118         pid_t childpid;
1119
1120         while ((childpid = waitpid(-1, &status, WNOHANG | WUNTRACED)) > 0) {
1121                 for (pi = job_list->head; pi; pi = pi->next) {
1122                         prognum = 0;
1123                         while (prognum < pi->num_progs &&
1124                                    pi->progs[prognum].pid != childpid) prognum++;
1125                         if (prognum < pi->num_progs)
1126                                 break;
1127                 }
1128
1129                 if (WIFEXITED(status) || WIFSIGNALED(status)) {
1130                         /* child exited */
1131                         pi->running_progs--;
1132                         pi->progs[prognum].pid = 0;
1133
1134                         if (!pi->running_progs) {
1135                                 printf(JOB_STATUS_FORMAT, pi->jobid, "Done", pi->text);
1136                                 remove_bg_job(pi);
1137                         }
1138                 } else {
1139                         /* child stopped */
1140                         pi->stopped_progs++;
1141                         pi->progs[prognum].is_stopped = 1;
1142
1143                         if (pi->stopped_progs == pi->num_progs) {
1144                                 printf(JOB_STATUS_FORMAT, pi->jobid, "Stopped",
1145                                                 pi->text);
1146                         }
1147                 }
1148         }
1149
1150         if (childpid == -1 && errno != ECHILD)
1151                 perror_msg("waitpid");
1152
1153         /* move the shell to the foreground */
1154         if (tcsetpgrp(0, getpgrp()) && errno != ENOTTY)
1155                 perror_msg("tcsetpgrp"); 
1156 }
1157
1158 /* run_pipe_real() starts all the jobs, but doesn't wait for anything
1159  * to finish.  See pipe_wait().
1160  *
1161  * return code is normally -1, when the caller has to wait for children
1162  * to finish to determine the exit status of the pipe.  If the pipe
1163  * is a simple builtin command, however, the action is done by the
1164  * time run_pipe_real returns, and the exit code is provided as the
1165  * return value.
1166  *
1167  * The input of the pipe is always stdin, the output is always
1168  * stdout.  The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
1169  * because it tries to avoid running the command substitution in
1170  * subshell, when that is in fact necessary.  The subshell process
1171  * now has its stdout directed to the input of the appropriate pipe,
1172  * so this routine is noticeably simpler.
1173  */
1174 static int run_pipe_real(struct pipe *pi)
1175 {
1176         int i;
1177         int ctty;
1178         int nextin, nextout;
1179         int pipefds[2];                         /* pipefds[0] is for reading */
1180         struct child_prog *child;
1181         struct built_in_command *x;
1182
1183         ctty = -1;
1184         nextin = 0;
1185         pi->pgrp = 0;
1186
1187         /* Check if we are supposed to run in the foreground */
1188         if (interactive && pi->followup!=PIPE_BG) {
1189                 if ((pi->pgrp = tcgetpgrp(ctty = 2)) < 0
1190                                 && (pi->pgrp = tcgetpgrp(ctty = 0)) < 0
1191                                 && (pi->pgrp = tcgetpgrp(ctty = 1)) < 0)
1192                         return errno = ENOTTY, -1;
1193
1194                 if (pi->pgrp < 0 && pi->pgrp != getpgrp())
1195                         return errno = EPERM, -1;
1196         }
1197
1198         /* Check if this is a simple builtin (not part of a pipe).
1199          * Builtins within pipes have to fork anyway, and are handled in
1200          * pseudo_exec.  "echo foo | read bar" doesn't work on bash, either.
1201          */
1202         if (pi->num_progs == 1 && pi->progs[0].argv != NULL) {
1203                 child = & (pi->progs[0]);
1204                 if (child->group && ! child->subshell) {
1205                         int squirrel[] = {-1, -1, -1};
1206                         int rcode;
1207                         debug_printf("non-subshell grouping\n");
1208                         setup_redirects(child, squirrel);
1209                         /* XXX could we merge code with following builtin case,
1210                          * by creating a pseudo builtin that calls run_list_real? */
1211                         rcode = run_list_real(child->group);
1212                         restore_redirects(squirrel);
1213                         return rcode;
1214                 }
1215                 for (x = bltins; x->cmd; x++) {
1216                         if (strcmp(child->argv[0], x->cmd) == 0 ) {
1217                                 int squirrel[] = {-1, -1, -1};
1218                                 int rcode;
1219                                 debug_printf("builtin inline %s\n", child->argv[0]);
1220                                 /* XXX setup_redirects acts on file descriptors, not FILEs.
1221                                  * This is perfect for work that comes after exec().
1222                                  * Is it really safe for inline use?  Experimentally,
1223                                  * things seem to work with glibc. */
1224                                 setup_redirects(child, squirrel);
1225                                 rcode = x->function(child);
1226                                 restore_redirects(squirrel);
1227                                 return rcode;
1228                         }
1229                 }
1230         }
1231
1232         for (i = 0; i < pi->num_progs; i++) {
1233                 child = & (pi->progs[i]);
1234
1235                 /* pipes are inserted between pairs of commands */
1236                 if ((i + 1) < pi->num_progs) {
1237                         if (pipe(pipefds)<0) perror_msg_and_die("pipe");
1238                         nextout = pipefds[1];
1239                 } else {
1240                         nextout=1;
1241                         pipefds[0] = -1;
1242                 }
1243
1244                 /* XXX test for failed fork()? */
1245                 if (!(child->pid = fork())) {
1246
1247                         signal(SIGTTOU, SIG_DFL);
1248                         
1249                         close_all();
1250
1251                         if (nextin != 0) {
1252                                 dup2(nextin, 0);
1253                                 close(nextin);
1254                         }
1255                         if (nextout != 1) {
1256                                 dup2(nextout, 1);
1257                                 close(nextout);
1258                         }
1259                         if (pipefds[0]!=-1) {
1260                                 close(pipefds[0]);  /* opposite end of our output pipe */
1261                         }
1262
1263                         /* Like bash, explicit redirects override pipes,
1264                          * and the pipe fd is available for dup'ing. */
1265                         setup_redirects(child,NULL);
1266                         
1267                         if (pi->followup!=PIPE_BG) {
1268                                 /* Put our child in the process group whose leader is the
1269                                  * first process in this pipe. */
1270                                 if (pi->pgrp < 0) {
1271                                         pi->pgrp = child->pid;
1272                                 }
1273                                 /* Don't check for errors.  The child may be dead already,
1274                                  * in which case setpgid returns error code EACCES. */
1275                                 if (setpgid(0, pi->pgrp) == 0) {
1276                                         signal(SIGTTOU, SIG_IGN);
1277                                         tcsetpgrp(ctty, pi->pgrp);
1278                                         signal(SIGTTOU, SIG_DFL);
1279                                 }
1280                         }
1281
1282                         pseudo_exec(child);
1283                 }
1284                 /* Put our child in the process group whose leader is the
1285                  * first process in this pipe. */
1286                 if (pi->pgrp < 0) {
1287                         pi->pgrp = child->pid;
1288                 }
1289                 /* Don't check for errors.  The child may be dead already,
1290                  * in which case setpgid returns error code EACCES. */
1291                 setpgid(child->pid, pi->pgrp);
1292
1293                 if (nextin != 0)
1294                         close(nextin);
1295                 if (nextout != 1)
1296                         close(nextout);
1297
1298                 /* If there isn't another process, nextin is garbage 
1299                    but it doesn't matter */
1300                 nextin = pipefds[0];
1301         }
1302         return -1;
1303 }
1304
1305 static int run_list_real(struct pipe *pi)
1306 {
1307         int rcode=0;
1308         int if_code=0, next_if_code=0;  /* need double-buffer to handle elif */
1309         reserved_style rmode, skip_more_in_this_rmode=RES_XXXX;
1310         for (;pi;pi=pi->next) {
1311                 rmode = pi->r_mode;
1312                 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);
1313                 if (rmode == skip_more_in_this_rmode) continue;
1314                 skip_more_in_this_rmode = RES_XXXX;
1315                 if (rmode == RES_THEN || rmode == RES_ELSE) if_code = next_if_code;
1316                 if (rmode == RES_THEN &&  if_code) continue;
1317                 if (rmode == RES_ELSE && !if_code) continue;
1318                 if (rmode == RES_ELIF && !if_code) continue;
1319                 if (pi->num_progs == 0) continue;
1320                 rcode = run_pipe_real(pi);
1321                 if (rcode!=-1) {
1322                         /* We only ran a builtin: rcode was set by the return value
1323                          * of run_pipe_real(), and we don't need to wait for anything. */
1324                 } else if (pi->followup==PIPE_BG) {
1325                         /* XXX check bash's behavior with nontrivial pipes */
1326                         /* XXX compute jobid */
1327                         /* XXX what does bash do with attempts to background builtins? */
1328                         insert_bg_job(pi);
1329                         rcode = EXIT_SUCCESS;
1330                 } else {
1331
1332                         if (interactive) {
1333                                 /* move the new process group into the foreground */
1334                                 /* suppress messages when run from /linuxrc mag@sysgo.de */
1335                                 //signal(SIGTTIN, SIG_IGN);
1336                                 //signal(SIGTTOU, SIG_IGN);
1337                                 if (tcsetpgrp(0, pi->pgrp) && errno != ENOTTY)
1338                                         perror_msg("tcsetpgrp");
1339                                 rcode = pipe_wait(pi);
1340                                 if (tcsetpgrp(0, getpgrp()) && errno != ENOTTY)
1341                                         perror_msg("tcsetpgrp");
1342                                 //signal(SIGTTIN, SIG_DFL);
1343                                 //signal(SIGTTOU, SIG_DFL);
1344                         } else {
1345                                 rcode = pipe_wait(pi);
1346                         }
1347                 }
1348                 last_return_code=rcode;
1349                 if ( rmode == RES_IF || rmode == RES_ELIF )
1350                         next_if_code=rcode;  /* can be overwritten a number of times */
1351                 if ( (rcode==EXIT_SUCCESS && pi->followup==PIPE_OR) ||
1352                      (rcode!=EXIT_SUCCESS && pi->followup==PIPE_AND) )
1353                         skip_more_in_this_rmode=rmode;
1354                         /* return rcode; */ /* XXX broken if list is part of if/then/else */
1355         }
1356         checkjobs();
1357         return rcode;
1358 }
1359
1360 /* broken, of course, but OK for testing */
1361 static char *indenter(int i)
1362 {
1363         static char blanks[]="                                    ";
1364         return &blanks[sizeof(blanks)-i-1];
1365 }
1366
1367 /* return code is the exit status of the pipe */
1368 static int run_pipe_test(struct pipe *pi, int indent)
1369 {
1370         char **p;
1371         struct child_prog *child;
1372         struct redir_struct *r, *rnext;
1373         int a, i, ret_code=0;
1374         char *ind = indenter(indent);
1375         final_printf("%s run pipe: (pid %d)\n",ind,getpid());
1376         for (i=0; i<pi->num_progs; i++) {
1377                 child = &pi->progs[i];
1378                 final_printf("%s  command %d:\n",ind,i);
1379                 if (child->argv) {
1380                         for (a=0,p=child->argv; *p; a++,p++) {
1381                                 final_printf("%s   argv[%d] = %s\n",ind,a,*p);
1382                         }
1383                         globfree(&child->glob_result);
1384                         child->argv=NULL;
1385                 } else if (child->group) {
1386                         final_printf("%s   begin group (subshell:%d)\n",ind, child->subshell);
1387                         ret_code = run_list_test(child->group,indent+3);
1388                         final_printf("%s   end group\n",ind);
1389                 } else {
1390                         final_printf("%s   (nil)\n",ind);
1391                 }
1392                 for (r=child->redirects; r; r=rnext) {
1393                         final_printf("%s   redirect %d%s", ind, r->fd, redir_table[r->type].descrip);
1394                         if (r->dup == -1) {
1395                                 final_printf(" %s\n", *r->word.gl_pathv);
1396                                 globfree(&r->word);
1397                         } else {
1398                                 final_printf("&%d\n", r->dup);
1399                         }
1400                         rnext=r->next;
1401                         free(r);
1402                 }
1403                 child->redirects=NULL;
1404         }
1405         free(pi->progs);   /* children are an array, they get freed all at once */
1406         pi->progs=NULL;
1407         return ret_code;
1408 }
1409
1410 static int run_list_test(struct pipe *head, int indent)
1411 {
1412         int rcode=0;   /* if list has no members */
1413         struct pipe *pi, *next;
1414         char *ind = indenter(indent);
1415         for (pi=head; pi; pi=next) {
1416                 if (pi->num_progs == 0) break;
1417                 final_printf("%s pipe reserved mode %d\n", ind, pi->r_mode);
1418                 rcode = run_pipe_test(pi, indent);
1419                 final_printf("%s pipe followup code %d\n", ind, pi->followup);
1420                 next=pi->next;
1421                 pi->next=NULL;
1422                 free(pi);
1423         }
1424         return rcode;   
1425 }
1426
1427 /* Select which version we will use */
1428 static int run_list(struct pipe *pi)
1429 {
1430         int rcode=0;
1431         if (fake_mode==0) {
1432                 rcode = run_list_real(pi);
1433         } 
1434         /* run_list_test has the side effect of clearing memory
1435          * In the long run that function can be merged with run_list_real,
1436          * but doing that now would hobble the debugging effort. */
1437         run_list_test(pi,0);
1438         return rcode;
1439 }
1440
1441 /* The API for glob is arguably broken.  This routine pushes a non-matching
1442  * string into the output structure, removing non-backslashed backslashes.
1443  * If someone can prove me wrong, by performing this function within the
1444  * original glob(3) api, feel free to rewrite this routine into oblivion.
1445  * Return code (0 vs. GLOB_NOSPACE) matches glob(3).
1446  * XXX broken if the last character is '\\', check that before calling.
1447  */
1448 static int globhack(const char *src, int flags, glob_t *pglob)
1449 {
1450         int cnt, pathc;
1451         const char *s;
1452         char *dest;
1453         for (cnt=1, s=src; *s; s++) {
1454                 if (*s == '\\') s++;
1455                 cnt++;
1456         }
1457         dest = malloc(cnt);
1458         if (!dest) return GLOB_NOSPACE;
1459         if (!(flags & GLOB_APPEND)) {
1460                 pglob->gl_pathv=NULL;
1461                 pglob->gl_pathc=0;
1462                 pglob->gl_offs=0;
1463                 pglob->gl_offs=0;
1464         }
1465         pathc = ++pglob->gl_pathc;
1466         pglob->gl_pathv = realloc(pglob->gl_pathv, (pathc+1)*sizeof(*pglob->gl_pathv));
1467         if (pglob->gl_pathv == NULL) return GLOB_NOSPACE;
1468         pglob->gl_pathv[pathc-1]=dest;
1469         pglob->gl_pathv[pathc]=NULL;
1470         for (s=src; *s; s++, dest++) {
1471                 if (*s == '\\') s++;
1472                 *dest = *s;
1473         }
1474         *dest='\0';
1475         return 0;
1476 }
1477
1478 /* XXX broken if the last character is '\\', check that before calling */
1479 static int glob_needed(const char *s)
1480 {
1481         for (; *s; s++) {
1482                 if (*s == '\\') s++;
1483                 if (strchr("*[?",*s)) return 1;
1484         }
1485         return 0;
1486 }
1487
1488 #if 0
1489 static void globprint(glob_t *pglob)
1490 {
1491         int i;
1492         debug_printf("glob_t at %p:\n", pglob);
1493         debug_printf("  gl_pathc=%d  gl_pathv=%p  gl_offs=%d  gl_flags=%d\n",
1494                 pglob->gl_pathc, pglob->gl_pathv, pglob->gl_offs, pglob->gl_flags);
1495         for (i=0; i<pglob->gl_pathc; i++)
1496                 debug_printf("pglob->gl_pathv[%d] = %p = %s\n", i,
1497                         pglob->gl_pathv[i], pglob->gl_pathv[i]);
1498 }
1499 #endif
1500
1501 static int xglob(o_string *dest, int flags, glob_t *pglob)
1502 {
1503         int gr;
1504
1505         /* short-circuit for null word */
1506         /* we can code this better when the debug_printf's are gone */
1507         if (dest->length == 0) {
1508                 if (dest->nonnull) {
1509                         /* bash man page calls this an "explicit" null */
1510                         gr = globhack(dest->data, flags, pglob);
1511                         debug_printf("globhack returned %d\n",gr);
1512                 } else {
1513                         return 0;
1514                 }
1515         } else if (glob_needed(dest->data)) {
1516                 gr = glob(dest->data, flags, NULL, pglob);
1517                 debug_printf("glob returned %d\n",gr);
1518                 if (gr == GLOB_NOMATCH) {
1519                         /* quote removal, or more accurately, backslash removal */
1520                         gr = globhack(dest->data, flags, pglob);
1521                         debug_printf("globhack returned %d\n",gr);
1522                 }
1523         } else {
1524                 gr = globhack(dest->data, flags, pglob);
1525                 debug_printf("globhack returned %d\n",gr);
1526         }
1527         if (gr == GLOB_NOSPACE) {
1528                 fprintf(stderr,"out of memory during glob\n");
1529                 exit(1);
1530         }
1531         if (gr != 0) { /* GLOB_ABORTED ? */
1532                 fprintf(stderr,"glob(3) error %d\n",gr);
1533         }
1534         /* globprint(glob_target); */
1535         return gr;
1536 }
1537
1538 /* the src parameter allows us to peek forward to a possible &n syntax
1539  * for file descriptor duplication, e.g., "2>&1".
1540  * Return code is 0 normally, 1 if a syntax error is detected in src.
1541  * Resource errors (in xmalloc) cause the process to exit */
1542 static int setup_redirect(struct p_context *ctx, int fd, redir_type style,
1543         struct in_str *input)
1544 {
1545         struct child_prog *child=ctx->child;
1546         struct redir_struct *redir = child->redirects;
1547         struct redir_struct *last_redir=NULL;
1548
1549         /* Create a new redir_struct and drop it onto the end of the linked list */
1550         while(redir) {
1551                 last_redir=redir;
1552                 redir=redir->next;
1553         }
1554         redir = xmalloc(sizeof(struct redir_struct));
1555         redir->next=NULL;
1556         if (last_redir) {
1557                 last_redir->next=redir;
1558         } else {
1559                 child->redirects=redir;
1560         }
1561
1562         redir->type=style;
1563         redir->fd= (fd==-1) ? redir_table[style].default_fd : fd ;
1564
1565         debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
1566
1567         /* Check for a '2>&1' type redirect */ 
1568         redir->dup = redirect_dup_num(input);
1569         if (redir->dup == -2) return 1;  /* syntax error */
1570         if (redir->dup != -1) {
1571                 /* Erik had a check here that the file descriptor in question
1572                  * is legit; I postpone that to "run time" */
1573                 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
1574         } else {
1575                 /* We do _not_ try to open the file that src points to,
1576                  * since we need to return and let src be expanded first.
1577                  * Set ctx->pending_redirect, so we know what to do at the
1578                  * end of the next parsed word.
1579                  */
1580                 ctx->pending_redirect = redir;
1581         }
1582         return 0;
1583 }
1584
1585 struct pipe *new_pipe(void) {
1586         struct pipe *pi;
1587         pi = xmalloc(sizeof(struct pipe));
1588         pi->num_progs = 0;
1589         pi->progs = NULL;
1590         pi->next = NULL;
1591         pi->followup = 0;  /* invalid */
1592         return pi;
1593 }
1594
1595 static void initialize_context(struct p_context *ctx)
1596 {
1597         ctx->pipe=NULL;
1598         ctx->pending_redirect=NULL;
1599         ctx->child=NULL;
1600         ctx->list_head=new_pipe();
1601         ctx->pipe=ctx->list_head;
1602         ctx->w=RES_NONE;
1603         ctx->stack=NULL;
1604         done_command(ctx);   /* creates the memory for working child */
1605 }
1606
1607 /* normal return is 0
1608  * if a reserved word is found, and processed, return 1
1609  * should handle if, then, elif, else, fi, for, while, until, do, done.
1610  * case, function, and select are obnoxious, save those for later.
1611  */
1612 int reserved_word(o_string *dest, struct p_context *ctx)
1613 {
1614         struct reserved_combo {
1615                 char *literal;
1616                 int code;
1617                 long flag;
1618         };
1619         /* Mostly a list of accepted follow-up reserved words.
1620          * FLAG_END means we are done with the sequence, and are ready
1621          * to turn the compound list into a command.
1622          * FLAG_START means the word must start a new compound list.
1623          */
1624         static struct reserved_combo reserved_list[] = {
1625                 { "if",    RES_IF,    FLAG_THEN | FLAG_START },
1626                 { "then",  RES_THEN,  FLAG_ELIF | FLAG_ELSE | FLAG_FI },
1627                 { "elif",  RES_ELIF,  FLAG_THEN },
1628                 { "else",  RES_ELSE,  FLAG_FI   },
1629                 { "fi",    RES_FI,    FLAG_END  },
1630                 { "for",   RES_FOR,   FLAG_DO   | FLAG_START },
1631                 { "while", RES_WHILE, FLAG_DO   | FLAG_START },
1632                 { "until", RES_UNTIL, FLAG_DO   | FLAG_START },
1633                 { "do",    RES_DO,    FLAG_DONE },
1634                 { "done",  RES_DONE,  FLAG_END  }
1635         };
1636         struct reserved_combo *r;
1637         for (r=reserved_list;
1638 #define NRES sizeof(reserved_list)/sizeof(struct reserved_combo)
1639                 r<reserved_list+NRES; r++) {
1640                 if (strcmp(dest->data, r->literal) == 0) {
1641                         debug_printf("found reserved word %s, code %d\n",r->literal,r->code);
1642                         if (r->flag & FLAG_START) {
1643                                 struct p_context *new = xmalloc(sizeof(struct p_context));
1644                                 debug_printf("push stack\n");
1645                                 *new = *ctx;   /* physical copy */
1646                                 initialize_context(ctx);
1647                                 ctx->stack=new;
1648                         } else if ( ctx->w == RES_NONE || ! (ctx->old_flag & (1<<r->code))) {
1649                                 syntax();
1650                                 ctx->w = RES_SNTX;
1651                                 b_reset (dest);
1652                                 return 1;
1653                         }
1654                         ctx->w=r->code;
1655                         ctx->old_flag = r->flag;
1656                         if (ctx->old_flag & FLAG_END) {
1657                                 struct p_context *old;
1658                                 debug_printf("pop stack\n");
1659                                 old = ctx->stack;
1660                                 old->child->group = ctx->list_head;
1661                                 *ctx = *old;   /* physical copy */
1662                                 free(old);
1663                         }
1664                         b_reset (dest);
1665                         return 1;
1666                 }
1667         }
1668         return 0;
1669 }
1670
1671 /* normal return is 0.
1672  * Syntax or xglob errors return 1. */
1673 static int done_word(o_string *dest, struct p_context *ctx)
1674 {
1675         struct child_prog *child=ctx->child;
1676         glob_t *glob_target;
1677         int gr, flags = 0;
1678
1679         debug_printf("done_word: %s %p\n", dest->data, child);
1680         if (dest->length == 0 && !dest->nonnull) {
1681                 debug_printf("  true null, ignored\n");
1682                 return 0;
1683         }
1684         if (ctx->pending_redirect) {
1685                 glob_target = &ctx->pending_redirect->word;
1686         } else {
1687                 if (child->group) {
1688                         syntax();
1689                         return 1;  /* syntax error, groups and arglists don't mix */
1690                 }
1691                 if (!child->argv) {
1692                         debug_printf("checking %s for reserved-ness\n",dest->data);
1693                         if (reserved_word(dest,ctx)) return ctx->w==RES_SNTX;
1694                 }
1695                 glob_target = &child->glob_result;
1696                 if (child->argv) flags |= GLOB_APPEND;
1697         }
1698         gr = xglob(dest, flags, glob_target);
1699         if (gr != 0) return 1;
1700
1701         b_reset(dest);
1702         if (ctx->pending_redirect) {
1703                 ctx->pending_redirect=NULL;
1704                 if (glob_target->gl_pathc != 1) {
1705                         fprintf(stderr, "ambiguous redirect\n");
1706                         return 1;
1707                 }
1708         } else {
1709                 child->argv = glob_target->gl_pathv;
1710         }
1711         return 0;
1712 }
1713
1714 /* The only possible error here is out of memory, in which case
1715  * xmalloc exits. */
1716 static int done_command(struct p_context *ctx)
1717 {
1718         /* The child is really already in the pipe structure, so
1719          * advance the pipe counter and make a new, null child.
1720          * Only real trickiness here is that the uncommitted
1721          * child structure, to which ctx->child points, is not
1722          * counted in pi->num_progs. */
1723         struct pipe *pi=ctx->pipe;
1724         struct child_prog *prog=ctx->child;
1725
1726         if (prog && prog->group == NULL
1727                  && prog->argv == NULL
1728                  && prog->redirects == NULL) {
1729                 debug_printf("done_command: skipping null command\n");
1730                 return 0;
1731         } else if (prog) {
1732                 pi->num_progs++;
1733                 debug_printf("done_command: num_progs incremented to %d\n",pi->num_progs);
1734         } else {
1735                 debug_printf("done_command: initializing\n");
1736         }
1737         pi->progs = xrealloc(pi->progs, sizeof(*pi->progs) * (pi->num_progs+1));
1738
1739         prog = pi->progs + pi->num_progs;
1740         prog->redirects = NULL;
1741         prog->argv = NULL;
1742         prog->is_stopped = 0;
1743         prog->group = NULL;
1744         prog->glob_result.gl_pathv = NULL;
1745         prog->family = pi;
1746
1747         ctx->child=prog;
1748         /* but ctx->pipe and ctx->list_head remain unchanged */
1749         return 0;
1750 }
1751
1752 static int done_pipe(struct p_context *ctx, pipe_style type)
1753 {
1754         struct pipe *new_p;
1755         done_command(ctx);  /* implicit closure of previous command */
1756         debug_printf("done_pipe, type %d\n", type);
1757         ctx->pipe->followup = type;
1758         ctx->pipe->r_mode = ctx->w;
1759         new_p=new_pipe();
1760         ctx->pipe->next = new_p;
1761         ctx->pipe = new_p;
1762         ctx->child = NULL;
1763         done_command(ctx);  /* set up new pipe to accept commands */
1764         return 0;
1765 }
1766
1767 /* peek ahead in the in_str to find out if we have a "&n" construct,
1768  * as in "2>&1", that represents duplicating a file descriptor.
1769  * returns either -2 (syntax error), -1 (no &), or the number found.
1770  */
1771 static int redirect_dup_num(struct in_str *input)
1772 {
1773         int ch, d=0, ok=0;
1774         ch = b_peek(input);
1775         if (ch != '&') return -1;
1776
1777         b_getch(input);  /* get the & */
1778         while (ch=b_peek(input),isdigit(ch)) {
1779                 d = d*10+(ch-'0');
1780                 ok=1;
1781                 b_getch(input);
1782         }
1783         if (ok) return d;
1784
1785         fprintf(stderr, "ambiguous redirect\n");
1786         return -2;
1787 }
1788
1789 /* If a redirect is immediately preceded by a number, that number is
1790  * supposed to tell which file descriptor to redirect.  This routine
1791  * looks for such preceding numbers.  In an ideal world this routine
1792  * needs to handle all the following classes of redirects...
1793  *     echo 2>foo     # redirects fd  2 to file "foo", nothing passed to echo
1794  *     echo 49>foo    # redirects fd 49 to file "foo", nothing passed to echo
1795  *     echo -2>foo    # redirects fd  1 to file "foo",    "-2" passed to echo
1796  *     echo 49x>foo   # redirects fd  1 to file "foo",   "49x" passed to echo
1797  * A -1 output from this program means no valid number was found, so the
1798  * caller should use the appropriate default for this redirection.
1799  */
1800 static int redirect_opt_num(o_string *o)
1801 {
1802         int num;
1803
1804         if (o->length==0) return -1;
1805         for(num=0; num<o->length; num++) {
1806                 if (!isdigit(*(o->data+num))) {
1807                         return -1;
1808                 }
1809         }
1810         /* reuse num (and save an int) */
1811         num=atoi(o->data);
1812         b_reset(o);
1813         return num;
1814 }
1815
1816 FILE *generate_stream_from_list(struct pipe *head)
1817 {
1818         FILE *pf;
1819 #if 1
1820         int pid, channel[2];
1821         if (pipe(channel)<0) perror_msg_and_die("pipe");
1822         pid=fork();
1823         if (pid<0) {
1824                 perror_msg_and_die("fork");
1825         } else if (pid==0) {
1826                 close(channel[0]);
1827                 if (channel[1] != 1) {
1828                         dup2(channel[1],1);
1829                         close(channel[1]);
1830                 }
1831 #if 0
1832 #define SURROGATE "surrogate response"
1833                 write(1,SURROGATE,sizeof(SURROGATE));
1834                 exit(run_list(head));
1835 #else
1836                 exit(run_list_real(head));   /* leaks memory */
1837 #endif
1838         }
1839         debug_printf("forked child %d\n",pid);
1840         close(channel[1]);
1841         pf = fdopen(channel[0],"r");
1842         debug_printf("pipe on FILE *%p\n",pf);
1843 #else
1844         run_list_test(head,0);
1845         pf=popen("echo surrogate response","r");
1846         debug_printf("started fake pipe on FILE *%p\n",pf);
1847 #endif
1848         return pf;
1849 }
1850
1851 /* this version hacked for testing purposes */
1852 /* return code is exit status of the process that is run. */
1853 static int process_command_subs(o_string *dest, struct p_context *ctx, struct in_str *input, int subst_end)
1854 {
1855         int retcode;
1856         o_string result=NULL_O_STRING;
1857         struct p_context inner;
1858         FILE *p;
1859         struct in_str pipe_str;
1860         initialize_context(&inner);
1861
1862         /* recursion to generate command */
1863         retcode = parse_stream(&result, &inner, input, subst_end);
1864         if (retcode != 0) return retcode;  /* syntax error or EOF */
1865         done_word(&result, &inner);
1866         done_pipe(&inner, PIPE_SEQ);
1867         b_free(&result);
1868
1869         p=generate_stream_from_list(inner.list_head);
1870         if (p==NULL) return 1;
1871         mark_open(fileno(p));
1872         setup_file_in_str(&pipe_str, p);
1873
1874         /* now send results of command back into original context */
1875         retcode = parse_stream(dest, ctx, &pipe_str, '\0');
1876         /* XXX In case of a syntax error, should we try to kill the child?
1877          * That would be tough to do right, so just read until EOF. */
1878         if (retcode == 1) {
1879                 while (b_getch(&pipe_str)!=EOF) { /* discard */ };
1880         }
1881
1882         debug_printf("done reading from pipe, pclose()ing\n");
1883         /* This is the step that wait()s for the child.  Should be pretty
1884          * safe, since we just read an EOF from its stdout.  We could try
1885          * to better, by using wait(), and keeping track of background jobs
1886          * at the same time.  That would be a lot of work, and contrary
1887          * to the KISS philosophy of this program. */
1888         mark_closed(fileno(p));
1889         retcode=pclose(p);
1890         debug_printf("pclosed, retcode=%d\n",retcode);
1891         /* XXX this process fails to trim a single trailing newline */
1892         return retcode;
1893 }
1894
1895 static int parse_group(o_string *dest, struct p_context *ctx,
1896         struct in_str *input, int ch)
1897 {
1898         int rcode, endch=0;
1899         struct p_context sub;
1900         struct child_prog *child = ctx->child;
1901         if (child->argv) {
1902                 syntax();
1903                 return 1;  /* syntax error, groups and arglists don't mix */
1904         }
1905         initialize_context(&sub);
1906         switch(ch) {
1907                 case '(': endch=')'; child->subshell=1; break;
1908                 case '{': endch='}'; break;
1909                 default: syntax();   /* really logic error */
1910         }
1911         rcode=parse_stream(dest,&sub,input,endch);
1912         done_word(dest,&sub); /* finish off the final word in the subcontext */
1913         done_pipe(&sub, PIPE_SEQ);  /* and the final command there, too */
1914         child->group = sub.list_head;
1915         return rcode;
1916         /* child remains "open", available for possible redirects */
1917 }
1918
1919 /* basically useful version until someone wants to get fancier,
1920  * see the bash man page under "Parameter Expansion" */
1921 static void lookup_param(o_string *dest, struct p_context *ctx, o_string *src)
1922 {
1923         const char *p=NULL;
1924         if (src->data) p = getenv(src->data);
1925         if (p) parse_string(dest, ctx, p);   /* recursion */
1926         b_free(src);
1927 }
1928
1929 /* return code: 0 for OK, 1 for syntax error */
1930 static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input)
1931 {
1932         int i, advance=0;
1933         o_string alt=NULL_O_STRING;
1934         char sep[]=" ";
1935         int ch = input->peek(input);  /* first character after the $ */
1936         debug_printf("handle_dollar: ch=%c\n",ch);
1937         if (isalpha(ch)) {
1938                 while(ch=b_peek(input),isalnum(ch) || ch=='_') {
1939                         b_getch(input);
1940                         b_addchr(&alt,ch);
1941                 }
1942                 lookup_param(dest, ctx, &alt);
1943         } else if (isdigit(ch)) {
1944                 i = ch-'0';  /* XXX is $0 special? */
1945                 if (i<global_argc) {
1946                         parse_string(dest, ctx, global_argv[i]); /* recursion */
1947                 }
1948                 advance = 1;
1949         } else switch (ch) {
1950                 case '$':
1951                         b_adduint(dest,getpid());
1952                         advance = 1;
1953                         break;
1954                 case '!':
1955                         if (last_bg_pid > 0) b_adduint(dest, last_bg_pid);
1956                         advance = 1;
1957                         break;
1958                 case '?':
1959                         b_adduint(dest,last_return_code);
1960                         advance = 1;
1961                         break;
1962                 case '#':
1963                         b_adduint(dest,global_argc ? global_argc-1 : 0);
1964                         advance = 1;
1965                         break;
1966                 case '{':
1967                         b_getch(input);
1968                         /* XXX maybe someone will try to escape the '}' */
1969                         while(ch=b_getch(input),ch!=EOF && ch!='}') {
1970                                 b_addchr(&alt,ch);
1971                         }
1972                         if (ch != '}') {
1973                                 syntax();
1974                                 return 1;
1975                         }
1976                         lookup_param(dest, ctx, &alt);
1977                         break;
1978                 case '(':
1979                         b_getch(input);
1980                         process_command_subs(dest, ctx, input, ')');
1981                         break;
1982                 case '*':
1983                         sep[0]=ifs[0];
1984                         for (i=1; i<global_argc; i++) {
1985                                 parse_string(dest, ctx, global_argv[i]);
1986                                 if (i+1 < global_argc) parse_string(dest, ctx, sep);
1987                         }
1988                         break;
1989                 case '@':
1990                 case '-':
1991                 case '_':
1992                         /* still unhandled, but should be eventually */
1993                         fprintf(stderr,"unhandled syntax: $%c\n",ch);
1994                         return 1;
1995                         break;
1996                 default:
1997                         b_addqchr(dest,'$',dest->quote);
1998         }
1999         /* Eat the character if the flag was set.  If the compiler
2000          * is smart enough, we could substitute "b_getch(input);"
2001          * for all the "advance = 1;" above, and also end up with
2002          * a nice size-optimized program.  Hah!  That'll be the day.
2003          */
2004         if (advance) b_getch(input);
2005         return 0;
2006 }
2007
2008 int parse_string(o_string *dest, struct p_context *ctx, const char *src)
2009 {
2010         struct in_str foo;
2011         setup_string_in_str(&foo, src);
2012         return parse_stream(dest, ctx, &foo, '\0');
2013 }
2014
2015 /* return code is 0 for normal exit, 1 for syntax error */
2016 int parse_stream(o_string *dest, struct p_context *ctx,
2017         struct in_str *input, int end_trigger)
2018 {
2019         unsigned int ch, m;
2020         int redir_fd;
2021         redir_type redir_style;
2022         int next;
2023
2024         /* Only double-quote state is handled in the state variable dest->quote.
2025          * A single-quote triggers a bypass of the main loop until its mate is
2026          * found.  When recursing, quote state is passed in via dest->quote. */
2027
2028         debug_printf("parse_stream, end_trigger=%d\n",end_trigger);
2029         while ((ch=b_getch(input))!=EOF) {
2030                 m = map[ch];
2031                 next = (ch == '\n') ? 0 : b_peek(input);
2032                 debug_printf("parse_stream: ch=%c (%d) m=%d quote=%d\n",
2033                         ch,ch,m,dest->quote);
2034                 if (m==0 || ((m==1 || m==2) && dest->quote)) {
2035                         b_addqchr(dest, ch, dest->quote);
2036                 } else {
2037                         if (m==2) {  /* unquoted IFS */
2038                                 done_word(dest, ctx);
2039                                 /* If we aren't performing a substitution, treat a newline as a
2040                                  * command separator.  */
2041                                 if (end_trigger != '\0' && ch=='\n')
2042                                         done_pipe(ctx,PIPE_SEQ);
2043                         }
2044                         if (ch == end_trigger && !dest->quote && ctx->w==RES_NONE) {
2045                                 debug_printf("leaving parse_stream\n");
2046                                 return 0;
2047                         }
2048 #if 0
2049                         if (ch=='\n') {
2050                                 /* Yahoo!  Time to run with it! */
2051                                 done_pipe(ctx,PIPE_SEQ);
2052                                 run_list(ctx->list_head);
2053                                 initialize_context(ctx);
2054                         }
2055 #endif
2056                         if (m!=2) switch (ch) {
2057                 case '#':
2058                         if (dest->length == 0 && !dest->quote) {
2059                                 while(ch=b_peek(input),ch!=EOF && ch!='\n') { b_getch(input); }
2060                         } else {
2061                                 b_addqchr(dest, ch, dest->quote);
2062                         }
2063                         break;
2064                 case '\\':
2065                         if (next == EOF) {
2066                                 syntax();
2067                                 return 1;
2068                         }
2069                         b_addqchr(dest, '\\', dest->quote);
2070                         b_addqchr(dest, b_getch(input), dest->quote);
2071                         break;
2072                 case '$':
2073                         if (handle_dollar(dest, ctx, input)!=0) return 1;
2074                         break;
2075                 case '\'':
2076                         dest->nonnull = 1;
2077                         while(ch=b_getch(input),ch!=EOF && ch!='\'') {
2078                                 b_addchr(dest,ch);
2079                         }
2080                         if (ch==EOF) {
2081                                 syntax();
2082                                 return 1;
2083                         }
2084                         break;
2085                 case '"':
2086                         dest->nonnull = 1;
2087                         dest->quote = !dest->quote;
2088                         break;
2089                 case '`':
2090                         process_command_subs(dest, ctx, input, '`');
2091                         break;
2092                 case '>':
2093                         redir_fd = redirect_opt_num(dest);
2094                         done_word(dest, ctx);
2095                         redir_style=REDIRECT_OVERWRITE;
2096                         if (next == '>') {
2097                                 redir_style=REDIRECT_APPEND;
2098                                 b_getch(input);
2099                         } else if (next == '(') {
2100                                 syntax();   /* until we support >(list) Process Substitution */
2101                                 return 1;
2102                         }
2103                         setup_redirect(ctx, redir_fd, redir_style, input);
2104                         break;
2105                 case '<':
2106                         redir_fd = redirect_opt_num(dest);
2107                         done_word(dest, ctx);
2108                         redir_style=REDIRECT_INPUT;
2109                         if (next == '<') {
2110                                 redir_style=REDIRECT_HEREIS;
2111                                 b_getch(input);
2112                         } else if (next == '>') {
2113                                 redir_style=REDIRECT_IO;
2114                                 b_getch(input);
2115                         } else if (next == '(') {
2116                                 syntax();   /* until we support <(list) Process Substitution */
2117                                 return 1;
2118                         }
2119                         setup_redirect(ctx, redir_fd, redir_style, input);
2120                         break;
2121                 case ';':
2122                         done_word(dest, ctx);
2123                         done_pipe(ctx,PIPE_SEQ);
2124                         break;
2125                 case '&':
2126                         done_word(dest, ctx);
2127                         if (next=='&') {
2128                                 b_getch(input);
2129                                 done_pipe(ctx,PIPE_AND);
2130                         } else {
2131                                 done_pipe(ctx,PIPE_BG);
2132                         }
2133                         break;
2134                 case '|':
2135                         done_word(dest, ctx);
2136                         if (next=='|') {
2137                                 b_getch(input);
2138                                 done_pipe(ctx,PIPE_OR);
2139                         } else {
2140                                 /* we could pick up a file descriptor choice here
2141                                  * with redirect_opt_num(), but bash doesn't do it.
2142                                  * "echo foo 2| cat" yields "foo 2". */
2143                                 done_command(ctx);
2144                         }
2145                         break;
2146                 case '(':
2147                 case '{':
2148                         if (parse_group(dest, ctx, input, ch)!=0) return 1;
2149                         break;
2150                 case ')':
2151                 case '}':
2152                         syntax();   /* Proper use of this character caught by end_trigger */
2153                         return 1;
2154                         break;
2155                 default:
2156                         syntax();   /* this is really an internal logic error */
2157                         return 1;
2158                         }
2159                 }
2160         }
2161         /* complain if quote?  No, maybe we just finished a command substitution
2162          * that was quoted.  Example:
2163          * $ echo "`cat foo` plus more" 
2164          * and we just got the EOF generated by the subshell that ran "cat foo"
2165          * The only real complaint is if we got an EOF when end_trigger != '\0',
2166          * that is, we were really supposed to get end_trigger, and never got
2167          * one before the EOF.  Can't use the standard "syntax error" return code,
2168          * so that parse_stream_outer can distinguish the EOF and exit smoothly. */
2169         if (end_trigger != '\0') return -1;
2170         return 0;
2171 }
2172
2173 void mapset(const unsigned char *set, int code)
2174 {
2175         const unsigned char *s;
2176         for (s=set; *s; s++) map[*s] = code;
2177 }
2178
2179 void update_ifs_map(void)
2180 {
2181         /* char *ifs and char map[256] are both globals. */
2182         ifs = getenv("IFS");
2183         if (ifs == NULL) ifs=" \t\n";
2184         /* Precompute a list of 'flow through' behavior so it can be treated
2185          * quickly up front.  Computation is necessary because of IFS.
2186          * Special case handling of IFS == " \t\n" is not implemented.
2187          * The map[] array only really needs two bits each, and on most machines
2188          * that would be faster because of the reduced L1 cache footprint.
2189          */
2190         memset(map,0,256);        /* most characters flow through always */
2191         mapset("\\$'\"`", 3);     /* never flow through */
2192         mapset("<>;&|(){}#", 1);  /* flow through if quoted */
2193         mapset(ifs, 2);           /* also flow through if quoted */
2194 }
2195
2196 /* most recursion does not come through here, the exeception is
2197  * from builtin_source() */
2198 int parse_stream_outer(struct in_str *inp)
2199 {
2200
2201         struct p_context ctx;
2202         o_string temp=NULL_O_STRING;
2203         int rcode;
2204         do {
2205                 initialize_context(&ctx);
2206                 update_ifs_map();
2207                 inp->promptmode=1;
2208                 rcode = parse_stream(&temp, &ctx, inp, '\n');
2209                 done_word(&temp, &ctx);
2210                 done_pipe(&ctx,PIPE_SEQ);
2211                 run_list(ctx.list_head);
2212         } while (rcode != -1);   /* loop on syntax errors, return on EOF */
2213         return 0;
2214 }
2215
2216 static int parse_string_outer(const char *s)
2217 {
2218         struct in_str input;
2219         setup_string_in_str(&input, s);
2220         return parse_stream_outer(&input);
2221 }
2222
2223 static int parse_file_outer(FILE *f)
2224 {
2225         int rcode;
2226         struct in_str input;
2227         setup_file_in_str(&input, f);
2228         rcode = parse_stream_outer(&input);
2229         return rcode;
2230 }
2231
2232 int shell_main(int argc, char **argv)
2233 {
2234         int opt;
2235         FILE *input;
2236         struct jobset joblist_end = { NULL, NULL };
2237         job_list = &joblist_end;
2238
2239         last_return_code=EXIT_SUCCESS;
2240
2241         /* XXX what should these be while sourcing /etc/profile? */
2242         global_argc = argc;
2243         global_argv = argv;
2244
2245         /* don't pay any attention to this signal; it just confuses 
2246            things and isn't really meant for shells anyway */
2247         signal(SIGTTOU, SIG_IGN);
2248
2249         if (argv[0] && argv[0][0] == '-') {
2250                 debug_printf("\nsourcing /etc/profile\n");
2251                 input = xfopen("/etc/profile", "r");
2252                 mark_open(fileno(input));
2253                 parse_file_outer(input);
2254                 mark_closed(fileno(input));
2255                 fclose(input);
2256         }
2257         input=stdin;
2258         
2259         /* initialize the cwd -- this is never freed...*/
2260         cwd = xgetcwd(0);
2261 #ifdef BB_FEATURE_COMMAND_EDITING
2262         cmdedit_set_initial_prompt();
2263 #else
2264         PS1 = NULL;
2265 #endif
2266         
2267         while ((opt = getopt(argc, argv, "c:xif")) > 0) {
2268                 switch (opt) {
2269                         case 'c':
2270                                 {
2271                                         global_argv = argv+optind;
2272                                         global_argc = argc-optind;
2273                                         opt = parse_string_outer(optarg);
2274                                         goto final_return;
2275                                 }
2276                                 break;
2277                         case 'i':
2278                                 interactive++;
2279                                 break;
2280                         case 'f':
2281                                 fake_mode++;
2282                                 break;
2283                         default:
2284                                 fprintf(stderr, "Usage: sh [FILE]...\n"
2285                                                 "   or: sh -c command [args]...\n\n");
2286                                 exit(EXIT_FAILURE);
2287                 }
2288         }
2289         /* A shell is interactive if the `-i' flag was given, or if all of
2290          * the following conditions are met:
2291          *        no -c command
2292          *    no arguments remaining or the -s flag given
2293          *    standard input is a terminal
2294          *    standard output is a terminal
2295          *    Refer to Posix.2, the description of the `sh' utility. */
2296         if (argv[optind]==NULL && input==stdin &&
2297                         isatty(fileno(stdin)) && isatty(fileno(stdout))) {
2298                 interactive++;
2299         }
2300
2301         debug_printf("\ninteractive=%d\n", interactive);
2302         if (interactive) {
2303                 /* Looks like they want an interactive shell */
2304                 fprintf(stdout, "\nhush -- the humble shell v0.01 (testing)\n\n");
2305                 opt=parse_file_outer(stdin);
2306                 goto final_return;
2307         }
2308
2309         debug_printf("\nrunning script '%s'\n", argv[optind]);
2310         global_argv = argv+optind;
2311         global_argc = argc-optind;
2312         input = xfopen(argv[optind], "r");
2313         opt = parse_file_outer(input);
2314
2315 #ifdef BB_FEATURE_CLEAN_UP
2316         fclose(input.file);
2317 #endif
2318
2319 final_return:
2320         return(opt?opt:last_return_code);
2321 }