blob: f81203e2bc2494c6192c4d06ca43b507b89a5576 [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:
Denis Vlasenkoa8442002008-06-14 11:00:17 +000023 * o_addchr() derived from similar w_addchar function in glibc-2.2.
Eric Andersen25f27032001-04-26 23:22:31 +000024 * 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
Denis Vlasenkoa8442002008-06-14 11:00:17 +000026 * miscellaneous bugfixes from Matt Kraai.
Eric Andersen25f27032001-04-26 23:22:31 +000027 *
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?)
Eric Andersen25f27032001-04-26 23:22:31 +000040 * $_
Eric Andersen25f27032001-04-26 23:22:31 +000041 * &> and >& redirection of stdout+stderr
42 * Brace Expansion
43 * Tilde Expansion
44 * fancy forms of Parameter Expansion
Eric Andersen78a7c992001-05-15 16:30:25 +000045 * aliases
Eric Andersen25f27032001-04-26 23:22:31 +000046 * Arithmetic Expansion
47 * <(list) and >(list) Process Substitution
Eric Andersen83a2ae22001-05-07 17:59:25 +000048 * reserved words: case, esac, select, function
Eric Andersen25f27032001-04-26 23:22:31 +000049 * Here Documents ( << word )
50 * Functions
51 * Major bugs:
Denis Vlasenkob81b3df2007-04-28 16:48:04 +000052 * job handling woefully incomplete and buggy (improved --vda)
Eric Andersen25f27032001-04-26 23:22:31 +000053 * reserved word execution woefully incomplete and buggy
Eric Andersen25f27032001-04-26 23:22:31 +000054 * to-do:
Eric Andersen83a2ae22001-05-07 17:59:25 +000055 * port selected bugfixes from post-0.49 busybox lash - done?
Eric Andersen83a2ae22001-05-07 17:59:25 +000056 * change { and } from special chars to reserved words
57 * builtins: break, continue, eval, return, set, trap, ulimit
58 * test magic exec
Eric Andersen25f27032001-04-26 23:22:31 +000059 * check setting of global_argc and global_argv
Eric Andersen25f27032001-04-26 23:22:31 +000060 * follow IFS rules more precisely, including update semantics
Eric Andersen25f27032001-04-26 23:22:31 +000061 * figure out what to do with backslash-newline
Eric Andersen25f27032001-04-26 23:22:31 +000062 * propagate syntax errors, die on resource errors?
63 * continuation lines, both explicit and implicit - done?
64 * memory leak finding and plugging - done?
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +000065 * maybe change charmap[] to use 2-bit entries
Eric Andersen25f27032001-04-26 23:22:31 +000066 *
Bernhard Reutner-Fischer86f5c992006-01-22 22:55:11 +000067 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
Eric Andersen25f27032001-04-26 23:22:31 +000068 */
Bernhard Reutner-Fischere15d7572006-06-02 20:56:16 +000069
Denis Vlasenkob6adbf12007-05-26 19:00:18 +000070
Eric Andersen25f27032001-04-26 23:22:31 +000071#include <glob.h> /* glob, of course */
Eric Andersen25f27032001-04-26 23:22:31 +000072/* #include <dmalloc.h> */
Denis Vlasenkob6adbf12007-05-26 19:00:18 +000073
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000074#include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
Denis Vlasenkob6adbf12007-05-26 19:00:18 +000075
Denis Vlasenkod01ff132007-05-02 21:40:23 +000076
Denis Vlasenko05743d72008-02-10 12:10:08 +000077#if !BB_MMU && ENABLE_HUSH_TICK
78//#undef ENABLE_HUSH_TICK
79//#define ENABLE_HUSH_TICK 0
80#warning On NOMMU, hush command substitution is dangerous.
81#warning Dont use it for commands which produce lots of output.
82#warning For more info see shell/hush.c, generate_stream_from_list().
83#endif
84
85#if !BB_MMU && ENABLE_HUSH_JOB
86#undef ENABLE_HUSH_JOB
87#define ENABLE_HUSH_JOB 0
88#endif
89
90#if !ENABLE_HUSH_INTERACTIVE
91#undef ENABLE_FEATURE_EDITING
92#define ENABLE_FEATURE_EDITING 0
93#undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
94#define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +000095#endif
96
97
Denis Vlasenkod01ff132007-05-02 21:40:23 +000098/* If you comment out one of these below, it will be #defined later
99 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000100#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000101/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000102#define debug_printf_parse(...) do {} while (0)
103#define debug_print_tree(a, b) do {} while (0)
104#define debug_printf_exec(...) do {} while (0)
105#define debug_printf_jobs(...) do {} while (0)
106#define debug_printf_expand(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000107#define debug_printf_glob(...) do {} while (0)
108#define debug_printf_list(...) do {} while (0)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000109#define debug_printf_subst(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000110#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000111
112#ifndef debug_printf
113#define debug_printf(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000114#endif
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000115
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000116#ifndef debug_printf_parse
117#define debug_printf_parse(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000118#endif
119
120#ifndef debug_printf_exec
121#define debug_printf_exec(...) fprintf(stderr, __VA_ARGS__)
122#endif
123
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000124#ifndef debug_printf_jobs
125#define debug_printf_jobs(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000126#define DEBUG_JOBS 1
127#else
128#define DEBUG_JOBS 0
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000129#endif
130
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000131#ifndef debug_printf_expand
132#define debug_printf_expand(...) fprintf(stderr, __VA_ARGS__)
133#define DEBUG_EXPAND 1
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000134#else
135#define DEBUG_EXPAND 0
136#endif
137
138#ifndef debug_printf_glob
139#define debug_printf_glob(...) fprintf(stderr, __VA_ARGS__)
140#define DEBUG_GLOB 1
141#else
142#define DEBUG_GLOB 0
143#endif
144
145#ifndef debug_printf_list
146#define debug_printf_list(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000147#endif
148
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000149#ifndef debug_printf_subst
150#define debug_printf_subst(...) fprintf(stderr, __VA_ARGS__)
151#endif
152
Denis Vlasenko170435c2007-05-23 13:01:10 +0000153/* Keep unconditionally on for now */
154#define ENABLE_HUSH_DEBUG 1
155
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000156#ifndef debug_printf_clean
157/* broken, of course, but OK for testing */
158static const char *indenter(int i)
159{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000160 static const char blanks[] ALIGN1 =
161 " ";
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000162 return &blanks[sizeof(blanks) - i - 1];
163}
164#define debug_printf_clean(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkoc666f712007-05-16 22:18:54 +0000165#define DEBUG_CLEAN 1
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +0000166#endif
167
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000168#if DEBUG_EXPAND
169static void debug_print_strings(const char *prefix, char **vv)
170{
171 fprintf(stderr, "%s:\n", prefix);
172 while (*vv)
173 fprintf(stderr, " '%s'\n", *vv++);
174}
175#else
176#define debug_print_strings(prefix, vv) ((void)0)
177#endif
178
Eric Andersen25f27032001-04-26 23:22:31 +0000179
Denis Vlasenkof962a032007-11-23 12:50:54 +0000180/*
181 * Leak hunting. Use hush_leaktool.sh for post-processing.
182 */
183#ifdef FOR_HUSH_LEAKTOOL
Denis Vlasenkoccce59d2008-06-16 14:35:57 +0000184/* suppress "warning: no previous prototype..." */
185void *xxmalloc(int lineno, size_t size);
186void *xxrealloc(int lineno, void *ptr, size_t size);
187char *xxstrdup(int lineno, const char *str);
188void xxfree(void *ptr);
Denis Vlasenkof962a032007-11-23 12:50:54 +0000189void *xxmalloc(int lineno, size_t size)
190{
191 void *ptr = xmalloc((size + 0xff) & ~0xff);
192 fprintf(stderr, "line %d: malloc %p\n", lineno, ptr);
193 return ptr;
194}
195void *xxrealloc(int lineno, void *ptr, size_t size)
196{
197 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
198 fprintf(stderr, "line %d: realloc %p\n", lineno, ptr);
199 return ptr;
200}
201char *xxstrdup(int lineno, const char *str)
202{
203 char *ptr = xstrdup(str);
204 fprintf(stderr, "line %d: strdup %p\n", lineno, ptr);
205 return ptr;
206}
207void xxfree(void *ptr)
208{
209 fprintf(stderr, "free %p\n", ptr);
210 free(ptr);
211}
212#define xmalloc(s) xxmalloc(__LINE__, s)
213#define xrealloc(p, s) xxrealloc(__LINE__, p, s)
214#define xstrdup(s) xxstrdup(__LINE__, s)
215#define free(p) xxfree(p)
216#endif
217
218
Denis Vlasenko5703c222008-06-15 11:49:42 +0000219#define SPECIAL_VAR_SYMBOL 3
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000220#define PARSEFLAG_EXIT_FROM_LOOP 1
Eric Andersen25f27032001-04-26 23:22:31 +0000221
222typedef enum {
223 REDIRECT_INPUT = 1,
224 REDIRECT_OVERWRITE = 2,
225 REDIRECT_APPEND = 3,
226 REDIRECT_HEREIS = 4,
227 REDIRECT_IO = 5
228} redir_type;
229
230/* The descrip member of this structure is only used to make debugging
231 * output pretty */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +0000232static const struct {
233 int mode;
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000234 signed char default_fd;
235 char descrip[3];
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +0000236} redir_table[] = {
Eric Andersen25f27032001-04-26 23:22:31 +0000237 { 0, 0, "()" },
238 { O_RDONLY, 0, "<" },
239 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
240 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
241 { O_RDONLY, -1, "<<" },
242 { O_RDWR, 1, "<>" }
243};
244
245typedef enum {
246 PIPE_SEQ = 1,
247 PIPE_AND = 2,
248 PIPE_OR = 3,
249 PIPE_BG = 4,
250} pipe_style;
251
Eric Andersen25f27032001-04-26 23:22:31 +0000252typedef enum {
253 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000254#if ENABLE_HUSH_IF
Eric Andersen25f27032001-04-26 23:22:31 +0000255 RES_IF = 1,
256 RES_THEN = 2,
257 RES_ELIF = 3,
258 RES_ELSE = 4,
259 RES_FI = 5,
Denis Vlasenko06810332007-05-21 23:30:54 +0000260#endif
261#if ENABLE_HUSH_LOOPS
Eric Andersen25f27032001-04-26 23:22:31 +0000262 RES_FOR = 6,
263 RES_WHILE = 7,
264 RES_UNTIL = 8,
265 RES_DO = 9,
266 RES_DONE = 10,
Denis Vlasenko06810332007-05-21 23:30:54 +0000267 RES_IN = 11,
268#endif
269 RES_XXXX = 12,
Eric Andersen4c9b68f2002-04-13 12:33:41 +0000270 RES_SNTX = 13
Eric Andersen25f27032001-04-26 23:22:31 +0000271} reserved_style;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000272
Eric Andersen25f27032001-04-26 23:22:31 +0000273/* This holds pointers to the various results of parsing */
274struct p_context {
275 struct child_prog *child;
276 struct pipe *list_head;
277 struct pipe *pipe;
278 struct redir_struct *pending_redirect;
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000279 smallint res_w;
Denis Vlasenkoa8442002008-06-14 11:00:17 +0000280 smallint ctx_inverted; /* "! cmd | cmd" */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000281 int old_flag; /* bitmask of FLAG_xxx, for figuring out valid reserved words */
Eric Andersen25f27032001-04-26 23:22:31 +0000282 struct p_context *stack;
Eric Andersen25f27032001-04-26 23:22:31 +0000283};
284
285struct redir_struct {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000286 struct redir_struct *next; /* pointer to the next redirect in the list */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000287 redir_type type; /* type of redirection */
288 int fd; /* file descriptor being redirected */
289 int dup; /* -1, or file descriptor being duplicated */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +0000290 char *rd_filename; /* filename */
Eric Andersen25f27032001-04-26 23:22:31 +0000291};
292
293struct child_prog {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000294 pid_t pid; /* 0 if exited */
295 char **argv; /* program name and arguments */
296 struct pipe *group; /* if non-NULL, first in group or subshell */
Denis Vlasenko262d7652007-05-20 21:52:49 +0000297 smallint subshell; /* flag, non-zero if group must be forked */
298 smallint is_stopped; /* is the program currently running? */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000299 struct redir_struct *redirects; /* I/O redirections */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000300 struct pipe *family; /* pointer back to the child's parent pipe */
Eric Andersen25f27032001-04-26 23:22:31 +0000301};
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000302/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
303 * and on execution these are substituted with their values.
304 * Substitution can make _several_ words out of one argv[n]!
305 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000306 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000307 */
Eric Andersen25f27032001-04-26 23:22:31 +0000308
309struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000310 struct pipe *next;
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000311 int num_progs; /* total number of programs in job */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000312 int running_progs; /* number of programs running (not exited) */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000313 int stopped_progs; /* number of programs alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000314#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000315 int jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000316 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000317 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000318#endif
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000319 char *cmdbuf; /* buffer various argv's point into */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000320 struct child_prog *progs; /* array of commands in pipe */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000321 int job_context; /* bitmask defining current context */
Denis Vlasenkoa8442002008-06-14 11:00:17 +0000322 smallint pi_inverted; /* "! cmd | cmd" */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000323 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
324 smallint res_word; /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000325};
326
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000327/* On program start, environ points to initial environment.
328 * putenv adds new pointers into it, unsetenv removes them.
329 * Neither of these (de)allocates the strings.
330 * setenv allocates new strings in malloc space and does putenv,
331 * and thus setenv is unusable (leaky) for shell's purposes */
332#define setenv(...) setenv_is_leaky_dont_use()
333struct variable {
334 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000335 char *varstr; /* points to "name=" portion */
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000336 int max_len; /* if > 0, name is part of initial env; else name is malloced */
337 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000338 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000339};
340
Eric Andersen25f27032001-04-26 23:22:31 +0000341typedef struct {
342 char *data;
343 int length;
344 int maxlen;
Denis Vlasenkoff097622007-10-01 10:00:45 +0000345 smallint o_quote;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000346 smallint o_glob;
Denis Vlasenkoff097622007-10-01 10:00:45 +0000347 smallint nonnull;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000348 smallint has_empty_slot;
Eric Andersen25f27032001-04-26 23:22:31 +0000349} o_string;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000350/* Used for initialization: o_string foo = NULL_O_STRING; */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000351#define NULL_O_STRING { NULL }
Eric Andersen25f27032001-04-26 23:22:31 +0000352
353/* I can almost use ordinary FILE *. Is open_memstream() universally
354 * available? Where is it documented? */
355struct in_str {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +0000356 const char *p;
357 /* eof_flag=1: last char in ->p is really an EOF */
358 char eof_flag; /* meaningless if ->p == NULL */
359 char peek_buf[2];
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000360#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000361 smallint promptme;
362 smallint promptmode; /* 0: PS1, 1: PS2 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000363#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000364 FILE *file;
365 int (*get) (struct in_str *);
366 int (*peek) (struct in_str *);
367};
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000368#define i_getch(input) ((input)->get(input))
369#define i_peek(input) ((input)->peek(input))
Eric Andersen25f27032001-04-26 23:22:31 +0000370
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000371enum {
372 CHAR_ORDINARY = 0,
373 CHAR_ORDINARY_IF_QUOTED = 1, /* example: *, # */
374 CHAR_IFS = 2, /* treated as ordinary if quoted */
375 CHAR_SPECIAL = 3, /* example: $ */
Eric Andersen25f27032001-04-26 23:22:31 +0000376};
377
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000378#define HUSH_VER_STR "0.02"
379
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000380/* "Globals" within this file */
381
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000382/* Sorted roughly by size (smaller offsets == smaller code) */
383struct globals {
384#if ENABLE_HUSH_INTERACTIVE
385 /* 'interactive_fd' is a fd# open to ctty, if we have one
386 * _AND_ if we decided to act interactively */
387 int interactive_fd;
388 const char *PS1;
389 const char *PS2;
390#endif
391#if ENABLE_FEATURE_EDITING
392 line_input_t *line_input_state;
393#endif
394#if ENABLE_HUSH_JOB
395 int run_list_level;
396 pid_t saved_task_pgrp;
397 pid_t saved_tty_pgrp;
Denis Vlasenko16c2fea2008-06-17 12:28:44 +0000398 pid_t root_pid;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000399 int last_jobid;
400 struct pipe *job_list;
401 struct pipe *toplevel_list;
402 smallint ctrl_z_flag;
403#endif
404 smallint fake_mode;
405 /* these three support $?, $#, and $1 */
406 char **global_argv;
407 int global_argc;
408 int last_return_code;
409 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000410 const char *cwd;
411 unsigned last_bg_pid;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +0000412 struct variable *top_var; /* = &shell_ver (set in main()) */
413 struct variable shell_ver;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000414#if ENABLE_FEATURE_SH_STANDALONE
415 struct nofork_save_area nofork_save;
416#endif
417#if ENABLE_HUSH_JOB
418 sigjmp_buf toplevel_jb;
419#endif
420 unsigned char charmap[256];
421 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
422};
423
424#define G (*ptr_to_globals)
425
426#if !ENABLE_HUSH_INTERACTIVE
427enum { interactive_fd = 0 };
428#endif
429#if !ENABLE_HUSH_JOB
430enum { run_list_level = 0 };
431#endif
432
433#if ENABLE_HUSH_INTERACTIVE
434#define interactive_fd (G.interactive_fd )
435#define PS1 (G.PS1 )
436#define PS2 (G.PS2 )
437#endif
438#if ENABLE_FEATURE_EDITING
439#define line_input_state (G.line_input_state)
440#endif
441#if ENABLE_HUSH_JOB
442#define run_list_level (G.run_list_level )
443#define saved_task_pgrp (G.saved_task_pgrp )
444#define saved_tty_pgrp (G.saved_tty_pgrp )
Denis Vlasenko16c2fea2008-06-17 12:28:44 +0000445#define root_pid (G.root_pid )
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000446#define last_jobid (G.last_jobid )
447#define job_list (G.job_list )
448#define toplevel_list (G.toplevel_list )
449#define toplevel_jb (G.toplevel_jb )
450#define ctrl_z_flag (G.ctrl_z_flag )
451#endif /* JOB */
452#define global_argv (G.global_argv )
453#define global_argc (G.global_argc )
454#define last_return_code (G.last_return_code)
455#define ifs (G.ifs )
456#define fake_mode (G.fake_mode )
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000457#define cwd (G.cwd )
458#define last_bg_pid (G.last_bg_pid )
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000459#define top_var (G.top_var )
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000460#define shell_ver (G.shell_ver )
461#if ENABLE_FEATURE_SH_STANDALONE
462#define nofork_save (G.nofork_save )
Denis Vlasenko4b924f32007-05-30 00:29:55 +0000463#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000464#if ENABLE_HUSH_JOB
465#define toplevel_jb (G.toplevel_jb )
466#endif
467#define charmap (G.charmap )
468#define user_input_buf (G.user_input_buf )
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000469#define INIT_G() do { \
470 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
471} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000472
473
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000474#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
475
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000476#if 1
477/* Normal */
478static void syntax(const char *msg)
479{
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000480 /* Was using fancy stuff:
481 * (interactive_fd ? bb_error_msg : bb_error_msg_and_die)(...params...)
482 * but it SEGVs. ?! Oh well... explicit temp ptr works around that */
483 void (*fp)(const char *s, ...);
484
485 fp = (interactive_fd ? bb_error_msg : bb_error_msg_and_die);
486 fp(msg ? "%s: %s" : "syntax error", "syntax error", msg);
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000487}
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000488
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000489#else
490/* Debug */
491static void syntax_lineno(int line)
Denis Vlasenkob6aae0f2007-01-29 22:51:25 +0000492{
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000493 void (*fp)(const char *s, ...);
494
495 fp = (interactive_fd ? bb_error_msg : bb_error_msg_and_die);
496 fp("syntax error hush.c:%d", line);
Eric Andersen25f27032001-04-26 23:22:31 +0000497}
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000498#define syntax(str) syntax_lineno(__LINE__)
499#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000500
501/* Index of subroutines: */
Eric Andersen25f27032001-04-26 23:22:31 +0000502/* in_str manipulations: */
503static int static_get(struct in_str *i);
504static int static_peek(struct in_str *i);
505static int file_get(struct in_str *i);
506static int file_peek(struct in_str *i);
507static void setup_file_in_str(struct in_str *i, FILE *f);
508static void setup_string_in_str(struct in_str *i, const char *s);
Eric Andersen25f27032001-04-26 23:22:31 +0000509/* "run" the final data structures: */
Denis Vlasenkoc666f712007-05-16 22:18:54 +0000510#if !defined(DEBUG_CLEAN)
511#define free_pipe_list(head, indent) free_pipe_list(head)
512#define free_pipe(pi, indent) free_pipe(pi)
513#endif
Eric Andersenbf7df042001-05-23 22:18:35 +0000514static int free_pipe_list(struct pipe *head, int indent);
515static int free_pipe(struct pipe *pi, int indent);
Eric Andersen25f27032001-04-26 23:22:31 +0000516/* really run the final data structures: */
517static int setup_redirects(struct child_prog *prog, int squirrel[]);
Denis Vlasenko05743d72008-02-10 12:10:08 +0000518static int run_list(struct pipe *pi);
Denis Vlasenko76d50412008-06-10 16:19:39 +0000519#if BB_MMU
520#define pseudo_exec_argv(ptrs2free, argv) pseudo_exec_argv(argv)
521#define pseudo_exec(ptrs2free, child) pseudo_exec(child)
522#endif
523static void pseudo_exec_argv(char **ptrs2free, char **argv) ATTRIBUTE_NORETURN;
524static void pseudo_exec(char **ptrs2free, struct child_prog *child) ATTRIBUTE_NORETURN;
Denis Vlasenko05743d72008-02-10 12:10:08 +0000525static int run_pipe(struct pipe *pi);
Eric Andersen25f27032001-04-26 23:22:31 +0000526/* data structure manipulation: */
527static int setup_redirect(struct p_context *ctx, int fd, redir_type style, struct in_str *input);
528static void initialize_context(struct p_context *ctx);
529static int done_word(o_string *dest, struct p_context *ctx);
530static int done_command(struct p_context *ctx);
Denis Vlasenkoa8442002008-06-14 11:00:17 +0000531static void done_pipe(struct p_context *ctx, pipe_style type);
Eric Andersen25f27032001-04-26 23:22:31 +0000532/* primary string parsing: */
533static int redirect_dup_num(struct in_str *input);
534static int redirect_opt_num(o_string *o);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +0000535#if ENABLE_HUSH_TICK
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000536static int process_command_subs(o_string *dest,
Denis Vlasenko68404f12008-03-17 09:00:54 +0000537 struct in_str *input, const char *subst_end);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +0000538#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000539static int parse_group(o_string *dest, struct p_context *ctx, struct in_str *input, int ch);
Denis Vlasenko15d78fb2007-01-30 22:28:21 +0000540static const char *lookup_param(const char *src);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000541static int handle_dollar(o_string *dest,
Denis Vlasenko68404f12008-03-17 09:00:54 +0000542 struct in_str *input);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +0000543static 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 +0000544/* setup: */
Denis Vlasenko170435c2007-05-23 13:01:10 +0000545static int parse_and_run_stream(struct in_str *inp, int parse_flag);
546static int parse_and_run_string(const char *s, int parse_flag);
547static int parse_and_run_file(FILE *f);
Eric Andersenbafd94f2001-05-02 16:11:59 +0000548/* job management: */
Eric Andersenc798b072001-06-22 06:23:03 +0000549static int checkjobs(struct pipe* fg_pipe);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000550#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +0000551static int checkjobs_and_fg_shell(struct pipe* fg_pipe);
Eric Andersenbafd94f2001-05-02 16:11:59 +0000552static void insert_bg_job(struct pipe *pi);
553static void remove_bg_job(struct pipe *pi);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000554static void delete_finished_bg_job(struct pipe *pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000555#else
556int checkjobs_and_fg_shell(struct pipe* fg_pipe); /* never called */
557#endif
Eric Andersenf72f5622001-05-15 23:21:41 +0000558/* local variable support */
Denis Vlasenko170435c2007-05-23 13:01:10 +0000559static char **expand_strvec_to_strvec(char **argv);
560/* used for eval */
561static char *expand_strvec_to_string(char **argv);
Denis Vlasenkob6a741f2007-05-17 14:38:17 +0000562/* used for expansion of right hand of assignments */
Denis Vlasenko170435c2007-05-23 13:01:10 +0000563static char *expand_string_to_string(const char *str);
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000564static struct variable *get_local_var(const char *name);
565static int set_local_var(char *str, int flg_export);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +0000566static void unset_local_var(const char *name);
Eric Andersen25f27032001-04-26 23:22:31 +0000567
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000568
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000569static int glob_needed(const char *s)
570{
571 while (*s) {
572 if (*s == '\\')
573 s++;
574 if (*s == '*' || *s == '[' || *s == '?')
575 return 1;
576 s++;
577 }
578 return 0;
579}
580
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000581static int is_assignment(const char *s)
582{
583 if (!s || !isalpha(*s))
584 return 0;
585 s++;
586 while (isalnum(*s) || *s == '_')
587 s++;
588 return *s == '=';
589}
590
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000591static char **add_malloced_strings_to_strings(char **strings, char **add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000592{
593 int i;
594 unsigned count1;
595 unsigned count2;
596 char **v;
597
598 v = strings;
599 count1 = 0;
600 if (v) {
601 while (*v) {
602 count1++;
603 v++;
604 }
605 }
606 count2 = 0;
607 v = add;
608 while (*v) {
609 count2++;
610 v++;
611 }
612 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
613 v[count1 + count2] = NULL;
614 i = count2;
615 while (--i >= 0)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000616 v[count1 + i] = add[i];
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000617 return v;
618}
619
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000620static char **add_malloced_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000621{
622 char *v[2];
623
624 v[0] = add;
625 v[1] = NULL;
626
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000627 return add_malloced_strings_to_strings(strings, v);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000628}
629
630static void free_strings(char **strings)
631{
632 if (strings) {
633 char **v = strings;
634 while (*v)
635 free(*v++);
636 free(strings);
637 }
638}
639
Denis Vlasenko76d50412008-06-10 16:19:39 +0000640#if !BB_MMU
641#define EXTRA_PTRS 5 /* 1 for NULL, 1 for args, 3 for paranoid reasons */
642static char **alloc_ptrs(char **argv)
643{
644 char **v = argv;
645 while (*v)
646 v++;
647 return xzalloc((v - argv + EXTRA_PTRS) * sizeof(v[0]));
648}
649#endif
650
651
Denis Vlasenko83506862007-11-23 13:11:42 +0000652/* Function prototypes for builtins */
653static int builtin_cd(char **argv);
Denis Vlasenko5bc593c2007-11-23 21:20:21 +0000654static int builtin_echo(char **argv);
Denis Vlasenko83506862007-11-23 13:11:42 +0000655static int builtin_eval(char **argv);
656static int builtin_exec(char **argv);
657static int builtin_exit(char **argv);
658static int builtin_export(char **argv);
659#if ENABLE_HUSH_JOB
660static int builtin_fg_bg(char **argv);
661static int builtin_jobs(char **argv);
662#endif
663#if ENABLE_HUSH_HELP
664static int builtin_help(char **argv);
665#endif
666static int builtin_pwd(char **argv);
667static int builtin_read(char **argv);
668static int builtin_test(char **argv);
Denis Vlasenkodd316dd2008-06-14 15:50:55 +0000669static int builtin_true(char **argv);
Denis Vlasenko83506862007-11-23 13:11:42 +0000670static int builtin_set(char **argv);
671static int builtin_shift(char **argv);
672static int builtin_source(char **argv);
673static int builtin_umask(char **argv);
674static int builtin_unset(char **argv);
675//static int builtin_not_written(char **argv);
676
Eric Andersen25f27032001-04-26 23:22:31 +0000677/* Table of built-in functions. They can be forked or not, depending on
678 * context: within pipes, they fork. As simple commands, they do not.
679 * When used in non-forking context, they can change global variables
Denis Vlasenkoe1a0d482006-10-20 13:28:22 +0000680 * in the parent shell process. If forked, of course they cannot.
Eric Andersen25f27032001-04-26 23:22:31 +0000681 * For example, 'unset foo | whatever' will parse and run, but foo will
682 * still be set at the end. */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000683struct built_in_command {
Denis Vlasenkodd316dd2008-06-14 15:50:55 +0000684 const char *cmd;
685 int (*function)(char **argv);
Denis Vlasenko06810332007-05-21 23:30:54 +0000686#if ENABLE_HUSH_HELP
Denis Vlasenkodd316dd2008-06-14 15:50:55 +0000687 const char *descr;
Denis Vlasenko06810332007-05-21 23:30:54 +0000688#define BLTIN(cmd, func, help) { cmd, func, help }
689#else
690#define BLTIN(cmd, func, help) { cmd, func }
691#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000692};
693
Denis Vlasenko5bc593c2007-11-23 21:20:21 +0000694/* For now, echo and test are unconditionally enabled.
695 * Maybe make it configurable? */
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +0000696static const struct built_in_command bltins[] = {
Denis Vlasenkodd316dd2008-06-14 15:50:55 +0000697 BLTIN("." , builtin_source, "Run commands in a file"),
698 BLTIN(":" , builtin_true, "No-op"),
Denis Vlasenko83506862007-11-23 13:11:42 +0000699 BLTIN("[" , builtin_test, "Test condition"),
700 BLTIN("[[" , builtin_test, "Test condition"),
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000701#if ENABLE_HUSH_JOB
Denis Vlasenko06810332007-05-21 23:30:54 +0000702 BLTIN("bg" , builtin_fg_bg, "Resume a job in the background"),
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000703#endif
Denis Vlasenko06810332007-05-21 23:30:54 +0000704// BLTIN("break" , builtin_not_written, "Exit for, while or until loop"),
Denis Vlasenkodd316dd2008-06-14 15:50:55 +0000705 BLTIN("cd" , builtin_cd, "Change directory"),
Denis Vlasenko06810332007-05-21 23:30:54 +0000706// BLTIN("continue", builtin_not_written, "Continue for, while or until loop"),
Denis Vlasenko5bc593c2007-11-23 21:20:21 +0000707 BLTIN("echo" , builtin_echo, "Write strings to stdout"),
Denis Vlasenko06810332007-05-21 23:30:54 +0000708 BLTIN("eval" , builtin_eval, "Construct and run shell command"),
Denis Vlasenkodd316dd2008-06-14 15:50:55 +0000709 BLTIN("exec" , builtin_exec, "Execute command, don't return to shell"),
710 BLTIN("exit" , builtin_exit, "Exit"),
Denis Vlasenko06810332007-05-21 23:30:54 +0000711 BLTIN("export", builtin_export, "Set environment variable"),
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000712#if ENABLE_HUSH_JOB
Denis Vlasenko06810332007-05-21 23:30:54 +0000713 BLTIN("fg" , builtin_fg_bg, "Bring job into the foreground"),
Denis Vlasenkodd316dd2008-06-14 15:50:55 +0000714 BLTIN("jobs" , builtin_jobs, "List active jobs"),
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000715#endif
Denis Vlasenko06810332007-05-21 23:30:54 +0000716 BLTIN("pwd" , builtin_pwd, "Print current directory"),
717 BLTIN("read" , builtin_read, "Input environment variable"),
718// BLTIN("return", builtin_not_written, "Return from a function"),
719 BLTIN("set" , builtin_set, "Set/unset shell local variables"),
720 BLTIN("shift" , builtin_shift, "Shift positional parameters"),
721// BLTIN("trap" , builtin_not_written, "Trap signals"),
Denis Vlasenko83506862007-11-23 13:11:42 +0000722 BLTIN("test" , builtin_test, "Test condition"),
Denis Vlasenkodd316dd2008-06-14 15:50:55 +0000723// BLTIN("ulimit", builtin_not_written, "Control resource limits"),
724 BLTIN("umask" , builtin_umask, "Set file creation mask"),
Denis Vlasenko06810332007-05-21 23:30:54 +0000725 BLTIN("unset" , builtin_unset, "Unset environment variable"),
Denis Vlasenko06810332007-05-21 23:30:54 +0000726#if ENABLE_HUSH_HELP
727 BLTIN("help" , builtin_help, "List shell built-in commands"),
728#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000729};
730
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000731
Denis Vlasenko4830fc52008-05-25 21:50:55 +0000732/* Signals are grouped, we handle them in batches */
733static void set_misc_sighandler(void (*handler)(int))
734{
735 bb_signals(0
736 + (1 << SIGINT)
737 + (1 << SIGQUIT)
738 + (1 << SIGTERM)
739 , handler);
740}
741
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000742#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000743
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000744static void set_fatal_sighandler(void (*handler)(int))
745{
Denis Vlasenko25591c32008-02-16 22:58:56 +0000746 bb_signals(0
747 + (1 << SIGILL)
748 + (1 << SIGTRAP)
749 + (1 << SIGABRT)
750 + (1 << SIGFPE)
751 + (1 << SIGBUS)
752 + (1 << SIGSEGV)
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000753 /* bash 3.2 seems to handle these just like 'fatal' ones */
Denis Vlasenko25591c32008-02-16 22:58:56 +0000754 + (1 << SIGHUP)
755 + (1 << SIGPIPE)
756 + (1 << SIGALRM)
757 , handler);
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000758}
759static void set_jobctrl_sighandler(void (*handler)(int))
760{
Denis Vlasenko25591c32008-02-16 22:58:56 +0000761 bb_signals(0
762 + (1 << SIGTSTP)
763 + (1 << SIGTTIN)
764 + (1 << SIGTTOU)
765 , handler);
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000766}
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000767/* SIGCHLD is special and handled separately */
768
769static void set_every_sighandler(void (*handler)(int))
770{
771 set_fatal_sighandler(handler);
772 set_jobctrl_sighandler(handler);
773 set_misc_sighandler(handler);
774 signal(SIGCHLD, handler);
775}
776
Denis Vlasenko68404f12008-03-17 09:00:54 +0000777static void handler_ctrl_c(int sig ATTRIBUTE_UNUSED)
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000778{
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000779 debug_printf_jobs("got sig %d\n", sig);
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000780// as usual we can have all kinds of nasty problems with leaked malloc data here
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000781 siglongjmp(toplevel_jb, 1);
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000782}
783
Denis Vlasenko68404f12008-03-17 09:00:54 +0000784static void handler_ctrl_z(int sig ATTRIBUTE_UNUSED)
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000785{
786 pid_t pid;
787
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000788 debug_printf_jobs("got tty sig %d in pid %d\n", sig, getpid());
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000789 pid = fork();
Denis Vlasenkoc2990322007-05-16 12:57:12 +0000790 if (pid < 0) /* can't fork. Pretend there was no ctrl-Z */
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000791 return;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000792 ctrl_z_flag = 1;
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000793 if (!pid) { /* child */
Denis Vlasenko83177992008-02-11 08:44:36 +0000794 if (ENABLE_HUSH_JOB)
795 die_sleep = 0; /* let nofork's xfuncs die */
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000796 setpgrp();
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000797 debug_printf_jobs("set pgrp for child %d ok\n", getpid());
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000798 set_every_sighandler(SIG_DFL);
Denis Vlasenko18e19f22007-04-28 16:43:18 +0000799 raise(SIGTSTP); /* resend TSTP so that child will be stopped */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000800 debug_printf_jobs("returning in child\n");
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000801 /* return to nofork, it will eventually exit now,
802 * not return back to shell */
803 return;
804 }
805 /* parent */
806 /* finish filling up pipe info */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000807 toplevel_list->pgrp = pid; /* child is in its own pgrp */
808 toplevel_list->progs[0].pid = pid;
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000809 /* parent needs to longjmp out of running nofork.
810 * we will "return" exitcode 0, with child put in background */
811// as usual we can have all kinds of nasty problems with leaked malloc data here
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000812 debug_printf_jobs("siglongjmp in parent\n");
813 siglongjmp(toplevel_jb, 1);
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000814}
815
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000816/* Restores tty foreground process group, and exits.
817 * May be called as signal handler for fatal signal
818 * (will faithfully resend signal to itself, producing correct exit state)
819 * or called directly with -EXITCODE.
820 * We also call it if xfunc is exiting. */
821static void sigexit(int sig) ATTRIBUTE_NORETURN;
822static void sigexit(int sig)
823{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000824 /* Disable all signals: job control, SIGPIPE, etc. */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +0000825 sigprocmask_allsigs(SIG_BLOCK);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000826
Denis Vlasenko87cb2db2007-04-21 10:00:01 +0000827 if (interactive_fd)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000828 tcsetpgrp(interactive_fd, saved_tty_pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000829
830 /* Not a signal, just exit */
831 if (sig <= 0)
832 _exit(- sig);
833
Denis Vlasenko400d8bb2008-02-24 13:36:01 +0000834 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000835}
836
837/* Restores tty foreground process group, and exits. */
838static void hush_exit(int exitcode) ATTRIBUTE_NORETURN;
839static void hush_exit(int exitcode)
840{
841 fflush(NULL); /* flush all streams */
842 sigexit(- (exitcode & 0xff));
843}
844
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000845#else /* !JOB */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000846
847#define set_fatal_sighandler(handler) ((void)0)
848#define set_jobctrl_sighandler(handler) ((void)0)
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000849#define hush_exit(e) exit(e)
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000850
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000851#endif /* JOB */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000852
853
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000854static const char *set_cwd(void)
855{
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000856 if (cwd == bb_msg_unknown)
Denis Vlasenko7cced6e2007-04-12 17:08:53 +0000857 cwd = NULL; /* xrealloc_getcwd_or_warn(arg) calls free(arg)! */
Denis Vlasenko6ca04442007-02-11 16:19:28 +0000858 cwd = xrealloc_getcwd_or_warn((char *)cwd);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000859 if (!cwd)
Manuel Novoa III cad53642003-03-19 09:13:01 +0000860 cwd = bb_msg_unknown;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000861 return cwd;
862}
863
Denis Vlasenko83506862007-11-23 13:11:42 +0000864
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000865/*
866 * o_string support
867 */
868#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +0000869
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000870static void o_reset(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +0000871{
872 o->length = 0;
873 o->nonnull = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000874 if (o->data)
875 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +0000876}
877
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000878static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +0000879{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +0000880 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000881 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +0000882}
883
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000884static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000885{
886 if (o->length + len > o->maxlen) {
887 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
888 o->data = xrealloc(o->data, 1 + o->maxlen);
889 }
890}
891
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000892static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000893{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000894 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
895 o_grow_by(o, 1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000896 o->data[o->length] = ch;
897 o->length++;
898 o->data[o->length] = '\0';
899}
900
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000901static void o_addstr(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000902{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000903 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000904 memcpy(&o->data[o->length], str, len);
905 o->length += len;
906 o->data[o->length] = '\0';
907}
908
Eric Andersen25f27032001-04-26 23:22:31 +0000909/* My analysis of quoting semantics tells me that state information
910 * is associated with a destination, not a source.
911 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +0000912static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +0000913{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +0000914 int sz = 1;
915 if (strchr("*?[\\", ch)) {
916 sz++;
917 o->data[o->length] = '\\';
918 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +0000919 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +0000920 o_grow_by(o, sz);
921 o->data[o->length] = ch;
922 o->length++;
923 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +0000924}
925
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +0000926static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +0000927{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +0000928 int sz = 1;
929 if (o->o_quote && strchr("*?[\\", ch)) {
930 sz++;
931 o->data[o->length] = '\\';
932 o->length++;
933 }
934 o_grow_by(o, sz);
935 o->data[o->length] = ch;
936 o->length++;
937 o->data[o->length] = '\0';
938}
939
940static void o_addQstr(o_string *o, const char *str, int len)
941{
942 if (!o->o_quote) {
Denis Vlasenko87f40ba2008-06-10 22:39:37 +0000943 o_addstr(o, str, len);
944 return;
945 }
946 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +0000947 char ch;
948 int sz;
949 int ordinary_cnt = strcspn(str, "*?[\\");
950 if (ordinary_cnt > len) /* paranoia */
951 ordinary_cnt = len;
952 o_addstr(o, str, ordinary_cnt);
953 if (ordinary_cnt == len)
954 return;
955 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000956 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +0000957
Denis Vlasenko87f40ba2008-06-10 22:39:37 +0000958 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +0000959 sz = 1;
960 if (ch) { /* it is necessarily one of "*?[\\" */
961 sz++;
962 o->data[o->length] = '\\';
963 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +0000964 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +0000965 o_grow_by(o, sz);
966 o->data[o->length] = ch;
967 o->length++;
968 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +0000969 }
970}
971
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000972/* A special kind of o_string for $VAR and `cmd` expansion.
973 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000974 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000975 * list[i] contains an INDEX (int!) into this string data.
976 * It means that if list[] needs to grow, data needs to be moved higher up
977 * but list[i]'s need not be modified.
978 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000979 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000980 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
981 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000982#if DEBUG_EXPAND || DEBUG_GLOB
983static void debug_print_list(const char *prefix, o_string *o, int n)
984{
985 char **list = (char**)o->data;
986 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
987 int i = 0;
988 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
989 prefix, list, n, string_start, o->length, o->maxlen);
990 while (i < n) {
991 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
992 o->data + (int)list[i] + string_start,
993 o->data + (int)list[i] + string_start);
994 i++;
995 }
996 if (n) {
997 const char *p = o->data + (int)list[n - 1] + string_start;
998 fprintf(stderr, " total_sz:%d\n", (p + strlen(p) + 1) - o->data);
999 }
1000}
1001#else
1002#define debug_print_list(prefix, o, n) ((void)0)
1003#endif
1004
1005/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1006 * in list[n] so that it points past last stored byte so far.
1007 * It returns n+1. */
1008static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001009{
1010 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00001011 int string_start;
1012 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001013
1014 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00001015 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1016 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001017 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001018 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001019 /* list[n] points to string_start, make space for 16 more pointers */
1020 o->maxlen += 0x10 * sizeof(list[0]);
1021 o->data = xrealloc(o->data, o->maxlen + 1);
1022 list = (char**)o->data;
1023 memmove(list + n + 0x10, list + n, string_len);
1024 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001025 } else
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001026 debug_printf_list("list[%d]=%d string_start=%d\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001027 } else {
1028 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00001029 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1030 string_len = o->length - string_start;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001031 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001032 o->has_empty_slot = 0;
1033 }
1034 list[n] = (char*)string_len;
1035 return n + 1;
1036}
1037
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001038/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001039static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001040{
1041 char **list = (char**)o->data;
1042 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1043
1044 return ((int)list[n-1]) + string_start;
1045}
1046
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001047/* o_glob performs globbing on last list[], saving each result
1048 * as a new list[]. unbackslash() is just a helper */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001049static char *unbackslash(char *src)
1050{
1051 char *dst = src;
1052 while (1) {
1053 if (*src == '\\')
1054 src++;
1055 if ((*dst++ = *src++) == '\0')
1056 break;
1057 }
1058 return dst;
1059}
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001060static int o_glob(o_string *o, int n)
1061{
1062 glob_t globdata;
1063 int gr;
1064 char *pattern;
1065
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001066 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001067 if (!o->data)
1068 return o_save_ptr_helper(o, n);
1069 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001070 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001071 if (!glob_needed(pattern)) {
1072 literal:
1073 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001074 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001075 return o_save_ptr_helper(o, n);
1076 }
1077
1078 memset(&globdata, 0, sizeof(globdata));
1079 gr = glob(pattern, 0, NULL, &globdata);
1080 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
1081 if (gr == GLOB_NOSPACE)
1082 bb_error_msg_and_die("out of memory during glob");
1083 if (gr == GLOB_NOMATCH) {
1084 globfree(&globdata);
1085 goto literal;
1086 }
1087 if (gr != 0) { /* GLOB_ABORTED ? */
1088//TODO: testcase for bad glob pattern behavior
1089 bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
1090 }
1091 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
1092 char **argv = globdata.gl_pathv;
1093 o->length = pattern - o->data; /* "forget" pattern */
1094 while (1) {
1095 o_addstr(o, *argv, strlen(*argv) + 1);
1096 n = o_save_ptr_helper(o, n);
1097 argv++;
1098 if (!*argv)
1099 break;
1100 }
1101 }
1102 globfree(&globdata);
1103 if (DEBUG_GLOB)
1104 debug_print_list("o_glob returning", o, n);
1105 return n;
1106}
1107
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001108/* If o->o_glob == 1, glob the string so far remembered.
1109 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001110static int o_save_ptr(o_string *o, int n)
1111{
1112 if (o->o_glob)
1113 return o_glob(o, n); /* o_save_ptr_helper is inside */
1114 return o_save_ptr_helper(o, n);
1115}
1116
1117/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001118static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001119{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001120 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001121 int string_start;
1122
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001123 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
1124 if (DEBUG_EXPAND)
1125 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001126 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001127 list = (char**)o->data;
1128 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1129 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001130 while (n) {
1131 n--;
1132 list[n] = o->data + (int)list[n] + string_start;
1133 }
1134 return list;
1135}
1136
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001137
1138/*
1139 * in_str support
1140 */
Eric Andersen25f27032001-04-26 23:22:31 +00001141static int static_get(struct in_str *i)
1142{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001143 int ch = *i->p++;
1144 if (ch == '\0') return EOF;
Eric Andersen25f27032001-04-26 23:22:31 +00001145 return ch;
1146}
1147
1148static int static_peek(struct in_str *i)
1149{
1150 return *i->p;
1151}
1152
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001153#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001154
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001155#if ENABLE_FEATURE_EDITING
Rob Landley88621d72006-08-29 19:41:06 +00001156static void cmdedit_set_initial_prompt(void)
Eric Andersen25f27032001-04-26 23:22:31 +00001157{
Denis Vlasenko38f63192007-01-22 09:03:07 +00001158#if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
Eric Andersen25f27032001-04-26 23:22:31 +00001159 PS1 = NULL;
1160#else
1161 PS1 = getenv("PS1");
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001162 if (PS1 == NULL)
Eric Andersen25f27032001-04-26 23:22:31 +00001163 PS1 = "\\w \\$ ";
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001164#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001165}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001166#endif /* EDITING */
Eric Andersen25f27032001-04-26 23:22:31 +00001167
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001168static const char* setup_prompt_string(int promptmode)
Eric Andersen25f27032001-04-26 23:22:31 +00001169{
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001170 const char *prompt_str;
1171 debug_printf("setup_prompt_string %d ", promptmode);
Denis Vlasenko38f63192007-01-22 09:03:07 +00001172#if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
Eric Andersen25f27032001-04-26 23:22:31 +00001173 /* Set up the prompt */
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001174 if (promptmode == 0) { /* PS1 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001175 free((char*)PS1);
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001176 PS1 = xasprintf("%s %c ", cwd, (geteuid() != 0) ? '$' : '#');
1177 prompt_str = PS1;
Eric Andersen25f27032001-04-26 23:22:31 +00001178 } else {
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001179 prompt_str = PS2;
Eric Andersen25f27032001-04-26 23:22:31 +00001180 }
1181#else
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001182 prompt_str = (promptmode == 0) ? PS1 : PS2;
Eric Andersenaf44a0e2001-04-27 07:26:12 +00001183#endif
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001184 debug_printf("result '%s'\n", prompt_str);
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001185 return prompt_str;
Eric Andersen25f27032001-04-26 23:22:31 +00001186}
1187
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001188static void get_user_input(struct in_str *i)
Eric Andersen25f27032001-04-26 23:22:31 +00001189{
Denis Vlasenko0937be52007-04-28 16:47:08 +00001190 int r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001191 const char *prompt_str;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001192
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001193 prompt_str = setup_prompt_string(i->promptmode);
Denis Vlasenko38f63192007-01-22 09:03:07 +00001194#if ENABLE_FEATURE_EDITING
Denis Vlasenko170435c2007-05-23 13:01:10 +00001195 /* Enable command line editing only while a command line
Denis Vlasenkoe376d452008-02-20 22:23:24 +00001196 * is actually being read */
1197 do {
1198 r = read_line_input(prompt_str, user_input_buf, BUFSIZ-1, line_input_state);
1199 } while (r == 0); /* repeat if Ctrl-C */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001200 i->eof_flag = (r < 0);
1201 if (i->eof_flag) { /* EOF/error detected */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001202 user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1203 user_input_buf[1] = '\0';
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001204 }
Eric Andersen25f27032001-04-26 23:22:31 +00001205#else
1206 fputs(prompt_str, stdout);
1207 fflush(stdout);
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001208 user_input_buf[0] = r = fgetc(i->file);
1209 /*user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001210 i->eof_flag = (r == EOF);
Eric Andersen25f27032001-04-26 23:22:31 +00001211#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001212 i->p = user_input_buf;
Eric Andersen25f27032001-04-26 23:22:31 +00001213}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001214
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001215#endif /* INTERACTIVE */
Eric Andersen25f27032001-04-26 23:22:31 +00001216
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001217/* This is the magic location that prints prompts
Eric Andersen25f27032001-04-26 23:22:31 +00001218 * and gets data back from the user */
1219static int file_get(struct in_str *i)
1220{
1221 int ch;
1222
Eric Andersen25f27032001-04-26 23:22:31 +00001223 /* If there is data waiting, eat it up */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001224 if (i->p && *i->p) {
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001225#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001226 take_cached:
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001227#endif
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001228 ch = *i->p++;
1229 if (i->eof_flag && !*i->p)
1230 ch = EOF;
Eric Andersen25f27032001-04-26 23:22:31 +00001231 } else {
1232 /* need to double check i->file because we might be doing something
1233 * more complicated by now, like sourcing or substituting. */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001234#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001235 if (interactive_fd && i->promptme && i->file == stdin) {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001236 do {
1237 get_user_input(i);
1238 } while (!*i->p); /* need non-empty line */
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001239 i->promptmode = 1; /* PS2 */
1240 i->promptme = 0;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001241 goto take_cached;
Eric Andersen25f27032001-04-26 23:22:31 +00001242 }
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001243#endif
1244 ch = fgetc(i->file);
Eric Andersen25f27032001-04-26 23:22:31 +00001245 }
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001246 debug_printf("file_get: got a '%c' %d\n", ch, ch);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001247#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001248 if (ch == '\n')
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001249 i->promptme = 1;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001250#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001251 return ch;
1252}
1253
1254/* All the callers guarantee this routine will never be
1255 * used right after a newline, so prompting is not needed.
1256 */
1257static int file_peek(struct in_str *i)
1258{
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00001259 int ch;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001260 if (i->p && *i->p) {
1261 if (i->eof_flag && !i->p[1])
1262 return EOF;
1263 return *i->p;
Eric Andersen25f27032001-04-26 23:22:31 +00001264 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00001265 ch = fgetc(i->file);
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001266 i->eof_flag = (ch == EOF);
1267 i->peek_buf[0] = ch;
1268 i->peek_buf[1] = '\0';
1269 i->p = i->peek_buf;
1270 debug_printf("file_peek: got a '%c' %d\n", *i->p, *i->p);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00001271 return ch;
Eric Andersen25f27032001-04-26 23:22:31 +00001272}
1273
1274static void setup_file_in_str(struct in_str *i, FILE *f)
1275{
1276 i->peek = file_peek;
1277 i->get = file_get;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001278#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001279 i->promptme = 1;
1280 i->promptmode = 0; /* PS1 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001281#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001282 i->file = f;
1283 i->p = NULL;
1284}
1285
1286static void setup_string_in_str(struct in_str *i, const char *s)
1287{
1288 i->peek = static_peek;
1289 i->get = static_get;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001290#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001291 i->promptme = 1;
1292 i->promptmode = 0; /* PS1 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001293#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001294 i->p = s;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001295 i->eof_flag = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00001296}
1297
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001298
Eric Andersen25f27032001-04-26 23:22:31 +00001299/* squirrel != NULL means we squirrel away copies of stdin, stdout,
1300 * and stderr if they are redirected. */
1301static int setup_redirects(struct child_prog *prog, int squirrel[])
1302{
1303 int openfd, mode;
1304 struct redir_struct *redir;
1305
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001306 for (redir = prog->redirects; redir; redir = redir->next) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00001307 if (redir->dup == -1 && redir->rd_filename == NULL) {
Eric Andersen817e73c2001-06-06 17:56:09 +00001308 /* something went wrong in the parse. Pretend it didn't happen */
1309 continue;
1310 }
Eric Andersen25f27032001-04-26 23:22:31 +00001311 if (redir->dup == -1) {
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00001312 char *p;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001313 mode = redir_table[redir->type].mode;
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00001314 p = expand_string_to_string(redir->rd_filename);
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00001315 openfd = open_or_warn(p, mode);
1316 free(p);
Eric Andersen25f27032001-04-26 23:22:31 +00001317 if (openfd < 0) {
1318 /* this could get lost if stderr has been redirected, but
1319 bash and ash both lose it as well (though zsh doesn't!) */
Eric Andersen25f27032001-04-26 23:22:31 +00001320 return 1;
1321 }
1322 } else {
1323 openfd = redir->dup;
1324 }
1325
1326 if (openfd != redir->fd) {
1327 if (squirrel && redir->fd < 3) {
1328 squirrel[redir->fd] = dup(redir->fd);
1329 }
Eric Andersen83a2ae22001-05-07 17:59:25 +00001330 if (openfd == -3) {
Denis Vlasenko8412d792007-10-01 09:59:47 +00001331 //close(openfd); // close(-3) ??!
Eric Andersen83a2ae22001-05-07 17:59:25 +00001332 } else {
1333 dup2(openfd, redir->fd);
Matt Kraaic616e532001-06-05 16:50:08 +00001334 if (redir->dup == -1)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001335 close(openfd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00001336 }
Eric Andersen25f27032001-04-26 23:22:31 +00001337 }
1338 }
1339 return 0;
1340}
1341
1342static void restore_redirects(int squirrel[])
1343{
1344 int i, fd;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001345 for (i = 0; i < 3; i++) {
Eric Andersen25f27032001-04-26 23:22:31 +00001346 fd = squirrel[i];
1347 if (fd != -1) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00001348 /* We simply die on error */
1349 xmove_fd(fd, i);
Eric Andersen25f27032001-04-26 23:22:31 +00001350 }
1351 }
1352}
1353
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001354
Denis Vlasenko05743d72008-02-10 12:10:08 +00001355/* Called after [v]fork() in run_pipe(), or from builtin_exec().
Denis Vlasenko8412d792007-10-01 09:59:47 +00001356 * Never returns.
1357 * XXX no exit() here. If you don't exec, use _exit instead.
Eric Andersen94ac2442001-05-22 19:05:18 +00001358 * The at_exit handlers apparently confuse the calling process,
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001359 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
Denis Vlasenko76d50412008-06-10 16:19:39 +00001360static void pseudo_exec_argv(char **ptrs2free, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00001361{
Eric Andersen78a7c992001-05-15 16:30:25 +00001362 int i, rcode;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001363 char *p;
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +00001364 const struct built_in_command *x;
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001365
Denis Vlasenko1359da62007-04-21 23:27:30 +00001366 for (i = 0; is_assignment(argv[i]); i++) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001367 debug_printf_exec("pid %d environment modification: %s\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001368 getpid(), argv[i]);
Denis Vlasenko170435c2007-05-23 13:01:10 +00001369 p = expand_string_to_string(argv[i]);
Denis Vlasenko76d50412008-06-10 16:19:39 +00001370#if !BB_MMU
1371 *ptrs2free++ = p;
1372#endif
Denis Vlasenko170435c2007-05-23 13:01:10 +00001373 putenv(p);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001374 }
1375 argv += i;
1376 /* If a variable is assigned in a forest, and nobody listens,
1377 * was it ever really set?
1378 */
Denis Vlasenko05743d72008-02-10 12:10:08 +00001379 if (!argv[0])
Denis Vlasenko1359da62007-04-21 23:27:30 +00001380 _exit(EXIT_SUCCESS);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001381
Denis Vlasenko170435c2007-05-23 13:01:10 +00001382 argv = expand_strvec_to_strvec(argv);
Denis Vlasenko76d50412008-06-10 16:19:39 +00001383#if !BB_MMU
1384 *ptrs2free++ = (char*) argv;
1385#endif
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001386
Denis Vlasenko1359da62007-04-21 23:27:30 +00001387 /*
1388 * Check if the command matches any of the builtins.
1389 * Depending on context, this might be redundant. But it's
1390 * easier to waste a few CPU cycles than it is to figure out
1391 * if this is one of those cases.
1392 */
Denis Vlasenkodd316dd2008-06-14 15:50:55 +00001393 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
Denis Vlasenko1359da62007-04-21 23:27:30 +00001394 if (strcmp(argv[0], x->cmd) == 0) {
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001395 debug_printf_exec("running builtin '%s'\n", argv[0]);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001396 rcode = x->function(argv);
1397 fflush(stdout);
1398 _exit(rcode);
Eric Andersen94ac2442001-05-22 19:05:18 +00001399 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00001400 }
Eric Andersen78a7c992001-05-15 16:30:25 +00001401
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001402 /* Check if the command matches any busybox applets */
Denis Vlasenko80d14be2007-04-10 23:03:30 +00001403#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001404 if (strchr(argv[0], '/') == NULL) {
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00001405 int a = find_applet_by_name(argv[0]);
1406 if (a >= 0) {
1407 if (APPLET_IS_NOEXEC(a)) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001408 debug_printf_exec("running applet '%s'\n", argv[0]);
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00001409// is it ok that run_applet_no_and_exit() does exit(), not _exit()?
1410 run_applet_no_and_exit(a, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001411 }
1412 /* re-exec ourselves with the new arguments */
1413 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denis Vlasenkobdbbb7e2007-06-08 15:02:55 +00001414 execvp(bb_busybox_exec_path, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001415 /* If they called chroot or otherwise made the binary no longer
1416 * executable, fall through */
1417 }
1418 }
Eric Andersenaac75e52001-04-30 18:18:45 +00001419#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001420
1421 debug_printf_exec("execing '%s'\n", argv[0]);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001422 execvp(argv[0], argv);
1423 bb_perror_msg("cannot exec '%s'", argv[0]);
Bernhard Reutner-Fischer636a1f82008-05-19 09:29:47 +00001424 _exit(EXIT_FAILURE);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001425}
1426
Denis Vlasenko05743d72008-02-10 12:10:08 +00001427/* Called after [v]fork() in run_pipe()
Denis Vlasenko8412d792007-10-01 09:59:47 +00001428 */
Denis Vlasenko76d50412008-06-10 16:19:39 +00001429static void pseudo_exec(char **ptrs2free, struct child_prog *child)
Denis Vlasenko1359da62007-04-21 23:27:30 +00001430{
Denis Vlasenko05743d72008-02-10 12:10:08 +00001431 if (child->argv)
Denis Vlasenko76d50412008-06-10 16:19:39 +00001432 pseudo_exec_argv(ptrs2free, child->argv);
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001433
1434 if (child->group) {
Denis Vlasenko8412d792007-10-01 09:59:47 +00001435#if !BB_MMU
Denis Vlasenko3b492162007-12-24 14:26:57 +00001436 bb_error_msg_and_die("nested lists are not supported on NOMMU");
Denis Vlasenko8412d792007-10-01 09:59:47 +00001437#else
Denis Vlasenko3b492162007-12-24 14:26:57 +00001438 int rcode;
Denis Vlasenko05743d72008-02-10 12:10:08 +00001439 debug_printf_exec("pseudo_exec: run_list\n");
1440 rcode = run_list(child->group);
Eric Andersenbf7df042001-05-23 22:18:35 +00001441 /* OK to leak memory by not calling free_pipe_list,
Eric Andersen25f27032001-04-26 23:22:31 +00001442 * since this process is about to exit */
Eric Andersen94ac2442001-05-22 19:05:18 +00001443 _exit(rcode);
Denis Vlasenko8412d792007-10-01 09:59:47 +00001444#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001445 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001446
1447 /* Can happen. See what bash does with ">foo" by itself. */
1448 debug_printf("trying to pseudo_exec null command\n");
1449 _exit(EXIT_SUCCESS);
Eric Andersen25f27032001-04-26 23:22:31 +00001450}
1451
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001452#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001453static const char *get_cmdtext(struct pipe *pi)
1454{
1455 char **argv;
1456 char *p;
1457 int len;
1458
1459 /* This is subtle. ->cmdtext is created only on first backgrounding.
1460 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001461 * On subsequent bg argv is trashed, but we won't use it */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001462 if (pi->cmdtext)
1463 return pi->cmdtext;
1464 argv = pi->progs[0].argv;
Denis Vlasenkoa8442002008-06-14 11:00:17 +00001465 if (!argv || !argv[0]) {
1466 pi->cmdtext = xzalloc(1);
1467 return pi->cmdtext;
1468 }
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001469
1470 len = 0;
1471 do len += strlen(*argv) + 1; while (*++argv);
1472 pi->cmdtext = p = xmalloc(len);
1473 argv = pi->progs[0].argv;
1474 do {
1475 len = strlen(*argv);
1476 memcpy(p, *argv, len);
1477 p += len;
1478 *p++ = ' ';
1479 } while (*++argv);
1480 p[-1] = '\0';
1481 return pi->cmdtext;
1482}
1483
Eric Andersenbafd94f2001-05-02 16:11:59 +00001484static void insert_bg_job(struct pipe *pi)
1485{
1486 struct pipe *thejob;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001487 int i;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001488
1489 /* Linear search for the ID of the job to use */
1490 pi->jobid = 1;
Eric Andersenc798b072001-06-22 06:23:03 +00001491 for (thejob = job_list; thejob; thejob = thejob->next)
Eric Andersenbafd94f2001-05-02 16:11:59 +00001492 if (thejob->jobid >= pi->jobid)
1493 pi->jobid = thejob->jobid + 1;
1494
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001495 /* Add thejob to the list of running jobs */
Eric Andersenc798b072001-06-22 06:23:03 +00001496 if (!job_list) {
Eric Andersen52a97ca2001-06-22 06:49:26 +00001497 thejob = job_list = xmalloc(sizeof(*thejob));
Eric Andersenbafd94f2001-05-02 16:11:59 +00001498 } else {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001499 for (thejob = job_list; thejob->next; thejob = thejob->next)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001500 continue;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001501 thejob->next = xmalloc(sizeof(*thejob));
1502 thejob = thejob->next;
1503 }
1504
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001505 /* Physically copy the struct job */
Eric Andersen0fcd4472001-05-02 20:12:03 +00001506 memcpy(thejob, pi, sizeof(struct pipe));
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001507 thejob->progs = xzalloc(sizeof(pi->progs[0]) * pi->num_progs);
1508 /* We cannot copy entire pi->progs[] vector! Double free()s will happen */
1509 for (i = 0; i < pi->num_progs; i++) {
1510// TODO: do we really need to have so many fields which are just dead weight
1511// at execution stage?
1512 thejob->progs[i].pid = pi->progs[i].pid;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001513 /* all other fields are not used and stay zero */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001514 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00001515 thejob->next = NULL;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001516 thejob->cmdtext = xstrdup(get_cmdtext(pi));
Eric Andersenbafd94f2001-05-02 16:11:59 +00001517
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001518 /* We don't wait for background thejobs to return -- append it
Eric Andersenbafd94f2001-05-02 16:11:59 +00001519 to the list of backgrounded thejobs and leave it alone */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001520 printf("[%d] %d %s\n", thejob->jobid, thejob->progs[0].pid, thejob->cmdtext);
Eric Andersen1a6d39b2001-05-08 05:11:54 +00001521 last_bg_pid = thejob->progs[0].pid;
Eric Andersenc798b072001-06-22 06:23:03 +00001522 last_jobid = thejob->jobid;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001523}
1524
Eric Andersenbafd94f2001-05-02 16:11:59 +00001525static void remove_bg_job(struct pipe *pi)
1526{
1527 struct pipe *prev_pipe;
1528
Eric Andersenc798b072001-06-22 06:23:03 +00001529 if (pi == job_list) {
Eric Andersen52a97ca2001-06-22 06:49:26 +00001530 job_list = pi->next;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001531 } else {
Eric Andersenc798b072001-06-22 06:23:03 +00001532 prev_pipe = job_list;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001533 while (prev_pipe->next != pi)
1534 prev_pipe = prev_pipe->next;
1535 prev_pipe->next = pi->next;
1536 }
Eric Andersen028b65b2001-06-28 01:10:11 +00001537 if (job_list)
1538 last_jobid = job_list->jobid;
1539 else
1540 last_jobid = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001541}
Eric Andersen028b65b2001-06-28 01:10:11 +00001542
Denis Vlasenko1359da62007-04-21 23:27:30 +00001543/* remove a backgrounded job */
1544static void delete_finished_bg_job(struct pipe *pi)
1545{
1546 remove_bg_job(pi);
Eric Andersen52a97ca2001-06-22 06:49:26 +00001547 pi->stopped_progs = 0;
Eric Andersenbf7df042001-05-23 22:18:35 +00001548 free_pipe(pi, 0);
Eric Andersenbafd94f2001-05-02 16:11:59 +00001549 free(pi);
1550}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001551#endif /* JOB */
Eric Andersenbafd94f2001-05-02 16:11:59 +00001552
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001553/* Checks to see if any processes have exited -- if they
Eric Andersenbafd94f2001-05-02 16:11:59 +00001554 have, figure out why and see if a job has completed */
Eric Andersenc798b072001-06-22 06:23:03 +00001555static int checkjobs(struct pipe* fg_pipe)
Eric Andersenbafd94f2001-05-02 16:11:59 +00001556{
Eric Andersenc798b072001-06-22 06:23:03 +00001557 int attributes;
1558 int status;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001559#if ENABLE_HUSH_JOB
Eric Andersenbafd94f2001-05-02 16:11:59 +00001560 int prognum = 0;
1561 struct pipe *pi;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001562#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00001563 pid_t childpid;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001564 int rcode = 0;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001565
Eric Andersenc798b072001-06-22 06:23:03 +00001566 attributes = WUNTRACED;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001567 if (fg_pipe == NULL) {
Eric Andersenc798b072001-06-22 06:23:03 +00001568 attributes |= WNOHANG;
1569 }
1570
Denis Vlasenko1359da62007-04-21 23:27:30 +00001571/* Do we do this right?
1572 * bash-3.00# sleep 20 | false
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001573 * <ctrl-Z pressed>
Denis Vlasenko1359da62007-04-21 23:27:30 +00001574 * [3]+ Stopped sleep 20 | false
1575 * bash-3.00# echo $?
1576 * 1 <========== bg pipe is not fully done, but exitcode is already known!
1577 */
1578
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001579//FIXME: non-interactive bash does not continue even if all processes in fg pipe
1580//are stopped. Testcase: "cat | cat" in a script (not on command line)
1581// + killall -STOP cat
1582
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001583 wait_more:
Denis Vlasenkofb0eba72008-01-02 19:55:04 +00001584// TODO: safe_waitpid?
Eric Andersenc798b072001-06-22 06:23:03 +00001585 while ((childpid = waitpid(-1, &status, attributes)) > 0) {
Denis Vlasenko1359da62007-04-21 23:27:30 +00001586 const int dead = WIFEXITED(status) || WIFSIGNALED(status);
1587
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001588#if DEBUG_JOBS
Denis Vlasenko1359da62007-04-21 23:27:30 +00001589 if (WIFSTOPPED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001590 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001591 childpid, WSTOPSIG(status), WEXITSTATUS(status));
1592 if (WIFSIGNALED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001593 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001594 childpid, WTERMSIG(status), WEXITSTATUS(status));
1595 if (WIFEXITED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001596 debug_printf_jobs("pid %d exited, exitcode %d\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001597 childpid, WEXITSTATUS(status));
1598#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001599 /* Were we asked to wait for fg pipe? */
Eric Andersenc798b072001-06-22 06:23:03 +00001600 if (fg_pipe) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001601 int i;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001602 for (i = 0; i < fg_pipe->num_progs; i++) {
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001603 debug_printf_jobs("check pid %d\n", fg_pipe->progs[i].pid);
Eric Andersenc798b072001-06-22 06:23:03 +00001604 if (fg_pipe->progs[i].pid == childpid) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001605 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001606 if (dead) {
1607 fg_pipe->progs[i].pid = 0;
1608 fg_pipe->running_progs--;
Denis Vlasenkoa8442002008-06-14 11:00:17 +00001609 if (i == fg_pipe->num_progs - 1) {
Denis Vlasenko1359da62007-04-21 23:27:30 +00001610 /* last process gives overall exitstatus */
1611 rcode = WEXITSTATUS(status);
Denis Vlasenkoa8442002008-06-14 11:00:17 +00001612 if (fg_pipe->pi_inverted)
1613 rcode = !rcode;
1614 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00001615 } else {
1616 fg_pipe->progs[i].is_stopped = 1;
1617 fg_pipe->stopped_progs++;
1618 }
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001619 debug_printf_jobs("fg_pipe: running_progs %d stopped_progs %d\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001620 fg_pipe->running_progs, fg_pipe->stopped_progs);
1621 if (fg_pipe->running_progs - fg_pipe->stopped_progs <= 0) {
1622 /* All processes in fg pipe have exited/stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001623#if ENABLE_HUSH_JOB
Denis Vlasenko1359da62007-04-21 23:27:30 +00001624 if (fg_pipe->running_progs)
1625 insert_bg_job(fg_pipe);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001626#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001627 return rcode;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001628 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001629 /* There are still running processes in the fg pipe */
1630 goto wait_more;
Eric Andersenc798b072001-06-22 06:23:03 +00001631 }
1632 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00001633 /* fall through to searching process in bg pipes */
Eric Andersenc798b072001-06-22 06:23:03 +00001634 }
1635
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001636#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001637 /* We asked to wait for bg or orphaned children */
1638 /* No need to remember exitcode in this case */
Eric Andersenc798b072001-06-22 06:23:03 +00001639 for (pi = job_list; pi; pi = pi->next) {
Eric Andersenbafd94f2001-05-02 16:11:59 +00001640 prognum = 0;
Denis Vlasenko5f786c22007-04-20 08:35:45 +00001641 while (prognum < pi->num_progs) {
1642 if (pi->progs[prognum].pid == childpid)
1643 goto found_pi_and_prognum;
Eric Andersen52a97ca2001-06-22 06:49:26 +00001644 prognum++;
1645 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00001646 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001647#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00001648
Denis Vlasenko5f786c22007-04-20 08:35:45 +00001649 /* Happens when shell is used as init process (init=/bin/sh) */
1650 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001651 goto wait_more;
Eric Andersenaeb44c42001-05-22 20:29:00 +00001652
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001653#if ENABLE_HUSH_JOB
Denis Vlasenko5f786c22007-04-20 08:35:45 +00001654 found_pi_and_prognum:
Denis Vlasenko1359da62007-04-21 23:27:30 +00001655 if (dead) {
Eric Andersenbafd94f2001-05-02 16:11:59 +00001656 /* child exited */
Eric Andersenbafd94f2001-05-02 16:11:59 +00001657 pi->progs[prognum].pid = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001658 pi->running_progs--;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001659 if (!pi->running_progs) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001660 printf(JOB_STATUS_FORMAT, pi->jobid,
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001661 "Done", pi->cmdtext);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001662 delete_finished_bg_job(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00001663 }
1664 } else {
1665 /* child stopped */
1666 pi->stopped_progs++;
1667 pi->progs[prognum].is_stopped = 1;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001668 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001669#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00001670 }
1671
Denis Vlasenko1359da62007-04-21 23:27:30 +00001672 /* wait found no children or failed */
1673
1674 if (childpid && errno != ECHILD)
Manuel Novoa III cad53642003-03-19 09:13:01 +00001675 bb_perror_msg("waitpid");
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001676 return rcode;
Eric Andersenada18ff2001-05-21 16:18:22 +00001677}
1678
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001679#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +00001680static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
1681{
1682 pid_t p;
1683 int rcode = checkjobs(fg_pipe);
1684 /* Job finished, move the shell to the foreground */
Denis Vlasenko170435c2007-05-23 13:01:10 +00001685 p = getpgid(0); /* pgid of our process */
1686 debug_printf_jobs("fg'ing ourself: getpgid(0)=%d\n", (int)p);
Denis Vlasenko52881e92007-04-21 13:42:52 +00001687 if (tcsetpgrp(interactive_fd, p) && errno != ENOTTY)
1688 bb_perror_msg("tcsetpgrp-4a");
1689 return rcode;
1690}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001691#endif
Denis Vlasenko52881e92007-04-21 13:42:52 +00001692
Denis Vlasenko05743d72008-02-10 12:10:08 +00001693/* run_pipe() starts all the jobs, but doesn't wait for anything
Eric Andersenc798b072001-06-22 06:23:03 +00001694 * to finish. See checkjobs().
Eric Andersen25f27032001-04-26 23:22:31 +00001695 *
1696 * return code is normally -1, when the caller has to wait for children
1697 * to finish to determine the exit status of the pipe. If the pipe
1698 * is a simple builtin command, however, the action is done by the
Denis Vlasenko05743d72008-02-10 12:10:08 +00001699 * time run_pipe returns, and the exit code is provided as the
Eric Andersen25f27032001-04-26 23:22:31 +00001700 * return value.
1701 *
1702 * The input of the pipe is always stdin, the output is always
1703 * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
1704 * because it tries to avoid running the command substitution in
1705 * subshell, when that is in fact necessary. The subshell process
1706 * now has its stdout directed to the input of the appropriate pipe,
1707 * so this routine is noticeably simpler.
Denis Vlasenko170435c2007-05-23 13:01:10 +00001708 *
1709 * Returns -1 only if started some children. IOW: we have to
1710 * mask out retvals of builtins etc with 0xff!
Eric Andersen25f27032001-04-26 23:22:31 +00001711 */
Denis Vlasenko05743d72008-02-10 12:10:08 +00001712static int run_pipe(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00001713{
1714 int i;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001715 int nextin;
1716 int pipefds[2]; /* pipefds[0] is for reading */
Rob Landley53702e52006-07-19 21:43:53 +00001717 struct child_prog *child;
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +00001718 const struct built_in_command *x;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001719 char *p;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001720 /* it is not always needed, but we aim to smaller code */
1721 int squirrel[] = { -1, -1, -1 };
1722 int rcode;
Denis Vlasenko52881e92007-04-21 13:42:52 +00001723 const int single_fg = (pi->num_progs == 1 && pi->followup != PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00001724
Denis Vlasenko05743d72008-02-10 12:10:08 +00001725 debug_printf_exec("run_pipe start: single_fg=%d\n", single_fg);
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00001726
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001727#if ENABLE_HUSH_JOB
Eric Andersenada18ff2001-05-21 16:18:22 +00001728 pi->pgrp = -1;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001729#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001730 pi->running_progs = 1;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001731 pi->stopped_progs = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00001732
1733 /* Check if this is a simple builtin (not part of a pipe).
1734 * Builtins within pipes have to fork anyway, and are handled in
1735 * pseudo_exec. "echo foo | read bar" doesn't work on bash, either.
1736 */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001737 child = &(pi->progs[0]);
Denis Vlasenko52881e92007-04-21 13:42:52 +00001738 if (single_fg && child->group && child->subshell == 0) {
Eric Andersen04407e52001-06-07 16:42:05 +00001739 debug_printf("non-subshell grouping\n");
1740 setup_redirects(child, squirrel);
Denis Vlasenko05743d72008-02-10 12:10:08 +00001741 debug_printf_exec(": run_list\n");
1742 rcode = run_list(child->group) & 0xff;
Eric Andersen04407e52001-06-07 16:42:05 +00001743 restore_redirects(squirrel);
Denis Vlasenko05743d72008-02-10 12:10:08 +00001744 debug_printf_exec("run_pipe return %d\n", rcode);
Denis Vlasenkoa8442002008-06-14 11:00:17 +00001745 if (pi->pi_inverted)
1746 rcode = !rcode;
Denis Vlasenko05743d72008-02-10 12:10:08 +00001747 return rcode;
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001748 }
1749
Denis Vlasenko1359da62007-04-21 23:27:30 +00001750 if (single_fg && child->argv != NULL) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001751 char **argv_expanded;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001752 char **argv = child->argv;
1753
1754 for (i = 0; is_assignment(argv[i]); i++)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001755 continue;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001756 if (i != 0 && argv[i] == NULL) {
Eric Andersen78a7c992001-05-15 16:30:25 +00001757 /* assignments, but no command: set the local environment */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001758 for (i = 0; argv[i] != NULL; i++) {
Denis Vlasenkod76c0492007-05-25 02:16:25 +00001759 debug_printf("local environment set: %s\n", argv[i]);
Denis Vlasenko170435c2007-05-23 13:01:10 +00001760 p = expand_string_to_string(argv[i]);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00001761 set_local_var(p, 0);
Eric Andersen78a7c992001-05-15 16:30:25 +00001762 }
1763 return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
1764 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00001765 for (i = 0; is_assignment(argv[i]); i++) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00001766 p = expand_string_to_string(argv[i]);
Denis Vlasenko170435c2007-05-23 13:01:10 +00001767 putenv(p);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001768 }
Denis Vlasenkodd316dd2008-06-14 15:50:55 +00001769 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
Denis Vlasenko1359da62007-04-21 23:27:30 +00001770 if (strcmp(argv[i], x->cmd) == 0) {
1771 if (x->function == builtin_exec && argv[i+1] == NULL) {
Eric Andersen83a2ae22001-05-07 17:59:25 +00001772 debug_printf("magic exec\n");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001773 setup_redirects(child, NULL);
Eric Andersen83a2ae22001-05-07 17:59:25 +00001774 return EXIT_SUCCESS;
1775 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00001776 debug_printf("builtin inline %s\n", argv[0]);
Eric Andersen25f27032001-04-26 23:22:31 +00001777 /* XXX setup_redirects acts on file descriptors, not FILEs.
1778 * This is perfect for work that comes after exec().
1779 * Is it really safe for inline use? Experimentally,
1780 * things seem to work with glibc. */
1781 setup_redirects(child, squirrel);
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001782 debug_printf_exec(": builtin '%s' '%s'...\n", x->cmd, argv[i+1]);
Denis Vlasenko170435c2007-05-23 13:01:10 +00001783 argv_expanded = expand_strvec_to_strvec(argv + i);
1784 rcode = x->function(argv_expanded) & 0xff;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001785 free(argv_expanded);
Eric Andersen25f27032001-04-26 23:22:31 +00001786 restore_redirects(squirrel);
Denis Vlasenko05743d72008-02-10 12:10:08 +00001787 debug_printf_exec("run_pipe return %d\n", rcode);
Denis Vlasenkoa8442002008-06-14 11:00:17 +00001788 if (pi->pi_inverted)
1789 rcode = !rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00001790 return rcode;
1791 }
1792 }
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001793#if ENABLE_FEATURE_SH_STANDALONE
1794 {
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00001795 int a = find_applet_by_name(argv[i]);
1796 if (a >= 0 && APPLET_IS_NOFORK(a)) {
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001797 setup_redirects(child, squirrel);
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001798 save_nofork_data(&nofork_save);
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001799 argv_expanded = argv + i;
Denis Vlasenko170435c2007-05-23 13:01:10 +00001800 argv_expanded = expand_strvec_to_strvec(argv + i);
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001801 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n", argv_expanded[0], argv_expanded[1]);
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00001802 rcode = run_nofork_applet_prime(&nofork_save, a, argv_expanded);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001803 free(argv_expanded);
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001804 restore_redirects(squirrel);
Denis Vlasenko05743d72008-02-10 12:10:08 +00001805 debug_printf_exec("run_pipe return %d\n", rcode);
Denis Vlasenkoa8442002008-06-14 11:00:17 +00001806 if (pi->pi_inverted)
1807 rcode = !rcode;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001808 return rcode;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001809 }
1810 }
1811#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001812 }
1813
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001814 /* Disable job control signals for shell (parent) and
1815 * for initial child code after fork */
1816 set_jobctrl_sighandler(SIG_IGN);
1817
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001818 /* Going to fork a child per each pipe member */
1819 pi->running_progs = 0;
1820 nextin = 0;
1821
Eric Andersen25f27032001-04-26 23:22:31 +00001822 for (i = 0; i < pi->num_progs; i++) {
Denis Vlasenko76d50412008-06-10 16:19:39 +00001823#if !BB_MMU
1824 char **ptrs2free = NULL;
1825#endif
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001826 child = &(pi->progs[i]);
Denis Vlasenko76d50412008-06-10 16:19:39 +00001827 if (child->argv) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001828 debug_printf_exec(": pipe member '%s' '%s'...\n", child->argv[0], child->argv[1]);
Denis Vlasenko76d50412008-06-10 16:19:39 +00001829#if !BB_MMU
1830 ptrs2free = alloc_ptrs(child->argv);
1831#endif
1832 } else
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001833 debug_printf_exec(": pipe member with no argv\n");
Eric Andersen25f27032001-04-26 23:22:31 +00001834
1835 /* pipes are inserted between pairs of commands */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001836 pipefds[0] = 0;
1837 pipefds[1] = 1;
1838 if ((i + 1) < pi->num_progs)
1839 xpipe(pipefds);
Eric Andersen25f27032001-04-26 23:22:31 +00001840
Denis Vlasenko05743d72008-02-10 12:10:08 +00001841 child->pid = BB_MMU ? fork() : vfork();
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001842 if (!child->pid) { /* child */
Denis Vlasenko83177992008-02-11 08:44:36 +00001843 if (ENABLE_HUSH_JOB)
1844 die_sleep = 0; /* let nofork's xfuncs die */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001845#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001846 /* Every child adds itself to new process group
Denis Vlasenko05743d72008-02-10 12:10:08 +00001847 * with pgid == pid_of_first_child_in_pipe */
Denis Vlasenko170435c2007-05-23 13:01:10 +00001848 if (run_list_level == 1 && interactive_fd) {
Denis Vlasenko05743d72008-02-10 12:10:08 +00001849 pid_t pgrp;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001850 /* Don't do pgrp restore anymore on fatal signals */
1851 set_fatal_sighandler(SIG_DFL);
Denis Vlasenko05743d72008-02-10 12:10:08 +00001852 pgrp = pi->pgrp;
1853 if (pgrp < 0) /* true for 1st process only */
1854 pgrp = getpid();
1855 if (setpgid(0, pgrp) == 0 && pi->followup != PIPE_BG) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001856 /* We do it in *every* child, not just first,
1857 * to avoid races */
Denis Vlasenko05743d72008-02-10 12:10:08 +00001858 tcsetpgrp(interactive_fd, pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001859 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001860 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001861#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +00001862 xmove_fd(nextin, 0);
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001863 xmove_fd(pipefds[1], 1); /* write end */
1864 if (pipefds[0] > 1)
1865 close(pipefds[0]); /* read end */
Eric Andersen25f27032001-04-26 23:22:31 +00001866 /* Like bash, explicit redirects override pipes,
1867 * and the pipe fd is available for dup'ing. */
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001868 setup_redirects(child, NULL);
Eric Andersen52a97ca2001-06-22 06:49:26 +00001869
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001870 /* Restore default handlers just prior to exec */
1871 set_jobctrl_sighandler(SIG_DFL);
1872 set_misc_sighandler(SIG_DFL);
1873 signal(SIGCHLD, SIG_DFL);
Denis Vlasenko76d50412008-06-10 16:19:39 +00001874 pseudo_exec(ptrs2free, child); /* does not return */
Eric Andersen25f27032001-04-26 23:22:31 +00001875 }
Denis Vlasenko76d50412008-06-10 16:19:39 +00001876#if !BB_MMU
1877 free_strings(ptrs2free);
1878#endif
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001879 if (child->pid < 0) { /* [v]fork failed */
1880 /* Clearly indicate, was it fork or vfork */
Denis Vlasenko05743d72008-02-10 12:10:08 +00001881 bb_perror_msg(BB_MMU ? "fork" : "vfork");
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001882 } else {
1883 pi->running_progs++;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001884#if ENABLE_HUSH_JOB
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001885 /* Second and next children need to know pid of first one */
1886 if (pi->pgrp < 0)
1887 pi->pgrp = child->pid;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001888#endif
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001889 }
Eric Andersen25f27032001-04-26 23:22:31 +00001890
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001891 if (i)
1892 close(nextin);
1893 if ((i + 1) < pi->num_progs)
1894 close(pipefds[1]); /* write end */
1895 /* Pass read (output) pipe end to next iteration */
Eric Andersen25f27032001-04-26 23:22:31 +00001896 nextin = pipefds[0];
1897 }
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001898
Denis Vlasenko05743d72008-02-10 12:10:08 +00001899 if (!pi->running_progs) {
1900 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
1901 return 1;
1902 }
1903
1904 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->running_progs);
Eric Andersen25f27032001-04-26 23:22:31 +00001905 return -1;
1906}
1907
Denis Vlasenko4b924f32007-05-30 00:29:55 +00001908#ifndef debug_print_tree
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001909static void debug_print_tree(struct pipe *pi, int lvl)
1910{
1911 static const char *PIPE[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001912 [PIPE_SEQ] = "SEQ",
1913 [PIPE_AND] = "AND",
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001914 [PIPE_OR ] = "OR" ,
1915 [PIPE_BG ] = "BG" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001916 };
1917 static const char *RES[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001918 [RES_NONE ] = "NONE" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00001919#if ENABLE_HUSH_IF
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001920 [RES_IF ] = "IF" ,
1921 [RES_THEN ] = "THEN" ,
1922 [RES_ELIF ] = "ELIF" ,
1923 [RES_ELSE ] = "ELSE" ,
1924 [RES_FI ] = "FI" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00001925#endif
1926#if ENABLE_HUSH_LOOPS
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001927 [RES_FOR ] = "FOR" ,
1928 [RES_WHILE] = "WHILE",
1929 [RES_UNTIL] = "UNTIL",
1930 [RES_DO ] = "DO" ,
1931 [RES_DONE ] = "DONE" ,
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001932 [RES_IN ] = "IN" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00001933#endif
1934 [RES_XXXX ] = "XXXX" ,
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001935 [RES_SNTX ] = "SNTX" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001936 };
1937
1938 int pin, prn;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00001939
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001940 pin = 0;
1941 while (pi) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00001942 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
1943 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001944 prn = 0;
1945 while (prn < pi->num_progs) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00001946 struct child_prog *child = &pi->progs[prn];
1947 char **argv = child->argv;
1948
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001949 fprintf(stderr, "%*s prog %d", lvl*2, "", prn);
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00001950 if (child->group) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001951 fprintf(stderr, " group %s: (argv=%p)\n",
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00001952 (child->subshell ? "()" : "{}"),
1953 argv);
1954 debug_print_tree(child->group, lvl+1);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001955 prn++;
1956 continue;
1957 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001958 if (argv) while (*argv) {
1959 fprintf(stderr, " '%s'", *argv);
1960 argv++;
Denis Vlasenko4b924f32007-05-30 00:29:55 +00001961 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001962 fprintf(stderr, "\n");
1963 prn++;
1964 }
1965 pi = pi->next;
1966 pin++;
1967 }
1968}
1969#endif
1970
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001971/* NB: called by pseudo_exec, and therefore must not modify any
1972 * global data until exec/_exit (we can be a child after vfork!) */
Denis Vlasenko05743d72008-02-10 12:10:08 +00001973static int run_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00001974{
Denis Vlasenko06810332007-05-21 23:30:54 +00001975 struct pipe *rpipe;
1976#if ENABLE_HUSH_LOOPS
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00001977 char *for_varname = NULL;
1978 char **for_lcur = NULL;
1979 char **for_list = NULL;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001980 int flag_rep = 0;
Denis Vlasenko06810332007-05-21 23:30:54 +00001981#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001982 int flag_skip = 1;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00001983 int rcode = 0; /* probably for gcc only */
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001984 int flag_restore = 0;
Denis Vlasenko06810332007-05-21 23:30:54 +00001985#if ENABLE_HUSH_IF
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001986 int if_code = 0, next_if_code = 0; /* need double-buffer to handle elif */
Denis Vlasenko06810332007-05-21 23:30:54 +00001987#else
1988 enum { if_code = 0, next_if_code = 0 };
1989#endif
Denis Vlasenko219e88d2007-05-21 10:18:23 +00001990 reserved_style rword;
1991 reserved_style skip_more_for_this_rword = RES_XXXX;
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00001992
Denis Vlasenko05743d72008-02-10 12:10:08 +00001993 debug_printf_exec("run_list start lvl %d\n", run_list_level + 1);
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00001994
Denis Vlasenko06810332007-05-21 23:30:54 +00001995#if ENABLE_HUSH_LOOPS
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001996 /* check syntax for "for" */
1997 for (rpipe = pi; rpipe; rpipe = rpipe->next) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00001998 if ((rpipe->res_word == RES_IN || rpipe->res_word == RES_FOR)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001999 && (rpipe->next == NULL)
2000 ) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00002001 syntax("malformed for"); /* no IN or no commands after IN */
Denis Vlasenko05743d72008-02-10 12:10:08 +00002002 debug_printf_exec("run_list lvl %d return 1\n", run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002003 return 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002004 }
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002005 if ((rpipe->res_word == RES_IN && rpipe->next->res_word == RES_IN && rpipe->next->progs[0].argv != NULL)
2006 || (rpipe->res_word == RES_FOR && rpipe->next->res_word != RES_IN)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002007 ) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002008 /* TODO: what is tested in the first condition? */
Denis Vlasenko6eaf8de2008-06-17 12:09:21 +00002009 syntax("malformed for"); /* 2nd condition: FOR not followed by IN */
Denis Vlasenko05743d72008-02-10 12:10:08 +00002010 debug_printf_exec("run_list lvl %d return 1\n", run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002011 return 1;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002012 }
2013 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002014#else
2015 rpipe = NULL;
2016#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002017
2018#if ENABLE_HUSH_JOB
2019 /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
2020 * We are saving state before entering outermost list ("while...done")
2021 * so that ctrl-Z will correctly background _entire_ outermost list,
2022 * not just a part of it (like "sleep 1 | exit 2") */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00002023 if (++run_list_level == 1 && interactive_fd) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002024 if (sigsetjmp(toplevel_jb, 1)) {
2025 /* ctrl-Z forked and we are parent; or ctrl-C.
2026 * Sighandler has longjmped us here */
2027 signal(SIGINT, SIG_IGN);
2028 signal(SIGTSTP, SIG_IGN);
2029 /* Restore level (we can be coming from deep inside
2030 * nested levels) */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00002031 run_list_level = 1;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002032#if ENABLE_FEATURE_SH_STANDALONE
2033 if (nofork_save.saved) { /* if save area is valid */
2034 debug_printf_jobs("exiting nofork early\n");
2035 restore_nofork_data(&nofork_save);
2036 }
2037#endif
2038 if (ctrl_z_flag) {
2039 /* ctrl-Z has forked and stored pid of the child in pi->pid.
2040 * Remember this child as background job */
2041 insert_bg_job(pi);
2042 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002043 /* ctrl-C. We just stop doing whatever we were doing */
Denis Vlasenko4daad902007-09-27 10:20:47 +00002044 bb_putchar('\n');
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002045 }
2046 rcode = 0;
2047 goto ret;
2048 }
2049 /* ctrl-Z handler will store pid etc in pi */
2050 toplevel_list = pi;
2051 ctrl_z_flag = 0;
2052#if ENABLE_FEATURE_SH_STANDALONE
2053 nofork_save.saved = 0; /* in case we will run a nofork later */
2054#endif
Denis Vlasenko8e2cfec2008-03-12 23:19:35 +00002055 signal_SA_RESTART_empty_mask(SIGTSTP, handler_ctrl_z);
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002056 signal(SIGINT, handler_ctrl_c);
2057 }
Denis Vlasenko05743d72008-02-10 12:10:08 +00002058#endif /* JOB */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002059
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002060 for (; pi; pi = flag_restore ? rpipe : pi->next) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002061 rword = pi->res_word;
Denis Vlasenko06810332007-05-21 23:30:54 +00002062#if ENABLE_HUSH_LOOPS
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002063 if (rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002064 flag_restore = 0;
2065 if (!rpipe) {
2066 flag_rep = 0;
2067 rpipe = pi;
2068 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002069 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002070#endif
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002071 debug_printf_exec(": rword=%d if_code=%d next_if_code=%d skip_more=%d\n",
2072 rword, if_code, next_if_code, skip_more_for_this_rword);
2073 if (rword == skip_more_for_this_rword && flag_skip) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002074 if (pi->followup == PIPE_SEQ)
2075 flag_skip = 0;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002076 continue;
2077 }
2078 flag_skip = 1;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002079 skip_more_for_this_rword = RES_XXXX;
Denis Vlasenko06810332007-05-21 23:30:54 +00002080#if ENABLE_HUSH_IF
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002081 if (rword == RES_THEN || rword == RES_ELSE)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002082 if_code = next_if_code;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002083 if (rword == RES_THEN && if_code)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002084 continue;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002085 if (rword == RES_ELSE && !if_code)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002086 continue;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002087 if (rword == RES_ELIF && !if_code)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002088 break;
Denis Vlasenko06810332007-05-21 23:30:54 +00002089#endif
2090#if ENABLE_HUSH_LOOPS
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002091 if (rword == RES_FOR && pi->num_progs) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002092 if (!for_lcur) {
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002093 /* first loop through for */
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002094 /* if no variable values after "in" we skip "for" */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002095 if (!pi->next->progs->argv)
2096 continue;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002097 /* create list of variable values */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00002098 debug_print_strings("for_list made from", pi->next->progs->argv);
Denis Vlasenko170435c2007-05-23 13:01:10 +00002099 for_list = expand_strvec_to_strvec(pi->next->progs->argv);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00002100 debug_print_strings("for_list", for_list);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002101 for_lcur = for_list;
2102 for_varname = pi->progs->argv[0];
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002103 pi->progs->argv[0] = NULL;
2104 flag_rep = 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002105 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002106 free(pi->progs->argv[0]);
2107 if (!*for_lcur) {
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002108 /* for loop is over, clean up */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002109 free(for_list);
2110 for_lcur = NULL;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002111 flag_rep = 0;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002112 pi->progs->argv[0] = for_varname;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002113 continue;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002114 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002115 /* insert next value from for_lcur */
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002116 /* vda: does it need escaping? */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002117 pi->progs->argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002118 }
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002119 if (rword == RES_IN)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002120 continue;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002121 if (rword == RES_DO) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002122 if (!flag_rep)
2123 continue;
Tim Rikerc1ef7bd2006-01-25 00:08:53 +00002124 }
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002125 if (rword == RES_DONE) {
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002126 if (flag_rep) {
2127 flag_restore = 1;
2128 } else {
2129 rpipe = NULL;
2130 }
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002131 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002132#endif
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002133 if (pi->num_progs == 0)
2134 continue;
Denis Vlasenko05743d72008-02-10 12:10:08 +00002135 debug_printf_exec(": run_pipe with %d members\n", pi->num_progs);
2136 rcode = run_pipe(pi);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002137 if (rcode != -1) {
Eric Andersen25f27032001-04-26 23:22:31 +00002138 /* We only ran a builtin: rcode was set by the return value
Denis Vlasenko05743d72008-02-10 12:10:08 +00002139 * of run_pipe(), and we don't need to wait for anything. */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002140 } else if (pi->followup == PIPE_BG) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002141 /* What does bash do with attempts to background builtins? */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002142 /* Even bash 3.2 doesn't do that well with nested bg:
2143 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
Denis Vlasenko170435c2007-05-23 13:01:10 +00002144 * I'm NOT treating inner &'s as jobs */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002145#if ENABLE_HUSH_JOB
Denis Vlasenko4b924f32007-05-30 00:29:55 +00002146 if (run_list_level == 1)
Denis Vlasenko170435c2007-05-23 13:01:10 +00002147 insert_bg_job(pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002148#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002149 rcode = EXIT_SUCCESS;
2150 } else {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002151#if ENABLE_HUSH_JOB
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00002152 if (run_list_level == 1 && interactive_fd) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00002153 /* waits for completion, then fg's main shell */
Denis Vlasenko52881e92007-04-21 13:42:52 +00002154 rcode = checkjobs_and_fg_shell(pi);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002155 } else
2156#endif
2157 {
Denis Vlasenko170435c2007-05-23 13:01:10 +00002158 /* this one just waits for completion */
Eric Andersenc798b072001-06-22 06:23:03 +00002159 rcode = checkjobs(pi);
Eric Andersen25f27032001-04-26 23:22:31 +00002160 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002161 debug_printf_exec(": checkjobs returned %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00002162 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002163 debug_printf_exec(": setting last_return_code=%d\n", rcode);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002164 last_return_code = rcode;
Denis Vlasenko06810332007-05-21 23:30:54 +00002165#if ENABLE_HUSH_IF
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002166 if (rword == RES_IF || rword == RES_ELIF)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002167 next_if_code = rcode; /* can be overwritten a number of times */
Denis Vlasenko06810332007-05-21 23:30:54 +00002168#endif
2169#if ENABLE_HUSH_LOOPS
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002170 if (rword == RES_WHILE)
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002171 flag_rep = !last_return_code;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002172 if (rword == RES_UNTIL)
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002173 flag_rep = last_return_code;
Denis Vlasenko06810332007-05-21 23:30:54 +00002174#endif
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002175 if ((rcode == EXIT_SUCCESS && pi->followup == PIPE_OR)
2176 || (rcode != EXIT_SUCCESS && pi->followup == PIPE_AND)
2177 ) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002178 skip_more_for_this_rword = rword;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002179 }
Eric Andersen028b65b2001-06-28 01:10:11 +00002180 checkjobs(NULL);
Eric Andersen25f27032001-04-26 23:22:31 +00002181 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002182
2183#if ENABLE_HUSH_JOB
2184 if (ctrl_z_flag) {
2185 /* ctrl-Z forked somewhere in the past, we are the child,
2186 * and now we completed running the list. Exit. */
2187 exit(rcode);
2188 }
2189 ret:
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00002190 if (!--run_list_level && interactive_fd) {
2191 signal(SIGTSTP, SIG_IGN);
2192 signal(SIGINT, SIG_IGN);
2193 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002194#endif
Denis Vlasenko05743d72008-02-10 12:10:08 +00002195 debug_printf_exec("run_list lvl %d return %d\n", run_list_level + 1, rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00002196 return rcode;
2197}
2198
Eric Andersen25f27032001-04-26 23:22:31 +00002199/* return code is the exit status of the pipe */
Eric Andersenbf7df042001-05-23 22:18:35 +00002200static int free_pipe(struct pipe *pi, int indent)
Eric Andersen25f27032001-04-26 23:22:31 +00002201{
2202 char **p;
2203 struct child_prog *child;
2204 struct redir_struct *r, *rnext;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002205 int a, i, ret_code = 0;
Eric Andersen52a97ca2001-06-22 06:49:26 +00002206
2207 if (pi->stopped_progs > 0)
2208 return ret_code;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002209 debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002210 for (i = 0; i < pi->num_progs; i++) {
Eric Andersen25f27032001-04-26 23:22:31 +00002211 child = &pi->progs[i];
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002212 debug_printf_clean("%s command %d:\n", indenter(indent), i);
Eric Andersen25f27032001-04-26 23:22:31 +00002213 if (child->argv) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002214 for (a = 0, p = child->argv; *p; a++, p++) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002215 debug_printf_clean("%s argv[%d] = %s\n", indenter(indent), a, *p);
Eric Andersen25f27032001-04-26 23:22:31 +00002216 }
Denis Vlasenkof962a032007-11-23 12:50:54 +00002217 free_strings(child->argv);
2218 child->argv = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002219 } else if (child->group) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002220 debug_printf_clean("%s begin group (subshell:%d)\n", indenter(indent), child->subshell);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002221 ret_code = free_pipe_list(child->group, indent+3);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002222 debug_printf_clean("%s end group\n", indenter(indent));
Eric Andersen25f27032001-04-26 23:22:31 +00002223 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002224 debug_printf_clean("%s (nil)\n", indenter(indent));
Eric Andersen25f27032001-04-26 23:22:31 +00002225 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002226 for (r = child->redirects; r; r = rnext) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002227 debug_printf_clean("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->type].descrip);
Eric Andersen25f27032001-04-26 23:22:31 +00002228 if (r->dup == -1) {
Eric Andersen817e73c2001-06-06 17:56:09 +00002229 /* guard against the case >$FOO, where foo is unset or blank */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002230 if (r->rd_filename) {
2231 debug_printf_clean(" %s\n", r->rd_filename);
2232 free(r->rd_filename);
2233 r->rd_filename = NULL;
Eric Andersen817e73c2001-06-06 17:56:09 +00002234 }
Eric Andersen25f27032001-04-26 23:22:31 +00002235 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002236 debug_printf_clean("&%d\n", r->dup);
Eric Andersen25f27032001-04-26 23:22:31 +00002237 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002238 rnext = r->next;
Eric Andersen25f27032001-04-26 23:22:31 +00002239 free(r);
2240 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002241 child->redirects = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002242 }
2243 free(pi->progs); /* children are an array, they get freed all at once */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002244 pi->progs = NULL;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002245#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002246 free(pi->cmdtext);
2247 pi->cmdtext = NULL;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002248#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002249 return ret_code;
2250}
2251
Eric Andersenbf7df042001-05-23 22:18:35 +00002252static int free_pipe_list(struct pipe *head, int indent)
Eric Andersen25f27032001-04-26 23:22:31 +00002253{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002254 int rcode = 0; /* if list has no members */
Eric Andersen25f27032001-04-26 23:22:31 +00002255 struct pipe *pi, *next;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002256
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002257 for (pi = head; pi; pi = next) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002258 debug_printf_clean("%s pipe reserved mode %d\n", indenter(indent), pi->res_word);
Eric Andersenbf7df042001-05-23 22:18:35 +00002259 rcode = free_pipe(pi, indent);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002260 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002261 next = pi->next;
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002262 /*pi->next = NULL;*/
Eric Andersen25f27032001-04-26 23:22:31 +00002263 free(pi);
2264 }
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002265 return rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00002266}
2267
2268/* Select which version we will use */
Denis Vlasenko05743d72008-02-10 12:10:08 +00002269static int run_and_free_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00002270{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002271 int rcode = 0;
Denis Vlasenko05743d72008-02-10 12:10:08 +00002272 debug_printf_exec("run_and_free_list entered\n");
2273 if (!fake_mode) {
2274 debug_printf_exec(": run_list with %d members\n", pi->num_progs);
2275 rcode = run_list(pi);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002276 }
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002277 /* free_pipe_list has the side effect of clearing memory.
Denis Vlasenko05743d72008-02-10 12:10:08 +00002278 * In the long run that function can be merged with run_list,
Eric Andersen25f27032001-04-26 23:22:31 +00002279 * but doing that now would hobble the debugging effort. */
Denis Vlasenko05743d72008-02-10 12:10:08 +00002280 free_pipe_list(pi, /* indent: */ 0);
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002281 debug_printf_exec("run_and_free_list return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00002282 return rcode;
2283}
2284
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002285
Denis Vlasenko170435c2007-05-23 13:01:10 +00002286/* expand_strvec_to_strvec() takes a list of strings, expands
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002287 * all variable references within and returns a pointer to
2288 * a list of expanded strings, possibly with larger number
2289 * of strings. (Think VAR="a b"; echo $VAR).
2290 * This new list is allocated as a single malloc block.
2291 * NULL-terminated list of char* pointers is at the beginning of it,
2292 * followed by strings themself.
2293 * Caller can deallocate entire list by single free(list). */
2294
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002295/* Store given string, finalizing the word and starting new one whenever
2296 * we encounter ifs char(s). This is used for expanding variable values.
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002297 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002298static int expand_on_ifs(o_string *output, int n, const char *str)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002299{
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002300 while (1) {
2301 int word_len = strcspn(str, ifs);
2302 if (word_len) {
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002303 o_addstr(output, str, word_len);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002304 str += word_len;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002305 }
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002306 if (!*str) /* EOL - do not finalize word */
2307 break;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002308 o_addchr(output, '\0');
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002309 debug_print_list("expand_on_ifs", output, n);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002310 n = o_save_ptr(output, n);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002311 str += strspn(str, ifs); /* skip ifs chars */
2312 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002313 debug_print_list("expand_on_ifs[1]", output, n);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002314 return n;
2315}
2316
2317/* Expand all variable references in given string, adding words to list[]
2318 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2319 * to be filled). This routine is extremely tricky: has to deal with
2320 * variables/parameters with whitespace, $* and $@, and constructs like
2321 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002322/* NB: another bug is that we cannot detect empty strings yet:
2323 * "" or $empty"" expands to zero words, has to expand to empty word */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002324static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002325{
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002326 /* or_mask is either 0 (normal case) or 0x80
2327 * (expansion of right-hand side of assignment == 1-element expand) */
2328
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002329 char first_ch, ored_ch;
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002330 int i;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002331 const char *val;
2332 char *p;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002333
2334 ored_ch = 0;
2335
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002336 debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002337 debug_print_list("expand_vars_to_list", output, n);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002338 n = o_save_ptr(output, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002339 debug_print_list("expand_vars_to_list[0]", output, n);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002340
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002341 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
Denis Vlasenkoccce59d2008-06-16 14:35:57 +00002342#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002343 o_string subst_result = NULL_O_STRING;
Denis Vlasenkoccce59d2008-06-16 14:35:57 +00002344#endif
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002345
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002346 o_addstr(output, arg, p - arg);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002347 debug_print_list("expand_vars_to_list[1]", output, n);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002348 arg = ++p;
2349 p = strchr(p, SPECIAL_VAR_SYMBOL);
2350
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002351 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002352 ored_ch |= first_ch;
2353 val = NULL;
2354 switch (first_ch & 0x7f) {
2355 /* Highest bit in first_ch indicates that var is double-quoted */
2356 case '$': /* pid */
Denis Vlasenko16c2fea2008-06-17 12:28:44 +00002357 val = utoa(root_pid);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002358 break;
2359 case '!': /* bg pid */
2360 val = last_bg_pid ? utoa(last_bg_pid) : (char*)"";
2361 break;
2362 case '?': /* exitcode */
2363 val = utoa(last_return_code);
2364 break;
2365 case '#': /* argc */
2366 val = utoa(global_argc ? global_argc-1 : 0);
2367 break;
2368 case '*':
2369 case '@':
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002370 i = 1;
Denis Vlasenkoc3c66592007-11-24 00:22:42 +00002371 if (!global_argv[i])
2372 break;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002373 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denis Vlasenkoc3c66592007-11-24 00:22:42 +00002374 while (global_argv[i]) {
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002375 n = expand_on_ifs(output, n, global_argv[i]);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002376 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, global_argc-1);
Denis Vlasenkoc3c66592007-11-24 00:22:42 +00002377 if (global_argv[i++][0] && global_argv[i]) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002378 /* this argv[] is not empty and not last:
2379 * put terminating NUL, start new word */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002380 o_addchr(output, '\0');
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002381 debug_print_list("expand_vars_to_list[2]", output, n);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002382 n = o_save_ptr(output, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002383 debug_print_list("expand_vars_to_list[3]", output, n);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002384 }
2385 }
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002386 } else
2387 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00002388 * and in this case should treat it like '$*' - see 'else...' below */
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002389 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002390 while (1) {
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002391 o_addQstr(output, global_argv[i], strlen(global_argv[i])); ///really Q?
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002392 if (++i >= global_argc)
2393 break;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002394 o_addchr(output, '\0');
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002395 debug_print_list("expand_vars_to_list[4]", output, n);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002396 n = o_save_ptr(output, n);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002397 }
2398 } else { /* quoted $*: add as one word */
Denis Vlasenkoc3c66592007-11-24 00:22:42 +00002399 while (1) {
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002400 o_addQstr(output, global_argv[i], strlen(global_argv[i])); ///really Q?
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00002401 if (!global_argv[++i])
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002402 break;
2403 if (ifs[0])
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002404 o_addchr(output, ifs[0]);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002405 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002406 }
2407 break;
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00002408 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
2409 /* "Empty variable", used to make "" etc to not disappear */
2410 arg++;
2411 ored_ch = 0x80;
2412 break;
Denis Vlasenkoccce59d2008-06-16 14:35:57 +00002413#if ENABLE_HUSH_TICK
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00002414 case '`': { /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002415 struct in_str input;
2416 *p = '\0';
2417 arg++;
Denis Vlasenkoccce59d2008-06-16 14:35:57 +00002418//TODO: can we just stuff it into "output" directly?
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002419 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002420 setup_string_in_str(&input, arg);
2421 process_command_subs(&subst_result, &input, NULL);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002422 debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002423 val = subst_result.data;
2424 goto store_val;
2425 }
Denis Vlasenkoccce59d2008-06-16 14:35:57 +00002426#endif
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00002427 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002428 *p = '\0';
2429 arg[0] = first_ch & 0x7f;
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002430 if (isdigit(arg[0])) {
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002431 i = xatoi_u(arg);
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002432 val = NULL;
2433 if (i < global_argc)
2434 val = global_argv[i];
2435 } else
2436 val = lookup_param(arg);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002437 arg[0] = first_ch;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002438#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002439 store_val:
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002440#endif
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002441 *p = SPECIAL_VAR_SYMBOL;
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002442 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002443 debug_printf_expand("unquoted '%s', output->o_quote:%d\n", val, output->o_quote);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002444 if (val) {
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002445 n = expand_on_ifs(output, n, val);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002446 val = NULL;
2447 }
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002448 } else /* quoted $VAR, val will be appended below */
2449 debug_printf_expand("quoted '%s', output->o_quote:%d\n", val, output->o_quote);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002450 }
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002451 if (val) {
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002452 o_addQstr(output, val, strlen(val)); ///maybe q?
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002453 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002454
Denis Vlasenkoccce59d2008-06-16 14:35:57 +00002455#if ENABLE_HUSH_TICK
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002456 o_free(&subst_result);
Denis Vlasenkoccce59d2008-06-16 14:35:57 +00002457#endif
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002458 arg = ++p;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002459 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
2460
Denis Vlasenko2e76c3f2008-06-10 18:27:50 +00002461 if (arg[0]) {
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002462 debug_print_list("expand_vars_to_list[a]", output, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002463 /* this part is literal, and it was already pre-quoted
2464 * if needed (much earlier), do not use o_addQstr here! */
2465 o_addstr(output, arg, strlen(arg) + 1);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002466 debug_print_list("expand_vars_to_list[b]", output, n);
Denis Vlasenko2e76c3f2008-06-10 18:27:50 +00002467 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
2468 && !(ored_ch & 0x80) /* and all vars were not quoted. */
2469 ) {
2470 n--;
2471 /* allow to reuse list[n] later without re-growth */
2472 output->has_empty_slot = 1;
2473 } else {
2474 o_addchr(output, '\0');
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002475 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002476 return n;
2477}
2478
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002479static char **expand_variables(char **argv, int or_mask)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002480{
2481 int n;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002482 char **list;
2483 char **v;
2484 o_string output = NULL_O_STRING;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002485
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002486 if (or_mask & 0x100) {
2487 output.o_quote = 1;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002488 output.o_glob = 1;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002489 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002490
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002491 n = 0;
2492 v = argv;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002493 while (*v) {
2494 n = expand_vars_to_list(&output, n, *v, (char)or_mask);
2495 v++;
2496 }
2497 debug_print_list("expand_variables", &output, n);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002498
Denis Vlasenko82dfec32008-06-16 12:47:11 +00002499 /* output.data (malloced in one block) gets returned in "list" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002500 list = o_finalize_list(&output, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002501 debug_print_strings("expand_variables[1]", list);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002502 return list;
2503}
2504
Denis Vlasenko170435c2007-05-23 13:01:10 +00002505static char **expand_strvec_to_strvec(char **argv)
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002506{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002507 return expand_variables(argv, 0x100);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002508}
2509
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002510/* Used for expansion of right hand of assignments */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00002511/* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
2512 * "v=/bin/c*" */
Denis Vlasenko170435c2007-05-23 13:01:10 +00002513static char *expand_string_to_string(const char *str)
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002514{
2515 char *argv[2], **list;
2516
2517 argv[0] = (char*)str;
2518 argv[1] = NULL;
2519 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
Denis Vlasenko170435c2007-05-23 13:01:10 +00002520 if (ENABLE_HUSH_DEBUG)
2521 if (!list[0] || list[1])
2522 bb_error_msg_and_die("BUG in varexp2");
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002523 /* actually, just move string 2*sizeof(char*) bytes back */
2524 strcpy((char*)list, list[0]);
Denis Vlasenko170435c2007-05-23 13:01:10 +00002525 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2526 return (char*)list;
2527}
2528
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002529/* Used for "eval" builtin */
Denis Vlasenko170435c2007-05-23 13:01:10 +00002530static char* expand_strvec_to_string(char **argv)
2531{
2532 char **list;
2533
2534 list = expand_variables(argv, 0x80);
2535 /* Convert all NULs to spaces */
2536 if (list[0]) {
2537 int n = 1;
2538 while (list[n]) {
2539 if (ENABLE_HUSH_DEBUG)
2540 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2541 bb_error_msg_and_die("BUG in varexp3");
2542 list[n][-1] = ' '; /* TODO: or to ifs[0]? */
2543 n++;
2544 }
2545 }
2546 strcpy((char*)list, list[0]);
2547 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002548 return (char*)list;
2549}
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002550
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002551
2552/* Used to get/check local shell variables */
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002553static struct variable *get_local_var(const char *name)
Eric Andersenf72f5622001-05-15 23:21:41 +00002554{
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002555 struct variable *cur;
2556 int len;
Eric Andersenf72f5622001-05-15 23:21:41 +00002557
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002558 if (!name)
Eric Andersenf72f5622001-05-15 23:21:41 +00002559 return NULL;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002560 len = strlen(name);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002561 for (cur = top_var; cur; cur = cur->next) {
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002562 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002563 return cur;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00002564 }
Eric Andersenf72f5622001-05-15 23:21:41 +00002565 return NULL;
2566}
2567
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002568/* str holds "NAME=VAL" and is expected to be malloced.
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002569 * We take ownership of it. */
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002570static int set_local_var(char *str, int flg_export)
Eric Andersen78a7c992001-05-15 16:30:25 +00002571{
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002572 struct variable *cur;
2573 char *value;
2574 int name_len;
Eric Andersen20a69a72001-05-15 17:24:44 +00002575
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002576 value = strchr(str, '=');
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002577 if (!value) { /* not expected to ever happen? */
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002578 free(str);
Eric Andersen99785762001-05-22 21:37:48 +00002579 return -1;
2580 }
Eric Andersen20a69a72001-05-15 17:24:44 +00002581
Denis Vlasenko201c72a2007-05-25 10:00:36 +00002582 name_len = value - str + 1; /* including '=' */
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002583 cur = top_var; /* cannot be NULL (we have HUSH_VERSION and it's RO) */
2584 while (1) {
Denis Vlasenko201c72a2007-05-25 10:00:36 +00002585 if (strncmp(cur->varstr, str, name_len) != 0) {
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002586 if (!cur->next) {
Denis Vlasenko201c72a2007-05-25 10:00:36 +00002587 /* Bail out. Note that now cur points
2588 * to last var in linked list */
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002589 break;
Eric Andersen20a69a72001-05-15 17:24:44 +00002590 }
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002591 cur = cur->next;
2592 continue;
Eric Andersen20a69a72001-05-15 17:24:44 +00002593 }
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002594 /* We found an existing var with this name */
2595 *value = '\0';
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002596 if (cur->flg_read_only) {
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002597 bb_error_msg("%s: readonly variable", str);
2598 free(str);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002599 return -1;
2600 }
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002601 unsetenv(str); /* just in case */
2602 *value = '=';
2603 if (strcmp(cur->varstr, str) == 0) {
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002604 free_and_exp:
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002605 free(str);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002606 goto exp;
2607 }
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002608 if (cur->max_len >= strlen(str)) {
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002609 /* This one is from startup env, reuse space */
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002610 strcpy(cur->varstr, str);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002611 goto free_and_exp;
2612 }
2613 /* max_len == 0 signifies "malloced" var, which we can
2614 * (and has to) free */
2615 if (!cur->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002616 free(cur->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002617 cur->max_len = 0;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002618 goto set_str_and_exp;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002619 }
Eric Andersen20a69a72001-05-15 17:24:44 +00002620
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002621 /* Not found - create next variable struct */
2622 cur->next = xzalloc(sizeof(*cur));
2623 cur = cur->next;
2624
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002625 set_str_and_exp:
2626 cur->varstr = str;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002627 exp:
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002628 if (flg_export)
2629 cur->flg_export = 1;
2630 if (cur->flg_export)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002631 return putenv(cur->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002632 return 0;
Eric Andersen20a69a72001-05-15 17:24:44 +00002633}
2634
Eric Andersenf72f5622001-05-15 23:21:41 +00002635static void unset_local_var(const char *name)
Eric Andersen20a69a72001-05-15 17:24:44 +00002636{
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002637 struct variable *cur;
2638 struct variable *prev = prev; /* for gcc */
2639 int name_len;
Eric Andersen20a69a72001-05-15 17:24:44 +00002640
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002641 if (!name)
2642 return;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002643 name_len = strlen(name);
2644 cur = top_var;
2645 while (cur) {
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002646 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002647 if (cur->flg_read_only) {
Manuel Novoa III cad53642003-03-19 09:13:01 +00002648 bb_error_msg("%s: readonly variable", name);
Eric Andersen94ac2442001-05-22 19:05:18 +00002649 return;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002650 }
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002651 /* prev is ok to use here because 1st variable, HUSH_VERSION,
2652 * is ro, and we cannot reach this code on the 1st pass */
2653 prev->next = cur->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002654 unsetenv(cur->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002655 if (!cur->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002656 free(cur->varstr);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002657 free(cur);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002658 return;
Eric Andersenf72f5622001-05-15 23:21:41 +00002659 }
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002660 prev = cur;
2661 cur = cur->next;
Eric Andersen20a69a72001-05-15 17:24:44 +00002662 }
Eric Andersen78a7c992001-05-15 16:30:25 +00002663}
2664
Eric Andersen25f27032001-04-26 23:22:31 +00002665/* the src parameter allows us to peek forward to a possible &n syntax
2666 * for file descriptor duplication, e.g., "2>&1".
2667 * Return code is 0 normally, 1 if a syntax error is detected in src.
2668 * Resource errors (in xmalloc) cause the process to exit */
2669static int setup_redirect(struct p_context *ctx, int fd, redir_type style,
2670 struct in_str *input)
2671{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002672 struct child_prog *child = ctx->child;
Eric Andersen25f27032001-04-26 23:22:31 +00002673 struct redir_struct *redir = child->redirects;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002674 struct redir_struct *last_redir = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002675
2676 /* Create a new redir_struct and drop it onto the end of the linked list */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002677 while (redir) {
2678 last_redir = redir;
2679 redir = redir->next;
Eric Andersen25f27032001-04-26 23:22:31 +00002680 }
Denis Vlasenkoff097622007-10-01 10:00:45 +00002681 redir = xzalloc(sizeof(struct redir_struct));
2682 /* redir->next = NULL; */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002683 /* redir->rd_filename = NULL; */
Eric Andersen25f27032001-04-26 23:22:31 +00002684 if (last_redir) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002685 last_redir->next = redir;
Eric Andersen25f27032001-04-26 23:22:31 +00002686 } else {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002687 child->redirects = redir;
Eric Andersen25f27032001-04-26 23:22:31 +00002688 }
2689
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002690 redir->type = style;
2691 redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
Eric Andersen25f27032001-04-26 23:22:31 +00002692
2693 debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
2694
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002695 /* Check for a '2>&1' type redirect */
Eric Andersen25f27032001-04-26 23:22:31 +00002696 redir->dup = redirect_dup_num(input);
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002697 if (redir->dup == -2)
2698 return 1; /* syntax error */
Eric Andersen25f27032001-04-26 23:22:31 +00002699 if (redir->dup != -1) {
2700 /* Erik had a check here that the file descriptor in question
Eric Andersen83a2ae22001-05-07 17:59:25 +00002701 * is legit; I postpone that to "run time"
2702 * A "-" representation of "close me" shows up as a -3 here */
Eric Andersen25f27032001-04-26 23:22:31 +00002703 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
2704 } else {
2705 /* We do _not_ try to open the file that src points to,
2706 * since we need to return and let src be expanded first.
2707 * Set ctx->pending_redirect, so we know what to do at the
Denis Vlasenko201c72a2007-05-25 10:00:36 +00002708 * end of the next parsed word. */
Eric Andersen25f27032001-04-26 23:22:31 +00002709 ctx->pending_redirect = redir;
2710 }
2711 return 0;
2712}
2713
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00002714static struct pipe *new_pipe(void)
2715{
Eric Andersen25f27032001-04-26 23:22:31 +00002716 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002717 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002718 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002719 if (RES_NONE)
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002720 pi->res_word = RES_NONE;
Eric Andersen25f27032001-04-26 23:22:31 +00002721 return pi;
2722}
2723
2724static void initialize_context(struct p_context *ctx)
2725{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002726 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00002727 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002728 /* Create the memory for child, roughly:
2729 * ctx->pipe->progs = new struct child_prog;
2730 * ctx->pipe->progs[0].family = ctx->pipe;
2731 * ctx->child = &ctx->pipe->progs[0];
2732 */
2733 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00002734}
2735
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002736/* If a reserved word is found and processed, parse context is modified
2737 * and 1 is returned.
2738 * Handles if, then, elif, else, fi, for, while, until, do, done.
Eric Andersen25f27032001-04-26 23:22:31 +00002739 * case, function, and select are obnoxious, save those for later.
2740 */
Denis Vlasenko06810332007-05-21 23:30:54 +00002741#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002742static int reserved_word(const o_string *word, struct p_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00002743{
2744 struct reserved_combo {
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002745 char literal[7];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002746 unsigned char res;
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002747 int flag;
Eric Andersen25f27032001-04-26 23:22:31 +00002748 };
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002749 enum {
2750 FLAG_END = (1 << RES_NONE ),
2751#if ENABLE_HUSH_IF
2752 FLAG_IF = (1 << RES_IF ),
2753 FLAG_THEN = (1 << RES_THEN ),
2754 FLAG_ELIF = (1 << RES_ELIF ),
2755 FLAG_ELSE = (1 << RES_ELSE ),
2756 FLAG_FI = (1 << RES_FI ),
2757#endif
2758#if ENABLE_HUSH_LOOPS
2759 FLAG_FOR = (1 << RES_FOR ),
2760 FLAG_WHILE = (1 << RES_WHILE),
2761 FLAG_UNTIL = (1 << RES_UNTIL),
2762 FLAG_DO = (1 << RES_DO ),
2763 FLAG_DONE = (1 << RES_DONE ),
2764 FLAG_IN = (1 << RES_IN ),
2765#endif
2766 FLAG_START = (1 << RES_XXXX ),
2767 };
Eric Andersen25f27032001-04-26 23:22:31 +00002768 /* Mostly a list of accepted follow-up reserved words.
2769 * FLAG_END means we are done with the sequence, and are ready
2770 * to turn the compound list into a command.
2771 * FLAG_START means the word must start a new compound list.
2772 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002773 static const struct reserved_combo reserved_list[] = {
Denis Vlasenko06810332007-05-21 23:30:54 +00002774#if ENABLE_HUSH_IF
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002775 { "!", RES_NONE, 0 },
Eric Andersen25f27032001-04-26 23:22:31 +00002776 { "if", RES_IF, FLAG_THEN | FLAG_START },
2777 { "then", RES_THEN, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2778 { "elif", RES_ELIF, FLAG_THEN },
2779 { "else", RES_ELSE, FLAG_FI },
2780 { "fi", RES_FI, FLAG_END },
Denis Vlasenko06810332007-05-21 23:30:54 +00002781#endif
2782#if ENABLE_HUSH_LOOPS
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002783 { "for", RES_FOR, FLAG_IN | FLAG_START },
2784 { "while", RES_WHILE, FLAG_DO | FLAG_START },
2785 { "until", RES_UNTIL, FLAG_DO | FLAG_START },
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002786 { "in", RES_IN, FLAG_DO },
Eric Andersen25f27032001-04-26 23:22:31 +00002787 { "do", RES_DO, FLAG_DONE },
2788 { "done", RES_DONE, FLAG_END }
Denis Vlasenko06810332007-05-21 23:30:54 +00002789#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002790 };
Denis Vlasenko80b8b392007-06-25 10:55:35 +00002791
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002792 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002793
Denis Vlasenko80b8b392007-06-25 10:55:35 +00002794 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002795 if (strcmp(word->data, r->literal) != 0)
Denis Vlasenko1a735862007-05-23 00:32:25 +00002796 continue;
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002797 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
2798 if (r->flag == 0) { /* '!' */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002799#if ENABLE_HUSH_LOOPS
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002800 if (ctx->res_w == RES_IN) {
2801 /* 'for a in ! a b c; ...' - ! isn't a keyword here */
2802 break;
2803 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002804#endif
2805 if (ctx->ctx_inverted /* bash doesn't accept '! ! true' */
2806#if ENABLE_HUSH_LOOPS
2807 || ctx->res_w == RES_FOR /* example: 'for ! a' */
2808#endif
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002809 ) {
2810 syntax(NULL);
2811 ctx->res_w = RES_SNTX;
2812 }
2813 ctx->ctx_inverted = 1;
2814 return 1;
2815 }
Denis Vlasenko1a735862007-05-23 00:32:25 +00002816 if (r->flag & FLAG_START) {
2817 struct p_context *new;
2818 debug_printf("push stack\n");
Denis Vlasenko06810332007-05-21 23:30:54 +00002819#if ENABLE_HUSH_LOOPS
Denis Vlasenko1a735862007-05-23 00:32:25 +00002820 if (ctx->res_w == RES_IN || ctx->res_w == RES_FOR) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00002821 syntax("malformed for"); /* example: 'for if' */
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002822 ctx->res_w = RES_SNTX;
Eric Andersenaf44a0e2001-04-27 07:26:12 +00002823 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002824 }
Denis Vlasenko1a735862007-05-23 00:32:25 +00002825#endif
2826 new = xmalloc(sizeof(*new));
2827 *new = *ctx; /* physical copy */
2828 initialize_context(ctx);
2829 ctx->stack = new;
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002830 } else if (ctx->res_w == RES_NONE || !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00002831 syntax(NULL);
Denis Vlasenko1a735862007-05-23 00:32:25 +00002832 ctx->res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00002833 return 1;
2834 }
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002835 ctx->res_w = r->res;
Denis Vlasenko1a735862007-05-23 00:32:25 +00002836 ctx->old_flag = r->flag;
2837 if (ctx->old_flag & FLAG_END) {
2838 struct p_context *old;
2839 debug_printf("pop stack\n");
2840 done_pipe(ctx, PIPE_SEQ);
2841 old = ctx->stack;
2842 old->child->group = ctx->list_head;
2843 old->child->subshell = 0;
2844 *ctx = *old; /* physical copy */
2845 free(old);
2846 }
Denis Vlasenko1a735862007-05-23 00:32:25 +00002847 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002848 }
2849 return 0;
2850}
Denis Vlasenko06810332007-05-21 23:30:54 +00002851#else
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002852#define reserved_word(word, ctx) ((int)0)
Denis Vlasenko06810332007-05-21 23:30:54 +00002853#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002854
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002855/* Word is complete, look at it and update parsing context.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002856 * Normal return is 0. Syntax errors return 1. */
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002857static int done_word(o_string *word, struct p_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00002858{
Denis Vlasenkobb81c582007-01-30 22:32:09 +00002859 struct child_prog *child = ctx->child;
Eric Andersen25f27032001-04-26 23:22:31 +00002860
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002861 debug_printf_parse("done_word entered: '%s' %p\n", word->data, child);
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002862 if (word->length == 0 && word->nonnull == 0) {
2863 debug_printf_parse("done_word return 0: true null, ignored\n");
2864 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00002865 }
2866 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002867 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
2868 * only if run as "bash", not "sh" */
2869 ctx->pending_redirect->rd_filename = xstrdup(word->data);
2870 debug_printf("word stored in rd_filename: '%s'\n", word->data);
Eric Andersen25f27032001-04-26 23:22:31 +00002871 } else {
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002872 if (child->group) { /* TODO: example how to trigger? */
Denis Vlasenko90e485c2007-05-23 15:22:50 +00002873 syntax(NULL);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002874 debug_printf_parse("done_word return 1: syntax error, groups and arglists don't mix\n");
2875 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002876 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00002877 if (!child->argv) { /* if it's the first word... */
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002878 debug_printf_parse(": checking '%s' for reserved-ness\n", word->data);
2879 if (reserved_word(word, ctx)) {
2880 o_reset(word);
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002881 debug_printf_parse("done_word return %d\n", (ctx->res_w == RES_SNTX));
2882 return (ctx->res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002883 }
Eric Andersen25f27032001-04-26 23:22:31 +00002884 }
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002885 if (word->nonnull
2886 /* && word->data[0] != */
2887 ) {
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00002888 /* Insert "empty variable" reference, this makes e.g. "", '',
2889 * $empty"" etc to not disappear */
2890 o_addchr(word, SPECIAL_VAR_SYMBOL);
2891 o_addchr(word, SPECIAL_VAR_SYMBOL);
2892 }
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002893 child->argv = add_malloced_string_to_strings(child->argv, xstrdup(word->data));
2894 debug_print_strings("word appended to argv", child->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002895 }
Eric Andersen25f27032001-04-26 23:22:31 +00002896
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002897 o_reset(word);
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002898 ctx->pending_redirect = NULL;
2899
Denis Vlasenko06810332007-05-21 23:30:54 +00002900#if ENABLE_HUSH_LOOPS
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002901 /* Force FOR to have just one word (variable name) */
2902 if (ctx->res_w == RES_FOR)
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00002903 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko06810332007-05-21 23:30:54 +00002904#endif
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002905 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00002906 return 0;
2907}
2908
Denis Vlasenko6eaf8de2008-06-17 12:09:21 +00002909/* Command (member of a pipe) is complete. The only possible error here
2910 * is out of memory, in which case xmalloc exits. */
Eric Andersen25f27032001-04-26 23:22:31 +00002911static int done_command(struct p_context *ctx)
2912{
2913 /* The child is really already in the pipe structure, so
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002914 * advance the pipe counter and make a new, null child. */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00002915 struct pipe *pi = ctx->pipe;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002916 struct child_prog *child = ctx->child;
Eric Andersen25f27032001-04-26 23:22:31 +00002917
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002918 if (child) {
2919 if (child->group == NULL
2920 && child->argv == NULL
2921 && child->redirects == NULL
2922 ) {
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00002923 debug_printf_parse("done_command: skipping null cmd, num_progs=%d\n", pi->num_progs);
2924 return pi->num_progs;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002925 }
Eric Andersen25f27032001-04-26 23:22:31 +00002926 pi->num_progs++;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002927 debug_printf_parse("done_command: ++num_progs=%d\n", pi->num_progs);
Eric Andersen25f27032001-04-26 23:22:31 +00002928 } else {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002929 debug_printf_parse("done_command: initializing, num_progs=%d\n", pi->num_progs);
Eric Andersen25f27032001-04-26 23:22:31 +00002930 }
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002931
2932 /* Only real trickiness here is that the uncommitted
2933 * child structure is not counted in pi->num_progs. */
Eric Andersen25f27032001-04-26 23:22:31 +00002934 pi->progs = xrealloc(pi->progs, sizeof(*pi->progs) * (pi->num_progs+1));
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002935 child = &pi->progs[pi->num_progs];
Eric Andersen25f27032001-04-26 23:22:31 +00002936
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002937 memset(child, 0, sizeof(*child));
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002938 child->family = pi;
Eric Andersen25f27032001-04-26 23:22:31 +00002939
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002940 ctx->child = child;
Eric Andersen25f27032001-04-26 23:22:31 +00002941 /* but ctx->pipe and ctx->list_head remain unchanged */
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002942
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00002943 return pi->num_progs; /* used only for 0/nonzero check */
Eric Andersen25f27032001-04-26 23:22:31 +00002944}
2945
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002946static void done_pipe(struct p_context *ctx, pipe_style type)
Eric Andersen25f27032001-04-26 23:22:31 +00002947{
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00002948 int not_null;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002949
2950 debug_printf_parse("done_pipe entered, followup %d\n", type);
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00002951 not_null = done_command(ctx); /* implicit closure of previous command */
Eric Andersen25f27032001-04-26 23:22:31 +00002952 ctx->pipe->followup = type;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002953 ctx->pipe->res_word = ctx->res_w;
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002954 ctx->pipe->pi_inverted = ctx->ctx_inverted;
2955 ctx->ctx_inverted = 0;
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00002956 /* Without this check, even just <enter> on command line generates
2957 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenko6eaf8de2008-06-17 12:09:21 +00002958 * IOW: it is safe to do it unconditionally.
2959 * RES_IN case is for "for a in; do ..." (empty IN set)
2960 * to work. */
2961 if (not_null || ctx->pipe->res_word == RES_IN) {
2962 struct pipe *new_p = new_pipe();
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00002963 ctx->pipe->next = new_p;
2964 ctx->pipe = new_p;
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002965 ctx->child = NULL; /* needed! */
2966 /* Create the memory for child, roughly:
2967 * ctx->pipe->progs = new struct child_prog;
2968 * ctx->pipe->progs[0].family = ctx->pipe;
2969 * ctx->child = &ctx->pipe->progs[0];
2970 */
2971 done_command(ctx);
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00002972 }
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002973 debug_printf_parse("done_pipe return\n");
Eric Andersen25f27032001-04-26 23:22:31 +00002974}
2975
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002976/* Peek ahead in the in_str to find out if we have a "&n" construct,
Eric Andersen25f27032001-04-26 23:22:31 +00002977 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002978 * Return either -2 (syntax error), -1 (no &), or the number found.
Eric Andersen25f27032001-04-26 23:22:31 +00002979 */
2980static int redirect_dup_num(struct in_str *input)
2981{
Denis Vlasenkobb81c582007-01-30 22:32:09 +00002982 int ch, d = 0, ok = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002983 ch = i_peek(input);
Eric Andersen25f27032001-04-26 23:22:31 +00002984 if (ch != '&') return -1;
2985
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002986 i_getch(input); /* get the & */
2987 ch = i_peek(input);
Eric Andersen83a2ae22001-05-07 17:59:25 +00002988 if (ch == '-') {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002989 i_getch(input);
Eric Andersen83a2ae22001-05-07 17:59:25 +00002990 return -3; /* "-" represents "close me" */
2991 }
2992 while (isdigit(ch)) {
Denis Vlasenko7d4c44e2007-04-16 22:34:39 +00002993 d = d*10 + (ch-'0');
Denis Vlasenkobb81c582007-01-30 22:32:09 +00002994 ok = 1;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002995 i_getch(input);
2996 ch = i_peek(input);
Eric Andersen25f27032001-04-26 23:22:31 +00002997 }
2998 if (ok) return d;
2999
Manuel Novoa III cad53642003-03-19 09:13:01 +00003000 bb_error_msg("ambiguous redirect");
Eric Andersen25f27032001-04-26 23:22:31 +00003001 return -2;
3002}
3003
3004/* If a redirect is immediately preceded by a number, that number is
3005 * supposed to tell which file descriptor to redirect. This routine
3006 * looks for such preceding numbers. In an ideal world this routine
3007 * needs to handle all the following classes of redirects...
3008 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3009 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3010 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3011 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3012 * A -1 output from this program means no valid number was found, so the
3013 * caller should use the appropriate default for this redirection.
3014 */
3015static int redirect_opt_num(o_string *o)
3016{
3017 int num;
3018
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003019 if (o->length == 0)
3020 return -1;
3021 for (num = 0; num < o->length; num++) {
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00003022 if (!isdigit(o->data[num])) {
Eric Andersen25f27032001-04-26 23:22:31 +00003023 return -1;
3024 }
3025 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003026 num = atoi(o->data);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003027 o_reset(o);
Eric Andersen25f27032001-04-26 23:22:31 +00003028 return num;
3029}
3030
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003031#if ENABLE_HUSH_TICK
"Vladimir N. Oleynik"19c37012005-09-22 14:33:15 +00003032static FILE *generate_stream_from_list(struct pipe *head)
Eric Andersen25f27032001-04-26 23:22:31 +00003033{
3034 FILE *pf;
Eric Andersen25f27032001-04-26 23:22:31 +00003035 int pid, channel[2];
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003036
Denis Vlasenko5a6aedd2007-05-26 16:44:20 +00003037 xpipe(channel);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003038/* *** NOMMU WARNING *** */
3039/* By using vfork here, we suspend parent till child exits or execs.
3040 * If child will not do it before it fills the pipe, it can block forever
3041 * in write(STDOUT_FILENO), and parent (shell) will be also stuck.
Denis Vlasenko3fe4f982008-06-09 16:02:39 +00003042 * Try this script:
3043 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >TESTFILE
3044 * huge=`cat TESTFILE` # will block here forever
3045 * echo OK
Denis Vlasenko05743d72008-02-10 12:10:08 +00003046 */
3047 pid = BB_MMU ? fork() : vfork();
3048 if (pid < 0)
3049 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
3050 if (pid == 0) { /* child */
Denis Vlasenko83177992008-02-11 08:44:36 +00003051 if (ENABLE_HUSH_JOB)
3052 die_sleep = 0; /* let nofork's xfuncs die */
Denis Vlasenko284d0fa2008-02-16 13:18:17 +00003053 close(channel[0]); /* NB: close _first_, then move fd! */
Denis Vlasenko05743d72008-02-10 12:10:08 +00003054 xmove_fd(channel[1], 1);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003055 /* Prevent it from trying to handle ctrl-z etc */
Denis Vlasenko27f79ff2007-05-30 00:55:52 +00003056#if ENABLE_HUSH_JOB
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003057 run_list_level = 1;
Denis Vlasenko27f79ff2007-05-30 00:55:52 +00003058#endif
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003059 /* Process substitution is not considered to be usual
3060 * 'command execution'.
3061 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not. */
3062 /* Not needed, we are relying on it being disabled
3063 * everywhere outside actual command execution. */
3064 /*set_jobctrl_sighandler(SIG_IGN);*/
3065 set_misc_sighandler(SIG_DFL);
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00003066 /* Freeing 'head' here would break NOMMU. */
3067 _exit(run_list(head));
Eric Andersen25f27032001-04-26 23:22:31 +00003068 }
Eric Andersen25f27032001-04-26 23:22:31 +00003069 close(channel[1]);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003070 pf = fdopen(channel[0], "r");
Eric Andersen25f27032001-04-26 23:22:31 +00003071 return pf;
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00003072 /* 'head' is freed by the caller */
Eric Andersen25f27032001-04-26 23:22:31 +00003073}
3074
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003075/* Return code is exit status of the process that is run. */
Denis Vlasenko68404f12008-03-17 09:00:54 +00003076static int process_command_subs(o_string *dest,
Denis Vlasenko68404f12008-03-17 09:00:54 +00003077 struct in_str *input,
3078 const char *subst_end)
Eric Andersen25f27032001-04-26 23:22:31 +00003079{
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003080 int retcode, ch, eol_cnt;
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003081 o_string result = NULL_O_STRING;
Eric Andersen25f27032001-04-26 23:22:31 +00003082 struct p_context inner;
3083 FILE *p;
3084 struct in_str pipe_str;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003085
Eric Andersen25f27032001-04-26 23:22:31 +00003086 initialize_context(&inner);
3087
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003088 /* Recursion to generate command */
Eric Andersen25f27032001-04-26 23:22:31 +00003089 retcode = parse_stream(&result, &inner, input, subst_end);
Denis Vlasenko1a735862007-05-23 00:32:25 +00003090 if (retcode != 0)
3091 return retcode; /* syntax error or EOF */
Eric Andersen25f27032001-04-26 23:22:31 +00003092 done_word(&result, &inner);
3093 done_pipe(&inner, PIPE_SEQ);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003094 o_free(&result);
Eric Andersen25f27032001-04-26 23:22:31 +00003095
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003096 p = generate_stream_from_list(inner.list_head);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003097 if (p == NULL)
3098 return 1;
Denis Vlasenkoa0898172007-10-01 09:59:01 +00003099 close_on_exec_on(fileno(p));
Eric Andersen25f27032001-04-26 23:22:31 +00003100 setup_file_in_str(&pipe_str, p);
3101
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003102 /* Now send results of command back into original context */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003103 eol_cnt = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003104 while ((ch = i_getch(&pipe_str)) != EOF) {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003105 if (ch == '\n') {
3106 eol_cnt++;
3107 continue;
3108 }
3109 while (eol_cnt) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003110 o_addQchr(dest, '\n');
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003111 eol_cnt--;
3112 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003113 /* Even unquoted `echo '\'` results in two backslashes
3114 * (which are converted into one by globbing later) */
3115 if (!dest->o_quote && ch == '\\') {
3116 o_addchr(dest, ch);
3117 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003118 o_addQchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003119 }
3120
3121 debug_printf("done reading from pipe, pclose()ing\n");
3122 /* This is the step that wait()s for the child. Should be pretty
3123 * safe, since we just read an EOF from its stdout. We could try
Denis Vlasenko262d7652007-05-20 21:52:49 +00003124 * to do better, by using wait(), and keeping track of background jobs
Eric Andersen25f27032001-04-26 23:22:31 +00003125 * at the same time. That would be a lot of work, and contrary
3126 * to the KISS philosophy of this program. */
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003127 retcode = fclose(p);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003128 free_pipe_list(inner.list_head, /* indent: */ 0);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003129 debug_printf("closed FILE from child, retcode=%d\n", retcode);
Eric Andersen25f27032001-04-26 23:22:31 +00003130 return retcode;
3131}
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003132#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003133
3134static int parse_group(o_string *dest, struct p_context *ctx,
3135 struct in_str *input, int ch)
3136{
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003137 int rcode;
3138 const char *endch = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003139 struct p_context sub;
3140 struct child_prog *child = ctx->child;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003141
3142 debug_printf_parse("parse_group entered\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003143 if (child->argv) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003144 syntax(NULL);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003145 debug_printf_parse("parse_group return 1: syntax error, groups and arglists don't mix\n");
3146 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003147 }
3148 initialize_context(&sub);
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003149 endch = "}";
3150 if (ch == '(') {
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003151 endch = ")";
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003152 child->subshell = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003153 }
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003154 rcode = parse_stream(dest, &sub, input, endch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003155 if (rcode == 0) {
3156 done_word(dest, &sub); /* finish off the final word in the subcontext */
3157 done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */
3158 child->group = sub.list_head;
3159 }
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003160 debug_printf_parse("parse_group return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00003161 return rcode;
3162 /* child remains "open", available for possible redirects */
3163}
3164
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003165/* Basically useful version until someone wants to get fancier,
Eric Andersen25f27032001-04-26 23:22:31 +00003166 * see the bash man page under "Parameter Expansion" */
Denis Vlasenko15d78fb2007-01-30 22:28:21 +00003167static const char *lookup_param(const char *src)
Eric Andersen25f27032001-04-26 23:22:31 +00003168{
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003169 struct variable *var = get_local_var(src);
3170 if (var)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00003171 return strchr(var->varstr, '=') + 1;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003172 return NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003173}
3174
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003175#if ENABLE_HUSH_TICK
3176/* Subroutines for copying $(...) and `...` things */
3177static void add_till_backquote(o_string *dest, struct in_str *input);
3178/* '...' */
3179static void add_till_single_quote(o_string *dest, struct in_str *input)
3180{
3181 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003182 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003183 if (ch == EOF)
3184 break;
3185 if (ch == '\'')
3186 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003187 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003188 }
3189}
3190/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
3191static void add_till_double_quote(o_string *dest, struct in_str *input)
3192{
3193 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003194 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003195 if (ch == '"')
3196 break;
3197 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003198 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003199 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003200 }
3201 if (ch == EOF)
3202 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003203 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003204 if (ch == '`') {
3205 add_till_backquote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003206 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003207 continue;
3208 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00003209 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003210 }
3211}
3212/* Process `cmd` - copy contents until "`" is seen. Complicated by
3213 * \` quoting.
3214 * "Within the backquoted style of command substitution, backslash
3215 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3216 * The search for the matching backquote shall be satisfied by the first
3217 * backquote found without a preceding backslash; during this search,
3218 * if a non-escaped backquote is encountered within a shell comment,
3219 * a here-document, an embedded command substitution of the $(command)
3220 * form, or a quoted string, undefined results occur. A single-quoted
3221 * or double-quoted string that begins, but does not end, within the
3222 * "`...`" sequence produces undefined results."
3223 * Example Output
3224 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3225 */
3226static void add_till_backquote(o_string *dest, struct in_str *input)
3227{
3228 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003229 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003230 if (ch == '`')
3231 break;
3232 if (ch == '\\') { /* \x. Copy both chars unless it is \` */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003233 int ch2 = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003234 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003235 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003236 ch = ch2;
3237 }
3238 if (ch == EOF)
3239 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003240 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003241 }
3242}
3243/* Process $(cmd) - copy contents until ")" is seen. Complicated by
3244 * quoting and nested ()s.
3245 * "With the $(command) style of command substitution, all characters
3246 * following the open parenthesis to the matching closing parenthesis
3247 * constitute the command. Any valid shell script can be used for command,
3248 * except a script consisting solely of redirections which produces
3249 * unspecified results."
3250 * Example Output
3251 * echo $(echo '(TEST)' BEST) (TEST) BEST
3252 * echo $(echo 'TEST)' BEST) TEST) BEST
3253 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
3254 */
3255static void add_till_closing_curly_brace(o_string *dest, struct in_str *input)
3256{
3257 int count = 0;
3258 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003259 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003260 if (ch == EOF)
3261 break;
3262 if (ch == '(')
3263 count++;
3264 if (ch == ')')
3265 if (--count < 0)
3266 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003267 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003268 if (ch == '\'') {
3269 add_till_single_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003270 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003271 continue;
3272 }
3273 if (ch == '"') {
3274 add_till_double_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003275 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003276 continue;
3277 }
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003278 if (ch == '\\') { /* \x. Copy verbatim. Important for \(, \) */
3279 ch = i_getch(input);
3280 if (ch == EOF)
3281 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003282 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003283 continue;
3284 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003285 }
3286}
3287#endif /* ENABLE_HUSH_TICK */
3288
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003289/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003290static int handle_dollar(o_string *dest, struct in_str *input)
Eric Andersen25f27032001-04-26 23:22:31 +00003291{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003292 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkoff097622007-10-01 10:00:45 +00003293 unsigned char quote_mask = dest->o_quote ? 0x80 : 0;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003294
3295 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003296 if (isalpha(ch)) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003297 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003298 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003299 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003300 i_getch(input);
3301 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003302 quote_mask = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003303 ch = i_peek(input);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003304 if (!isalnum(ch) && ch != '_')
3305 break;
Eric Andersen25f27032001-04-26 23:22:31 +00003306 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003307 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003308 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003309 make_one_char_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003310 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003311 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003312 i_getch(input);
3313 o_addchr(dest, ch | quote_mask);
3314 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003315 } else switch (ch) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003316 case '$': /* pid */
3317 case '!': /* last bg pid */
3318 case '?': /* last exit code */
3319 case '#': /* number of args */
3320 case '*': /* args */
3321 case '@': /* args */
3322 goto make_one_char_var;
Eric Andersen25f27032001-04-26 23:22:31 +00003323 case '{':
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003324 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3325 i_getch(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003326 /* XXX maybe someone will try to escape the '}' */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003327 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003328 ch = i_getch(input);
Denis Vlasenkob0550012007-05-24 12:18:16 +00003329 if (ch == '}')
3330 break;
3331 if (!isalnum(ch) && ch != '_') {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003332 syntax("unterminated ${name}");
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003333 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
3334 return 1;
3335 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003336 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003337 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003338 quote_mask = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003339 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003340 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003341 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003342#if ENABLE_HUSH_TICK
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003343 case '(': {
3344 //int pos = dest->length;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003345 i_getch(input);
3346 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3347 o_addchr(dest, quote_mask | '`');
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003348 add_till_closing_curly_brace(dest, input);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003349 //debug_printf_subst("SUBST RES2 '%s'\n", dest->data + pos);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003350 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003351 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003352 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003353#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003354 case '-':
3355 case '_':
3356 /* still unhandled, but should be eventually */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003357 bb_error_msg("unhandled syntax: $%c", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003358 return 1;
3359 break;
3360 default:
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003361 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00003362 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003363 debug_printf_parse("handle_dollar return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003364 return 0;
3365}
3366
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003367/* Return code is 0 for normal exit, 1 for syntax error */
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003368static int parse_stream(o_string *dest, struct p_context *ctx,
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003369 struct in_str *input, const char *end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00003370{
"Vladimir N. Oleynik"4ccd2b42006-01-31 09:27:48 +00003371 int ch, m;
Eric Andersen25f27032001-04-26 23:22:31 +00003372 int redir_fd;
3373 redir_type redir_style;
3374 int next;
3375
Denis Vlasenkoff097622007-10-01 10:00:45 +00003376 /* Only double-quote state is handled in the state variable dest->o_quote.
Eric Andersen25f27032001-04-26 23:22:31 +00003377 * A single-quote triggers a bypass of the main loop until its mate is
Denis Vlasenkoff097622007-10-01 10:00:45 +00003378 * found. When recursing, quote state is passed in via dest->o_quote. */
Eric Andersen25f27032001-04-26 23:22:31 +00003379
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003380 debug_printf_parse("parse_stream entered, end_trigger='%s'\n", end_trigger);
3381
Denis Vlasenko1a735862007-05-23 00:32:25 +00003382 while (1) {
Denis Vlasenko1a735862007-05-23 00:32:25 +00003383 m = CHAR_IFS;
3384 next = '\0';
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003385 ch = i_getch(input);
Denis Vlasenko1a735862007-05-23 00:32:25 +00003386 if (ch != EOF) {
3387 m = charmap[ch];
3388 if (ch != '\n')
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003389 next = i_peek(input);
Denis Vlasenko1a735862007-05-23 00:32:25 +00003390 }
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003391 debug_printf_parse(": ch=%c (%d) m=%d quote=%d\n",
Denis Vlasenkoff097622007-10-01 10:00:45 +00003392 ch, ch, m, dest->o_quote);
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003393 if (m == CHAR_ORDINARY
Denis Vlasenkoff097622007-10-01 10:00:45 +00003394 || (m != CHAR_SPECIAL && dest->o_quote)
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003395 ) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00003396 if (ch == EOF) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003397 syntax("unterminated \"");
Denis Vlasenko170435c2007-05-23 13:01:10 +00003398 debug_printf_parse("parse_stream return 1: unterminated \"\n");
3399 return 1;
3400 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003401 o_addQchr(dest, ch);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003402 continue;
3403 }
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003404 if (m == CHAR_IFS) {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003405 if (done_word(dest, ctx)) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003406 debug_printf_parse("parse_stream return 1: done_word!=0\n");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003407 return 1;
Eric Andersenaac75e52001-04-30 18:18:45 +00003408 }
Denis Vlasenko1a735862007-05-23 00:32:25 +00003409 if (ch == EOF)
3410 break;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003411 /* If we aren't performing a substitution, treat
3412 * a newline as a command separator.
3413 * [why we don't handle it exactly like ';'? --vda] */
3414 if (end_trigger && ch == '\n') {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003415 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003416 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003417 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003418 if (end_trigger) {
3419 if (!dest->o_quote && strchr(end_trigger, ch)) {
3420 /* Special case: (...word) makes last word terminate,
3421 * as if ';' is seen */
3422 if (ch == ')') {
3423 done_word(dest, ctx);
3424 done_pipe(ctx, PIPE_SEQ);
3425 }
3426 if (ctx->res_w == RES_NONE) {
3427 debug_printf_parse("parse_stream return 0: end_trigger char found\n");
3428 return 0;
3429 }
3430 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003431 }
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003432 if (m == CHAR_IFS)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003433 continue;
3434 switch (ch) {
Eric Andersen25f27032001-04-26 23:22:31 +00003435 case '#':
Denis Vlasenkoff097622007-10-01 10:00:45 +00003436 if (dest->length == 0 && !dest->o_quote) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003437 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003438 ch = i_peek(input);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003439 if (ch == EOF || ch == '\n')
3440 break;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003441 i_getch(input);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003442 }
Eric Andersen25f27032001-04-26 23:22:31 +00003443 } else {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003444 o_addQchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003445 }
3446 break;
3447 case '\\':
3448 if (next == EOF) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003449 syntax("\\<eof>");
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003450 debug_printf_parse("parse_stream return 1: \\<eof>\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003451 return 1;
3452 }
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003453 /* bash:
3454 * "The backslash retains its special meaning [in "..."]
3455 * only when followed by one of the following characters:
3456 * $, `, ", \, or <newline>. A double quote may be quoted
3457 * within double quotes by preceding it with a backslash.
3458 * If enabled, history expansion will be performed unless
3459 * an ! appearing in double quotes is escaped using
3460 * a backslash. The backslash preceding the ! is not removed."
3461 */
3462 if (dest->o_quote) {
3463 if (strchr("$`\"\\", next) != NULL) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003464 o_addqchr(dest, i_getch(input));
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003465 } else {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003466 o_addqchr(dest, '\\');
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003467 }
3468 } else {
3469 o_addchr(dest, '\\');
3470 o_addchr(dest, i_getch(input));
3471 }
Eric Andersen25f27032001-04-26 23:22:31 +00003472 break;
3473 case '$':
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003474 if (handle_dollar(dest, input) != 0) {
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003475 debug_printf_parse("parse_stream return 1: handle_dollar returned non-0\n");
3476 return 1;
3477 }
Eric Andersen25f27032001-04-26 23:22:31 +00003478 break;
3479 case '\'':
3480 dest->nonnull = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003481 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003482 ch = i_getch(input);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003483 if (ch == EOF) {
3484 syntax("unterminated '");
3485 debug_printf_parse("parse_stream return 1: unterminated '\n");
3486 return 1;
3487 }
3488 if (ch == '\'')
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003489 break;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003490 o_addqchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003491 }
Eric Andersen25f27032001-04-26 23:22:31 +00003492 break;
3493 case '"':
3494 dest->nonnull = 1;
Denis Vlasenkoff097622007-10-01 10:00:45 +00003495 dest->o_quote ^= 1; /* invert */
Eric Andersen25f27032001-04-26 23:22:31 +00003496 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003497#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003498 case '`': {
3499 //int pos = dest->length;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003500 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3501 o_addchr(dest, dest->o_quote ? 0x80 | '`' : '`');
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003502 add_till_backquote(dest, input);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003503 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003504 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00003505 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003506 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003507#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003508 case '>':
3509 redir_fd = redirect_opt_num(dest);
3510 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003511 redir_style = REDIRECT_OVERWRITE;
Eric Andersen25f27032001-04-26 23:22:31 +00003512 if (next == '>') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003513 redir_style = REDIRECT_APPEND;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003514 i_getch(input);
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003515 }
3516#if 0
3517 else if (next == '(') {
3518 syntax(">(process) not supported");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003519 debug_printf_parse("parse_stream return 1: >(process) not supported\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003520 return 1;
3521 }
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003522#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003523 setup_redirect(ctx, redir_fd, redir_style, input);
3524 break;
3525 case '<':
3526 redir_fd = redirect_opt_num(dest);
3527 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003528 redir_style = REDIRECT_INPUT;
Eric Andersen25f27032001-04-26 23:22:31 +00003529 if (next == '<') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003530 redir_style = REDIRECT_HEREIS;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003531 i_getch(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003532 } else if (next == '>') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003533 redir_style = REDIRECT_IO;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003534 i_getch(input);
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003535 }
3536#if 0
3537 else if (next == '(') {
3538 syntax("<(process) not supported");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003539 debug_printf_parse("parse_stream return 1: <(process) not supported\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003540 return 1;
3541 }
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003542#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003543 setup_redirect(ctx, redir_fd, redir_style, input);
3544 break;
3545 case ';':
3546 done_word(dest, ctx);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003547 done_pipe(ctx, PIPE_SEQ);
Eric Andersen25f27032001-04-26 23:22:31 +00003548 break;
3549 case '&':
3550 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003551 if (next == '&') {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003552 i_getch(input);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003553 done_pipe(ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00003554 } else {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003555 done_pipe(ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00003556 }
3557 break;
3558 case '|':
3559 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003560 if (next == '|') {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003561 i_getch(input);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003562 done_pipe(ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00003563 } else {
3564 /* we could pick up a file descriptor choice here
3565 * with redirect_opt_num(), but bash doesn't do it.
3566 * "echo foo 2| cat" yields "foo 2". */
3567 done_command(ctx);
3568 }
3569 break;
3570 case '(':
3571 case '{':
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003572 if (parse_group(dest, ctx, input, ch) != 0) {
3573 debug_printf_parse("parse_stream return 1: parse_group returned non-0\n");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003574 return 1;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003575 }
Eric Andersen25f27032001-04-26 23:22:31 +00003576 break;
3577 case ')':
3578 case '}':
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003579 /* proper use of this character is caught by end_trigger */
3580 syntax("unexpected } or )");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003581 debug_printf_parse("parse_stream return 1: unexpected '}'\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003582 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003583 default:
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003584 if (ENABLE_HUSH_DEBUG)
3585 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003586 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003587 } /* while (1) */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003588 /* Complain if quote? No, maybe we just finished a command substitution
Eric Andersen25f27032001-04-26 23:22:31 +00003589 * that was quoted. Example:
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003590 * $ echo "`cat foo` plus more"
Eric Andersen25f27032001-04-26 23:22:31 +00003591 * and we just got the EOF generated by the subshell that ran "cat foo"
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003592 * The only real complaint is if we got an EOF when end_trigger != NULL,
Eric Andersen25f27032001-04-26 23:22:31 +00003593 * that is, we were really supposed to get end_trigger, and never got
3594 * one before the EOF. Can't use the standard "syntax error" return code,
3595 * so that parse_stream_outer can distinguish the EOF and exit smoothly. */
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003596 debug_printf_parse("parse_stream return %d\n", -(end_trigger != NULL));
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003597 if (end_trigger)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003598 return -1;
Eric Andersen25f27032001-04-26 23:22:31 +00003599 return 0;
3600}
3601
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003602static void set_in_charmap(const char *set, int code)
Eric Andersen25f27032001-04-26 23:22:31 +00003603{
Denis Vlasenkof5294e12007-04-14 10:09:57 +00003604 while (*set)
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003605 charmap[(unsigned char)*set++] = code;
Eric Andersen25f27032001-04-26 23:22:31 +00003606}
3607
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003608static void update_charmap(void)
Eric Andersen25f27032001-04-26 23:22:31 +00003609{
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003610 /* char *ifs and char charmap[256] are both globals. */
Eric Andersen25f27032001-04-26 23:22:31 +00003611 ifs = getenv("IFS");
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003612 if (ifs == NULL)
3613 ifs = " \t\n";
Eric Andersen25f27032001-04-26 23:22:31 +00003614 /* Precompute a list of 'flow through' behavior so it can be treated
3615 * quickly up front. Computation is necessary because of IFS.
3616 * Special case handling of IFS == " \t\n" is not implemented.
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003617 * The charmap[] array only really needs two bits each,
3618 * and on most machines that would be faster (reduced L1 cache use).
Eric Andersen25f27032001-04-26 23:22:31 +00003619 */
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003620 memset(charmap, CHAR_ORDINARY, sizeof(charmap));
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003621#if ENABLE_HUSH_TICK
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003622 set_in_charmap("\\$\"`", CHAR_SPECIAL);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003623#else
3624 set_in_charmap("\\$\"", CHAR_SPECIAL);
3625#endif
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003626 set_in_charmap("<>;&|(){}#'", CHAR_ORDINARY_IF_QUOTED);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003627 set_in_charmap(ifs, CHAR_IFS); /* are ordinary if quoted */
Eric Andersen25f27032001-04-26 23:22:31 +00003628}
3629
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003630/* Most recursion does not come through here, the exception is
Denis Vlasenko170435c2007-05-23 13:01:10 +00003631 * from builtin_source() and builtin_eval() */
3632static int parse_and_run_stream(struct in_str *inp, int parse_flag)
Eric Andersen25f27032001-04-26 23:22:31 +00003633{
Eric Andersen25f27032001-04-26 23:22:31 +00003634 struct p_context ctx;
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003635 o_string temp = NULL_O_STRING;
Eric Andersen25f27032001-04-26 23:22:31 +00003636 int rcode;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003637
Eric Andersen25f27032001-04-26 23:22:31 +00003638 do {
3639 initialize_context(&ctx);
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003640 update_charmap();
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003641#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00003642 inp->promptmode = 0; /* PS1 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003643#endif
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003644 /* We will stop & execute after each ';' or '\n'.
3645 * Example: "sleep 9999; echo TEST" + ctrl-C:
3646 * TEST should be printed */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003647 rcode = parse_stream(&temp, &ctx, inp, ";\n");
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003648 if (rcode != 1 && ctx.old_flag != 0) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003649 syntax(NULL);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003650 }
3651 if (rcode != 1 && ctx.old_flag == 0) {
3652 done_word(&temp, &ctx);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003653 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003654 debug_print_tree(ctx.list_head, 0);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003655 debug_printf_exec("parse_stream_outer: run_and_free_list\n");
3656 run_and_free_list(ctx.list_head);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003657 } else {
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003658 /* We arrive here also if rcode == 1 (error in parse_stream) */
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003659 if (ctx.old_flag != 0) {
3660 free(ctx.stack);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003661 o_reset(&temp);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003662 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00003663 /*temp.nonnull = 0; - o_free does it below */
3664 /*temp.o_quote = 0; - o_free does it below */
Denis Vlasenko05743d72008-02-10 12:10:08 +00003665 free_pipe_list(ctx.list_head, /* indent: */ 0);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003666 /* Discard all unprocessed line input, force prompt on */
3667 inp->p = NULL;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003668#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003669 inp->promptme = 1;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003670#endif
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003671 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003672 o_free(&temp);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003673 /* loop on syntax errors, return on EOF: */
3674 } while (rcode != -1 && !(parse_flag & PARSEFLAG_EXIT_FROM_LOOP));
Eric Andersen25f27032001-04-26 23:22:31 +00003675 return 0;
3676}
3677
Denis Vlasenko170435c2007-05-23 13:01:10 +00003678static int parse_and_run_string(const char *s, int parse_flag)
Eric Andersen25f27032001-04-26 23:22:31 +00003679{
3680 struct in_str input;
3681 setup_string_in_str(&input, s);
Denis Vlasenko170435c2007-05-23 13:01:10 +00003682 return parse_and_run_stream(&input, parse_flag);
Eric Andersen25f27032001-04-26 23:22:31 +00003683}
3684
Denis Vlasenko170435c2007-05-23 13:01:10 +00003685static int parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00003686{
3687 int rcode;
3688 struct in_str input;
3689 setup_file_in_str(&input, f);
Denis Vlasenko5703c222008-06-15 11:49:42 +00003690 rcode = parse_and_run_stream(&input, 0 /* parse_flag */);
Eric Andersen25f27032001-04-26 23:22:31 +00003691 return rcode;
3692}
3693
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003694#if ENABLE_HUSH_JOB
Eric Andersen6c947d22001-06-25 22:24:38 +00003695/* Make sure we have a controlling tty. If we get started under a job
3696 * aware app (like bash for example), make sure we are now in charge so
3697 * we don't fight over who gets the foreground */
Eric Anderseneaecbf32001-10-31 10:41:31 +00003698static void setup_job_control(void)
Eric Andersen52a97ca2001-06-22 06:49:26 +00003699{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003700 pid_t shell_pgrp;
3701
Denis Vlasenkoa6a17852007-04-28 16:42:11 +00003702 saved_task_pgrp = shell_pgrp = getpgrp();
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003703 debug_printf_jobs("saved_task_pgrp=%d\n", saved_task_pgrp);
Denis Vlasenko96e1b382007-09-30 23:50:48 +00003704 close_on_exec_on(interactive_fd);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003705
Denis Vlasenkoa6a17852007-04-28 16:42:11 +00003706 /* If we were ran as 'hush &',
3707 * sleep until we are in the foreground. */
3708 while (tcgetpgrp(interactive_fd) != shell_pgrp) {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003709 /* Send TTIN to ourself (should stop us) */
Denis Vlasenkoff131b92007-04-10 15:42:06 +00003710 kill(- shell_pgrp, SIGTTIN);
Denis Vlasenkoa6a17852007-04-28 16:42:11 +00003711 shell_pgrp = getpgrp();
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003712 }
Eric Andersen52a97ca2001-06-22 06:49:26 +00003713
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003714 /* Ignore job-control and misc signals. */
3715 set_jobctrl_sighandler(SIG_IGN);
3716 set_misc_sighandler(SIG_IGN);
3717//huh? signal(SIGCHLD, SIG_IGN);
3718
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003719 /* We _must_ restore tty pgrp on fatal signals */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003720 set_fatal_sighandler(sigexit);
Eric Andersen6c947d22001-06-25 22:24:38 +00003721
3722 /* Put ourselves in our own process group. */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003723 setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
Eric Andersen6c947d22001-06-25 22:24:38 +00003724 /* Grab control of the terminal. */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003725 tcsetpgrp(interactive_fd, getpid());
Eric Andersen6c947d22001-06-25 22:24:38 +00003726}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003727#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00003728
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003729
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00003730int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00003731int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00003732{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00003733 static const char version_str[] ALIGN1 = "HUSH_VERSION="HUSH_VER_STR;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00003734 static const struct variable const_shell_ver = {
3735 .next = NULL,
3736 .varstr = (char*)version_str,
3737 .max_len = 1, /* 0 can provoke free(name) */
3738 .flg_export = 1,
3739 .flg_read_only = 1,
3740 };
3741
Eric Andersen25f27032001-04-26 23:22:31 +00003742 int opt;
3743 FILE *input;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003744 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003745 struct variable *cur_var;
Eric Andersenbc604a22001-05-16 05:24:03 +00003746
Denis Vlasenko574f2f42008-02-27 18:41:59 +00003747 INIT_G();
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003748
Denis Vlasenko16c2fea2008-06-17 12:28:44 +00003749 root_pid = getpid();
3750
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00003751 /* Deal with HUSH_VERSION */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00003752 shell_ver = const_shell_ver; /* copying struct here */
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003753 top_var = &shell_ver;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00003754 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
3755 /* Initialize our shell local variables with the values
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003756 * currently living in the environment */
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003757 cur_var = top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00003758 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003759 if (e) while (*e) {
3760 char *value = strchr(*e, '=');
3761 if (value) { /* paranoia */
3762 cur_var->next = xzalloc(sizeof(*cur_var));
3763 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00003764 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003765 cur_var->max_len = strlen(*e);
3766 cur_var->flg_export = 1;
3767 }
3768 e++;
3769 }
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00003770 putenv((char *)version_str); /* reinstate HUSH_VERSION */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00003771
Denis Vlasenko38f63192007-01-22 09:03:07 +00003772#if ENABLE_FEATURE_EDITING
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00003773 line_input_state = new_line_input_t(FOR_SHELL);
3774#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003775 /* XXX what should these be while sourcing /etc/profile? */
3776 global_argc = argc;
3777 global_argv = argv;
Eric Andersen94ac2442001-05-22 19:05:18 +00003778 /* Initialize some more globals to non-zero values */
3779 set_cwd();
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003780#if ENABLE_HUSH_INTERACTIVE
3781#if ENABLE_FEATURE_EDITING
3782 cmdedit_set_initial_prompt();
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003783#endif
Eric Andersen94ac2442001-05-22 19:05:18 +00003784 PS2 = "> ";
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003785#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00003786
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003787 if (EXIT_SUCCESS) /* otherwise is already done */
3788 last_return_code = EXIT_SUCCESS;
Eric Andersen25f27032001-04-26 23:22:31 +00003789
3790 if (argv[0] && argv[0][0] == '-') {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003791 debug_printf("sourcing /etc/profile\n");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003792 input = fopen("/etc/profile", "r");
3793 if (input != NULL) {
Denis Vlasenkoa0898172007-10-01 09:59:01 +00003794 close_on_exec_on(fileno(input));
Denis Vlasenko170435c2007-05-23 13:01:10 +00003795 parse_and_run_file(input);
Eric Andersena90f20b2001-06-26 23:00:21 +00003796 fclose(input);
3797 }
Eric Andersen25f27032001-04-26 23:22:31 +00003798 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003799 input = stdin;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003800
Eric Andersen25f27032001-04-26 23:22:31 +00003801 while ((opt = getopt(argc, argv, "c:xif")) > 0) {
3802 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003803 case 'c':
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003804 global_argv = argv + optind;
3805 global_argc = argc - optind;
Denis Vlasenko5703c222008-06-15 11:49:42 +00003806 opt = parse_and_run_string(optarg, 0 /* parse_flag */);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003807 goto final_return;
3808 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003809 /* Well, we cannot just declare interactiveness,
3810 * we have to have some stuff (ctty, etc) */
3811 /* interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003812 break;
3813 case 'f':
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00003814 fake_mode = 1;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003815 break;
3816 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00003817#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003818 fprintf(stderr, "Usage: sh [FILE]...\n"
3819 " or: sh -c command [args]...\n\n");
3820 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00003821#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003822 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00003823#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003824 }
3825 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003826#if ENABLE_HUSH_JOB
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003827 /* A shell is interactive if the '-i' flag was given, or if all of
Eric Andersen25f27032001-04-26 23:22:31 +00003828 * the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00003829 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00003830 * no arguments remaining or the -s flag given
3831 * standard input is a terminal
3832 * standard output is a terminal
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003833 * Refer to Posix.2, the description of the 'sh' utility. */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003834 if (argv[optind] == NULL && input == stdin
3835 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3836 ) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003837 saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
3838 debug_printf("saved_tty_pgrp=%d\n", saved_tty_pgrp);
3839 if (saved_tty_pgrp >= 0) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003840 /* try to dup to high fd#, >= 255 */
3841 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3842 if (interactive_fd < 0) {
3843 /* try to dup to any fd */
3844 interactive_fd = dup(STDIN_FILENO);
3845 if (interactive_fd < 0)
3846 /* give up */
3847 interactive_fd = 0;
3848 }
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00003849 // TODO: track & disallow any attempts of user
3850 // to (inadvertently) close/redirect it
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003851 }
Eric Andersen25f27032001-04-26 23:22:31 +00003852 }
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003853 debug_printf("interactive_fd=%d\n", interactive_fd);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003854 if (interactive_fd) {
Denis Vlasenko08126f62008-02-11 08:39:11 +00003855 fcntl(interactive_fd, F_SETFD, FD_CLOEXEC);
Eric Andersen25f27032001-04-26 23:22:31 +00003856 /* Looks like they want an interactive shell */
Eric Andersen52a97ca2001-06-22 06:49:26 +00003857 setup_job_control();
Denis Vlasenko4ecfcdc2008-02-11 08:32:31 +00003858 /* -1 is special - makes xfuncs longjmp, not exit
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00003859 * (we reset die_sleep = 0 whereever we [v]fork) */
3860 die_sleep = -1;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003861 if (setjmp(die_jmp)) {
3862 /* xfunc has failed! die die die */
3863 hush_exit(xfunc_error_retval);
3864 }
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00003865#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denis Vlasenkoca525b42007-06-13 12:27:17 +00003866 printf("\n\n%s hush - the humble shell v"HUSH_VER_STR"\n", bb_banner);
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00003867 printf("Enter 'help' for a list of built-in commands.\n\n");
3868#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00003869 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003870#elif ENABLE_HUSH_INTERACTIVE
3871/* no job control compiled, only prompt/line editing */
3872 if (argv[optind] == NULL && input == stdin
3873 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3874 ) {
3875 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3876 if (interactive_fd < 0) {
3877 /* try to dup to any fd */
3878 interactive_fd = dup(STDIN_FILENO);
3879 if (interactive_fd < 0)
3880 /* give up */
3881 interactive_fd = 0;
3882 }
Denis Vlasenko4830fc52008-05-25 21:50:55 +00003883 if (interactive_fd) {
Denis Vlasenko08126f62008-02-11 08:39:11 +00003884 fcntl(interactive_fd, F_SETFD, FD_CLOEXEC);
Denis Vlasenko4830fc52008-05-25 21:50:55 +00003885 set_misc_sighandler(SIG_IGN);
3886 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003887 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003888#endif
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003889
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003890 if (argv[optind] == NULL) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00003891 opt = parse_and_run_file(stdin);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003892 } else {
3893 debug_printf("\nrunning script '%s'\n", argv[optind]);
3894 global_argv = argv + optind;
3895 global_argc = argc - optind;
3896 input = xfopen(argv[optind], "r");
Denis Vlasenko459a5ad2008-02-11 08:35:03 +00003897 fcntl(fileno(input), F_SETFD, FD_CLOEXEC);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003898 opt = parse_and_run_file(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003899 }
Eric Andersen25f27032001-04-26 23:22:31 +00003900
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003901 final_return:
3902
Denis Vlasenko38f63192007-01-22 09:03:07 +00003903#if ENABLE_FEATURE_CLEAN_UP
Eric Andersenaeb44c42001-05-22 20:29:00 +00003904 fclose(input);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003905 if (cwd != bb_msg_unknown)
Eric Andersenaeb44c42001-05-22 20:29:00 +00003906 free((char*)cwd);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003907 cur_var = top_var->next;
3908 while (cur_var) {
3909 struct variable *tmp = cur_var;
3910 if (!cur_var->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00003911 free(cur_var->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003912 cur_var = cur_var->next;
3913 free(tmp);
Eric Andersenaeb44c42001-05-22 20:29:00 +00003914 }
Eric Andersen25f27032001-04-26 23:22:31 +00003915#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003916 hush_exit(opt ? opt : last_return_code);
Eric Andersen25f27032001-04-26 23:22:31 +00003917}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00003918
3919
3920#if ENABLE_LASH
3921int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
3922int lash_main(int argc, char **argv)
3923{
3924 //bb_error_msg("lash is deprecated, please use hush instead");
3925 return hush_main(argc, argv);
3926}
3927#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003928
3929
3930/*
3931 * Built-ins
3932 */
3933static int builtin_true(char **argv ATTRIBUTE_UNUSED)
3934{
3935 return 0;
3936}
3937
3938static int builtin_test(char **argv)
3939{
3940 int argc = 0;
3941 while (*argv) {
3942 argc++;
3943 argv++;
3944 }
3945 return test_main(argc, argv - argc);
3946}
3947
3948static int builtin_echo(char **argv)
3949{
3950 int argc = 0;
3951 while (*argv) {
3952 argc++;
3953 argv++;
3954 }
3955 return echo_main(argc, argv - argc);
3956}
3957
3958static int builtin_eval(char **argv)
3959{
3960 int rcode = EXIT_SUCCESS;
3961
3962 if (argv[1]) {
3963 char *str = expand_strvec_to_string(argv + 1);
3964 parse_and_run_string(str, PARSEFLAG_EXIT_FROM_LOOP);
3965 free(str);
3966 rcode = last_return_code;
3967 }
3968 return rcode;
3969}
3970
3971static int builtin_cd(char **argv)
3972{
3973 const char *newdir;
3974 if (argv[1] == NULL) {
3975 // bash does nothing (exitcode 0) if HOME is ""; if it's unset,
3976 // bash says "bash: cd: HOME not set" and does nothing (exitcode 1)
3977 newdir = getenv("HOME") ? : "/";
3978 } else
3979 newdir = argv[1];
3980 if (chdir(newdir)) {
3981 printf("cd: %s: %s\n", newdir, strerror(errno));
3982 return EXIT_FAILURE;
3983 }
3984 set_cwd();
3985 return EXIT_SUCCESS;
3986}
3987
3988static int builtin_exec(char **argv)
3989{
3990 if (argv[1] == NULL)
3991 return EXIT_SUCCESS; /* bash does this */
3992 {
3993#if !BB_MMU
3994 char **ptrs2free = alloc_ptrs(argv);
3995#endif
3996// FIXME: if exec fails, bash does NOT exit! We do...
3997 pseudo_exec_argv(ptrs2free, argv + 1);
3998 /* never returns */
3999 }
4000}
4001
4002static int builtin_exit(char **argv)
4003{
4004// TODO: bash does it ONLY on top-level sh exit (+interacive only?)
4005 //puts("exit"); /* bash does it */
4006// TODO: warn if we have background jobs: "There are stopped jobs"
4007// On second consecutive 'exit', exit anyway.
4008 if (argv[1] == NULL)
4009 hush_exit(last_return_code);
4010 /* mimic bash: exit 123abc == exit 255 + error msg */
4011 xfunc_error_retval = 255;
4012 /* bash: exit -2 == exit 254, no error msg */
4013 hush_exit(xatoi(argv[1]) & 0xff);
4014}
4015
4016static int builtin_export(char **argv)
4017{
4018 const char *value;
4019 char *name = argv[1];
4020
4021 if (name == NULL) {
4022 // TODO:
4023 // ash emits: export VAR='VAL'
4024 // bash: declare -x VAR="VAL"
4025 // (both also escape as needed (quotes, $, etc))
4026 char **e = environ;
4027 if (e)
4028 while (*e)
4029 puts(*e++);
4030 return EXIT_SUCCESS;
4031 }
4032
4033 value = strchr(name, '=');
4034 if (!value) {
4035 /* They are exporting something without a =VALUE */
4036 struct variable *var;
4037
4038 var = get_local_var(name);
4039 if (var) {
4040 var->flg_export = 1;
4041 putenv(var->varstr);
4042 }
4043 /* bash does not return an error when trying to export
4044 * an undefined variable. Do likewise. */
4045 return EXIT_SUCCESS;
4046 }
4047
4048 set_local_var(xstrdup(name), 1);
4049 return EXIT_SUCCESS;
4050}
4051
4052#if ENABLE_HUSH_JOB
4053/* built-in 'fg' and 'bg' handler */
4054static int builtin_fg_bg(char **argv)
4055{
4056 int i, jobnum;
4057 struct pipe *pi;
4058
4059 if (!interactive_fd)
4060 return EXIT_FAILURE;
4061 /* If they gave us no args, assume they want the last backgrounded task */
4062 if (!argv[1]) {
4063 for (pi = job_list; pi; pi = pi->next) {
4064 if (pi->jobid == last_jobid) {
4065 goto found;
4066 }
4067 }
4068 bb_error_msg("%s: no current job", argv[0]);
4069 return EXIT_FAILURE;
4070 }
4071 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
4072 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
4073 return EXIT_FAILURE;
4074 }
4075 for (pi = job_list; pi; pi = pi->next) {
4076 if (pi->jobid == jobnum) {
4077 goto found;
4078 }
4079 }
4080 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
4081 return EXIT_FAILURE;
4082 found:
4083 // TODO: bash prints a string representation
4084 // of job being foregrounded (like "sleep 1 | cat")
4085 if (*argv[0] == 'f') {
4086 /* Put the job into the foreground. */
4087 tcsetpgrp(interactive_fd, pi->pgrp);
4088 }
4089
4090 /* Restart the processes in the job */
4091 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_progs, pi->pgrp);
4092 for (i = 0; i < pi->num_progs; i++) {
4093 debug_printf_jobs("reviving pid %d\n", pi->progs[i].pid);
4094 pi->progs[i].is_stopped = 0;
4095 }
4096 pi->stopped_progs = 0;
4097
4098 i = kill(- pi->pgrp, SIGCONT);
4099 if (i < 0) {
4100 if (errno == ESRCH) {
4101 delete_finished_bg_job(pi);
4102 return EXIT_SUCCESS;
4103 } else {
4104 bb_perror_msg("kill (SIGCONT)");
4105 }
4106 }
4107
4108 if (*argv[0] == 'f') {
4109 remove_bg_job(pi);
4110 return checkjobs_and_fg_shell(pi);
4111 }
4112 return EXIT_SUCCESS;
4113}
4114#endif
4115
4116#if ENABLE_HUSH_HELP
4117static int builtin_help(char **argv ATTRIBUTE_UNUSED)
4118{
4119 const struct built_in_command *x;
4120
4121 printf("\nBuilt-in commands:\n");
4122 printf("-------------------\n");
4123 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
4124 printf("%s\t%s\n", x->cmd, x->descr);
4125 }
4126 printf("\n\n");
4127 return EXIT_SUCCESS;
4128}
4129#endif
4130
4131#if ENABLE_HUSH_JOB
4132static int builtin_jobs(char **argv ATTRIBUTE_UNUSED)
4133{
4134 struct pipe *job;
4135 const char *status_string;
4136
4137 for (job = job_list; job; job = job->next) {
4138 if (job->running_progs == job->stopped_progs)
4139 status_string = "Stopped";
4140 else
4141 status_string = "Running";
4142
4143 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
4144 }
4145 return EXIT_SUCCESS;
4146}
4147#endif
4148
4149static int builtin_pwd(char **argv ATTRIBUTE_UNUSED)
4150{
4151 puts(set_cwd());
4152 return EXIT_SUCCESS;
4153}
4154
4155static int builtin_read(char **argv)
4156{
4157 char *string;
4158 const char *name = argv[1] ? argv[1] : "REPLY";
4159
4160 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
4161 return set_local_var(string, 0);
4162}
4163
4164/* built-in 'set [VAR=value]' handler */
4165static int builtin_set(char **argv)
4166{
4167 char *temp = argv[1];
4168 struct variable *e;
4169
4170 if (temp == NULL)
4171 for (e = top_var; e; e = e->next)
4172 puts(e->varstr);
4173 else
4174 set_local_var(xstrdup(temp), 0);
4175
4176 return EXIT_SUCCESS;
4177}
4178
4179static int builtin_shift(char **argv)
4180{
4181 int n = 1;
4182 if (argv[1]) {
4183 n = atoi(argv[1]);
4184 }
4185 if (n >= 0 && n < global_argc) {
4186 global_argv[n] = global_argv[0];
4187 global_argc -= n;
4188 global_argv += n;
4189 return EXIT_SUCCESS;
4190 }
4191 return EXIT_FAILURE;
4192}
4193
4194static int builtin_source(char **argv)
4195{
4196 FILE *input;
4197 int status;
4198
4199 if (argv[1] == NULL)
4200 return EXIT_FAILURE;
4201
4202 /* XXX search through $PATH is missing */
4203 input = fopen(argv[1], "r");
4204 if (!input) {
4205 bb_error_msg("cannot open '%s'", argv[1]);
4206 return EXIT_FAILURE;
4207 }
4208 close_on_exec_on(fileno(input));
4209
4210 /* Now run the file */
4211 /* XXX argv and argc are broken; need to save old global_argv
4212 * (pointer only is OK!) on this stack frame,
4213 * set global_argv=argv+1, recurse, and restore. */
4214 status = parse_and_run_file(input);
4215 fclose(input);
4216 return status;
4217}
4218
4219static int builtin_umask(char **argv)
4220{
4221 mode_t new_umask;
4222 const char *arg = argv[1];
4223 char *end;
4224 if (arg) {
4225 new_umask = strtoul(arg, &end, 8);
4226 if (*end != '\0' || end == arg) {
4227 return EXIT_FAILURE;
4228 }
4229 } else {
4230 new_umask = umask(0);
4231 printf("%.3o\n", (unsigned) new_umask);
4232 }
4233 umask(new_umask);
4234 return EXIT_SUCCESS;
4235}
4236
4237static int builtin_unset(char **argv)
4238{
4239 /* bash always returns true */
4240 unset_local_var(argv[1]);
4241 return EXIT_SUCCESS;
4242}