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