blob: 90c89fba29dbb940451c6f451d74c77c63eed93a [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
Eric Andersencb81e642003-07-14 21:21:08 +000012 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
13 * execution engine, the builtins, and much of the underlying
14 * support has been adapted from busybox-0.49pre's lash, which is
Eric Andersenc7bda1c2004-03-15 08:29:22 +000015 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
Eric Andersencb81e642003-07-14 21:21:08 +000016 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
17 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
18 * Troan, which they placed in the public domain. I don't know
19 * how much of the Johnson/Troan code has survived the repeated
20 * rewrites.
21 *
Eric Andersen25f27032001-04-26 23:22:31 +000022 * Other credits:
Eric Andersen25f27032001-04-26 23:22:31 +000023 * b_addchr() derived from similar w_addchar function in glibc-2.2
24 * setup_redirect(), redirect_opt_num(), and big chunks of main()
Denis Vlasenko55b2de72007-04-18 17:21:28 +000025 * and many builtins derived from contributions by Erik Andersen
Eric Andersen25f27032001-04-26 23:22:31 +000026 * miscellaneous bugfixes from Matt Kraai
27 *
28 * There are two big (and related) architecture differences between
29 * this parser and the lash parser. One is that this version is
30 * actually designed from the ground up to understand nearly all
31 * of the Bourne grammar. The second, consequential change is that
32 * the parser and input reader have been turned inside out. Now,
33 * the parser is in control, and asks for input as needed. The old
34 * way had the input reader in control, and it asked for parsing to
35 * take place as needed. The new way makes it much easier to properly
36 * handle the recursion implicit in the various substitutions, especially
37 * across continuation lines.
38 *
39 * Bash grammar not implemented: (how many of these were in original sh?)
40 * $@ (those sure look like weird quoting rules)
41 * $_
42 * ! negation operator for pipes
43 * &> and >& redirection of stdout+stderr
44 * Brace Expansion
45 * Tilde Expansion
46 * fancy forms of Parameter Expansion
Eric Andersen78a7c992001-05-15 16:30:25 +000047 * aliases
Eric Andersen25f27032001-04-26 23:22:31 +000048 * Arithmetic Expansion
49 * <(list) and >(list) Process Substitution
Eric Andersen83a2ae22001-05-07 17:59:25 +000050 * reserved words: case, esac, select, function
Eric Andersen25f27032001-04-26 23:22:31 +000051 * Here Documents ( << word )
52 * Functions
53 * Major bugs:
Denis Vlasenkob81b3df2007-04-28 16:48:04 +000054 * job handling woefully incomplete and buggy (improved --vda)
Eric Andersen25f27032001-04-26 23:22:31 +000055 * reserved word execution woefully incomplete and buggy
Eric Andersen25f27032001-04-26 23:22:31 +000056 * to-do:
Eric Andersen83a2ae22001-05-07 17:59:25 +000057 * port selected bugfixes from post-0.49 busybox lash - done?
58 * finish implementing reserved words: for, while, until, do, done
59 * change { and } from special chars to reserved words
60 * builtins: break, continue, eval, return, set, trap, ulimit
61 * test magic exec
Eric Andersen25f27032001-04-26 23:22:31 +000062 * handle children going into background
63 * clean up recognition of null pipes
Eric Andersen25f27032001-04-26 23:22:31 +000064 * check setting of global_argc and global_argv
65 * control-C handling, probably with longjmp
Eric Andersen25f27032001-04-26 23:22:31 +000066 * 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
Eric Andersen78a7c992001-05-15 16:30:25 +000073 * document how quoting rules not precisely followed for variable assignments
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +000074 * maybe change charmap[] to use 2-bit entries
Eric Andersen25f27032001-04-26 23:22:31 +000075 * (eventually) remove all the printf's
Eric Andersen25f27032001-04-26 23:22:31 +000076 *
Bernhard Reutner-Fischer86f5c992006-01-22 22:55:11 +000077 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
Eric Andersen25f27032001-04-26 23:22:31 +000078 */
Bernhard Reutner-Fischere15d7572006-06-02 20:56:16 +000079
80#include "busybox.h"
Eric Andersen25f27032001-04-26 23:22:31 +000081#include <glob.h> /* glob, of course */
Eric Andersen25f27032001-04-26 23:22:31 +000082#include <getopt.h> /* should be pretty obvious */
Eric Andersen25f27032001-04-26 23:22:31 +000083/* #include <dmalloc.h> */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +000084extern char **environ; /* This is in <unistd.h>, but protected with __USE_GNU */
Denis Vlasenkod01ff132007-05-02 21:40:23 +000085
86
87/* If you comment out one of these below, it will be #defined later
88 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +000089#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +000090/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +000091#define debug_printf_parse(...) do {} while (0)
92#define debug_print_tree(a, b) do {} while (0)
93#define debug_printf_exec(...) do {} while (0)
94#define debug_printf_jobs(...) do {} while (0)
95#define debug_printf_expand(...) do {} while (0)
96#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +000097
98#ifndef debug_printf
99#define debug_printf(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000100#endif
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000101
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000102#ifndef debug_printf_parse
103#define debug_printf_parse(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000104#endif
105
106#ifndef debug_printf_exec
107#define debug_printf_exec(...) fprintf(stderr, __VA_ARGS__)
108#endif
109
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000110#ifndef debug_printf_jobs
111#define debug_printf_jobs(...) fprintf(stderr, __VA_ARGS__)
112#define DEBUG_SHELL_JOBS 1
113#endif
114
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000115#ifndef debug_printf_expand
116#define debug_printf_expand(...) fprintf(stderr, __VA_ARGS__)
117#define DEBUG_EXPAND 1
118#endif
119
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000120#ifndef debug_printf_clean
121/* broken, of course, but OK for testing */
122static const char *indenter(int i)
123{
124 static const char blanks[] = " ";
125 return &blanks[sizeof(blanks) - i - 1];
126}
127#define debug_printf_clean(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkoc666f712007-05-16 22:18:54 +0000128#define DEBUG_CLEAN 1
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +0000129#endif
130
Eric Andersen25f27032001-04-26 23:22:31 +0000131
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000132#if !ENABLE_HUSH_INTERACTIVE
133#undef ENABLE_FEATURE_EDITING
134#define ENABLE_FEATURE_EDITING 0
135#undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
136#define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
137#endif
"Robert P. J. Day"f3501602006-07-01 12:19:39 +0000138
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +0000139#define SPECIAL_VAR_SYMBOL 3
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000140
141#define PARSEFLAG_EXIT_FROM_LOOP 1
142#define PARSEFLAG_SEMICOLON (1 << 1) /* symbol ';' is special for parser */
143#define PARSEFLAG_REPARSING (1 << 2) /* >= 2nd pass */
Eric Andersen25f27032001-04-26 23:22:31 +0000144
145typedef enum {
146 REDIRECT_INPUT = 1,
147 REDIRECT_OVERWRITE = 2,
148 REDIRECT_APPEND = 3,
149 REDIRECT_HEREIS = 4,
150 REDIRECT_IO = 5
151} redir_type;
152
153/* The descrip member of this structure is only used to make debugging
154 * output pretty */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +0000155static const struct {
156 int mode;
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000157 signed char default_fd;
158 char descrip[3];
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +0000159} redir_table[] = {
Eric Andersen25f27032001-04-26 23:22:31 +0000160 { 0, 0, "()" },
161 { O_RDONLY, 0, "<" },
162 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
163 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
164 { O_RDONLY, -1, "<<" },
165 { O_RDWR, 1, "<>" }
166};
167
168typedef enum {
169 PIPE_SEQ = 1,
170 PIPE_AND = 2,
171 PIPE_OR = 3,
172 PIPE_BG = 4,
173} pipe_style;
174
175/* might eventually control execution */
176typedef enum {
177 RES_NONE = 0,
178 RES_IF = 1,
179 RES_THEN = 2,
180 RES_ELIF = 3,
181 RES_ELSE = 4,
182 RES_FI = 5,
183 RES_FOR = 6,
184 RES_WHILE = 7,
185 RES_UNTIL = 8,
186 RES_DO = 9,
187 RES_DONE = 10,
Eric Andersenaf44a0e2001-04-27 07:26:12 +0000188 RES_XXXX = 11,
Eric Andersen4c9b68f2002-04-13 12:33:41 +0000189 RES_IN = 12,
190 RES_SNTX = 13
Eric Andersen25f27032001-04-26 23:22:31 +0000191} reserved_style;
Denis Vlasenko5f786c22007-04-20 08:35:45 +0000192enum {
193 FLAG_END = (1 << RES_NONE ),
194 FLAG_IF = (1 << RES_IF ),
195 FLAG_THEN = (1 << RES_THEN ),
196 FLAG_ELIF = (1 << RES_ELIF ),
197 FLAG_ELSE = (1 << RES_ELSE ),
198 FLAG_FI = (1 << RES_FI ),
199 FLAG_FOR = (1 << RES_FOR ),
200 FLAG_WHILE = (1 << RES_WHILE),
201 FLAG_UNTIL = (1 << RES_UNTIL),
202 FLAG_DO = (1 << RES_DO ),
203 FLAG_DONE = (1 << RES_DONE ),
204 FLAG_IN = (1 << RES_IN ),
205 FLAG_START = (1 << RES_XXXX ),
206};
Eric Andersen25f27032001-04-26 23:22:31 +0000207
208/* This holds pointers to the various results of parsing */
209struct p_context {
210 struct child_prog *child;
211 struct pipe *list_head;
212 struct pipe *pipe;
213 struct redir_struct *pending_redirect;
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000214 smallint res_w;
215 smallint parse_type; /* bitmask of PARSEFLAG_xxx, defines type of parser : ";$" common or special symbol */
216 int old_flag; /* bitmask of FLAG_xxx, for figuring out valid reserved words */
Eric Andersen25f27032001-04-26 23:22:31 +0000217 struct p_context *stack;
218 /* How about quoting status? */
219};
220
221struct redir_struct {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000222 struct redir_struct *next; /* pointer to the next redirect in the list */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000223 redir_type type; /* type of redirection */
224 int fd; /* file descriptor being redirected */
225 int dup; /* -1, or file descriptor being duplicated */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000226 glob_t word; /* *word.gl_pathv is the filename */
Eric Andersen25f27032001-04-26 23:22:31 +0000227};
228
229struct child_prog {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000230 pid_t pid; /* 0 if exited */
231 char **argv; /* program name and arguments */
232 struct pipe *group; /* if non-NULL, first in group or subshell */
Denis Vlasenko262d7652007-05-20 21:52:49 +0000233 smallint subshell; /* flag, non-zero if group must be forked */
234 smallint is_stopped; /* is the program currently running? */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000235 struct redir_struct *redirects; /* I/O redirections */
236 glob_t glob_result; /* result of parameter globbing */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000237 struct pipe *family; /* pointer back to the child's parent pipe */
Denis Vlasenkoc666f712007-05-16 22:18:54 +0000238 //sp counting seems to be broken... so commented out, grep for '//sp:'
239 //sp: int sp; /* number of SPECIAL_VAR_SYMBOL */
Denis Vlasenko262d7652007-05-20 21:52:49 +0000240 //seems to be unused, grep for '//pt:'
241 //pt: int parse_type;
Eric Andersen25f27032001-04-26 23:22:31 +0000242};
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000243/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
244 * and on execution these are substituted with their values.
245 * Substitution can make _several_ words out of one argv[n]!
246 * Example: argv[0]=='.^C*^C.' here: echo .$*.
247 */
Eric Andersen25f27032001-04-26 23:22:31 +0000248
249struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000250 struct pipe *next;
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000251 int num_progs; /* total number of programs in job */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000252 int running_progs; /* number of programs running (not exited) */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000253 int stopped_progs; /* number of programs alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000254#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000255 int jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000256 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000257 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000258#endif
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000259 char *cmdbuf; /* buffer various argv's point into */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000260 struct child_prog *progs; /* array of commands in pipe */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000261 int job_context; /* bitmask defining current context */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000262 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
263 smallint res_word; /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000264};
265
Eric Andersen25f27032001-04-26 23:22:31 +0000266struct close_me {
Eric Andersen25f27032001-04-26 23:22:31 +0000267 struct close_me *next;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000268 int fd;
Eric Andersen25f27032001-04-26 23:22:31 +0000269};
270
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000271struct variables {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000272 struct variables *next;
Denis Vlasenko15d78fb2007-01-30 22:28:21 +0000273 const char *name;
274 const char *value;
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000275 smallint flg_export;
276 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000277};
278
Eric Andersen25f27032001-04-26 23:22:31 +0000279typedef struct {
280 char *data;
281 int length;
282 int maxlen;
283 int quote;
284 int nonnull;
285} o_string;
286#define NULL_O_STRING {NULL,0,0,0,0}
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000287/* used for initialization: o_string foo = NULL_O_STRING; */
Eric Andersen25f27032001-04-26 23:22:31 +0000288
289/* I can almost use ordinary FILE *. Is open_memstream() universally
290 * available? Where is it documented? */
291struct in_str {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +0000292 const char *p;
293 /* eof_flag=1: last char in ->p is really an EOF */
294 char eof_flag; /* meaningless if ->p == NULL */
295 char peek_buf[2];
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000296#if ENABLE_HUSH_INTERACTIVE
Eric Andersen25f27032001-04-26 23:22:31 +0000297 int __promptme;
298 int promptmode;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000299#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000300 FILE *file;
301 int (*get) (struct in_str *);
302 int (*peek) (struct in_str *);
303};
304#define b_getch(input) ((input)->get(input))
305#define b_peek(input) ((input)->peek(input))
306
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000307enum {
308 CHAR_ORDINARY = 0,
309 CHAR_ORDINARY_IF_QUOTED = 1, /* example: *, # */
310 CHAR_IFS = 2, /* treated as ordinary if quoted */
311 CHAR_SPECIAL = 3, /* example: $ */
Eric Andersen25f27032001-04-26 23:22:31 +0000312};
313
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000314
315/* "Globals" within this file */
316
317#define HUSH_VER_STR "0.02"
318static const struct variables const_shell_ver = {
319 NULL, "HUSH_VERSION", HUSH_VER_STR, 1, 1
320};
321
322/* Sorted roughly by size (smaller offsets == smaller code) */
323struct globals {
324#if ENABLE_HUSH_INTERACTIVE
325 /* 'interactive_fd' is a fd# open to ctty, if we have one
326 * _AND_ if we decided to act interactively */
327 int interactive_fd;
328 const char *PS1;
329 const char *PS2;
330#endif
331#if ENABLE_FEATURE_EDITING
332 line_input_t *line_input_state;
333#endif
334#if ENABLE_HUSH_JOB
335 int run_list_level;
336 pid_t saved_task_pgrp;
337 pid_t saved_tty_pgrp;
338 int last_jobid;
339 struct pipe *job_list;
340 struct pipe *toplevel_list;
341 smallint ctrl_z_flag;
342#endif
343 smallint fake_mode;
344 /* these three support $?, $#, and $1 */
345 char **global_argv;
346 int global_argc;
347 int last_return_code;
348 const char *ifs;
349 struct close_me *close_me_head;
350 const char *cwd;
351 unsigned last_bg_pid;
352 struct variables *top_vars; /* = &shell_ver (both are set in main()) */
353 struct variables shell_ver; /* = const_shell_ver */
354#if ENABLE_FEATURE_SH_STANDALONE
355 struct nofork_save_area nofork_save;
356#endif
357#if ENABLE_HUSH_JOB
358 sigjmp_buf toplevel_jb;
359#endif
360 unsigned char charmap[256];
361 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
362};
363
364#define G (*ptr_to_globals)
365
366#if !ENABLE_HUSH_INTERACTIVE
367enum { interactive_fd = 0 };
368#endif
369#if !ENABLE_HUSH_JOB
370enum { run_list_level = 0 };
371#endif
372
373#if ENABLE_HUSH_INTERACTIVE
374#define interactive_fd (G.interactive_fd )
375#define PS1 (G.PS1 )
376#define PS2 (G.PS2 )
377#endif
378#if ENABLE_FEATURE_EDITING
379#define line_input_state (G.line_input_state)
380#endif
381#if ENABLE_HUSH_JOB
382#define run_list_level (G.run_list_level )
383#define saved_task_pgrp (G.saved_task_pgrp )
384#define saved_tty_pgrp (G.saved_tty_pgrp )
385#define last_jobid (G.last_jobid )
386#define job_list (G.job_list )
387#define toplevel_list (G.toplevel_list )
388#define toplevel_jb (G.toplevel_jb )
389#define ctrl_z_flag (G.ctrl_z_flag )
390#endif /* JOB */
391#define global_argv (G.global_argv )
392#define global_argc (G.global_argc )
393#define last_return_code (G.last_return_code)
394#define ifs (G.ifs )
395#define fake_mode (G.fake_mode )
396#define close_me_head (G.close_me_head )
397#define cwd (G.cwd )
398#define last_bg_pid (G.last_bg_pid )
399#define top_vars (G.top_vars )
400#define shell_ver (G.shell_ver )
401#if ENABLE_FEATURE_SH_STANDALONE
402#define nofork_save (G.nofork_save )
403#endif
404#if ENABLE_HUSH_JOB
405#define toplevel_jb (G.toplevel_jb )
406#endif
407#define charmap (G.charmap )
408#define user_input_buf (G.user_input_buf )
409
410
411#define B_CHUNK 100
412#define B_NOSPAC 1
413#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
414
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000415static void __syntax(int line)
Denis Vlasenkob6aae0f2007-01-29 22:51:25 +0000416{
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000417 bb_error_msg("syntax error hush.c:%d", line);
Eric Andersen25f27032001-04-26 23:22:31 +0000418}
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000419#define syntax() __syntax(__LINE__)
Eric Andersen25f27032001-04-26 23:22:31 +0000420
421/* Index of subroutines: */
422/* function prototypes for builtins */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000423static int builtin_cd(char **argv);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000424static int builtin_eval(char **argv);
425static int builtin_exec(char **argv);
426static int builtin_exit(char **argv);
427static int builtin_export(char **argv);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000428#if ENABLE_HUSH_JOB
Denis Vlasenko1359da62007-04-21 23:27:30 +0000429static int builtin_fg_bg(char **argv);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000430static int builtin_jobs(char **argv);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000431#endif
432static int builtin_help(char **argv);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000433static int builtin_pwd(char **argv);
434static int builtin_read(char **argv);
435static int builtin_set(char **argv);
436static int builtin_shift(char **argv);
437static int builtin_source(char **argv);
438static int builtin_umask(char **argv);
439static int builtin_unset(char **argv);
440static int builtin_not_written(char **argv);
Eric Andersen25f27032001-04-26 23:22:31 +0000441/* o_string manipulation: */
442static int b_check_space(o_string *o, int len);
443static int b_addchr(o_string *o, int ch);
444static void b_reset(o_string *o);
445static int b_addqchr(o_string *o, int ch, int quote);
Eric Andersen25f27032001-04-26 23:22:31 +0000446/* in_str manipulations: */
447static int static_get(struct in_str *i);
448static int static_peek(struct in_str *i);
449static int file_get(struct in_str *i);
450static int file_peek(struct in_str *i);
451static void setup_file_in_str(struct in_str *i, FILE *f);
452static void setup_string_in_str(struct in_str *i, const char *s);
453/* close_me manipulations: */
454static void mark_open(int fd);
455static void mark_closed(int fd);
Eric Anderseneaecbf32001-10-31 10:41:31 +0000456static void close_all(void);
Eric Andersen25f27032001-04-26 23:22:31 +0000457/* "run" the final data structures: */
Denis Vlasenkoc666f712007-05-16 22:18:54 +0000458#if !defined(DEBUG_CLEAN)
459#define free_pipe_list(head, indent) free_pipe_list(head)
460#define free_pipe(pi, indent) free_pipe(pi)
461#endif
Eric Andersenbf7df042001-05-23 22:18:35 +0000462static int free_pipe_list(struct pipe *head, int indent);
463static int free_pipe(struct pipe *pi, int indent);
Eric Andersen25f27032001-04-26 23:22:31 +0000464/* really run the final data structures: */
465static int setup_redirects(struct child_prog *prog, int squirrel[]);
Eric Andersen25f27032001-04-26 23:22:31 +0000466static int run_list_real(struct pipe *pi);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000467static void pseudo_exec_argv(char **argv) ATTRIBUTE_NORETURN;
Bernhard Reutner-Fischer86f5c992006-01-22 22:55:11 +0000468static void pseudo_exec(struct child_prog *child) ATTRIBUTE_NORETURN;
Eric Andersen25f27032001-04-26 23:22:31 +0000469static int run_pipe_real(struct pipe *pi);
470/* extended glob support: */
471static int globhack(const char *src, int flags, glob_t *pglob);
472static int glob_needed(const char *s);
473static int xglob(o_string *dest, int flags, glob_t *pglob);
Eric Andersen78a7c992001-05-15 16:30:25 +0000474/* variable assignment: */
Eric Andersen78a7c992001-05-15 16:30:25 +0000475static int is_assignment(const char *s);
Eric Andersen25f27032001-04-26 23:22:31 +0000476/* data structure manipulation: */
477static int setup_redirect(struct p_context *ctx, int fd, redir_type style, struct in_str *input);
478static void initialize_context(struct p_context *ctx);
479static int done_word(o_string *dest, struct p_context *ctx);
480static int done_command(struct p_context *ctx);
481static int done_pipe(struct p_context *ctx, pipe_style type);
482/* primary string parsing: */
483static int redirect_dup_num(struct in_str *input);
484static int redirect_opt_num(o_string *o);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +0000485#if ENABLE_HUSH_TICK
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +0000486static int process_command_subs(o_string *dest, struct p_context *ctx, struct in_str *input, const char *subst_end);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +0000487#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000488static int parse_group(o_string *dest, struct p_context *ctx, struct in_str *input, int ch);
Denis Vlasenko15d78fb2007-01-30 22:28:21 +0000489static const char *lookup_param(const char *src);
Eric Andersen4c9b68f2002-04-13 12:33:41 +0000490static char *make_string(char **inp);
Eric Andersen25f27032001-04-26 23:22:31 +0000491static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +0000492static int parse_stream(o_string *dest, struct p_context *ctx, struct in_str *input0, const char *end_trigger);
Eric Andersen25f27032001-04-26 23:22:31 +0000493/* setup: */
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +0000494static int parse_stream_outer(struct in_str *inp, int parse_flag);
495static int parse_string_outer(const char *s, int parse_flag);
Eric Andersen25f27032001-04-26 23:22:31 +0000496static int parse_file_outer(FILE *f);
Eric Andersenbafd94f2001-05-02 16:11:59 +0000497/* job management: */
Eric Andersenc798b072001-06-22 06:23:03 +0000498static int checkjobs(struct pipe* fg_pipe);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000499#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +0000500static int checkjobs_and_fg_shell(struct pipe* fg_pipe);
Eric Andersenbafd94f2001-05-02 16:11:59 +0000501static void insert_bg_job(struct pipe *pi);
502static void remove_bg_job(struct pipe *pi);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000503static void delete_finished_bg_job(struct pipe *pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000504#else
505int checkjobs_and_fg_shell(struct pipe* fg_pipe); /* never called */
506#endif
Eric Andersenf72f5622001-05-15 23:21:41 +0000507/* local variable support */
Denis Vlasenkob6a741f2007-05-17 14:38:17 +0000508static char **expand_variables_to_list(char **argv);
509/* used for expansion of right hand of assignments */
510static char *expand_variables_to_string(const char *str);
Denis Vlasenko15d78fb2007-01-30 22:28:21 +0000511static const char *get_local_var(const char *var);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000512static int set_local_var(const char *s, int flg_export);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +0000513static void unset_local_var(const char *name);
Eric Andersen25f27032001-04-26 23:22:31 +0000514
515/* Table of built-in functions. They can be forked or not, depending on
516 * context: within pipes, they fork. As simple commands, they do not.
517 * When used in non-forking context, they can change global variables
Denis Vlasenkoe1a0d482006-10-20 13:28:22 +0000518 * in the parent shell process. If forked, of course they cannot.
Eric Andersen25f27032001-04-26 23:22:31 +0000519 * For example, 'unset foo | whatever' will parse and run, but foo will
520 * still be set at the end. */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000521struct built_in_command {
522 const char *cmd; /* name */
523 const char *descr; /* description */
524 int (*function) (char **argv); /* function ptr */
525};
526
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +0000527static const struct built_in_command bltins[] = {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000528#if ENABLE_HUSH_JOB
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000529 { "bg", "Resume a job in the background", builtin_fg_bg },
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000530#endif
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000531 { "break", "Exit for, while or until loop", builtin_not_written },
532 { "cd", "Change working directory", builtin_cd },
533 { "continue", "Continue for, while or until loop", builtin_not_written },
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000534 { "eval", "Construct and run shell command", builtin_eval },
535 { "exec", "Exec command, replacing this shell with the exec'd process",
536 builtin_exec },
537 { "exit", "Exit from shell()", builtin_exit },
538 { "export", "Set environment variable", builtin_export },
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000539#if ENABLE_HUSH_JOB
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000540 { "fg", "Bring job into the foreground", builtin_fg_bg },
541 { "jobs", "Lists the active jobs", builtin_jobs },
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000542#endif
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000543 { "pwd", "Print current directory", builtin_pwd },
544 { "read", "Input environment variable", builtin_read },
545 { "return", "Return from a function", builtin_not_written },
546 { "set", "Set/unset shell local variables", builtin_set },
547 { "shift", "Shift positional parameters", builtin_shift },
548 { "trap", "Trap signals", builtin_not_written },
549 { "ulimit","Controls resource limits", builtin_not_written },
550 { "umask","Sets file creation mask", builtin_umask },
551 { "unset", "Unset environment variable", builtin_unset },
552 { ".", "Source-in and run commands in a file", builtin_source },
553 { "help", "List shell built-in commands", builtin_help },
554 { NULL, NULL, NULL }
Eric Andersen25f27032001-04-26 23:22:31 +0000555};
556
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000557#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000558
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000559/* move to libbb? */
560static void signal_SA_RESTART(int sig, void (*handler)(int))
561{
562 struct sigaction sa;
563 sa.sa_handler = handler;
564 sa.sa_flags = SA_RESTART;
565 sigemptyset(&sa.sa_mask);
566 sigaction(sig, &sa, NULL);
567}
568
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000569/* Signals are grouped, we handle them in batches */
570static void set_fatal_sighandler(void (*handler)(int))
571{
572 signal(SIGILL , handler);
573 signal(SIGTRAP, handler);
574 signal(SIGABRT, handler);
575 signal(SIGFPE , handler);
576 signal(SIGBUS , handler);
577 signal(SIGSEGV, handler);
578 /* bash 3.2 seems to handle these just like 'fatal' ones */
579 signal(SIGHUP , handler);
580 signal(SIGPIPE, handler);
581 signal(SIGALRM, handler);
582}
583static void set_jobctrl_sighandler(void (*handler)(int))
584{
585 signal(SIGTSTP, handler);
586 signal(SIGTTIN, handler);
587 signal(SIGTTOU, handler);
588}
589static void set_misc_sighandler(void (*handler)(int))
590{
591 signal(SIGINT , handler);
592 signal(SIGQUIT, handler);
593 signal(SIGTERM, handler);
594}
595/* SIGCHLD is special and handled separately */
596
597static void set_every_sighandler(void (*handler)(int))
598{
599 set_fatal_sighandler(handler);
600 set_jobctrl_sighandler(handler);
601 set_misc_sighandler(handler);
602 signal(SIGCHLD, handler);
603}
604
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000605static void handler_ctrl_c(int sig)
606{
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000607 debug_printf_jobs("got sig %d\n", sig);
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000608// as usual we can have all kinds of nasty problems with leaked malloc data here
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000609 siglongjmp(toplevel_jb, 1);
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000610}
611
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000612static void handler_ctrl_z(int sig)
613{
614 pid_t pid;
615
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000616 debug_printf_jobs("got tty sig %d in pid %d\n", sig, getpid());
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000617 pid = fork();
Denis Vlasenkoc2990322007-05-16 12:57:12 +0000618 if (pid < 0) /* can't fork. Pretend there was no ctrl-Z */
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000619 return;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000620 ctrl_z_flag = 1;
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000621 if (!pid) { /* child */
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000622 setpgrp();
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000623 debug_printf_jobs("set pgrp for child %d ok\n", getpid());
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000624 set_every_sighandler(SIG_DFL);
Denis Vlasenko18e19f22007-04-28 16:43:18 +0000625 raise(SIGTSTP); /* resend TSTP so that child will be stopped */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000626 debug_printf_jobs("returning in child\n");
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000627 /* return to nofork, it will eventually exit now,
628 * not return back to shell */
629 return;
630 }
631 /* parent */
632 /* finish filling up pipe info */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000633 toplevel_list->pgrp = pid; /* child is in its own pgrp */
634 toplevel_list->progs[0].pid = pid;
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000635 /* parent needs to longjmp out of running nofork.
636 * we will "return" exitcode 0, with child put in background */
637// as usual we can have all kinds of nasty problems with leaked malloc data here
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000638 debug_printf_jobs("siglongjmp in parent\n");
639 siglongjmp(toplevel_jb, 1);
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000640}
641
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000642/* Restores tty foreground process group, and exits.
643 * May be called as signal handler for fatal signal
644 * (will faithfully resend signal to itself, producing correct exit state)
645 * or called directly with -EXITCODE.
646 * We also call it if xfunc is exiting. */
647static void sigexit(int sig) ATTRIBUTE_NORETURN;
648static void sigexit(int sig)
649{
650 sigset_t block_all;
651
652 /* Disable all signals: job control, SIGPIPE, etc. */
653 sigfillset(&block_all);
654 sigprocmask(SIG_SETMASK, &block_all, NULL);
655
Denis Vlasenko87cb2db2007-04-21 10:00:01 +0000656 if (interactive_fd)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000657 tcsetpgrp(interactive_fd, saved_tty_pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000658
659 /* Not a signal, just exit */
660 if (sig <= 0)
661 _exit(- sig);
662
663 /* Enable only this sig and kill ourself with it */
664 signal(sig, SIG_DFL);
665 sigdelset(&block_all, sig);
666 sigprocmask(SIG_SETMASK, &block_all, NULL);
667 raise(sig);
668 _exit(1); /* Should not reach it */
669}
670
671/* Restores tty foreground process group, and exits. */
672static void hush_exit(int exitcode) ATTRIBUTE_NORETURN;
673static void hush_exit(int exitcode)
674{
675 fflush(NULL); /* flush all streams */
676 sigexit(- (exitcode & 0xff));
677}
678
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000679#else /* !JOB */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000680
681#define set_fatal_sighandler(handler) ((void)0)
682#define set_jobctrl_sighandler(handler) ((void)0)
683#define set_misc_sighandler(handler) ((void)0)
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000684#define hush_exit(e) exit(e)
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000685
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000686#endif /* JOB */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000687
688
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000689static const char *set_cwd(void)
690{
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000691 if (cwd == bb_msg_unknown)
Denis Vlasenko7cced6e2007-04-12 17:08:53 +0000692 cwd = NULL; /* xrealloc_getcwd_or_warn(arg) calls free(arg)! */
Denis Vlasenko6ca04442007-02-11 16:19:28 +0000693 cwd = xrealloc_getcwd_or_warn((char *)cwd);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000694 if (!cwd)
Manuel Novoa III cad53642003-03-19 09:13:01 +0000695 cwd = bb_msg_unknown;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000696 return cwd;
697}
698
Eric Andersen4c9b68f2002-04-13 12:33:41 +0000699/* built-in 'eval' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000700static int builtin_eval(char **argv)
Eric Andersen4c9b68f2002-04-13 12:33:41 +0000701{
702 char *str = NULL;
703 int rcode = EXIT_SUCCESS;
Eric Andersenc7bda1c2004-03-15 08:29:22 +0000704
Denis Vlasenko1359da62007-04-21 23:27:30 +0000705 if (argv[1]) {
706 str = make_string(argv + 1);
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000707 parse_string_outer(str, PARSEFLAG_EXIT_FROM_LOOP |
708 PARSEFLAG_SEMICOLON);
Eric Andersen4c9b68f2002-04-13 12:33:41 +0000709 free(str);
710 rcode = last_return_code;
711 }
712 return rcode;
713}
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000714
Eric Andersen25f27032001-04-26 23:22:31 +0000715/* built-in 'cd <path>' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000716static int builtin_cd(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000717{
718 char *newdir;
Denis Vlasenko1359da62007-04-21 23:27:30 +0000719 if (argv[1] == NULL)
Eric Andersen25f27032001-04-26 23:22:31 +0000720 newdir = getenv("HOME");
721 else
Denis Vlasenko1359da62007-04-21 23:27:30 +0000722 newdir = argv[1];
Eric Andersen25f27032001-04-26 23:22:31 +0000723 if (chdir(newdir)) {
724 printf("cd: %s: %s\n", newdir, strerror(errno));
725 return EXIT_FAILURE;
726 }
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000727 set_cwd();
Eric Andersen25f27032001-04-26 23:22:31 +0000728 return EXIT_SUCCESS;
729}
730
Eric Andersen25f27032001-04-26 23:22:31 +0000731/* built-in 'exec' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000732static int builtin_exec(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000733{
Denis Vlasenko1359da62007-04-21 23:27:30 +0000734 if (argv[1] == NULL)
Eric Andersen25f27032001-04-26 23:22:31 +0000735 return EXIT_SUCCESS; /* Really? */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000736 pseudo_exec_argv(argv + 1);
Eric Andersen25f27032001-04-26 23:22:31 +0000737 /* never returns */
738}
739
740/* built-in 'exit' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000741static int builtin_exit(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000742{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000743// TODO: bash does it ONLY on top-level sh exit (+interacive only?)
744 //puts("exit"); /* bash does it */
Denis Vlasenkof2fffd02007-05-02 23:39:04 +0000745// TODO: warn if we have background jobs: "There are stopped jobs"
746// On second consecutive 'exit', exit anyway.
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000747
Denis Vlasenko1359da62007-04-21 23:27:30 +0000748 if (argv[1] == NULL)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000749 hush_exit(last_return_code);
Denis Vlasenko5f786c22007-04-20 08:35:45 +0000750 /* mimic bash: exit 123abc == exit 255 + error msg */
751 xfunc_error_retval = 255;
752 /* bash: exit -2 == exit 254, no error msg */
Denis Vlasenkof2fffd02007-05-02 23:39:04 +0000753 hush_exit(xatoi(argv[1]) & 0xff);
Eric Andersen25f27032001-04-26 23:22:31 +0000754}
755
756/* built-in 'export VAR=value' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000757static int builtin_export(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000758{
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000759 int res = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +0000760 char *name = argv[1];
Eric Andersen25f27032001-04-26 23:22:31 +0000761
Eric Andersenf72f5622001-05-15 23:21:41 +0000762 if (name == NULL) {
Denis Vlasenkof2fffd02007-05-02 23:39:04 +0000763 // TODO:
764 // ash emits: export VAR='VAL'
765 // bash: declare -x VAR="VAL"
766 // (both also escape as needed (quotes, $, etc))
767 char **e = environ;
768 if (e)
769 while (*e)
770 puts(*e++);
771 return EXIT_SUCCESS;
Eric Andersen25f27032001-04-26 23:22:31 +0000772 }
Eric Andersenf72f5622001-05-15 23:21:41 +0000773
Denis Vlasenkoc666f712007-05-16 22:18:54 +0000774 name = xstrdup(name);
775 {
Denis Vlasenko15d78fb2007-01-30 22:28:21 +0000776 const char *value = strchr(name, '=');
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000777
Eric Andersen94ac2442001-05-22 19:05:18 +0000778 if (!value) {
779 char *tmp;
780 /* They are exporting something without an =VALUE */
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000781
Eric Andersen94ac2442001-05-22 19:05:18 +0000782 value = get_local_var(name);
783 if (value) {
784 size_t ln = strlen(name);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000785
Denis Vlasenkoc666f712007-05-16 22:18:54 +0000786 tmp = xrealloc(name, ln+strlen(value)+2);
787 sprintf(tmp+ln, "=%s", value);
788 name = tmp;
Eric Andersen94ac2442001-05-22 19:05:18 +0000789 } else {
790 /* bash does not return an error when trying to export
791 * an undefined variable. Do likewise. */
792 res = 1;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000793 }
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000794 }
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000795 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000796 if (res < 0)
Manuel Novoa III cad53642003-03-19 09:13:01 +0000797 bb_perror_msg("export");
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000798 else if (res == 0)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000799 res = set_local_var(name, 1);
800 else
801 res = 0;
802 free(name);
803 return res;
Eric Andersen25f27032001-04-26 23:22:31 +0000804}
805
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000806#if ENABLE_HUSH_JOB
Eric Andersen25f27032001-04-26 23:22:31 +0000807/* built-in 'fg' and 'bg' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000808static int builtin_fg_bg(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000809{
Eric Andersen0fcd4472001-05-02 20:12:03 +0000810 int i, jobnum;
Denis Vlasenko8a28e622007-04-14 11:16:29 +0000811 struct pipe *pi;
Eric Andersen25f27032001-04-26 23:22:31 +0000812
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000813 if (!interactive_fd)
Eric Andersenc798b072001-06-22 06:23:03 +0000814 return EXIT_FAILURE;
Eric Andersen0fcd4472001-05-02 20:12:03 +0000815 /* If they gave us no args, assume they want the last backgrounded task */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000816 if (!argv[1]) {
Eric Andersenc798b072001-06-22 06:23:03 +0000817 for (pi = job_list; pi; pi = pi->next) {
818 if (pi->jobid == last_jobid) {
Denis Vlasenko8a28e622007-04-14 11:16:29 +0000819 goto found;
Eric Andersen0fcd4472001-05-02 20:12:03 +0000820 }
821 }
Denis Vlasenko1359da62007-04-21 23:27:30 +0000822 bb_error_msg("%s: no current job", argv[0]);
Denis Vlasenko8a28e622007-04-14 11:16:29 +0000823 return EXIT_FAILURE;
824 }
Denis Vlasenko1359da62007-04-21 23:27:30 +0000825 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
826 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
Denis Vlasenko8a28e622007-04-14 11:16:29 +0000827 return EXIT_FAILURE;
828 }
829 for (pi = job_list; pi; pi = pi->next) {
830 if (pi->jobid == jobnum) {
831 goto found;
Eric Andersen25f27032001-04-26 23:22:31 +0000832 }
833 }
Denis Vlasenko1359da62007-04-21 23:27:30 +0000834 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
Denis Vlasenko8a28e622007-04-14 11:16:29 +0000835 return EXIT_FAILURE;
836 found:
Denis Vlasenko52881e92007-04-21 13:42:52 +0000837 // TODO: bash prints a string representation
838 // of job being foregrounded (like "sleep 1 | cat")
Denis Vlasenko1359da62007-04-21 23:27:30 +0000839 if (*argv[0] == 'f') {
Eric Andersen028b65b2001-06-28 01:10:11 +0000840 /* Put the job into the foreground. */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000841 tcsetpgrp(interactive_fd, pi->pgrp);
Eric Andersen25f27032001-04-26 23:22:31 +0000842 }
843
844 /* Restart the processes in the job */
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000845 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_progs, pi->pgrp);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000846 for (i = 0; i < pi->num_progs; i++) {
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000847 debug_printf_jobs("reviving pid %d\n", pi->progs[i].pid);
Eric Andersen0fcd4472001-05-02 20:12:03 +0000848 pi->progs[i].is_stopped = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +0000849 }
850 pi->stopped_progs = 0;
Eric Andersen25f27032001-04-26 23:22:31 +0000851
Denis Vlasenkobb81c582007-01-30 22:32:09 +0000852 i = kill(- pi->pgrp, SIGCONT);
853 if (i < 0) {
Denis Vlasenko8a28e622007-04-14 11:16:29 +0000854 if (errno == ESRCH) {
Denis Vlasenko1359da62007-04-21 23:27:30 +0000855 delete_finished_bg_job(pi);
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000856 return EXIT_SUCCESS;
Eric Andersen028b65b2001-06-28 01:10:11 +0000857 } else {
Manuel Novoa III cad53642003-03-19 09:13:01 +0000858 bb_perror_msg("kill (SIGCONT)");
Eric Andersen028b65b2001-06-28 01:10:11 +0000859 }
860 }
Eric Andersen25f27032001-04-26 23:22:31 +0000861
Denis Vlasenko1359da62007-04-21 23:27:30 +0000862 if (*argv[0] == 'f') {
863 remove_bg_job(pi);
Denis Vlasenko52881e92007-04-21 13:42:52 +0000864 return checkjobs_and_fg_shell(pi);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000865 }
Eric Andersen25f27032001-04-26 23:22:31 +0000866 return EXIT_SUCCESS;
867}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000868#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000869
870/* built-in 'help' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000871static int builtin_help(char **argv ATTRIBUTE_UNUSED)
Eric Andersen25f27032001-04-26 23:22:31 +0000872{
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +0000873 const struct built_in_command *x;
Eric Andersen25f27032001-04-26 23:22:31 +0000874
875 printf("\nBuilt-in commands:\n");
876 printf("-------------------\n");
877 for (x = bltins; x->cmd; x++) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000878 if (x->descr == NULL)
Eric Andersen25f27032001-04-26 23:22:31 +0000879 continue;
880 printf("%s\t%s\n", x->cmd, x->descr);
881 }
882 printf("\n\n");
883 return EXIT_SUCCESS;
884}
885
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000886#if ENABLE_HUSH_JOB
Eric Andersen25f27032001-04-26 23:22:31 +0000887/* built-in 'jobs' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000888static int builtin_jobs(char **argv ATTRIBUTE_UNUSED)
Eric Andersen25f27032001-04-26 23:22:31 +0000889{
890 struct pipe *job;
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000891 const char *status_string;
Eric Andersen25f27032001-04-26 23:22:31 +0000892
Eric Andersenc798b072001-06-22 06:23:03 +0000893 for (job = job_list; job; job = job->next) {
Eric Andersen25f27032001-04-26 23:22:31 +0000894 if (job->running_progs == job->stopped_progs)
895 status_string = "Stopped";
896 else
897 status_string = "Running";
Eric Andersen52a97ca2001-06-22 06:49:26 +0000898
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000899 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
Eric Andersen25f27032001-04-26 23:22:31 +0000900 }
901 return EXIT_SUCCESS;
902}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000903#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000904
Eric Andersen25f27032001-04-26 23:22:31 +0000905/* built-in 'pwd' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000906static int builtin_pwd(char **argv ATTRIBUTE_UNUSED)
Eric Andersen25f27032001-04-26 23:22:31 +0000907{
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000908 puts(set_cwd());
Eric Andersen25f27032001-04-26 23:22:31 +0000909 return EXIT_SUCCESS;
910}
911
912/* built-in 'read VAR' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000913static int builtin_read(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000914{
Denis Vlasenko3e7b0e62007-05-16 12:52:15 +0000915 char string[BUFSIZ];
916 char *p;
917 const char *name = argv[1] ? argv[1] : "REPLY";
918 int name_len = strlen(name);
Eric Andersen25f27032001-04-26 23:22:31 +0000919
Denis Vlasenko3e7b0e62007-05-16 12:52:15 +0000920 if (name_len >= sizeof(string) - 2)
921 return EXIT_FAILURE;
922 strcpy(string, name);
923 p = string + name_len;
924 *p++ = '=';
925 *p = '\0'; /* In case stdin has only EOF */
926 /* read string. name_len+1 chars are already used by 'name=' */
927 fgets(p, sizeof(string) - 1 - name_len, stdin);
928 chomp(p);
929 return set_local_var(string, 0);
Eric Andersen25f27032001-04-26 23:22:31 +0000930}
931
Denis Vlasenko3e7b0e62007-05-16 12:52:15 +0000932/* built-in 'set [VAR=value]' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000933static int builtin_set(char **argv)
Eric Andersenf72f5622001-05-15 23:21:41 +0000934{
Denis Vlasenko1359da62007-04-21 23:27:30 +0000935 char *temp = argv[1];
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000936 struct variables *e;
Eric Andersenf72f5622001-05-15 23:21:41 +0000937
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000938 if (temp == NULL)
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000939 for (e = top_vars; e; e = e->next)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000940 printf("%s=%s\n", e->name, e->value);
941 else
942 set_local_var(temp, 0);
943
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000944 return EXIT_SUCCESS;
Eric Andersenf72f5622001-05-15 23:21:41 +0000945}
946
947
Eric Andersen25f27032001-04-26 23:22:31 +0000948/* Built-in 'shift' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000949static int builtin_shift(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000950{
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000951 int n = 1;
Denis Vlasenko1359da62007-04-21 23:27:30 +0000952 if (argv[1]) {
953 n = atoi(argv[1]);
Eric Andersen25f27032001-04-26 23:22:31 +0000954 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000955 if (n >= 0 && n < global_argc) {
Denis Vlasenko004baba2007-05-20 22:22:18 +0000956 global_argv[n] = global_argv[0];
Eric Andersen25f27032001-04-26 23:22:31 +0000957 global_argc -= n;
958 global_argv += n;
959 return EXIT_SUCCESS;
Eric Andersen25f27032001-04-26 23:22:31 +0000960 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +0000961 return EXIT_FAILURE;
Eric Andersen25f27032001-04-26 23:22:31 +0000962}
963
964/* Built-in '.' handler (read-in and execute commands from file) */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000965static int builtin_source(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000966{
967 FILE *input;
968 int status;
969
Denis Vlasenko1359da62007-04-21 23:27:30 +0000970 if (argv[1] == NULL)
Eric Andersen25f27032001-04-26 23:22:31 +0000971 return EXIT_FAILURE;
972
973 /* XXX search through $PATH is missing */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000974 input = fopen(argv[1], "r");
Eric Andersen25f27032001-04-26 23:22:31 +0000975 if (!input) {
Denis Vlasenko1359da62007-04-21 23:27:30 +0000976 bb_error_msg("cannot open '%s'", argv[1]);
Eric Andersen25f27032001-04-26 23:22:31 +0000977 return EXIT_FAILURE;
978 }
979
980 /* Now run the file */
981 /* XXX argv and argc are broken; need to save old global_argv
982 * (pointer only is OK!) on this stack frame,
Denis Vlasenko1359da62007-04-21 23:27:30 +0000983 * set global_argv=argv+1, recurse, and restore. */
Eric Andersen25f27032001-04-26 23:22:31 +0000984 mark_open(fileno(input));
985 status = parse_file_outer(input);
986 mark_closed(fileno(input));
987 fclose(input);
Denis Vlasenkod9e15f22006-11-27 16:49:55 +0000988 return status;
Eric Andersen25f27032001-04-26 23:22:31 +0000989}
990
Denis Vlasenko1359da62007-04-21 23:27:30 +0000991static int builtin_umask(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000992{
Eric Andersen83a2ae22001-05-07 17:59:25 +0000993 mode_t new_umask;
Denis Vlasenko1359da62007-04-21 23:27:30 +0000994 const char *arg = argv[1];
Eric Andersen83a2ae22001-05-07 17:59:25 +0000995 char *end;
996 if (arg) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000997 new_umask = strtoul(arg, &end, 8);
998 if (*end != '\0' || end == arg) {
Eric Andersen83a2ae22001-05-07 17:59:25 +0000999 return EXIT_FAILURE;
1000 }
1001 } else {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001002 new_umask = umask(0);
1003 printf("%.3o\n", (unsigned) new_umask);
Eric Andersen83a2ae22001-05-07 17:59:25 +00001004 }
1005 umask(new_umask);
1006 return EXIT_SUCCESS;
Eric Andersen25f27032001-04-26 23:22:31 +00001007}
1008
1009/* built-in 'unset VAR' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001010static int builtin_unset(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00001011{
Denis Vlasenko3e7b0e62007-05-16 12:52:15 +00001012 /* bash always returns true */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001013 unset_local_var(argv[1]);
Eric Andersen25f27032001-04-26 23:22:31 +00001014 return EXIT_SUCCESS;
1015}
1016
Denis Vlasenko1359da62007-04-21 23:27:30 +00001017static int builtin_not_written(char **argv)
Eric Andersen83a2ae22001-05-07 17:59:25 +00001018{
Denis Vlasenko1359da62007-04-21 23:27:30 +00001019 printf("builtin_%s not written\n", argv[0]);
Eric Andersen83a2ae22001-05-07 17:59:25 +00001020 return EXIT_FAILURE;
1021}
1022
Eric Andersen25f27032001-04-26 23:22:31 +00001023static int b_check_space(o_string *o, int len)
1024{
1025 /* It would be easy to drop a more restrictive policy
1026 * in here, such as setting a maximum string length */
1027 if (o->length + len > o->maxlen) {
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001028 /* assert(data == NULL || o->maxlen != 0); */
Denis Vlasenkoef36ead2007-05-02 15:34:47 +00001029 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001030 o->data = xrealloc(o->data, 1 + o->maxlen);
Eric Andersen25f27032001-04-26 23:22:31 +00001031 }
1032 return o->data == NULL;
1033}
1034
1035static int b_addchr(o_string *o, int ch)
1036{
Denis Vlasenko831dcc42007-05-16 15:05:36 +00001037 debug_printf("b_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001038 if (b_check_space(o, 1))
1039 return B_NOSPAC;
Eric Andersen25f27032001-04-26 23:22:31 +00001040 o->data[o->length] = ch;
1041 o->length++;
1042 o->data[o->length] = '\0';
1043 return 0;
1044}
1045
1046static void b_reset(o_string *o)
1047{
1048 o->length = 0;
1049 o->nonnull = 0;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001050 if (o->data != NULL)
1051 *o->data = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001052}
1053
1054static void b_free(o_string *o)
1055{
1056 b_reset(o);
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00001057 free(o->data);
Eric Andersen25f27032001-04-26 23:22:31 +00001058 o->data = NULL;
1059 o->maxlen = 0;
1060}
1061
1062/* My analysis of quoting semantics tells me that state information
1063 * is associated with a destination, not a source.
1064 */
1065static int b_addqchr(o_string *o, int ch, int quote)
1066{
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00001067 if (quote && strchr("*?[\\", ch)) {
Eric Andersen25f27032001-04-26 23:22:31 +00001068 int rc;
1069 rc = b_addchr(o, '\\');
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001070 if (rc)
1071 return rc;
Eric Andersen25f27032001-04-26 23:22:31 +00001072 }
1073 return b_addchr(o, ch);
1074}
1075
Eric Andersen25f27032001-04-26 23:22:31 +00001076static int static_get(struct in_str *i)
1077{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001078 int ch = *i->p++;
1079 if (ch == '\0') return EOF;
Eric Andersen25f27032001-04-26 23:22:31 +00001080 return ch;
1081}
1082
1083static int static_peek(struct in_str *i)
1084{
1085 return *i->p;
1086}
1087
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001088#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001089#if ENABLE_FEATURE_EDITING
Rob Landley88621d72006-08-29 19:41:06 +00001090static void cmdedit_set_initial_prompt(void)
Eric Andersen25f27032001-04-26 23:22:31 +00001091{
Denis Vlasenko38f63192007-01-22 09:03:07 +00001092#if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
Eric Andersen25f27032001-04-26 23:22:31 +00001093 PS1 = NULL;
1094#else
1095 PS1 = getenv("PS1");
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001096 if (PS1 == NULL)
Eric Andersen25f27032001-04-26 23:22:31 +00001097 PS1 = "\\w \\$ ";
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001098#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001099}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001100#endif /* EDITING */
Eric Andersen25f27032001-04-26 23:22:31 +00001101
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001102static const char* setup_prompt_string(int promptmode)
Eric Andersen25f27032001-04-26 23:22:31 +00001103{
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001104 const char *prompt_str;
1105 debug_printf("setup_prompt_string %d ", promptmode);
Denis Vlasenko38f63192007-01-22 09:03:07 +00001106#if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
Eric Andersen25f27032001-04-26 23:22:31 +00001107 /* Set up the prompt */
1108 if (promptmode == 1) {
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001109 char *ns;
1110 free((char*)PS1);
1111 ns = xmalloc(strlen(cwd)+4);
1112 sprintf(ns, "%s %s", cwd, (geteuid() != 0) ? "$ " : "# ");
1113 prompt_str = ns;
1114 PS1 = ns;
Eric Andersen25f27032001-04-26 23:22:31 +00001115 } else {
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001116 prompt_str = PS2;
Eric Andersen25f27032001-04-26 23:22:31 +00001117 }
1118#else
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001119 prompt_str = (promptmode == 1) ? PS1 : PS2;
Eric Andersenaf44a0e2001-04-27 07:26:12 +00001120#endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001121 debug_printf("result %s\n", prompt_str);
1122 return prompt_str;
Eric Andersen25f27032001-04-26 23:22:31 +00001123}
1124
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001125static void get_user_input(struct in_str *i)
Eric Andersen25f27032001-04-26 23:22:31 +00001126{
Denis Vlasenko0937be52007-04-28 16:47:08 +00001127 int r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001128 const char *prompt_str;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001129
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001130 prompt_str = setup_prompt_string(i->promptmode);
Denis Vlasenko38f63192007-01-22 09:03:07 +00001131#if ENABLE_FEATURE_EDITING
Eric Andersen25f27032001-04-26 23:22:31 +00001132 /*
1133 ** enable command line editing only while a command line
1134 ** is actually being read; otherwise, we'll end up bequeathing
1135 ** atexit() handlers and other unwanted stuff to our
1136 ** child processes (rob@sysgo.de)
1137 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001138 r = read_line_input(prompt_str, user_input_buf, BUFSIZ-1, line_input_state);
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001139 i->eof_flag = (r < 0);
1140 if (i->eof_flag) { /* EOF/error detected */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001141 user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1142 user_input_buf[1] = '\0';
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001143 }
Eric Andersen25f27032001-04-26 23:22:31 +00001144#else
1145 fputs(prompt_str, stdout);
1146 fflush(stdout);
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001147 user_input_buf[0] = r = fgetc(i->file);
1148 /*user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001149 i->eof_flag = (r == EOF);
Eric Andersen25f27032001-04-26 23:22:31 +00001150#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001151 i->p = user_input_buf;
Eric Andersen25f27032001-04-26 23:22:31 +00001152}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001153#endif /* INTERACTIVE */
Eric Andersen25f27032001-04-26 23:22:31 +00001154
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001155/* This is the magic location that prints prompts
Eric Andersen25f27032001-04-26 23:22:31 +00001156 * and gets data back from the user */
1157static int file_get(struct in_str *i)
1158{
1159 int ch;
1160
Eric Andersen25f27032001-04-26 23:22:31 +00001161 /* If there is data waiting, eat it up */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001162 if (i->p && *i->p) {
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001163#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001164 take_cached:
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001165#endif
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001166 ch = *i->p++;
1167 if (i->eof_flag && !*i->p)
1168 ch = EOF;
Eric Andersen25f27032001-04-26 23:22:31 +00001169 } else {
1170 /* need to double check i->file because we might be doing something
1171 * more complicated by now, like sourcing or substituting. */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001172#if ENABLE_HUSH_INTERACTIVE
1173 if (interactive_fd && i->__promptme && i->file == stdin) {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001174 do {
1175 get_user_input(i);
1176 } while (!*i->p); /* need non-empty line */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001177 i->promptmode = 2;
Eric Andersene67c3ce2001-05-02 02:09:36 +00001178 i->__promptme = 0;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001179 goto take_cached;
Eric Andersen25f27032001-04-26 23:22:31 +00001180 }
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001181#endif
1182 ch = fgetc(i->file);
Eric Andersen25f27032001-04-26 23:22:31 +00001183 }
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001184 debug_printf("file_get: got a '%c' %d\n", ch, ch);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001185#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001186 if (ch == '\n')
1187 i->__promptme = 1;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001188#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001189 return ch;
1190}
1191
1192/* All the callers guarantee this routine will never be
1193 * used right after a newline, so prompting is not needed.
1194 */
1195static int file_peek(struct in_str *i)
1196{
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00001197 int ch;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001198 if (i->p && *i->p) {
1199 if (i->eof_flag && !i->p[1])
1200 return EOF;
1201 return *i->p;
Eric Andersen25f27032001-04-26 23:22:31 +00001202 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00001203 ch = fgetc(i->file);
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001204 i->eof_flag = (ch == EOF);
1205 i->peek_buf[0] = ch;
1206 i->peek_buf[1] = '\0';
1207 i->p = i->peek_buf;
1208 debug_printf("file_peek: got a '%c' %d\n", *i->p, *i->p);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00001209 return ch;
Eric Andersen25f27032001-04-26 23:22:31 +00001210}
1211
1212static void setup_file_in_str(struct in_str *i, FILE *f)
1213{
1214 i->peek = file_peek;
1215 i->get = file_get;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001216#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001217 i->__promptme = 1;
1218 i->promptmode = 1;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001219#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001220 i->file = f;
1221 i->p = NULL;
1222}
1223
1224static void setup_string_in_str(struct in_str *i, const char *s)
1225{
1226 i->peek = static_peek;
1227 i->get = static_get;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001228#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenkobb81c582007-01-30 22:32:09 +00001229 i->__promptme = 1;
1230 i->promptmode = 1;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001231#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001232 i->p = s;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001233 i->eof_flag = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00001234}
1235
1236static void mark_open(int fd)
1237{
1238 struct close_me *new = xmalloc(sizeof(struct close_me));
1239 new->fd = fd;
1240 new->next = close_me_head;
1241 close_me_head = new;
1242}
1243
1244static void mark_closed(int fd)
1245{
1246 struct close_me *tmp;
1247 if (close_me_head == NULL || close_me_head->fd != fd)
Manuel Novoa III cad53642003-03-19 09:13:01 +00001248 bb_error_msg_and_die("corrupt close_me");
Eric Andersen25f27032001-04-26 23:22:31 +00001249 tmp = close_me_head;
1250 close_me_head = close_me_head->next;
1251 free(tmp);
1252}
1253
Eric Anderseneaecbf32001-10-31 10:41:31 +00001254static void close_all(void)
Eric Andersen25f27032001-04-26 23:22:31 +00001255{
1256 struct close_me *c;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001257 for (c = close_me_head; c; c = c->next) {
Eric Andersen25f27032001-04-26 23:22:31 +00001258 close(c->fd);
1259 }
1260 close_me_head = NULL;
1261}
1262
1263/* squirrel != NULL means we squirrel away copies of stdin, stdout,
1264 * and stderr if they are redirected. */
1265static int setup_redirects(struct child_prog *prog, int squirrel[])
1266{
1267 int openfd, mode;
1268 struct redir_struct *redir;
1269
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001270 for (redir = prog->redirects; redir; redir = redir->next) {
Eric Andersen817e73c2001-06-06 17:56:09 +00001271 if (redir->dup == -1 && redir->word.gl_pathv == NULL) {
1272 /* something went wrong in the parse. Pretend it didn't happen */
1273 continue;
1274 }
Eric Andersen25f27032001-04-26 23:22:31 +00001275 if (redir->dup == -1) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001276 mode = redir_table[redir->type].mode;
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001277 openfd = open_or_warn(redir->word.gl_pathv[0], mode);
Eric Andersen25f27032001-04-26 23:22:31 +00001278 if (openfd < 0) {
1279 /* this could get lost if stderr has been redirected, but
1280 bash and ash both lose it as well (though zsh doesn't!) */
Eric Andersen25f27032001-04-26 23:22:31 +00001281 return 1;
1282 }
1283 } else {
1284 openfd = redir->dup;
1285 }
1286
1287 if (openfd != redir->fd) {
1288 if (squirrel && redir->fd < 3) {
1289 squirrel[redir->fd] = dup(redir->fd);
1290 }
Eric Andersen83a2ae22001-05-07 17:59:25 +00001291 if (openfd == -3) {
1292 close(openfd);
1293 } else {
1294 dup2(openfd, redir->fd);
Matt Kraaic616e532001-06-05 16:50:08 +00001295 if (redir->dup == -1)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001296 close(openfd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00001297 }
Eric Andersen25f27032001-04-26 23:22:31 +00001298 }
1299 }
1300 return 0;
1301}
1302
1303static void restore_redirects(int squirrel[])
1304{
1305 int i, fd;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001306 for (i = 0; i < 3; i++) {
Eric Andersen25f27032001-04-26 23:22:31 +00001307 fd = squirrel[i];
1308 if (fd != -1) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00001309 /* We simply die on error */
1310 xmove_fd(fd, i);
Eric Andersen25f27032001-04-26 23:22:31 +00001311 }
1312 }
1313}
1314
Eric Andersenada18ff2001-05-21 16:18:22 +00001315/* never returns */
Eric Andersen94ac2442001-05-22 19:05:18 +00001316/* XXX no exit() here. If you don't exec, use _exit instead.
1317 * The at_exit handlers apparently confuse the calling process,
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001318 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001319static void pseudo_exec_argv(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00001320{
Eric Andersen78a7c992001-05-15 16:30:25 +00001321 int i, rcode;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001322 char *p;
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +00001323 const struct built_in_command *x;
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001324
Denis Vlasenko1359da62007-04-21 23:27:30 +00001325 for (i = 0; is_assignment(argv[i]); i++) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001326 debug_printf_exec("pid %d environment modification: %s\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001327 getpid(), argv[i]);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001328// FIXME: vfork case??
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00001329 p = expand_variables_to_string(argv[i]);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00001330 putenv(p == argv[i] ? xstrdup(p) : p);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001331 }
1332 argv += i;
1333 /* If a variable is assigned in a forest, and nobody listens,
1334 * was it ever really set?
1335 */
1336 if (argv[0] == NULL) {
1337 _exit(EXIT_SUCCESS);
1338 }
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001339
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00001340 argv = expand_variables_to_list(argv);
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001341
Denis Vlasenko1359da62007-04-21 23:27:30 +00001342 /*
1343 * Check if the command matches any of the builtins.
1344 * Depending on context, this might be redundant. But it's
1345 * easier to waste a few CPU cycles than it is to figure out
1346 * if this is one of those cases.
1347 */
1348 for (x = bltins; x->cmd; x++) {
1349 if (strcmp(argv[0], x->cmd) == 0) {
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001350 debug_printf_exec("running builtin '%s'\n", argv[0]);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001351 rcode = x->function(argv);
1352 fflush(stdout);
1353 _exit(rcode);
Eric Andersen94ac2442001-05-22 19:05:18 +00001354 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00001355 }
Eric Andersen78a7c992001-05-15 16:30:25 +00001356
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001357 /* Check if the command matches any busybox applets */
Denis Vlasenko80d14be2007-04-10 23:03:30 +00001358#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001359 if (strchr(argv[0], '/') == NULL) {
1360 const struct bb_applet *a = find_applet_by_name(argv[0]);
1361 if (a) {
1362 if (a->noexec) {
1363 current_applet = a;
1364 debug_printf_exec("running applet '%s'\n", argv[0]);
1365// is it ok that run_current_applet_and_exit() does exit(), not _exit()?
1366 run_current_applet_and_exit(argv);
1367 }
1368 /* re-exec ourselves with the new arguments */
1369 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
1370 execvp(CONFIG_BUSYBOX_EXEC_PATH, argv);
1371 /* If they called chroot or otherwise made the binary no longer
1372 * executable, fall through */
1373 }
1374 }
Eric Andersenaac75e52001-04-30 18:18:45 +00001375#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001376
1377 debug_printf_exec("execing '%s'\n", argv[0]);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001378 execvp(argv[0], argv);
1379 bb_perror_msg("cannot exec '%s'", argv[0]);
1380 _exit(1);
1381}
1382
1383static void pseudo_exec(struct child_prog *child)
1384{
Denis Vlasenkof2fffd02007-05-02 23:39:04 +00001385// FIXME: buggy wrt NOMMU! Must not modify any global data
1386// until it does exec/_exit, but currently it does.
Denis Vlasenko1359da62007-04-21 23:27:30 +00001387 int rcode;
1388
1389 if (child->argv) {
1390 pseudo_exec_argv(child->argv);
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001391 }
1392
1393 if (child->group) {
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001394 // FIXME: do not modify globals! Think vfork!
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001395#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001396 debug_printf_exec("pseudo_exec: setting interactive_fd=0\n");
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001397 interactive_fd = 0; /* crucial!!!! */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001398#endif
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001399 debug_printf_exec("pseudo_exec: run_list_real\n");
Eric Andersen25f27032001-04-26 23:22:31 +00001400 rcode = run_list_real(child->group);
Eric Andersenbf7df042001-05-23 22:18:35 +00001401 /* OK to leak memory by not calling free_pipe_list,
Eric Andersen25f27032001-04-26 23:22:31 +00001402 * since this process is about to exit */
Eric Andersen94ac2442001-05-22 19:05:18 +00001403 _exit(rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00001404 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001405
1406 /* Can happen. See what bash does with ">foo" by itself. */
1407 debug_printf("trying to pseudo_exec null command\n");
1408 _exit(EXIT_SUCCESS);
Eric Andersen25f27032001-04-26 23:22:31 +00001409}
1410
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001411#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001412static const char *get_cmdtext(struct pipe *pi)
1413{
1414 char **argv;
1415 char *p;
1416 int len;
1417
1418 /* This is subtle. ->cmdtext is created only on first backgrounding.
1419 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001420 * On subsequent bg argv is trashed, but we won't use it */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001421 if (pi->cmdtext)
1422 return pi->cmdtext;
1423 argv = pi->progs[0].argv;
1424 if (!argv || !argv[0])
1425 return (pi->cmdtext = xzalloc(1));
1426
1427 len = 0;
1428 do len += strlen(*argv) + 1; while (*++argv);
1429 pi->cmdtext = p = xmalloc(len);
1430 argv = pi->progs[0].argv;
1431 do {
1432 len = strlen(*argv);
1433 memcpy(p, *argv, len);
1434 p += len;
1435 *p++ = ' ';
1436 } while (*++argv);
1437 p[-1] = '\0';
1438 return pi->cmdtext;
1439}
1440
Eric Andersenbafd94f2001-05-02 16:11:59 +00001441static void insert_bg_job(struct pipe *pi)
1442{
1443 struct pipe *thejob;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001444 int i;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001445
1446 /* Linear search for the ID of the job to use */
1447 pi->jobid = 1;
Eric Andersenc798b072001-06-22 06:23:03 +00001448 for (thejob = job_list; thejob; thejob = thejob->next)
Eric Andersenbafd94f2001-05-02 16:11:59 +00001449 if (thejob->jobid >= pi->jobid)
1450 pi->jobid = thejob->jobid + 1;
1451
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001452 /* Add thejob to the list of running jobs */
Eric Andersenc798b072001-06-22 06:23:03 +00001453 if (!job_list) {
Eric Andersen52a97ca2001-06-22 06:49:26 +00001454 thejob = job_list = xmalloc(sizeof(*thejob));
Eric Andersenbafd94f2001-05-02 16:11:59 +00001455 } else {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001456 for (thejob = job_list; thejob->next; thejob = thejob->next)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001457 continue;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001458 thejob->next = xmalloc(sizeof(*thejob));
1459 thejob = thejob->next;
1460 }
1461
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001462 /* Physically copy the struct job */
Eric Andersen0fcd4472001-05-02 20:12:03 +00001463 memcpy(thejob, pi, sizeof(struct pipe));
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001464 thejob->progs = xzalloc(sizeof(pi->progs[0]) * pi->num_progs);
1465 /* We cannot copy entire pi->progs[] vector! Double free()s will happen */
1466 for (i = 0; i < pi->num_progs; i++) {
1467// TODO: do we really need to have so many fields which are just dead weight
1468// at execution stage?
1469 thejob->progs[i].pid = pi->progs[i].pid;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001470 /* all other fields are not used and stay zero */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001471 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00001472 thejob->next = NULL;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001473 thejob->cmdtext = xstrdup(get_cmdtext(pi));
Eric Andersenbafd94f2001-05-02 16:11:59 +00001474
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001475 /* We don't wait for background thejobs to return -- append it
Eric Andersenbafd94f2001-05-02 16:11:59 +00001476 to the list of backgrounded thejobs and leave it alone */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001477 printf("[%d] %d %s\n", thejob->jobid, thejob->progs[0].pid, thejob->cmdtext);
Eric Andersen1a6d39b2001-05-08 05:11:54 +00001478 last_bg_pid = thejob->progs[0].pid;
Eric Andersenc798b072001-06-22 06:23:03 +00001479 last_jobid = thejob->jobid;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001480}
1481
Eric Andersenbafd94f2001-05-02 16:11:59 +00001482static void remove_bg_job(struct pipe *pi)
1483{
1484 struct pipe *prev_pipe;
1485
Eric Andersenc798b072001-06-22 06:23:03 +00001486 if (pi == job_list) {
Eric Andersen52a97ca2001-06-22 06:49:26 +00001487 job_list = pi->next;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001488 } else {
Eric Andersenc798b072001-06-22 06:23:03 +00001489 prev_pipe = job_list;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001490 while (prev_pipe->next != pi)
1491 prev_pipe = prev_pipe->next;
1492 prev_pipe->next = pi->next;
1493 }
Eric Andersen028b65b2001-06-28 01:10:11 +00001494 if (job_list)
1495 last_jobid = job_list->jobid;
1496 else
1497 last_jobid = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001498}
Eric Andersen028b65b2001-06-28 01:10:11 +00001499
Denis Vlasenko1359da62007-04-21 23:27:30 +00001500/* remove a backgrounded job */
1501static void delete_finished_bg_job(struct pipe *pi)
1502{
1503 remove_bg_job(pi);
Eric Andersen52a97ca2001-06-22 06:49:26 +00001504 pi->stopped_progs = 0;
Eric Andersenbf7df042001-05-23 22:18:35 +00001505 free_pipe(pi, 0);
Eric Andersenbafd94f2001-05-02 16:11:59 +00001506 free(pi);
1507}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001508#endif /* JOB */
Eric Andersenbafd94f2001-05-02 16:11:59 +00001509
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001510/* Checks to see if any processes have exited -- if they
Eric Andersenbafd94f2001-05-02 16:11:59 +00001511 have, figure out why and see if a job has completed */
Eric Andersenc798b072001-06-22 06:23:03 +00001512static int checkjobs(struct pipe* fg_pipe)
Eric Andersenbafd94f2001-05-02 16:11:59 +00001513{
Eric Andersenc798b072001-06-22 06:23:03 +00001514 int attributes;
1515 int status;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001516#if ENABLE_HUSH_JOB
Eric Andersenbafd94f2001-05-02 16:11:59 +00001517 int prognum = 0;
1518 struct pipe *pi;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001519#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00001520 pid_t childpid;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001521 int rcode = 0;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001522
Eric Andersenc798b072001-06-22 06:23:03 +00001523 attributes = WUNTRACED;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001524 if (fg_pipe == NULL) {
Eric Andersenc798b072001-06-22 06:23:03 +00001525 attributes |= WNOHANG;
1526 }
1527
Denis Vlasenko1359da62007-04-21 23:27:30 +00001528/* Do we do this right?
1529 * bash-3.00# sleep 20 | false
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001530 * <ctrl-Z pressed>
Denis Vlasenko1359da62007-04-21 23:27:30 +00001531 * [3]+ Stopped sleep 20 | false
1532 * bash-3.00# echo $?
1533 * 1 <========== bg pipe is not fully done, but exitcode is already known!
1534 */
1535
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001536//FIXME: non-interactive bash does not continue even if all processes in fg pipe
1537//are stopped. Testcase: "cat | cat" in a script (not on command line)
1538// + killall -STOP cat
1539
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001540 wait_more:
Eric Andersenc798b072001-06-22 06:23:03 +00001541 while ((childpid = waitpid(-1, &status, attributes)) > 0) {
Denis Vlasenko1359da62007-04-21 23:27:30 +00001542 const int dead = WIFEXITED(status) || WIFSIGNALED(status);
1543
1544#ifdef DEBUG_SHELL_JOBS
1545 if (WIFSTOPPED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001546 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001547 childpid, WSTOPSIG(status), WEXITSTATUS(status));
1548 if (WIFSIGNALED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001549 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001550 childpid, WTERMSIG(status), WEXITSTATUS(status));
1551 if (WIFEXITED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001552 debug_printf_jobs("pid %d exited, exitcode %d\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001553 childpid, WEXITSTATUS(status));
1554#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001555 /* Were we asked to wait for fg pipe? */
Eric Andersenc798b072001-06-22 06:23:03 +00001556 if (fg_pipe) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001557 int i;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001558 for (i = 0; i < fg_pipe->num_progs; i++) {
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001559 debug_printf_jobs("check pid %d\n", fg_pipe->progs[i].pid);
Eric Andersenc798b072001-06-22 06:23:03 +00001560 if (fg_pipe->progs[i].pid == childpid) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001561 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001562 if (dead) {
1563 fg_pipe->progs[i].pid = 0;
1564 fg_pipe->running_progs--;
1565 if (i == fg_pipe->num_progs-1)
1566 /* last process gives overall exitstatus */
1567 rcode = WEXITSTATUS(status);
1568 } else {
1569 fg_pipe->progs[i].is_stopped = 1;
1570 fg_pipe->stopped_progs++;
1571 }
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001572 debug_printf_jobs("fg_pipe: running_progs %d stopped_progs %d\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001573 fg_pipe->running_progs, fg_pipe->stopped_progs);
1574 if (fg_pipe->running_progs - fg_pipe->stopped_progs <= 0) {
1575 /* All processes in fg pipe have exited/stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001576#if ENABLE_HUSH_JOB
Denis Vlasenko1359da62007-04-21 23:27:30 +00001577 if (fg_pipe->running_progs)
1578 insert_bg_job(fg_pipe);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001579#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001580 return rcode;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001581 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001582 /* There are still running processes in the fg pipe */
1583 goto wait_more;
Eric Andersenc798b072001-06-22 06:23:03 +00001584 }
1585 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00001586 /* fall through to searching process in bg pipes */
Eric Andersenc798b072001-06-22 06:23:03 +00001587 }
1588
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001589#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001590 /* We asked to wait for bg or orphaned children */
1591 /* No need to remember exitcode in this case */
Eric Andersenc798b072001-06-22 06:23:03 +00001592 for (pi = job_list; pi; pi = pi->next) {
Eric Andersenbafd94f2001-05-02 16:11:59 +00001593 prognum = 0;
Denis Vlasenko5f786c22007-04-20 08:35:45 +00001594 while (prognum < pi->num_progs) {
1595 if (pi->progs[prognum].pid == childpid)
1596 goto found_pi_and_prognum;
Eric Andersen52a97ca2001-06-22 06:49:26 +00001597 prognum++;
1598 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00001599 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001600#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00001601
Denis Vlasenko5f786c22007-04-20 08:35:45 +00001602 /* Happens when shell is used as init process (init=/bin/sh) */
1603 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001604 goto wait_more;
Eric Andersenaeb44c42001-05-22 20:29:00 +00001605
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001606#if ENABLE_HUSH_JOB
Denis Vlasenko5f786c22007-04-20 08:35:45 +00001607 found_pi_and_prognum:
Denis Vlasenko1359da62007-04-21 23:27:30 +00001608 if (dead) {
Eric Andersenbafd94f2001-05-02 16:11:59 +00001609 /* child exited */
Eric Andersenbafd94f2001-05-02 16:11:59 +00001610 pi->progs[prognum].pid = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001611 pi->running_progs--;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001612 if (!pi->running_progs) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001613 printf(JOB_STATUS_FORMAT, pi->jobid,
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001614 "Done", pi->cmdtext);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001615 delete_finished_bg_job(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00001616 }
1617 } else {
1618 /* child stopped */
1619 pi->stopped_progs++;
1620 pi->progs[prognum].is_stopped = 1;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001621 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001622#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00001623 }
1624
Denis Vlasenko1359da62007-04-21 23:27:30 +00001625 /* wait found no children or failed */
1626
1627 if (childpid && errno != ECHILD)
Manuel Novoa III cad53642003-03-19 09:13:01 +00001628 bb_perror_msg("waitpid");
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001629 return rcode;
Eric Andersenada18ff2001-05-21 16:18:22 +00001630}
1631
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001632#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +00001633static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
1634{
1635 pid_t p;
1636 int rcode = checkjobs(fg_pipe);
1637 /* Job finished, move the shell to the foreground */
1638 p = getpgid(0);
1639 debug_printf("fg'ing ourself: getpgid(0)=%d\n", (int)p);
1640 if (tcsetpgrp(interactive_fd, p) && errno != ENOTTY)
1641 bb_perror_msg("tcsetpgrp-4a");
1642 return rcode;
1643}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001644#endif
Denis Vlasenko52881e92007-04-21 13:42:52 +00001645
Eric Andersen25f27032001-04-26 23:22:31 +00001646/* run_pipe_real() starts all the jobs, but doesn't wait for anything
Eric Andersenc798b072001-06-22 06:23:03 +00001647 * to finish. See checkjobs().
Eric Andersen25f27032001-04-26 23:22:31 +00001648 *
1649 * return code is normally -1, when the caller has to wait for children
1650 * to finish to determine the exit status of the pipe. If the pipe
1651 * is a simple builtin command, however, the action is done by the
1652 * time run_pipe_real returns, and the exit code is provided as the
1653 * return value.
1654 *
1655 * The input of the pipe is always stdin, the output is always
1656 * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
1657 * because it tries to avoid running the command substitution in
1658 * subshell, when that is in fact necessary. The subshell process
1659 * now has its stdout directed to the input of the appropriate pipe,
1660 * so this routine is noticeably simpler.
1661 */
1662static int run_pipe_real(struct pipe *pi)
1663{
1664 int i;
1665 int nextin, nextout;
1666 int pipefds[2]; /* pipefds[0] is for reading */
Rob Landley53702e52006-07-19 21:43:53 +00001667 struct child_prog *child;
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +00001668 const struct built_in_command *x;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001669 char *p;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001670 /* it is not always needed, but we aim to smaller code */
1671 int squirrel[] = { -1, -1, -1 };
1672 int rcode;
Denis Vlasenko52881e92007-04-21 13:42:52 +00001673 const int single_fg = (pi->num_progs == 1 && pi->followup != PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00001674
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001675 debug_printf_exec("run_pipe_real start: single_fg=%d\n", single_fg);
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00001676
Eric Andersen25f27032001-04-26 23:22:31 +00001677 nextin = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001678#if ENABLE_HUSH_JOB
Eric Andersenada18ff2001-05-21 16:18:22 +00001679 pi->pgrp = -1;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001680#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001681 pi->running_progs = 1;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001682 pi->stopped_progs = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00001683
1684 /* Check if this is a simple builtin (not part of a pipe).
1685 * Builtins within pipes have to fork anyway, and are handled in
1686 * pseudo_exec. "echo foo | read bar" doesn't work on bash, either.
1687 */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001688 child = &(pi->progs[0]);
Denis Vlasenko52881e92007-04-21 13:42:52 +00001689 if (single_fg && child->group && child->subshell == 0) {
Eric Andersen04407e52001-06-07 16:42:05 +00001690 debug_printf("non-subshell grouping\n");
1691 setup_redirects(child, squirrel);
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001692 debug_printf_exec(": run_list_real\n");
Eric Andersen04407e52001-06-07 16:42:05 +00001693 rcode = run_list_real(child->group);
1694 restore_redirects(squirrel);
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001695 debug_printf_exec("run_pipe_real return %d\n", rcode);
Eric Andersen04407e52001-06-07 16:42:05 +00001696 return rcode;
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001697 }
1698
Denis Vlasenko1359da62007-04-21 23:27:30 +00001699 if (single_fg && child->argv != NULL) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001700 char **argv_expanded;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001701 char **argv = child->argv;
1702
1703 for (i = 0; is_assignment(argv[i]); i++)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001704 continue;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001705 if (i != 0 && argv[i] == NULL) {
Eric Andersen78a7c992001-05-15 16:30:25 +00001706 /* assignments, but no command: set the local environment */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001707 for (i = 0; argv[i] != NULL; i++) {
Eric Andersen99785762001-05-22 21:37:48 +00001708 /* Ok, this case is tricky. We have to decide if this is a
1709 * local variable, or an already exported variable. If it is
1710 * already exported, we have to export the new value. If it is
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001711 * not exported, we need only set this as a local variable.
Eric Andersen99785762001-05-22 21:37:48 +00001712 * This junk is all to decide whether or not to export this
1713 * variable. */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001714 int export_me = 0;
Eric Andersen99785762001-05-22 21:37:48 +00001715 char *name, *value;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001716 name = xstrdup(argv[i]);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00001717 debug_printf("local environment set: %s\n", name);
Eric Andersen99785762001-05-22 21:37:48 +00001718 value = strchr(name, '=');
1719 if (value)
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00001720 *value = '\0';
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001721 if (get_local_var(name)) {
1722 export_me = 1;
Eric Andersen99785762001-05-22 21:37:48 +00001723 }
1724 free(name);
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00001725 p = expand_variables_to_string(argv[i]);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001726 set_local_var(p, export_me);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001727 if (p != argv[i])
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001728 free(p);
Eric Andersen78a7c992001-05-15 16:30:25 +00001729 }
1730 return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
1731 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00001732 for (i = 0; is_assignment(argv[i]); i++) {
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00001733 p = expand_variables_to_string(argv[i]);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001734 if (p != argv[i]) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001735 //sp: child->sp--;
Denis Vlasenko602d13c2007-05-13 18:34:53 +00001736 putenv(p);
1737 } else {
1738 putenv(xstrdup(p));
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001739 }
1740 }
Eric Andersen25f27032001-04-26 23:22:31 +00001741 for (x = bltins; x->cmd; x++) {
Denis Vlasenko1359da62007-04-21 23:27:30 +00001742 if (strcmp(argv[i], x->cmd) == 0) {
1743 if (x->function == builtin_exec && argv[i+1] == NULL) {
Eric Andersen83a2ae22001-05-07 17:59:25 +00001744 debug_printf("magic exec\n");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001745 setup_redirects(child, NULL);
Eric Andersen83a2ae22001-05-07 17:59:25 +00001746 return EXIT_SUCCESS;
1747 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00001748 debug_printf("builtin inline %s\n", argv[0]);
Eric Andersen25f27032001-04-26 23:22:31 +00001749 /* XXX setup_redirects acts on file descriptors, not FILEs.
1750 * This is perfect for work that comes after exec().
1751 * Is it really safe for inline use? Experimentally,
1752 * things seem to work with glibc. */
1753 setup_redirects(child, squirrel);
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001754 debug_printf_exec(": builtin '%s' '%s'...\n", x->cmd, argv[i+1]);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001755 //sp: if (child->sp) /* btw we can do it unconditionally... */
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00001756 argv_expanded = expand_variables_to_list(argv + i);
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001757 rcode = x->function(argv_expanded);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001758 free(argv_expanded);
Eric Andersen25f27032001-04-26 23:22:31 +00001759 restore_redirects(squirrel);
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001760 debug_printf_exec("run_pipe_real return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00001761 return rcode;
1762 }
1763 }
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001764#if ENABLE_FEATURE_SH_STANDALONE
1765 {
Denis Vlasenko1359da62007-04-21 23:27:30 +00001766 const struct bb_applet *a = find_applet_by_name(argv[i]);
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001767 if (a && a->nofork) {
1768 setup_redirects(child, squirrel);
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001769 save_nofork_data(&nofork_save);
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001770 argv_expanded = argv + i;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001771 //sp: if (child->sp)
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00001772 argv_expanded = expand_variables_to_list(argv + i);
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001773 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n", argv_expanded[0], argv_expanded[1]);
1774 rcode = run_nofork_applet_prime(&nofork_save, a, argv_expanded);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001775 free(argv_expanded);
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001776 restore_redirects(squirrel);
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001777 debug_printf_exec("run_pipe_real return %d\n", rcode);
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001778 return rcode;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001779 }
1780 }
1781#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001782 }
1783
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001784 /* Going to fork a child per each pipe member */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001785 pi->running_progs = 0;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001786
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001787 /* Disable job control signals for shell (parent) and
1788 * for initial child code after fork */
1789 set_jobctrl_sighandler(SIG_IGN);
1790
Eric Andersen25f27032001-04-26 23:22:31 +00001791 for (i = 0; i < pi->num_progs; i++) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001792 child = &(pi->progs[i]);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001793 if (child->argv)
1794 debug_printf_exec(": pipe member '%s' '%s'...\n", child->argv[0], child->argv[1]);
1795 else
1796 debug_printf_exec(": pipe member with no argv\n");
Eric Andersen25f27032001-04-26 23:22:31 +00001797
1798 /* pipes are inserted between pairs of commands */
1799 if ((i + 1) < pi->num_progs) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001800 if (pipe(pipefds) < 0)
1801 bb_perror_msg_and_die("pipe");
Eric Andersen25f27032001-04-26 23:22:31 +00001802 nextout = pipefds[1];
1803 } else {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001804 nextout = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00001805 pipefds[0] = -1;
1806 }
1807
1808 /* XXX test for failed fork()? */
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001809#if BB_MMU
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001810 child->pid = fork();
Eric Andersen72f9a422001-10-28 05:12:20 +00001811#else
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001812 child->pid = vfork();
Eric Andersen72f9a422001-10-28 05:12:20 +00001813#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001814 if (!child->pid) { /* child */
1815 /* Every child adds itself to new process group
1816 * with pgid == pid of first child in pipe */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001817#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001818 if (interactive_fd) {
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001819 /* Don't do pgrp restore anymore on fatal signals */
1820 set_fatal_sighandler(SIG_DFL);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001821 if (pi->pgrp < 0) /* true for 1st process only */
1822 pi->pgrp = getpid();
1823 if (setpgid(0, pi->pgrp) == 0 && pi->followup != PIPE_BG) {
1824 /* We do it in *every* child, not just first,
1825 * to avoid races */
1826 tcsetpgrp(interactive_fd, pi->pgrp);
1827 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001828 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001829#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001830 /* in non-interactive case fatal sigs are already SIG_DFL */
Eric Andersen25f27032001-04-26 23:22:31 +00001831 close_all();
Eric Andersen25f27032001-04-26 23:22:31 +00001832 if (nextin != 0) {
1833 dup2(nextin, 0);
1834 close(nextin);
1835 }
1836 if (nextout != 1) {
1837 dup2(nextout, 1);
1838 close(nextout);
1839 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00001840 if (pipefds[0] != -1) {
Eric Andersen25f27032001-04-26 23:22:31 +00001841 close(pipefds[0]); /* opposite end of our output pipe */
1842 }
Eric Andersen25f27032001-04-26 23:22:31 +00001843 /* Like bash, explicit redirects override pipes,
1844 * and the pipe fd is available for dup'ing. */
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001845 setup_redirects(child, NULL);
Eric Andersen52a97ca2001-06-22 06:49:26 +00001846
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001847 /* Restore default handlers just prior to exec */
1848 set_jobctrl_sighandler(SIG_DFL);
1849 set_misc_sighandler(SIG_DFL);
1850 signal(SIGCHLD, SIG_DFL);
Eric Andersen25f27032001-04-26 23:22:31 +00001851 pseudo_exec(child);
1852 }
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001853
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001854 pi->running_progs++;
1855
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001856#if ENABLE_HUSH_JOB
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00001857 /* Second and next children need to know pid of first one */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001858 if (pi->pgrp < 0)
Eric Andersen0fcd4472001-05-02 20:12:03 +00001859 pi->pgrp = child->pid;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001860#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001861 if (nextin != 0)
1862 close(nextin);
1863 if (nextout != 1)
1864 close(nextout);
1865
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001866 /* If there isn't another process, nextin is garbage
Eric Andersen25f27032001-04-26 23:22:31 +00001867 but it doesn't matter */
1868 nextin = pipefds[0];
1869 }
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001870 debug_printf_exec("run_pipe_real return -1\n");
Eric Andersen25f27032001-04-26 23:22:31 +00001871 return -1;
1872}
1873
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001874#ifndef debug_print_tree
1875static void debug_print_tree(struct pipe *pi, int lvl)
1876{
1877 static const char *PIPE[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001878 [PIPE_SEQ] = "SEQ",
1879 [PIPE_AND] = "AND",
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001880 [PIPE_OR ] = "OR" ,
1881 [PIPE_BG ] = "BG" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001882 };
1883 static const char *RES[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001884 [RES_NONE ] = "NONE" ,
1885 [RES_IF ] = "IF" ,
1886 [RES_THEN ] = "THEN" ,
1887 [RES_ELIF ] = "ELIF" ,
1888 [RES_ELSE ] = "ELSE" ,
1889 [RES_FI ] = "FI" ,
1890 [RES_FOR ] = "FOR" ,
1891 [RES_WHILE] = "WHILE",
1892 [RES_UNTIL] = "UNTIL",
1893 [RES_DO ] = "DO" ,
1894 [RES_DONE ] = "DONE" ,
1895 [RES_XXXX ] = "XXXX" ,
1896 [RES_IN ] = "IN" ,
1897 [RES_SNTX ] = "SNTX" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001898 };
1899
1900 int pin, prn;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00001901
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001902 pin = 0;
1903 while (pi) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00001904 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
1905 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001906 prn = 0;
1907 while (prn < pi->num_progs) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00001908 struct child_prog *child = &pi->progs[prn];
1909 char **argv = child->argv;
1910
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001911 fprintf(stderr, "%*s prog %d", lvl*2, "", prn);
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00001912 if (child->group) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001913 fprintf(stderr, " group %s: (argv=%p)\n",
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00001914 (child->subshell ? "()" : "{}"),
1915 argv);
1916 debug_print_tree(child->group, lvl+1);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001917 prn++;
1918 continue;
1919 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001920 if (argv) while (*argv) {
1921 fprintf(stderr, " '%s'", *argv);
1922 argv++;
1923 }
1924 fprintf(stderr, "\n");
1925 prn++;
1926 }
1927 pi = pi->next;
1928 pin++;
1929 }
1930}
1931#endif
1932
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001933/* NB: called by pseudo_exec, and therefore must not modify any
1934 * global data until exec/_exit (we can be a child after vfork!) */
Eric Andersen25f27032001-04-26 23:22:31 +00001935static int run_list_real(struct pipe *pi)
1936{
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00001937 char *for_varname = NULL;
1938 char **for_lcur = NULL;
1939 char **for_list = NULL;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001940 struct pipe *rpipe;
1941 int flag_rep = 0;
1942 int save_num_progs;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001943 int flag_skip = 1;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00001944 int rcode = 0; /* probably for gcc only */
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001945 int flag_restore = 0;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001946 int if_code = 0, next_if_code = 0; /* need double-buffer to handle elif */
Denis Vlasenko219e88d2007-05-21 10:18:23 +00001947 reserved_style rword;
1948 reserved_style skip_more_for_this_rword = RES_XXXX;
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00001949
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001950 debug_printf_exec("run_list_real start lvl %d\n", run_list_level + 1);
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00001951
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001952 /* check syntax for "for" */
1953 for (rpipe = pi; rpipe; rpipe = rpipe->next) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00001954 if ((rpipe->res_word == RES_IN || rpipe->res_word == RES_FOR)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001955 && (rpipe->next == NULL)
1956 ) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001957 syntax(); /* unterminated FOR (no IN or no commands after IN) */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001958 debug_printf_exec("run_list_real lvl %d return 1\n", run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001959 return 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001960 }
Denis Vlasenko219e88d2007-05-21 10:18:23 +00001961 if ((rpipe->res_word == RES_IN && rpipe->next->res_word == RES_IN && rpipe->next->progs[0].argv != NULL)
1962 || (rpipe->res_word == RES_FOR && rpipe->next->res_word != RES_IN)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001963 ) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001964 /* TODO: what is tested in the first condition? */
1965 syntax(); /* 2nd: malformed FOR (not followed by IN) */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001966 debug_printf_exec("run_list_real lvl %d return 1\n", run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001967 return 1;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001968 }
1969 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001970
1971#if ENABLE_HUSH_JOB
1972 /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
1973 * We are saving state before entering outermost list ("while...done")
1974 * so that ctrl-Z will correctly background _entire_ outermost list,
1975 * not just a part of it (like "sleep 1 | exit 2") */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001976 if (++run_list_level == 1 && interactive_fd) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001977 if (sigsetjmp(toplevel_jb, 1)) {
1978 /* ctrl-Z forked and we are parent; or ctrl-C.
1979 * Sighandler has longjmped us here */
1980 signal(SIGINT, SIG_IGN);
1981 signal(SIGTSTP, SIG_IGN);
1982 /* Restore level (we can be coming from deep inside
1983 * nested levels) */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001984 run_list_level = 1;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001985#if ENABLE_FEATURE_SH_STANDALONE
1986 if (nofork_save.saved) { /* if save area is valid */
1987 debug_printf_jobs("exiting nofork early\n");
1988 restore_nofork_data(&nofork_save);
1989 }
1990#endif
1991 if (ctrl_z_flag) {
1992 /* ctrl-Z has forked and stored pid of the child in pi->pid.
1993 * Remember this child as background job */
1994 insert_bg_job(pi);
1995 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001996 /* ctrl-C. We just stop doing whatever we were doing */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001997 putchar('\n');
1998 }
1999 rcode = 0;
2000 goto ret;
2001 }
2002 /* ctrl-Z handler will store pid etc in pi */
2003 toplevel_list = pi;
2004 ctrl_z_flag = 0;
2005#if ENABLE_FEATURE_SH_STANDALONE
2006 nofork_save.saved = 0; /* in case we will run a nofork later */
2007#endif
2008 signal_SA_RESTART(SIGTSTP, handler_ctrl_z);
2009 signal(SIGINT, handler_ctrl_c);
2010 }
2011#endif
2012
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002013 for (; pi; pi = flag_restore ? rpipe : pi->next) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002014 rword = pi->res_word;
2015 if (rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002016 flag_restore = 0;
2017 if (!rpipe) {
2018 flag_rep = 0;
2019 rpipe = pi;
2020 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002021 }
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002022 debug_printf_exec(": rword=%d if_code=%d next_if_code=%d skip_more=%d\n",
2023 rword, if_code, next_if_code, skip_more_for_this_rword);
2024 if (rword == skip_more_for_this_rword && flag_skip) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002025 if (pi->followup == PIPE_SEQ)
2026 flag_skip = 0;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002027 continue;
2028 }
2029 flag_skip = 1;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002030 skip_more_for_this_rword = RES_XXXX;
2031 if (rword == RES_THEN || rword == RES_ELSE)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002032 if_code = next_if_code;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002033 if (rword == RES_THEN && if_code)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002034 continue;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002035 if (rword == RES_ELSE && !if_code)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002036 continue;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002037 if (rword == RES_ELIF && !if_code)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002038 break;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002039 if (rword == RES_FOR && pi->num_progs) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002040 if (!for_lcur) {
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002041 /* if no variable values after "in" we skip "for" */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002042 if (!pi->next->progs->argv)
2043 continue;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002044 /* create list of variable values */
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002045 for_list = expand_variables_to_list(pi->next->progs->argv);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002046 for_lcur = for_list;
2047 for_varname = pi->progs->argv[0];
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002048 pi->progs->argv[0] = NULL;
2049 flag_rep = 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002050 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002051 free(pi->progs->argv[0]);
2052 if (!*for_lcur) {
2053 free(for_list);
2054 for_lcur = NULL;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002055 flag_rep = 0;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002056 pi->progs->argv[0] = for_varname;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002057 pi->progs->glob_result.gl_pathv[0] = pi->progs->argv[0];
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002058 continue;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002059 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002060 /* insert next value from for_lcur */
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002061 /* vda: does it need escaping? */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002062 pi->progs->argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002063 pi->progs->glob_result.gl_pathv[0] = pi->progs->argv[0];
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002064 }
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002065 if (rword == RES_IN)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002066 continue;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002067 if (rword == RES_DO) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002068 if (!flag_rep)
2069 continue;
Tim Rikerc1ef7bd2006-01-25 00:08:53 +00002070 }
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002071 if (rword == RES_DONE) {
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002072 if (flag_rep) {
2073 flag_restore = 1;
2074 } else {
2075 rpipe = NULL;
2076 }
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002077 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002078 if (pi->num_progs == 0)
2079 continue;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002080 save_num_progs = pi->num_progs; /* save number of programs */
Denis Vlasenkod01ff132007-05-02 21:40:23 +00002081 debug_printf_exec(": run_pipe_real with %d members\n", pi->num_progs);
Eric Andersen25f27032001-04-26 23:22:31 +00002082 rcode = run_pipe_real(pi);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002083 if (rcode != -1) {
Eric Andersen25f27032001-04-26 23:22:31 +00002084 /* We only ran a builtin: rcode was set by the return value
2085 * of run_pipe_real(), and we don't need to wait for anything. */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002086 } else if (pi->followup == PIPE_BG) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002087 /* What does bash do with attempts to background builtins? */
2088
2089 /* Even bash 3.2 doesn't do that well with nested bg:
2090 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
2091 * I'm considering NOT treating inner bgs as jobs -
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00002092 * thus maybe "if (run_list_level == 1 && pi->followup == PIPE_BG)"
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002093 * above? */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002094#if ENABLE_HUSH_JOB
Eric Andersenbafd94f2001-05-02 16:11:59 +00002095 insert_bg_job(pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002096#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002097 rcode = EXIT_SUCCESS;
2098 } else {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002099#if ENABLE_HUSH_JOB
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002100 /* Paranoia, just "interactive_fd" should be enough */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00002101 if (run_list_level == 1 && interactive_fd) {
Denis Vlasenko52881e92007-04-21 13:42:52 +00002102 rcode = checkjobs_and_fg_shell(pi);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002103 } else
2104#endif
2105 {
Eric Andersenc798b072001-06-22 06:23:03 +00002106 rcode = checkjobs(pi);
Eric Andersen25f27032001-04-26 23:22:31 +00002107 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002108 debug_printf_exec(": checkjobs returned %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00002109 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002110 debug_printf_exec(": setting last_return_code=%d\n", rcode);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002111 last_return_code = rcode;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002112 pi->num_progs = save_num_progs; /* restore number of programs */
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002113 if (rword == RES_IF || rword == RES_ELIF)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002114 next_if_code = rcode; /* can be overwritten a number of times */
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002115 if (rword == RES_WHILE)
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002116 flag_rep = !last_return_code;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002117 if (rword == RES_UNTIL)
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002118 flag_rep = last_return_code;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002119 if ((rcode == EXIT_SUCCESS && pi->followup == PIPE_OR)
2120 || (rcode != EXIT_SUCCESS && pi->followup == PIPE_AND)
2121 ) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002122 skip_more_for_this_rword = rword;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002123 }
Eric Andersen028b65b2001-06-28 01:10:11 +00002124 checkjobs(NULL);
Eric Andersen25f27032001-04-26 23:22:31 +00002125 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002126
2127#if ENABLE_HUSH_JOB
2128 if (ctrl_z_flag) {
2129 /* ctrl-Z forked somewhere in the past, we are the child,
2130 * and now we completed running the list. Exit. */
2131 exit(rcode);
2132 }
2133 ret:
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00002134 run_list_level--;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002135#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00002136 debug_printf_exec("run_list_real lvl %d return %d\n", run_list_level + 1, rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00002137 return rcode;
2138}
2139
Eric Andersen25f27032001-04-26 23:22:31 +00002140/* return code is the exit status of the pipe */
Eric Andersenbf7df042001-05-23 22:18:35 +00002141static int free_pipe(struct pipe *pi, int indent)
Eric Andersen25f27032001-04-26 23:22:31 +00002142{
2143 char **p;
2144 struct child_prog *child;
2145 struct redir_struct *r, *rnext;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002146 int a, i, ret_code = 0;
Eric Andersen52a97ca2001-06-22 06:49:26 +00002147
2148 if (pi->stopped_progs > 0)
2149 return ret_code;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002150 debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002151 for (i = 0; i < pi->num_progs; i++) {
Eric Andersen25f27032001-04-26 23:22:31 +00002152 child = &pi->progs[i];
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002153 debug_printf_clean("%s command %d:\n", indenter(indent), i);
Eric Andersen25f27032001-04-26 23:22:31 +00002154 if (child->argv) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002155 for (a = 0, p = child->argv; *p; a++, p++) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002156 debug_printf_clean("%s argv[%d] = %s\n", indenter(indent), a, *p);
Eric Andersen25f27032001-04-26 23:22:31 +00002157 }
2158 globfree(&child->glob_result);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002159 child->argv = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002160 } else if (child->group) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002161 debug_printf_clean("%s begin group (subshell:%d)\n", indenter(indent), child->subshell);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002162 ret_code = free_pipe_list(child->group, indent+3);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002163 debug_printf_clean("%s end group\n", indenter(indent));
Eric Andersen25f27032001-04-26 23:22:31 +00002164 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002165 debug_printf_clean("%s (nil)\n", indenter(indent));
Eric Andersen25f27032001-04-26 23:22:31 +00002166 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002167 for (r = child->redirects; r; r = rnext) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002168 debug_printf_clean("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->type].descrip);
Eric Andersen25f27032001-04-26 23:22:31 +00002169 if (r->dup == -1) {
Eric Andersen817e73c2001-06-06 17:56:09 +00002170 /* guard against the case >$FOO, where foo is unset or blank */
2171 if (r->word.gl_pathv) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002172 debug_printf_clean(" %s\n", *r->word.gl_pathv);
Eric Andersen817e73c2001-06-06 17:56:09 +00002173 globfree(&r->word);
2174 }
Eric Andersen25f27032001-04-26 23:22:31 +00002175 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002176 debug_printf_clean("&%d\n", r->dup);
Eric Andersen25f27032001-04-26 23:22:31 +00002177 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002178 rnext = r->next;
Eric Andersen25f27032001-04-26 23:22:31 +00002179 free(r);
2180 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002181 child->redirects = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002182 }
2183 free(pi->progs); /* children are an array, they get freed all at once */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002184 pi->progs = NULL;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002185#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002186 free(pi->cmdtext);
2187 pi->cmdtext = NULL;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002188#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002189 return ret_code;
2190}
2191
Eric Andersenbf7df042001-05-23 22:18:35 +00002192static int free_pipe_list(struct pipe *head, int indent)
Eric Andersen25f27032001-04-26 23:22:31 +00002193{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002194 int rcode = 0; /* if list has no members */
Eric Andersen25f27032001-04-26 23:22:31 +00002195 struct pipe *pi, *next;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002196
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002197 for (pi = head; pi; pi = next) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002198 debug_printf_clean("%s pipe reserved mode %d\n", indenter(indent), pi->res_word);
Eric Andersenbf7df042001-05-23 22:18:35 +00002199 rcode = free_pipe(pi, indent);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002200 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002201 next = pi->next;
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002202 /*pi->next = NULL;*/
Eric Andersen25f27032001-04-26 23:22:31 +00002203 free(pi);
2204 }
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002205 return rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00002206}
2207
2208/* Select which version we will use */
2209static int run_list(struct pipe *pi)
2210{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002211 int rcode = 0;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002212 debug_printf_exec("run_list entered\n");
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002213 if (fake_mode == 0) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002214 debug_printf_exec(": run_list_real with %d members\n", pi->num_progs);
Eric Andersen25f27032001-04-26 23:22:31 +00002215 rcode = run_list_real(pi);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002216 }
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002217 /* free_pipe_list has the side effect of clearing memory.
Eric Andersen25f27032001-04-26 23:22:31 +00002218 * In the long run that function can be merged with run_list_real,
2219 * but doing that now would hobble the debugging effort. */
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002220 free_pipe_list(pi, 0);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002221 debug_printf_exec("run_list return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00002222 return rcode;
2223}
2224
2225/* The API for glob is arguably broken. This routine pushes a non-matching
2226 * string into the output structure, removing non-backslashed backslashes.
2227 * If someone can prove me wrong, by performing this function within the
2228 * original glob(3) api, feel free to rewrite this routine into oblivion.
2229 * Return code (0 vs. GLOB_NOSPACE) matches glob(3).
2230 * XXX broken if the last character is '\\', check that before calling.
2231 */
2232static int globhack(const char *src, int flags, glob_t *pglob)
2233{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002234 int cnt = 0, pathc;
Eric Andersen25f27032001-04-26 23:22:31 +00002235 const char *s;
2236 char *dest;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002237 for (cnt = 1, s = src; s && *s; s++) {
Eric Andersen25f27032001-04-26 23:22:31 +00002238 if (*s == '\\') s++;
2239 cnt++;
2240 }
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002241 dest = xmalloc(cnt);
Eric Andersen25f27032001-04-26 23:22:31 +00002242 if (!(flags & GLOB_APPEND)) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002243 pglob->gl_pathv = NULL;
2244 pglob->gl_pathc = 0;
2245 pglob->gl_offs = 0;
2246 pglob->gl_offs = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00002247 }
2248 pathc = ++pglob->gl_pathc;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002249 pglob->gl_pathv = xrealloc(pglob->gl_pathv, (pathc+1) * sizeof(*pglob->gl_pathv));
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002250 pglob->gl_pathv[pathc-1] = dest;
2251 pglob->gl_pathv[pathc] = NULL;
2252 for (s = src; s && *s; s++, dest++) {
Eric Andersen25f27032001-04-26 23:22:31 +00002253 if (*s == '\\') s++;
2254 *dest = *s;
2255 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002256 *dest = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002257 return 0;
2258}
2259
2260/* XXX broken if the last character is '\\', check that before calling */
2261static int glob_needed(const char *s)
2262{
2263 for (; *s; s++) {
2264 if (*s == '\\') s++;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002265 if (strchr("*[?", *s)) return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002266 }
2267 return 0;
2268}
2269
Eric Andersen25f27032001-04-26 23:22:31 +00002270static int xglob(o_string *dest, int flags, glob_t *pglob)
2271{
2272 int gr;
2273
Tim Rikerc1ef7bd2006-01-25 00:08:53 +00002274 /* short-circuit for null word */
Eric Andersen25f27032001-04-26 23:22:31 +00002275 /* we can code this better when the debug_printf's are gone */
Tim Rikerc1ef7bd2006-01-25 00:08:53 +00002276 if (dest->length == 0) {
2277 if (dest->nonnull) {
2278 /* bash man page calls this an "explicit" null */
2279 gr = globhack(dest->data, flags, pglob);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002280 debug_printf("globhack returned %d\n", gr);
Tim Rikerc1ef7bd2006-01-25 00:08:53 +00002281 } else {
Eric Andersen25f27032001-04-26 23:22:31 +00002282 return 0;
2283 }
Tim Rikerc1ef7bd2006-01-25 00:08:53 +00002284 } else if (glob_needed(dest->data)) {
Eric Andersen25f27032001-04-26 23:22:31 +00002285 gr = glob(dest->data, flags, NULL, pglob);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002286 debug_printf("glob returned %d\n", gr);
Eric Andersen25f27032001-04-26 23:22:31 +00002287 if (gr == GLOB_NOMATCH) {
2288 /* quote removal, or more accurately, backslash removal */
2289 gr = globhack(dest->data, flags, pglob);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002290 debug_printf("globhack returned %d\n", gr);
Eric Andersen25f27032001-04-26 23:22:31 +00002291 }
2292 } else {
2293 gr = globhack(dest->data, flags, pglob);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002294 debug_printf("globhack returned %d\n", gr);
Eric Andersen25f27032001-04-26 23:22:31 +00002295 }
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002296 if (gr == GLOB_NOSPACE)
Manuel Novoa III cad53642003-03-19 09:13:01 +00002297 bb_error_msg_and_die("out of memory during glob");
Eric Andersen25f27032001-04-26 23:22:31 +00002298 if (gr != 0) { /* GLOB_ABORTED ? */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002299 bb_error_msg("glob(3) error %d", gr);
Eric Andersen25f27032001-04-26 23:22:31 +00002300 }
2301 /* globprint(glob_target); */
2302 return gr;
2303}
2304
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002305/* expand_variables_to_list() takes a list of strings, expands
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002306 * all variable references within and returns a pointer to
2307 * a list of expanded strings, possibly with larger number
2308 * of strings. (Think VAR="a b"; echo $VAR).
2309 * This new list is allocated as a single malloc block.
2310 * NULL-terminated list of char* pointers is at the beginning of it,
2311 * followed by strings themself.
2312 * Caller can deallocate entire list by single free(list). */
2313
2314/* Helpers first:
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00002315 * count_XXX estimates size of the block we need. It's okay
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002316 * to over-estimate sizes a bit, if it makes code simpler */
2317static int count_ifs(const char *str)
2318{
2319 int cnt = 0;
2320 debug_printf_expand("count_ifs('%s') ifs='%s'", str, ifs);
2321 while (1) {
2322 str += strcspn(str, ifs);
2323 if (!*str) break;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002324 str++; /* str += strspn(str, ifs); */
2325 cnt++; /* cnt += strspn(str, ifs); - but this code is larger */
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002326 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002327 debug_printf_expand(" return %d\n", cnt);
2328 return cnt;
2329}
2330
2331static void count_var_expansion_space(int *countp, int *lenp, char *arg)
2332{
2333 char first_ch;
2334 int i;
2335 int len = *lenp;
2336 int count = *countp;
2337 const char *val;
2338 char *p;
2339
2340 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL))) {
2341 len += p - arg;
2342 arg = ++p;
2343 p = strchr(p, SPECIAL_VAR_SYMBOL);
2344 first_ch = arg[0];
2345
2346 switch (first_ch & 0x7f) {
2347 /* high bit in 1st_ch indicates that var is double-quoted */
2348 case '$': /* pid */
2349 case '!': /* bg pid */
2350 case '?': /* exitcode */
2351 case '#': /* argc */
2352 len += sizeof(int)*3 + 1; /* enough for int */
2353 break;
2354 case '*':
2355 case '@':
2356 for (i = 1; i < global_argc; i++) {
2357 len += strlen(global_argv[i]) + 1;
2358 count++;
2359 if (!(first_ch & 0x80))
2360 count += count_ifs(global_argv[i]);
2361 }
2362 break;
2363 default:
2364 *p = '\0';
2365 arg[0] = first_ch & 0x7f;
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002366 if (isdigit(arg[0])) {
2367 i = xatoi_u(arg);
2368 val = NULL;
2369 if (i < global_argc)
2370 val = global_argv[i];
2371 } else
2372 val = lookup_param(arg);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002373 arg[0] = first_ch;
2374 *p = SPECIAL_VAR_SYMBOL;
2375
2376 if (val) {
2377 len += strlen(val) + 1;
2378 if (!(first_ch & 0x80))
2379 count += count_ifs(val);
2380 }
2381 }
2382 arg = ++p;
2383 }
2384
2385 len += strlen(arg) + 1;
2386 count++;
2387 *lenp = len;
2388 *countp = count;
2389}
2390
2391/* Store given string, finalizing the word and starting new one whenever
2392 * we encounter ifs char(s). This is used for expanding variable values.
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002393 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002394static int expand_on_ifs(char **list, int n, char **posp, const char *str)
2395{
2396 char *pos = *posp;
2397 while (1) {
2398 int word_len = strcspn(str, ifs);
2399 if (word_len) {
2400 memcpy(pos, str, word_len); /* store non-ifs chars */
2401 pos += word_len;
2402 str += word_len;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002403 }
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002404 if (!*str) /* EOL - do not finalize word */
2405 break;
2406 *pos++ = '\0';
2407 if (n) debug_printf_expand("expand_on_ifs finalized list[%d]=%p '%s' "
2408 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2409 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2410 list[n++] = pos;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002411 str += strspn(str, ifs); /* skip ifs chars */
2412 }
2413 *posp = pos;
2414 return n;
2415}
2416
2417/* Expand all variable references in given string, adding words to list[]
2418 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2419 * to be filled). This routine is extremely tricky: has to deal with
2420 * variables/parameters with whitespace, $* and $@, and constructs like
2421 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002422/* NB: another bug is that we cannot detect empty strings yet:
2423 * "" or $empty"" expands to zero words, has to expand to empty word */
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002424static int expand_vars_to_list(char **list, int n, char **posp, char *arg, char or_mask)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002425{
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002426 /* or_mask is either 0 (normal case) or 0x80
2427 * (expansion of right-hand side of assignment == 1-element expand) */
2428
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002429 char first_ch, ored_ch;
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002430 int i;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002431 const char *val;
2432 char *p;
2433 char *pos = *posp;
2434
2435 ored_ch = 0;
2436
2437 if (n) debug_printf_expand("expand_vars_to_list finalized list[%d]=%p '%s' "
2438 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2439 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2440 list[n++] = pos;
2441
2442 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL))) {
2443 memcpy(pos, arg, p - arg);
2444 pos += (p - arg);
2445 arg = ++p;
2446 p = strchr(p, SPECIAL_VAR_SYMBOL);
2447
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002448 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002449 ored_ch |= first_ch;
2450 val = NULL;
2451 switch (first_ch & 0x7f) {
2452 /* Highest bit in first_ch indicates that var is double-quoted */
2453 case '$': /* pid */
2454 /* FIXME: (echo $$) should still print pid of main shell */
2455 val = utoa(getpid());
2456 break;
2457 case '!': /* bg pid */
2458 val = last_bg_pid ? utoa(last_bg_pid) : (char*)"";
2459 break;
2460 case '?': /* exitcode */
2461 val = utoa(last_return_code);
2462 break;
2463 case '#': /* argc */
2464 val = utoa(global_argc ? global_argc-1 : 0);
2465 break;
2466 case '*':
2467 case '@':
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002468 i = 1;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002469 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002470 while (i < global_argc) {
2471 n = expand_on_ifs(list, n, &pos, global_argv[i]);
2472 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, global_argc-1);
2473 if (global_argv[i++][0] && i < global_argc) {
2474 /* this argv[] is not empty and not last:
2475 * put terminating NUL, start new word */
2476 *pos++ = '\0';
2477 if (n) debug_printf_expand("expand_vars_to_list 2 finalized list[%d]=%p '%s' "
2478 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2479 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2480 list[n++] = pos;
2481 }
2482 }
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002483 } else
2484 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2485 * and in this case should theat it like '$*' */
2486 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002487 while (1) {
2488 strcpy(pos, global_argv[i]);
2489 pos += strlen(global_argv[i]);
2490 if (++i >= global_argc)
2491 break;
2492 *pos++ = '\0';
2493 if (n) debug_printf_expand("expand_vars_to_list 3 finalized list[%d]=%p '%s' "
2494 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2495 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2496 list[n++] = pos;
2497 }
2498 } else { /* quoted $*: add as one word */
2499 while (1) {
2500 strcpy(pos, global_argv[i]);
2501 pos += strlen(global_argv[i]);
2502 if (++i >= global_argc)
2503 break;
2504 if (ifs[0])
2505 *pos++ = ifs[0];
2506 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002507 }
2508 break;
2509 default:
2510 *p = '\0';
2511 arg[0] = first_ch & 0x7f;
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002512 if (isdigit(arg[0])) {
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002513 i = xatoi_u(arg);
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002514 val = NULL;
2515 if (i < global_argc)
2516 val = global_argv[i];
2517 } else
2518 val = lookup_param(arg);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002519 arg[0] = first_ch;
2520 *p = SPECIAL_VAR_SYMBOL;
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002521 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002522 if (val) {
2523 n = expand_on_ifs(list, n, &pos, val);
2524 val = NULL;
2525 }
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002526 } /* else: quoted $VAR, val will be appended at pos */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002527 }
2528 if (val) {
2529 strcpy(pos, val);
2530 pos += strlen(val);
2531 }
2532 arg = ++p;
2533 }
2534 debug_printf_expand("expand_vars_to_list adding tail '%s' at %p\n", arg, pos);
2535 strcpy(pos, arg);
2536 pos += strlen(arg) + 1;
2537 if (pos == list[n-1] + 1) { /* expansion is empty */
2538 if (!(ored_ch & 0x80)) { /* all vars were not quoted... */
2539 debug_printf_expand("expand_vars_to_list list[%d] empty, going back\n", n);
2540 pos--;
2541 n--;
2542 }
2543 }
2544
2545 *posp = pos;
2546 return n;
2547}
2548
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002549static char **expand_variables(char **argv, char or_mask)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002550{
2551 int n;
2552 int count = 1;
2553 int len = 0;
2554 char *pos, **v, **list;
2555
2556 v = argv;
2557 if (!*v) debug_printf_expand("count_var_expansion_space: "
2558 "argv[0]=NULL count=%d len=%d alloc_space=%d\n",
2559 count, len, sizeof(char*) * count + len);
2560 while (*v) {
2561 count_var_expansion_space(&count, &len, *v);
2562 debug_printf_expand("count_var_expansion_space: "
2563 "'%s' count=%d len=%d alloc_space=%d\n",
2564 *v, count, len, sizeof(char*) * count + len);
2565 v++;
2566 }
2567 len += sizeof(char*) * count; /* total to alloc */
2568 list = xmalloc(len);
2569 pos = (char*)(list + count);
2570 debug_printf_expand("list=%p, list[0] should be %p\n", list, pos);
2571 n = 0;
2572 v = argv;
2573 while (*v)
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002574 n = expand_vars_to_list(list, n, &pos, *v++, or_mask);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002575
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002576 if (n) debug_printf_expand("finalized list[%d]=%p '%s' "
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002577 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2578 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002579 list[n] = NULL;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002580
2581#ifdef DEBUG_EXPAND
2582 {
2583 int m = 0;
2584 while (m <= n) {
2585 debug_printf_expand("list[%d]=%p '%s'\n", m, list[m], list[m]);
2586 m++;
2587 }
2588 debug_printf_expand("used_space=%d\n", pos - (char*)list);
2589 }
2590#endif
2591 /* To be removed / made conditional later. */
2592 if (pos - (char*)list > len)
2593 bb_error_msg_and_die("BUG in varexp");
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002594 return list;
2595}
2596
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002597static char **expand_variables_to_list(char **argv)
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002598{
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002599 return expand_variables(argv, 0);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002600}
2601
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002602static char *expand_variables_to_string(const char *str)
2603{
2604 char *argv[2], **list;
2605
2606 argv[0] = (char*)str;
2607 argv[1] = NULL;
2608 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
2609 /* To be removed / made conditional later. */
2610 if (!list[0] || list[1])
2611 bb_error_msg_and_die("BUG in varexp");
2612 /* actually, just move string 2*sizeof(char*) bytes back */
2613 strcpy((char*)list, list[0]);
2614 return (char*)list;
2615}
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002616
Eric Andersenf72f5622001-05-15 23:21:41 +00002617/* This is used to get/check local shell variables */
Denis Vlasenko15d78fb2007-01-30 22:28:21 +00002618static const char *get_local_var(const char *s)
Eric Andersenf72f5622001-05-15 23:21:41 +00002619{
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002620 struct variables *cur;
Eric Andersenf72f5622001-05-15 23:21:41 +00002621
2622 if (!s)
2623 return NULL;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00002624 for (cur = top_vars; cur; cur = cur->next) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002625 if (strcmp(cur->name, s) == 0)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002626 return cur->value;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00002627 }
Eric Andersenf72f5622001-05-15 23:21:41 +00002628 return NULL;
2629}
2630
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002631/* This is used to set local shell variables
Denis Vlasenkobb81c582007-01-30 22:32:09 +00002632 flg_export == 0 if only local (not exporting) variable
2633 flg_export == 1 if "new" exporting environ
2634 flg_export > 1 if current startup environ (not call putenv()) */
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002635static int set_local_var(const char *s, int flg_export)
Eric Andersen78a7c992001-05-15 16:30:25 +00002636{
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002637 char *name, *value;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002638 int result = 0;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002639 struct variables *cur;
Eric Andersen20a69a72001-05-15 17:24:44 +00002640
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00002641 name = xstrdup(s);
Eric Andersen20a69a72001-05-15 17:24:44 +00002642
2643 /* Assume when we enter this function that we are already in
2644 * NAME=VALUE format. So the first order of business is to
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002645 * split 's' on the '=' into 'name' and 'value' */
Eric Andersen20a69a72001-05-15 17:24:44 +00002646 value = strchr(name, '=');
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00002647 /*if (value == 0 && ++value == 0) ??? -vda */
2648 if (value == NULL || value[1] == '\0') {
Eric Andersen99785762001-05-22 21:37:48 +00002649 free(name);
2650 return -1;
2651 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00002652 *value++ = '\0';
Eric Andersen20a69a72001-05-15 17:24:44 +00002653
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002654 for (cur = top_vars; cur; cur = cur->next) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00002655 if (strcmp(cur->name, name) == 0) {
2656 if (strcmp(cur->value, value) == 0) {
Denis Vlasenko3e7b0e62007-05-16 12:52:15 +00002657 if (flg_export && !cur->flg_export)
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00002658 cur->flg_export = flg_export;
2659 else
2660 result++;
2661 } else if (cur->flg_read_only) {
2662 bb_error_msg("%s: readonly variable", name);
Eric Andersen99785762001-05-22 21:37:48 +00002663 result = -1;
2664 } else {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00002665 if (flg_export > 0 || cur->flg_export > 1)
2666 cur->flg_export = 1;
2667 free((char*)cur->value);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002668 cur->value = xstrdup(value);
Eric Andersen20a69a72001-05-15 17:24:44 +00002669 }
Denis Vlasenko3e7b0e62007-05-16 12:52:15 +00002670 goto skip;
Eric Andersen20a69a72001-05-15 17:24:44 +00002671 }
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002672 }
Eric Andersen20a69a72001-05-15 17:24:44 +00002673
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002674 cur = xzalloc(sizeof(*cur));
2675 cur->name = xstrdup(name);
2676 cur->value = xstrdup(value);
2677 /*cur->next = 0;*/
2678 cur->flg_export = flg_export;
2679 /*cur->flg_read_only = 0;*/
2680 {
2681 struct variables *bottom = top_vars;
2682 while (bottom->next)
2683 bottom = bottom->next;
2684 bottom->next = cur;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00002685 }
2686 skip:
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002687 if (result == 0 && cur->flg_export == 1) {
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002688 *(value-1) = '=';
2689 result = putenv(name);
2690 } else {
Eric Andersen94ac2442001-05-22 19:05:18 +00002691 free(name);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002692 if (result > 0) /* equivalent to previous set */
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002693 result = 0;
2694 }
Eric Andersen20a69a72001-05-15 17:24:44 +00002695 return result;
2696}
2697
Eric Andersenf72f5622001-05-15 23:21:41 +00002698static void unset_local_var(const char *name)
Eric Andersen20a69a72001-05-15 17:24:44 +00002699{
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002700 struct variables *cur, *next;
Eric Andersen20a69a72001-05-15 17:24:44 +00002701
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002702 if (!name)
2703 return;
2704 for (cur = top_vars; cur; cur = cur->next) {
2705 if (strcmp(cur->name, name) == 0) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002706 if (cur->flg_read_only) {
Manuel Novoa III cad53642003-03-19 09:13:01 +00002707 bb_error_msg("%s: readonly variable", name);
Eric Andersen94ac2442001-05-22 19:05:18 +00002708 return;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002709 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002710 if (cur->flg_export)
2711 unsetenv(cur->name);
2712 free((char*)cur->name);
2713 free((char*)cur->value);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002714 next = top_vars;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002715 while (next->next != cur)
2716 next = next->next;
2717 next->next = cur->next;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002718 free(cur);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002719 return;
Eric Andersenf72f5622001-05-15 23:21:41 +00002720 }
Eric Andersen20a69a72001-05-15 17:24:44 +00002721 }
Eric Andersen78a7c992001-05-15 16:30:25 +00002722}
2723
2724static int is_assignment(const char *s)
2725{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002726 if (!s || !isalpha(*s))
2727 return 0;
2728 s++;
2729 while (isalnum(*s) || *s == '_')
2730 s++;
2731 return *s == '=';
Eric Andersen78a7c992001-05-15 16:30:25 +00002732}
2733
Eric Andersen25f27032001-04-26 23:22:31 +00002734/* the src parameter allows us to peek forward to a possible &n syntax
2735 * for file descriptor duplication, e.g., "2>&1".
2736 * Return code is 0 normally, 1 if a syntax error is detected in src.
2737 * Resource errors (in xmalloc) cause the process to exit */
2738static int setup_redirect(struct p_context *ctx, int fd, redir_type style,
2739 struct in_str *input)
2740{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002741 struct child_prog *child = ctx->child;
Eric Andersen25f27032001-04-26 23:22:31 +00002742 struct redir_struct *redir = child->redirects;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002743 struct redir_struct *last_redir = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002744
2745 /* Create a new redir_struct and drop it onto the end of the linked list */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002746 while (redir) {
2747 last_redir = redir;
2748 redir = redir->next;
Eric Andersen25f27032001-04-26 23:22:31 +00002749 }
2750 redir = xmalloc(sizeof(struct redir_struct));
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002751 redir->next = NULL;
2752 redir->word.gl_pathv = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002753 if (last_redir) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002754 last_redir->next = redir;
Eric Andersen25f27032001-04-26 23:22:31 +00002755 } else {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002756 child->redirects = redir;
Eric Andersen25f27032001-04-26 23:22:31 +00002757 }
2758
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002759 redir->type = style;
2760 redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
Eric Andersen25f27032001-04-26 23:22:31 +00002761
2762 debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
2763
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002764 /* Check for a '2>&1' type redirect */
Eric Andersen25f27032001-04-26 23:22:31 +00002765 redir->dup = redirect_dup_num(input);
2766 if (redir->dup == -2) return 1; /* syntax error */
2767 if (redir->dup != -1) {
2768 /* Erik had a check here that the file descriptor in question
Eric Andersen83a2ae22001-05-07 17:59:25 +00002769 * is legit; I postpone that to "run time"
2770 * A "-" representation of "close me" shows up as a -3 here */
Eric Andersen25f27032001-04-26 23:22:31 +00002771 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
2772 } else {
2773 /* We do _not_ try to open the file that src points to,
2774 * since we need to return and let src be expanded first.
2775 * Set ctx->pending_redirect, so we know what to do at the
2776 * end of the next parsed word.
2777 */
2778 ctx->pending_redirect = redir;
2779 }
2780 return 0;
2781}
2782
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00002783static struct pipe *new_pipe(void)
2784{
Eric Andersen25f27032001-04-26 23:22:31 +00002785 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002786 pi = xzalloc(sizeof(struct pipe));
2787 /*pi->num_progs = 0;*/
2788 /*pi->progs = NULL;*/
2789 /*pi->next = NULL;*/
2790 /*pi->followup = 0; invalid */
2791 if (RES_NONE)
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002792 pi->res_word = RES_NONE;
Eric Andersen25f27032001-04-26 23:22:31 +00002793 return pi;
2794}
2795
2796static void initialize_context(struct p_context *ctx)
2797{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002798 ctx->pipe = NULL;
2799 ctx->pending_redirect = NULL;
2800 ctx->child = NULL;
2801 ctx->list_head = new_pipe();
2802 ctx->pipe = ctx->list_head;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002803 ctx->res_w = RES_NONE;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002804 ctx->stack = NULL;
2805 ctx->old_flag = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00002806 done_command(ctx); /* creates the memory for working child */
2807}
2808
2809/* normal return is 0
2810 * if a reserved word is found, and processed, return 1
2811 * should handle if, then, elif, else, fi, for, while, until, do, done.
2812 * case, function, and select are obnoxious, save those for later.
2813 */
"Vladimir N. Oleynik"19c37012005-09-22 14:33:15 +00002814static int reserved_word(o_string *dest, struct p_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00002815{
2816 struct reserved_combo {
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002817 char literal[7];
2818 unsigned char code;
2819 int flag;
Eric Andersen25f27032001-04-26 23:22:31 +00002820 };
2821 /* Mostly a list of accepted follow-up reserved words.
2822 * FLAG_END means we are done with the sequence, and are ready
2823 * to turn the compound list into a command.
2824 * FLAG_START means the word must start a new compound list.
2825 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002826 static const struct reserved_combo reserved_list[] = {
Eric Andersen25f27032001-04-26 23:22:31 +00002827 { "if", RES_IF, FLAG_THEN | FLAG_START },
2828 { "then", RES_THEN, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2829 { "elif", RES_ELIF, FLAG_THEN },
2830 { "else", RES_ELSE, FLAG_FI },
2831 { "fi", RES_FI, FLAG_END },
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002832 { "for", RES_FOR, FLAG_IN | FLAG_START },
Eric Andersen25f27032001-04-26 23:22:31 +00002833 { "while", RES_WHILE, FLAG_DO | FLAG_START },
2834 { "until", RES_UNTIL, FLAG_DO | FLAG_START },
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002835 { "in", RES_IN, FLAG_DO },
Eric Andersen25f27032001-04-26 23:22:31 +00002836 { "do", RES_DO, FLAG_DONE },
2837 { "done", RES_DONE, FLAG_END }
2838 };
Denis Vlasenko7d4c44e2007-04-16 22:34:39 +00002839 enum { NRES = sizeof(reserved_list)/sizeof(reserved_list[0]) };
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002840 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002841
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002842 for (r = reserved_list; r < reserved_list + NRES; r++) {
Eric Andersen25f27032001-04-26 23:22:31 +00002843 if (strcmp(dest->data, r->literal) == 0) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00002844 debug_printf("found reserved word %s, code %d\n", r->literal, r->code);
Eric Andersen25f27032001-04-26 23:22:31 +00002845 if (r->flag & FLAG_START) {
2846 struct p_context *new = xmalloc(sizeof(struct p_context));
2847 debug_printf("push stack\n");
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002848 if (ctx->res_w == RES_IN || ctx->res_w == RES_FOR) {
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002849 syntax();
2850 free(new);
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002851 ctx->res_w = RES_SNTX;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002852 b_reset(dest);
2853 return 1;
2854 }
Eric Andersen25f27032001-04-26 23:22:31 +00002855 *new = *ctx; /* physical copy */
2856 initialize_context(ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00002857 ctx->stack = new;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002858 } else if (ctx->res_w == RES_NONE || !(ctx->old_flag & (1 << r->code))) {
Eric Andersenaf44a0e2001-04-27 07:26:12 +00002859 syntax();
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002860 ctx->res_w = RES_SNTX;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002861 b_reset(dest);
Eric Andersenaf44a0e2001-04-27 07:26:12 +00002862 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002863 }
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002864 ctx->res_w = r->code;
Eric Andersen25f27032001-04-26 23:22:31 +00002865 ctx->old_flag = r->flag;
2866 if (ctx->old_flag & FLAG_END) {
2867 struct p_context *old;
2868 debug_printf("pop stack\n");
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00002869 done_pipe(ctx, PIPE_SEQ);
Eric Andersen25f27032001-04-26 23:22:31 +00002870 old = ctx->stack;
2871 old->child->group = ctx->list_head;
Eric Andersen04407e52001-06-07 16:42:05 +00002872 old->child->subshell = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00002873 *ctx = *old; /* physical copy */
2874 free(old);
Eric Andersen25f27032001-04-26 23:22:31 +00002875 }
Denis Vlasenkoff131b92007-04-10 15:42:06 +00002876 b_reset(dest);
Eric Andersen25f27032001-04-26 23:22:31 +00002877 return 1;
2878 }
2879 }
2880 return 0;
2881}
2882
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002883/* Normal return is 0.
Eric Andersen25f27032001-04-26 23:22:31 +00002884 * Syntax or xglob errors return 1. */
2885static int done_word(o_string *dest, struct p_context *ctx)
2886{
Denis Vlasenkobb81c582007-01-30 22:32:09 +00002887 struct child_prog *child = ctx->child;
Eric Andersen25f27032001-04-26 23:22:31 +00002888 glob_t *glob_target;
2889 int gr, flags = 0;
2890
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002891 debug_printf_parse("done_word entered: '%s' %p\n", dest->data, child);
Eric Andersen25f27032001-04-26 23:22:31 +00002892 if (dest->length == 0 && !dest->nonnull) {
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002893 debug_printf_parse("done_word return 0: true null, ignored\n");
Eric Andersen25f27032001-04-26 23:22:31 +00002894 return 0;
2895 }
2896 if (ctx->pending_redirect) {
2897 glob_target = &ctx->pending_redirect->word;
2898 } else {
2899 if (child->group) {
2900 syntax();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002901 debug_printf_parse("done_word return 1: syntax error, groups and arglists don't mix\n");
2902 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002903 }
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002904 if (!child->argv && (ctx->parse_type & PARSEFLAG_SEMICOLON)) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002905 debug_printf_parse(": checking '%s' for reserved-ness\n", dest->data);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002906 if (reserved_word(dest, ctx)) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002907 debug_printf_parse("done_word return %d\n", (ctx->res_w == RES_SNTX));
2908 return (ctx->res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002909 }
Eric Andersen25f27032001-04-26 23:22:31 +00002910 }
2911 glob_target = &child->glob_result;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002912 if (child->argv)
2913 flags |= GLOB_APPEND;
Eric Andersen25f27032001-04-26 23:22:31 +00002914 }
2915 gr = xglob(dest, flags, glob_target);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002916 if (gr != 0) {
2917 debug_printf_parse("done_word return 1: xglob returned %d\n", gr);
2918 return 1;
2919 }
Eric Andersen25f27032001-04-26 23:22:31 +00002920
2921 b_reset(dest);
2922 if (ctx->pending_redirect) {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00002923 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002924 if (glob_target->gl_pathc != 1) {
Manuel Novoa III cad53642003-03-19 09:13:01 +00002925 bb_error_msg("ambiguous redirect");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002926 debug_printf_parse("done_word return 1: ambiguous redirect\n");
Eric Andersen25f27032001-04-26 23:22:31 +00002927 return 1;
2928 }
2929 } else {
2930 child->argv = glob_target->gl_pathv;
2931 }
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002932 if (ctx->res_w == RES_FOR) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00002933 done_word(dest, ctx);
2934 done_pipe(ctx, PIPE_SEQ);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002935 }
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002936 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00002937 return 0;
2938}
2939
2940/* The only possible error here is out of memory, in which case
2941 * xmalloc exits. */
2942static int done_command(struct p_context *ctx)
2943{
2944 /* The child is really already in the pipe structure, so
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002945 * advance the pipe counter and make a new, null child. */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00002946 struct pipe *pi = ctx->pipe;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002947 struct child_prog *child = ctx->child;
Eric Andersen25f27032001-04-26 23:22:31 +00002948
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002949 if (child) {
2950 if (child->group == NULL
2951 && child->argv == NULL
2952 && child->redirects == NULL
2953 ) {
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00002954 debug_printf_parse("done_command: skipping null cmd, num_progs=%d\n", pi->num_progs);
2955 return pi->num_progs;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002956 }
Eric Andersen25f27032001-04-26 23:22:31 +00002957 pi->num_progs++;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002958 debug_printf_parse("done_command: ++num_progs=%d\n", pi->num_progs);
Eric Andersen25f27032001-04-26 23:22:31 +00002959 } else {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002960 debug_printf_parse("done_command: initializing, num_progs=%d\n", pi->num_progs);
Eric Andersen25f27032001-04-26 23:22:31 +00002961 }
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002962
2963 /* Only real trickiness here is that the uncommitted
2964 * child structure is not counted in pi->num_progs. */
Eric Andersen25f27032001-04-26 23:22:31 +00002965 pi->progs = xrealloc(pi->progs, sizeof(*pi->progs) * (pi->num_progs+1));
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002966 child = &pi->progs[pi->num_progs];
Eric Andersen25f27032001-04-26 23:22:31 +00002967
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002968 memset(child, 0, sizeof(*child));
2969 /*child->redirects = NULL;*/
2970 /*child->argv = NULL;*/
2971 /*child->is_stopped = 0;*/
2972 /*child->group = NULL;*/
2973 /*child->glob_result.gl_pathv = NULL;*/
2974 child->family = pi;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002975 //sp: /*child->sp = 0;*/
Denis Vlasenko262d7652007-05-20 21:52:49 +00002976 //pt: child->parse_type = ctx->parse_type;
Eric Andersen25f27032001-04-26 23:22:31 +00002977
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002978 ctx->child = child;
Eric Andersen25f27032001-04-26 23:22:31 +00002979 /* but ctx->pipe and ctx->list_head remain unchanged */
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002980
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00002981 return pi->num_progs; /* used only for 0/nonzero check */
Eric Andersen25f27032001-04-26 23:22:31 +00002982}
2983
2984static int done_pipe(struct p_context *ctx, pipe_style type)
2985{
2986 struct pipe *new_p;
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00002987 int not_null;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002988
2989 debug_printf_parse("done_pipe entered, followup %d\n", type);
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00002990 not_null = done_command(ctx); /* implicit closure of previous command */
Eric Andersen25f27032001-04-26 23:22:31 +00002991 ctx->pipe->followup = type;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002992 ctx->pipe->res_word = ctx->res_w;
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00002993 /* Without this check, even just <enter> on command line generates
2994 * tree of three NOPs (!). Which is harmless but annoying.
2995 * IOW: it is safe to do it unconditionally. */
2996 if (not_null) {
2997 new_p = new_pipe();
2998 ctx->pipe->next = new_p;
2999 ctx->pipe = new_p;
3000 ctx->child = NULL;
3001 done_command(ctx); /* set up new pipe to accept commands */
3002 }
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003003 debug_printf_parse("done_pipe return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003004 return 0;
3005}
3006
3007/* peek ahead in the in_str to find out if we have a "&n" construct,
3008 * as in "2>&1", that represents duplicating a file descriptor.
3009 * returns either -2 (syntax error), -1 (no &), or the number found.
3010 */
3011static int redirect_dup_num(struct in_str *input)
3012{
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003013 int ch, d = 0, ok = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003014 ch = b_peek(input);
3015 if (ch != '&') return -1;
3016
3017 b_getch(input); /* get the & */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003018 ch = b_peek(input);
Eric Andersen83a2ae22001-05-07 17:59:25 +00003019 if (ch == '-') {
3020 b_getch(input);
3021 return -3; /* "-" represents "close me" */
3022 }
3023 while (isdigit(ch)) {
Denis Vlasenko7d4c44e2007-04-16 22:34:39 +00003024 d = d*10 + (ch-'0');
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003025 ok = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003026 b_getch(input);
Eric Andersen83a2ae22001-05-07 17:59:25 +00003027 ch = b_peek(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003028 }
3029 if (ok) return d;
3030
Manuel Novoa III cad53642003-03-19 09:13:01 +00003031 bb_error_msg("ambiguous redirect");
Eric Andersen25f27032001-04-26 23:22:31 +00003032 return -2;
3033}
3034
3035/* If a redirect is immediately preceded by a number, that number is
3036 * supposed to tell which file descriptor to redirect. This routine
3037 * looks for such preceding numbers. In an ideal world this routine
3038 * needs to handle all the following classes of redirects...
3039 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3040 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3041 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3042 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3043 * A -1 output from this program means no valid number was found, so the
3044 * caller should use the appropriate default for this redirection.
3045 */
3046static int redirect_opt_num(o_string *o)
3047{
3048 int num;
3049
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003050 if (o->length == 0)
3051 return -1;
3052 for (num = 0; num < o->length; num++) {
3053 if (!isdigit(*(o->data + num))) {
Eric Andersen25f27032001-04-26 23:22:31 +00003054 return -1;
3055 }
3056 }
3057 /* reuse num (and save an int) */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003058 num = atoi(o->data);
Eric Andersen25f27032001-04-26 23:22:31 +00003059 b_reset(o);
3060 return num;
3061}
3062
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003063#if ENABLE_HUSH_TICK
"Vladimir N. Oleynik"19c37012005-09-22 14:33:15 +00003064static FILE *generate_stream_from_list(struct pipe *head)
Eric Andersen25f27032001-04-26 23:22:31 +00003065{
3066 FILE *pf;
Eric Andersen25f27032001-04-26 23:22:31 +00003067 int pid, channel[2];
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003068 if (pipe(channel) < 0) bb_perror_msg_and_die("pipe");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003069#if BB_MMU
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003070 pid = fork();
Eric Andersen72f9a422001-10-28 05:12:20 +00003071#else
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003072 pid = vfork();
Eric Andersen72f9a422001-10-28 05:12:20 +00003073#endif
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003074 if (pid < 0) {
Manuel Novoa III cad53642003-03-19 09:13:01 +00003075 bb_perror_msg_and_die("fork");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003076 } else if (pid == 0) {
Eric Andersen25f27032001-04-26 23:22:31 +00003077 close(channel[0]);
3078 if (channel[1] != 1) {
Denis Vlasenko7d4c44e2007-04-16 22:34:39 +00003079 dup2(channel[1], 1);
Eric Andersen25f27032001-04-26 23:22:31 +00003080 close(channel[1]);
3081 }
Eric Andersen94ac2442001-05-22 19:05:18 +00003082 _exit(run_list_real(head)); /* leaks memory */
Eric Andersen25f27032001-04-26 23:22:31 +00003083 }
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003084 debug_printf("forked child %d\n", pid);
Eric Andersen25f27032001-04-26 23:22:31 +00003085 close(channel[1]);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003086 pf = fdopen(channel[0], "r");
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003087 debug_printf("pipe on FILE *%p\n", pf);
Eric Andersen25f27032001-04-26 23:22:31 +00003088 return pf;
3089}
3090
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003091/* Return code is exit status of the process that is run. */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003092static int process_command_subs(o_string *dest, struct p_context *ctx,
3093 struct in_str *input, const char *subst_end)
Eric Andersen25f27032001-04-26 23:22:31 +00003094{
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003095 int retcode, ch, eol_cnt;
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003096 o_string result = NULL_O_STRING;
Eric Andersen25f27032001-04-26 23:22:31 +00003097 struct p_context inner;
3098 FILE *p;
3099 struct in_str pipe_str;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003100
Eric Andersen25f27032001-04-26 23:22:31 +00003101 initialize_context(&inner);
3102
3103 /* recursion to generate command */
3104 retcode = parse_stream(&result, &inner, input, subst_end);
3105 if (retcode != 0) return retcode; /* syntax error or EOF */
3106 done_word(&result, &inner);
3107 done_pipe(&inner, PIPE_SEQ);
3108 b_free(&result);
3109
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003110 p = generate_stream_from_list(inner.list_head);
3111 if (p == NULL) return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003112 mark_open(fileno(p));
3113 setup_file_in_str(&pipe_str, p);
3114
3115 /* now send results of command back into original context */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003116 eol_cnt = 0;
3117 while ((ch = b_getch(&pipe_str)) != EOF) {
3118 if (ch == '\n') {
3119 eol_cnt++;
3120 continue;
3121 }
3122 while (eol_cnt) {
3123 b_addqchr(dest, '\n', dest->quote);
3124 eol_cnt--;
3125 }
3126 b_addqchr(dest, ch, dest->quote);
Eric Andersen25f27032001-04-26 23:22:31 +00003127 }
3128
3129 debug_printf("done reading from pipe, pclose()ing\n");
3130 /* This is the step that wait()s for the child. Should be pretty
3131 * safe, since we just read an EOF from its stdout. We could try
Denis Vlasenko262d7652007-05-20 21:52:49 +00003132 * to do better, by using wait(), and keeping track of background jobs
Eric Andersen25f27032001-04-26 23:22:31 +00003133 * at the same time. That would be a lot of work, and contrary
3134 * to the KISS philosophy of this program. */
3135 mark_closed(fileno(p));
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003136 retcode = pclose(p);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003137 free_pipe_list(inner.list_head, 0);
3138 debug_printf("pclosed, retcode=%d\n", retcode);
Eric Andersen25f27032001-04-26 23:22:31 +00003139 return retcode;
3140}
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003141#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003142
3143static int parse_group(o_string *dest, struct p_context *ctx,
3144 struct in_str *input, int ch)
3145{
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003146 int rcode;
3147 const char *endch = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003148 struct p_context sub;
3149 struct child_prog *child = ctx->child;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003150
3151 debug_printf_parse("parse_group entered\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003152 if (child->argv) {
3153 syntax();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003154 debug_printf_parse("parse_group return 1: syntax error, groups and arglists don't mix\n");
3155 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003156 }
3157 initialize_context(&sub);
Denis Vlasenkobf0a2012006-12-26 10:42:51 +00003158 switch (ch) {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003159 case '(':
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003160 endch = ")";
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003161 child->subshell = 1;
3162 break;
3163 case '{':
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003164 endch = "}";
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003165 break;
3166 default:
3167 syntax(); /* really logic error */
Eric Andersen25f27032001-04-26 23:22:31 +00003168 }
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003169 rcode = parse_stream(dest, &sub, input, endch);
3170 done_word(dest, &sub); /* finish off the final word in the subcontext */
Eric Andersen25f27032001-04-26 23:22:31 +00003171 done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */
3172 child->group = sub.list_head;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003173
3174 debug_printf_parse("parse_group return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00003175 return rcode;
3176 /* child remains "open", available for possible redirects */
3177}
3178
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003179/* Basically useful version until someone wants to get fancier,
Eric Andersen25f27032001-04-26 23:22:31 +00003180 * see the bash man page under "Parameter Expansion" */
Denis Vlasenko15d78fb2007-01-30 22:28:21 +00003181static const char *lookup_param(const char *src)
Eric Andersen25f27032001-04-26 23:22:31 +00003182{
Denis Vlasenko15d78fb2007-01-30 22:28:21 +00003183 const char *p = NULL;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003184 if (src) {
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003185 p = getenv(src);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003186 if (!p)
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003187 p = get_local_var(src);
Eric Andersen20a69a72001-05-15 17:24:44 +00003188 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003189 return p;
Eric Andersen25f27032001-04-26 23:22:31 +00003190}
3191
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00003192/* Make new string for parser */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003193static char* make_string(char **inp)
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00003194{
3195 char *p;
3196 char *str = NULL;
3197 int n;
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003198 int val_len;
3199 int len = 0;
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00003200
3201 for (n = 0; inp[n]; n++) {
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00003202 p = expand_variables_to_string(inp[n]);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003203 val_len = strlen(p);
3204 str = xrealloc(str, len + val_len + 3); /* +3: space, '\n', <nul>*/
3205 str[len++] = ' ';
3206 strcpy(str + len, p);
3207 len += val_len;
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00003208 if (p != inp[n]) free(p);
3209 }
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003210 /* We do not check for case where loop had no iterations at all
3211 * - cannot happen? */
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00003212 str[len] = '\n';
3213 str[len+1] = '\0';
3214 return str;
3215}
3216
Eric Andersen25f27032001-04-26 23:22:31 +00003217/* return code: 0 for OK, 1 for syntax error */
3218static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input)
3219{
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003220 int ch = b_peek(input); /* first character after the $ */
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003221 unsigned char quote_mask = dest->quote ? 0x80 : 0;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003222
3223 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003224 if (isalpha(ch)) {
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003225 b_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003226 //sp: ctx->child->sp++;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003227 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003228 debug_printf_parse(": '%c'\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003229 b_getch(input);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003230 b_addchr(dest, ch | quote_mask);
3231 quote_mask = 0;
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003232 ch = b_peek(input);
3233 if (!isalnum(ch) && ch != '_')
3234 break;
Eric Andersen25f27032001-04-26 23:22:31 +00003235 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003236 b_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003237 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003238 make_one_char_var:
3239 b_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003240 //sp: ctx->child->sp++;
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003241 debug_printf_parse(": '%c'\n", ch);
3242 b_getch(input);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003243 b_addchr(dest, ch | quote_mask);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003244 b_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003245 } else switch (ch) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003246 case '$': /* pid */
3247 case '!': /* last bg pid */
3248 case '?': /* last exit code */
3249 case '#': /* number of args */
3250 case '*': /* args */
3251 case '@': /* args */
3252 goto make_one_char_var;
Eric Andersen25f27032001-04-26 23:22:31 +00003253 case '{':
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003254 b_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003255 //sp: ctx->child->sp++;
Eric Andersen25f27032001-04-26 23:22:31 +00003256 b_getch(input);
3257 /* XXX maybe someone will try to escape the '}' */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003258 while (1) {
3259 ch = b_getch(input);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003260 if (ch == EOF) {
3261 syntax();
3262 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
3263 return 1;
3264 }
3265 if (ch == '}')
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003266 break;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003267 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003268 b_addchr(dest, ch | quote_mask);
3269 quote_mask = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003270 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003271 b_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003272 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003273#if ENABLE_HUSH_TICK
Eric Andersen25f27032001-04-26 23:22:31 +00003274 case '(':
Matt Kraai9f8caf12001-05-02 16:26:12 +00003275 b_getch(input);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003276 process_command_subs(dest, ctx, input, ")");
Eric Andersen25f27032001-04-26 23:22:31 +00003277 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003278#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003279 case '-':
3280 case '_':
3281 /* still unhandled, but should be eventually */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003282 bb_error_msg("unhandled syntax: $%c", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003283 return 1;
3284 break;
3285 default:
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003286 b_addqchr(dest, '$', dest->quote);
Eric Andersen25f27032001-04-26 23:22:31 +00003287 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003288 debug_printf_parse("handle_dollar return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003289 return 0;
3290}
3291
Eric Andersen25f27032001-04-26 23:22:31 +00003292/* return code is 0 for normal exit, 1 for syntax error */
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003293static int parse_stream(o_string *dest, struct p_context *ctx,
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003294 struct in_str *input, const char *end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00003295{
"Vladimir N. Oleynik"4ccd2b42006-01-31 09:27:48 +00003296 int ch, m;
Eric Andersen25f27032001-04-26 23:22:31 +00003297 int redir_fd;
3298 redir_type redir_style;
3299 int next;
3300
3301 /* Only double-quote state is handled in the state variable dest->quote.
3302 * A single-quote triggers a bypass of the main loop until its mate is
3303 * found. When recursing, quote state is passed in via dest->quote. */
3304
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003305 debug_printf_parse("parse_stream entered, end_trigger='%s'\n", end_trigger);
3306
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003307 while ((ch = b_getch(input)) != EOF) {
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003308 m = charmap[ch];
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003309 next = (ch == '\n') ? '\0' : b_peek(input);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003310 debug_printf_parse(": ch=%c (%d) m=%d quote=%d\n",
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003311 ch, ch, m, dest->quote);
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003312 if (m == CHAR_ORDINARY
3313 || (m != CHAR_SPECIAL && dest->quote)
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003314 ) {
Eric Andersen25f27032001-04-26 23:22:31 +00003315 b_addqchr(dest, ch, dest->quote);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003316 continue;
3317 }
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003318 if (m == CHAR_IFS) {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003319 if (done_word(dest, ctx)) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003320 debug_printf_parse("parse_stream return 1: done_word!=0\n");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003321 return 1;
Eric Andersenaac75e52001-04-30 18:18:45 +00003322 }
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003323 /* If we aren't performing a substitution, treat
3324 * a newline as a command separator.
3325 * [why we don't handle it exactly like ';'? --vda] */
3326 if (end_trigger && ch == '\n') {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003327 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003328 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003329 }
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003330 if ((end_trigger && strchr(end_trigger, ch))
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003331 && !dest->quote && ctx->res_w == RES_NONE
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003332 ) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003333 debug_printf_parse("parse_stream return 0: end_trigger char found\n");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003334 return 0;
3335 }
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003336 if (m == CHAR_IFS)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003337 continue;
3338 switch (ch) {
Eric Andersen25f27032001-04-26 23:22:31 +00003339 case '#':
3340 if (dest->length == 0 && !dest->quote) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003341 while (1) {
3342 ch = b_peek(input);
3343 if (ch == EOF || ch == '\n')
3344 break;
3345 b_getch(input);
3346 }
Eric Andersen25f27032001-04-26 23:22:31 +00003347 } else {
3348 b_addqchr(dest, ch, dest->quote);
3349 }
3350 break;
3351 case '\\':
3352 if (next == EOF) {
3353 syntax();
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003354 debug_printf_parse("parse_stream return 1: \\<eof>\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003355 return 1;
3356 }
3357 b_addqchr(dest, '\\', dest->quote);
3358 b_addqchr(dest, b_getch(input), dest->quote);
3359 break;
3360 case '$':
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003361 if (handle_dollar(dest, ctx, input) != 0) {
3362 debug_printf_parse("parse_stream return 1: handle_dollar returned non-0\n");
3363 return 1;
3364 }
Eric Andersen25f27032001-04-26 23:22:31 +00003365 break;
3366 case '\'':
3367 dest->nonnull = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003368 while (1) {
3369 ch = b_getch(input);
3370 if (ch == EOF || ch == '\'')
3371 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003372 b_addchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003373 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003374 if (ch == EOF) {
Eric Andersen25f27032001-04-26 23:22:31 +00003375 syntax();
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003376 debug_printf_parse("parse_stream return 1: unterminated '\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003377 return 1;
3378 }
3379 break;
3380 case '"':
3381 dest->nonnull = 1;
3382 dest->quote = !dest->quote;
3383 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003384#if ENABLE_HUSH_TICK
Eric Andersen25f27032001-04-26 23:22:31 +00003385 case '`':
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003386 process_command_subs(dest, ctx, input, "`");
Eric Andersen25f27032001-04-26 23:22:31 +00003387 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003388#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003389 case '>':
3390 redir_fd = redirect_opt_num(dest);
3391 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003392 redir_style = REDIRECT_OVERWRITE;
Eric Andersen25f27032001-04-26 23:22:31 +00003393 if (next == '>') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003394 redir_style = REDIRECT_APPEND;
Eric Andersen25f27032001-04-26 23:22:31 +00003395 b_getch(input);
3396 } else if (next == '(') {
3397 syntax(); /* until we support >(list) Process Substitution */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003398 debug_printf_parse("parse_stream return 1: >(process) not supported\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003399 return 1;
3400 }
3401 setup_redirect(ctx, redir_fd, redir_style, input);
3402 break;
3403 case '<':
3404 redir_fd = redirect_opt_num(dest);
3405 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003406 redir_style = REDIRECT_INPUT;
Eric Andersen25f27032001-04-26 23:22:31 +00003407 if (next == '<') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003408 redir_style = REDIRECT_HEREIS;
Eric Andersen25f27032001-04-26 23:22:31 +00003409 b_getch(input);
3410 } else if (next == '>') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003411 redir_style = REDIRECT_IO;
Eric Andersen25f27032001-04-26 23:22:31 +00003412 b_getch(input);
3413 } else if (next == '(') {
3414 syntax(); /* until we support <(list) Process Substitution */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003415 debug_printf_parse("parse_stream return 1: <(process) not supported\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003416 return 1;
3417 }
3418 setup_redirect(ctx, redir_fd, redir_style, input);
3419 break;
3420 case ';':
3421 done_word(dest, ctx);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003422 done_pipe(ctx, PIPE_SEQ);
Eric Andersen25f27032001-04-26 23:22:31 +00003423 break;
3424 case '&':
3425 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003426 if (next == '&') {
Eric Andersen25f27032001-04-26 23:22:31 +00003427 b_getch(input);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003428 done_pipe(ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00003429 } else {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003430 done_pipe(ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00003431 }
3432 break;
3433 case '|':
3434 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003435 if (next == '|') {
Eric Andersen25f27032001-04-26 23:22:31 +00003436 b_getch(input);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003437 done_pipe(ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00003438 } else {
3439 /* we could pick up a file descriptor choice here
3440 * with redirect_opt_num(), but bash doesn't do it.
3441 * "echo foo 2| cat" yields "foo 2". */
3442 done_command(ctx);
3443 }
3444 break;
3445 case '(':
3446 case '{':
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003447 if (parse_group(dest, ctx, input, ch) != 0) {
3448 debug_printf_parse("parse_stream return 1: parse_group returned non-0\n");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003449 return 1;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003450 }
Eric Andersen25f27032001-04-26 23:22:31 +00003451 break;
3452 case ')':
3453 case '}':
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003454 syntax(); /* Proper use of this character is caught by end_trigger */
3455 debug_printf_parse("parse_stream return 1: unexpected '}'\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003456 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003457 default:
3458 syntax(); /* this is really an internal logic error */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003459 debug_printf_parse("parse_stream return 1: internal logic error\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003460 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003461 }
3462 }
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003463 /* Complain if quote? No, maybe we just finished a command substitution
Eric Andersen25f27032001-04-26 23:22:31 +00003464 * that was quoted. Example:
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003465 * $ echo "`cat foo` plus more"
Eric Andersen25f27032001-04-26 23:22:31 +00003466 * and we just got the EOF generated by the subshell that ran "cat foo"
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003467 * The only real complaint is if we got an EOF when end_trigger != NULL,
Eric Andersen25f27032001-04-26 23:22:31 +00003468 * that is, we were really supposed to get end_trigger, and never got
3469 * one before the EOF. Can't use the standard "syntax error" return code,
3470 * so that parse_stream_outer can distinguish the EOF and exit smoothly. */
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003471 debug_printf_parse("parse_stream return %d\n", -(end_trigger != NULL));
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003472 if (end_trigger)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003473 return -1;
Eric Andersen25f27032001-04-26 23:22:31 +00003474 return 0;
3475}
3476
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003477static void set_in_charmap(const char *set, int code)
Eric Andersen25f27032001-04-26 23:22:31 +00003478{
Denis Vlasenkof5294e12007-04-14 10:09:57 +00003479 while (*set)
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003480 charmap[(unsigned char)*set++] = code;
Eric Andersen25f27032001-04-26 23:22:31 +00003481}
3482
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003483static void update_charmap(void)
Eric Andersen25f27032001-04-26 23:22:31 +00003484{
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003485 /* char *ifs and char charmap[256] are both globals. */
Eric Andersen25f27032001-04-26 23:22:31 +00003486 ifs = getenv("IFS");
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003487 if (ifs == NULL)
3488 ifs = " \t\n";
Eric Andersen25f27032001-04-26 23:22:31 +00003489 /* Precompute a list of 'flow through' behavior so it can be treated
3490 * quickly up front. Computation is necessary because of IFS.
3491 * Special case handling of IFS == " \t\n" is not implemented.
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003492 * The charmap[] array only really needs two bits each,
3493 * and on most machines that would be faster (reduced L1 cache use).
Eric Andersen25f27032001-04-26 23:22:31 +00003494 */
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003495 memset(charmap, CHAR_ORDINARY, sizeof(charmap));
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003496#if ENABLE_HUSH_TICK
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003497 set_in_charmap("\\$\"`", CHAR_SPECIAL);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003498#else
3499 set_in_charmap("\\$\"", CHAR_SPECIAL);
3500#endif
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003501 set_in_charmap("<>;&|(){}#'", CHAR_ORDINARY_IF_QUOTED);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003502 set_in_charmap(ifs, CHAR_IFS); /* are ordinary if quoted */
Eric Andersen25f27032001-04-26 23:22:31 +00003503}
3504
Eric Andersenaff114c2004-04-14 17:51:38 +00003505/* most recursion does not come through here, the exception is
Eric Andersen25f27032001-04-26 23:22:31 +00003506 * from builtin_source() */
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003507static int parse_stream_outer(struct in_str *inp, int parse_flag)
Eric Andersen25f27032001-04-26 23:22:31 +00003508{
Eric Andersen25f27032001-04-26 23:22:31 +00003509 struct p_context ctx;
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003510 o_string temp = NULL_O_STRING;
Eric Andersen25f27032001-04-26 23:22:31 +00003511 int rcode;
3512 do {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003513 ctx.parse_type = parse_flag;
Eric Andersen25f27032001-04-26 23:22:31 +00003514 initialize_context(&ctx);
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003515 update_charmap();
Denis Vlasenko219e88d2007-05-21 10:18:23 +00003516 if (!(parse_flag & PARSEFLAG_SEMICOLON) || (parse_flag & PARSEFLAG_REPARSING))
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003517 set_in_charmap(";$&|", CHAR_ORDINARY);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003518#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003519 inp->promptmode = 1;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003520#endif
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003521 /* We will stop & execute after each ';' or '\n'.
3522 * Example: "sleep 9999; echo TEST" + ctrl-C:
3523 * TEST should be printed */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003524 rcode = parse_stream(&temp, &ctx, inp, ";\n");
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003525 if (rcode != 1 && ctx.old_flag != 0) {
3526 syntax();
3527 }
3528 if (rcode != 1 && ctx.old_flag == 0) {
3529 done_word(&temp, &ctx);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003530 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003531 debug_print_tree(ctx.list_head, 0);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003532 debug_printf_exec("parse_stream_outer: run_list\n");
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003533 run_list(ctx.list_head);
3534 } else {
3535 if (ctx.old_flag != 0) {
3536 free(ctx.stack);
3537 b_reset(&temp);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003538 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003539 temp.nonnull = 0;
3540 temp.quote = 0;
3541 inp->p = NULL;
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00003542 free_pipe_list(ctx.list_head, 0);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003543 }
Eric Andersena813afc2001-05-24 16:19:36 +00003544 b_free(&temp);
Denis Vlasenko219e88d2007-05-21 10:18:23 +00003545 } while (rcode != -1 && !(parse_flag & PARSEFLAG_EXIT_FROM_LOOP)); /* loop on syntax errors, return on EOF */
Eric Andersen25f27032001-04-26 23:22:31 +00003546 return 0;
3547}
3548
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003549static int parse_string_outer(const char *s, int parse_flag)
Eric Andersen25f27032001-04-26 23:22:31 +00003550{
3551 struct in_str input;
3552 setup_string_in_str(&input, s);
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003553 return parse_stream_outer(&input, parse_flag);
Eric Andersen25f27032001-04-26 23:22:31 +00003554}
3555
3556static int parse_file_outer(FILE *f)
3557{
3558 int rcode;
3559 struct in_str input;
3560 setup_file_in_str(&input, f);
Denis Vlasenko219e88d2007-05-21 10:18:23 +00003561 rcode = parse_stream_outer(&input, PARSEFLAG_SEMICOLON);
Eric Andersen25f27032001-04-26 23:22:31 +00003562 return rcode;
3563}
3564
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003565#if ENABLE_HUSH_JOB
Eric Andersen6c947d22001-06-25 22:24:38 +00003566/* Make sure we have a controlling tty. If we get started under a job
3567 * aware app (like bash for example), make sure we are now in charge so
3568 * we don't fight over who gets the foreground */
Eric Anderseneaecbf32001-10-31 10:41:31 +00003569static void setup_job_control(void)
Eric Andersen52a97ca2001-06-22 06:49:26 +00003570{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003571 pid_t shell_pgrp;
3572
Denis Vlasenkoa6a17852007-04-28 16:42:11 +00003573 saved_task_pgrp = shell_pgrp = getpgrp();
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003574 debug_printf_jobs("saved_task_pgrp=%d\n", saved_task_pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003575 fcntl(interactive_fd, F_SETFD, FD_CLOEXEC);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003576
Denis Vlasenkoa6a17852007-04-28 16:42:11 +00003577 /* If we were ran as 'hush &',
3578 * sleep until we are in the foreground. */
3579 while (tcgetpgrp(interactive_fd) != shell_pgrp) {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003580 /* Send TTIN to ourself (should stop us) */
Denis Vlasenkoff131b92007-04-10 15:42:06 +00003581 kill(- shell_pgrp, SIGTTIN);
Denis Vlasenkoa6a17852007-04-28 16:42:11 +00003582 shell_pgrp = getpgrp();
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003583 }
Eric Andersen52a97ca2001-06-22 06:49:26 +00003584
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003585 /* Ignore job-control and misc signals. */
3586 set_jobctrl_sighandler(SIG_IGN);
3587 set_misc_sighandler(SIG_IGN);
3588//huh? signal(SIGCHLD, SIG_IGN);
3589
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003590 /* We _must_ restore tty pgrp on fatal signals */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003591 set_fatal_sighandler(sigexit);
Eric Andersen6c947d22001-06-25 22:24:38 +00003592
3593 /* Put ourselves in our own process group. */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003594 setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
Eric Andersen6c947d22001-06-25 22:24:38 +00003595 /* Grab control of the terminal. */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003596 tcsetpgrp(interactive_fd, getpid());
Eric Andersen6c947d22001-06-25 22:24:38 +00003597}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003598#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00003599
Denis Vlasenko06af2162007-02-03 17:28:39 +00003600int hush_main(int argc, char **argv);
Matt Kraai2d91deb2001-08-01 17:21:35 +00003601int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00003602{
3603 int opt;
3604 FILE *input;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003605 char **e;
Eric Andersenbc604a22001-05-16 05:24:03 +00003606
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00003607 PTR_TO_GLOBALS = xzalloc(sizeof(G));
3608 top_vars = &shell_ver;
3609 shell_ver = const_shell_ver; /* copying struct here */
3610
Denis Vlasenko38f63192007-01-22 09:03:07 +00003611#if ENABLE_FEATURE_EDITING
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00003612 line_input_state = new_line_input_t(FOR_SHELL);
3613#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003614 /* XXX what should these be while sourcing /etc/profile? */
3615 global_argc = argc;
3616 global_argv = argv;
Eric Andersen94ac2442001-05-22 19:05:18 +00003617 /* Initialize some more globals to non-zero values */
3618 set_cwd();
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003619#if ENABLE_HUSH_INTERACTIVE
3620#if ENABLE_FEATURE_EDITING
3621 cmdedit_set_initial_prompt();
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003622#endif
Eric Andersen94ac2442001-05-22 19:05:18 +00003623 PS2 = "> ";
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003624#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00003625
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003626 /* initialize our shell local variables with the values
Eric Andersen94ac2442001-05-22 19:05:18 +00003627 * currently living in the environment */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003628 e = environ;
3629 if (e)
3630 while (*e)
3631 set_local_var(*e++, 2); /* without call putenv() */
Eric Andersen94ac2442001-05-22 19:05:18 +00003632
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003633 last_return_code = EXIT_SUCCESS;
Eric Andersen25f27032001-04-26 23:22:31 +00003634
3635 if (argv[0] && argv[0][0] == '-') {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003636 debug_printf("sourcing /etc/profile\n");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003637 input = fopen("/etc/profile", "r");
3638 if (input != NULL) {
Eric Andersena90f20b2001-06-26 23:00:21 +00003639 mark_open(fileno(input));
3640 parse_file_outer(input);
3641 mark_closed(fileno(input));
3642 fclose(input);
3643 }
Eric Andersen25f27032001-04-26 23:22:31 +00003644 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003645 input = stdin;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003646
Eric Andersen25f27032001-04-26 23:22:31 +00003647 while ((opt = getopt(argc, argv, "c:xif")) > 0) {
3648 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003649 case 'c':
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003650 global_argv = argv + optind;
3651 global_argc = argc - optind;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00003652 opt = parse_string_outer(optarg, PARSEFLAG_SEMICOLON);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003653 goto final_return;
3654 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003655 /* Well, we cannot just declare interactiveness,
3656 * we have to have some stuff (ctty, etc) */
3657 /* interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003658 break;
3659 case 'f':
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00003660 fake_mode = 1;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003661 break;
3662 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00003663#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003664 fprintf(stderr, "Usage: sh [FILE]...\n"
3665 " or: sh -c command [args]...\n\n");
3666 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00003667#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003668 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00003669#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003670 }
3671 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003672#if ENABLE_HUSH_JOB
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003673 /* A shell is interactive if the '-i' flag was given, or if all of
Eric Andersen25f27032001-04-26 23:22:31 +00003674 * the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00003675 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00003676 * no arguments remaining or the -s flag given
3677 * standard input is a terminal
3678 * standard output is a terminal
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003679 * Refer to Posix.2, the description of the 'sh' utility. */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003680 if (argv[optind] == NULL && input == stdin
3681 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3682 ) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003683 saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
3684 debug_printf("saved_tty_pgrp=%d\n", saved_tty_pgrp);
3685 if (saved_tty_pgrp >= 0) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003686 /* try to dup to high fd#, >= 255 */
3687 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3688 if (interactive_fd < 0) {
3689 /* try to dup to any fd */
3690 interactive_fd = dup(STDIN_FILENO);
3691 if (interactive_fd < 0)
3692 /* give up */
3693 interactive_fd = 0;
3694 }
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00003695 // TODO: track & disallow any attempts of user
3696 // to (inadvertently) close/redirect it
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003697 }
Eric Andersen25f27032001-04-26 23:22:31 +00003698 }
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003699 debug_printf("interactive_fd=%d\n", interactive_fd);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003700 if (interactive_fd) {
Eric Andersen25f27032001-04-26 23:22:31 +00003701 /* Looks like they want an interactive shell */
Eric Andersen52a97ca2001-06-22 06:49:26 +00003702 setup_job_control();
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003703 /* Make xfuncs do cleanup on exit */
3704 die_sleep = -1; /* flag */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003705// FIXME: should we reset die_sleep = 0 whereever we fork?
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003706 if (setjmp(die_jmp)) {
3707 /* xfunc has failed! die die die */
3708 hush_exit(xfunc_error_retval);
3709 }
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00003710#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denis Vlasenkoef36ead2007-05-02 15:34:47 +00003711 printf("\n\n%s hush - the humble shell v"HUSH_VER_STR"\n", BB_BANNER);
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00003712 printf("Enter 'help' for a list of built-in commands.\n\n");
3713#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00003714 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003715#elif ENABLE_HUSH_INTERACTIVE
3716/* no job control compiled, only prompt/line editing */
3717 if (argv[optind] == NULL && input == stdin
3718 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3719 ) {
3720 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3721 if (interactive_fd < 0) {
3722 /* try to dup to any fd */
3723 interactive_fd = dup(STDIN_FILENO);
3724 if (interactive_fd < 0)
3725 /* give up */
3726 interactive_fd = 0;
3727 }
3728 }
3729
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003730#endif
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003731
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003732 if (argv[optind] == NULL) {
3733 opt = parse_file_outer(stdin);
Eric Andersene67c3ce2001-05-02 02:09:36 +00003734 goto final_return;
Eric Andersen25f27032001-04-26 23:22:31 +00003735 }
Eric Andersen25f27032001-04-26 23:22:31 +00003736
3737 debug_printf("\nrunning script '%s'\n", argv[optind]);
Denis Vlasenko4c978632007-02-03 03:31:13 +00003738 global_argv = argv + optind;
3739 global_argc = argc - optind;
Rob Landleyd921b2e2006-08-03 15:41:12 +00003740 input = xfopen(argv[optind], "r");
Eric Andersen25f27032001-04-26 23:22:31 +00003741 opt = parse_file_outer(input);
3742
Denis Vlasenko38f63192007-01-22 09:03:07 +00003743#if ENABLE_FEATURE_CLEAN_UP
Eric Andersenaeb44c42001-05-22 20:29:00 +00003744 fclose(input);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003745 if (cwd != bb_msg_unknown)
Eric Andersenaeb44c42001-05-22 20:29:00 +00003746 free((char*)cwd);
3747 {
3748 struct variables *cur, *tmp;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003749 for (cur = top_vars; cur; cur = tmp) {
Eric Andersenaeb44c42001-05-22 20:29:00 +00003750 tmp = cur->next;
3751 if (!cur->flg_read_only) {
Denis Vlasenko4c978632007-02-03 03:31:13 +00003752 free((char*)cur->name);
3753 free((char*)cur->value);
Eric Andersenaeb44c42001-05-22 20:29:00 +00003754 free(cur);
3755 }
3756 }
3757 }
Eric Andersen25f27032001-04-26 23:22:31 +00003758#endif
3759
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003760 final_return:
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003761 hush_exit(opt ? opt : last_return_code);
Eric Andersen25f27032001-04-26 23:22:31 +00003762}