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