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