blob: 47e53f8c1a1e07dbeb7584ef5be493210add67c5 [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 Vlasenko17f02e72008-07-14 04:32:29 +000076// TEMP
77#define ENABLE_HUSH_CASE 0
78
Denis Vlasenkod01ff132007-05-02 21:40:23 +000079
Denis Vlasenko05743d72008-02-10 12:10:08 +000080#if !BB_MMU && ENABLE_HUSH_TICK
81//#undef ENABLE_HUSH_TICK
82//#define ENABLE_HUSH_TICK 0
83#warning On NOMMU, hush command substitution is dangerous.
84#warning Dont use it for commands which produce lots of output.
85#warning For more info see shell/hush.c, generate_stream_from_list().
86#endif
87
88#if !BB_MMU && ENABLE_HUSH_JOB
89#undef ENABLE_HUSH_JOB
90#define ENABLE_HUSH_JOB 0
91#endif
92
93#if !ENABLE_HUSH_INTERACTIVE
94#undef ENABLE_FEATURE_EDITING
95#define ENABLE_FEATURE_EDITING 0
96#undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
97#define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +000098#endif
99
100
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000101/* If you comment out one of these below, it will be #defined later
102 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000103#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000104/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000105#define debug_printf_parse(...) do {} while (0)
106#define debug_print_tree(a, b) do {} while (0)
107#define debug_printf_exec(...) do {} while (0)
108#define debug_printf_jobs(...) do {} while (0)
109#define debug_printf_expand(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000110#define debug_printf_glob(...) do {} while (0)
111#define debug_printf_list(...) do {} while (0)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000112#define debug_printf_subst(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000113#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000114
115#ifndef debug_printf
116#define debug_printf(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000117#endif
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000118
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000119#ifndef debug_printf_parse
120#define debug_printf_parse(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000121#endif
122
123#ifndef debug_printf_exec
124#define debug_printf_exec(...) fprintf(stderr, __VA_ARGS__)
125#endif
126
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000127#ifndef debug_printf_jobs
128#define debug_printf_jobs(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000129#define DEBUG_JOBS 1
130#else
131#define DEBUG_JOBS 0
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000132#endif
133
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000134#ifndef debug_printf_expand
135#define debug_printf_expand(...) fprintf(stderr, __VA_ARGS__)
136#define DEBUG_EXPAND 1
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000137#else
138#define DEBUG_EXPAND 0
139#endif
140
141#ifndef debug_printf_glob
142#define debug_printf_glob(...) fprintf(stderr, __VA_ARGS__)
143#define DEBUG_GLOB 1
144#else
145#define DEBUG_GLOB 0
146#endif
147
148#ifndef debug_printf_list
149#define debug_printf_list(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000150#endif
151
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000152#ifndef debug_printf_subst
153#define debug_printf_subst(...) fprintf(stderr, __VA_ARGS__)
154#endif
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
Denis Vlasenkof962a032007-11-23 12:50:54 +0000179/*
180 * Leak hunting. Use hush_leaktool.sh for post-processing.
181 */
182#ifdef FOR_HUSH_LEAKTOOL
Denis Vlasenkoccce59d2008-06-16 14:35:57 +0000183/* suppress "warning: no previous prototype..." */
184void *xxmalloc(int lineno, size_t size);
185void *xxrealloc(int lineno, void *ptr, size_t size);
186char *xxstrdup(int lineno, const char *str);
187void xxfree(void *ptr);
Denis Vlasenkof962a032007-11-23 12:50:54 +0000188void *xxmalloc(int lineno, size_t size)
189{
190 void *ptr = xmalloc((size + 0xff) & ~0xff);
191 fprintf(stderr, "line %d: malloc %p\n", lineno, ptr);
192 return ptr;
193}
194void *xxrealloc(int lineno, void *ptr, size_t size)
195{
196 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
197 fprintf(stderr, "line %d: realloc %p\n", lineno, ptr);
198 return ptr;
199}
200char *xxstrdup(int lineno, const char *str)
201{
202 char *ptr = xstrdup(str);
203 fprintf(stderr, "line %d: strdup %p\n", lineno, ptr);
204 return ptr;
205}
206void xxfree(void *ptr)
207{
208 fprintf(stderr, "free %p\n", ptr);
209 free(ptr);
210}
211#define xmalloc(s) xxmalloc(__LINE__, s)
212#define xrealloc(p, s) xxrealloc(__LINE__, p, s)
213#define xstrdup(s) xxstrdup(__LINE__, s)
214#define free(p) xxfree(p)
215#endif
216
217
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000218/* Keep unconditionally on for now */
219#define HUSH_DEBUG 1
220/* Do we support ANY keywords? */
221#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS
222#define HAS_KEYWORDS 1
223#define IF_HAS_KEYWORDS(...) __VA_ARGS__
224#define IF_HAS_NO_KEYWORDS(...)
225#else
226#define HAS_KEYWORDS 0
227#define IF_HAS_KEYWORDS(...)
228#define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
229#endif
230
231
Denis Vlasenko5703c222008-06-15 11:49:42 +0000232#define SPECIAL_VAR_SYMBOL 3
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000233#define PARSEFLAG_EXIT_FROM_LOOP 1
Eric Andersen25f27032001-04-26 23:22:31 +0000234
235typedef enum {
236 REDIRECT_INPUT = 1,
237 REDIRECT_OVERWRITE = 2,
238 REDIRECT_APPEND = 3,
239 REDIRECT_HEREIS = 4,
240 REDIRECT_IO = 5
241} redir_type;
242
Denis Vlasenko55789c62008-06-18 16:30:42 +0000243/* The descrip member of this structure is only used to make
244 * debugging output pretty */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +0000245static const struct {
246 int mode;
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000247 signed char default_fd;
248 char descrip[3];
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +0000249} redir_table[] = {
Eric Andersen25f27032001-04-26 23:22:31 +0000250 { 0, 0, "()" },
251 { O_RDONLY, 0, "<" },
252 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
253 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
254 { O_RDONLY, -1, "<<" },
255 { O_RDWR, 1, "<>" }
256};
257
258typedef enum {
259 PIPE_SEQ = 1,
260 PIPE_AND = 2,
261 PIPE_OR = 3,
262 PIPE_BG = 4,
263} pipe_style;
264
Eric Andersen25f27032001-04-26 23:22:31 +0000265typedef enum {
266 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000267#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000268 RES_IF ,
269 RES_THEN ,
270 RES_ELIF ,
271 RES_ELSE ,
272 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000273#endif
274#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000275 RES_FOR ,
276 RES_WHILE ,
277 RES_UNTIL ,
278 RES_DO ,
279 RES_DONE ,
280 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000281#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000282#if ENABLE_HUSH_CASE
283 RES_CASE ,
284 /* two pseudo-keywords support contrived "case" syntax: */
285 RES_MATCH , /* "word)" */
286 RES_CASEI , /* "this command is inside CASE" */
287 RES_ESAC ,
288#endif
289 RES_XXXX ,
290 RES_SNTX
Eric Andersen25f27032001-04-26 23:22:31 +0000291} reserved_style;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000292
Eric Andersen25f27032001-04-26 23:22:31 +0000293/* This holds pointers to the various results of parsing */
294struct p_context {
295 struct child_prog *child;
296 struct pipe *list_head;
297 struct pipe *pipe;
298 struct redir_struct *pending_redirect;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000299#if HAS_KEYWORDS
300 smallint ctx_res_w;
301 smallint ctx_inverted; /* "! cmd | cmd" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000302#if ENABLE_HUSH_CASE
303 smallint ctx_dsemicolon; /* ";;" seen */
304#endif
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000305 int old_flag; /* bitmask of FLAG_xxx, for figuring out valid reserved words */
Eric Andersen25f27032001-04-26 23:22:31 +0000306 struct p_context *stack;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000307#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000308};
309
310struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000311 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000312 char *rd_filename; /* filename */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000313 int fd; /* file descriptor being redirected */
314 int dup; /* -1, or file descriptor being duplicated */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000315 smallint /*enum redir_type*/ rd_type;
Eric Andersen25f27032001-04-26 23:22:31 +0000316};
317
318struct child_prog {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000319 pid_t pid; /* 0 if exited */
Denis Vlasenko55789c62008-06-18 16:30:42 +0000320 smallint is_stopped; /* is the program currently running? */
321 smallint subshell; /* flag, non-zero if group must be forked */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000322 char **argv; /* program name and arguments */
323 struct pipe *group; /* if non-NULL, first in group or subshell */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000324 struct redir_struct *redirects; /* I/O redirections */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000325 struct pipe *family; /* pointer back to the child's parent pipe */
Eric Andersen25f27032001-04-26 23:22:31 +0000326};
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000327/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
328 * and on execution these are substituted with their values.
329 * Substitution can make _several_ words out of one argv[n]!
330 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000331 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000332 */
Eric Andersen25f27032001-04-26 23:22:31 +0000333
334struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000335 struct pipe *next;
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000336 int num_progs; /* total number of programs in job */
Denis Vlasenko003f9fb2008-06-24 00:47:58 +0000337 int alive_progs; /* number of programs running (not exited) */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000338 int stopped_progs; /* number of programs alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000339#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000340 int jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000341 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000342 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000343#endif
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000344 struct child_prog *progs; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000345 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000346 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
347 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000348};
349
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000350/* On program start, environ points to initial environment.
351 * putenv adds new pointers into it, unsetenv removes them.
352 * Neither of these (de)allocates the strings.
353 * setenv allocates new strings in malloc space and does putenv,
354 * and thus setenv is unusable (leaky) for shell's purposes */
355#define setenv(...) setenv_is_leaky_dont_use()
356struct variable {
357 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000358 char *varstr; /* points to "name=" portion */
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000359 int max_len; /* if > 0, name is part of initial env; else name is malloced */
360 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000361 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000362};
363
Eric Andersen25f27032001-04-26 23:22:31 +0000364typedef struct {
365 char *data;
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000366 int length; /* position where data is appended */
Eric Andersen25f27032001-04-26 23:22:31 +0000367 int maxlen;
Denis Vlasenko324a3fd2008-06-18 17:49:58 +0000368 /* Misnomer! it's not "quoting", it's "protection against globbing"!
369 * (by prepending \ to *, ?, [ and to \ too) */
Denis Vlasenkoff097622007-10-01 10:00:45 +0000370 smallint o_quote;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000371 smallint o_glob;
Denis Vlasenkoff097622007-10-01 10:00:45 +0000372 smallint nonnull;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000373 smallint has_empty_slot;
Denis Vlasenko55789c62008-06-18 16:30:42 +0000374 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
Eric Andersen25f27032001-04-26 23:22:31 +0000375} o_string;
Denis Vlasenko55789c62008-06-18 16:30:42 +0000376enum {
377 MAYBE_ASSIGNMENT = 0,
378 DEFINITELY_ASSIGNMENT = 1,
379 NOT_ASSIGNMENT = 2,
380};
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000381/* Used for initialization: o_string foo = NULL_O_STRING; */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000382#define NULL_O_STRING { NULL }
Eric Andersen25f27032001-04-26 23:22:31 +0000383
384/* I can almost use ordinary FILE *. Is open_memstream() universally
385 * available? Where is it documented? */
386struct in_str {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +0000387 const char *p;
388 /* eof_flag=1: last char in ->p is really an EOF */
389 char eof_flag; /* meaningless if ->p == NULL */
390 char peek_buf[2];
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000391#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000392 smallint promptme;
393 smallint promptmode; /* 0: PS1, 1: PS2 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000394#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000395 FILE *file;
396 int (*get) (struct in_str *);
397 int (*peek) (struct in_str *);
398};
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000399#define i_getch(input) ((input)->get(input))
400#define i_peek(input) ((input)->peek(input))
Eric Andersen25f27032001-04-26 23:22:31 +0000401
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000402enum {
403 CHAR_ORDINARY = 0,
404 CHAR_ORDINARY_IF_QUOTED = 1, /* example: *, # */
405 CHAR_IFS = 2, /* treated as ordinary if quoted */
406 CHAR_SPECIAL = 3, /* example: $ */
Eric Andersen25f27032001-04-26 23:22:31 +0000407};
408
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000409#define HUSH_VER_STR "0.02"
410
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000411/* "Globals" within this file */
412
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000413/* Sorted roughly by size (smaller offsets == smaller code) */
414struct globals {
415#if ENABLE_HUSH_INTERACTIVE
416 /* 'interactive_fd' is a fd# open to ctty, if we have one
417 * _AND_ if we decided to act interactively */
418 int interactive_fd;
419 const char *PS1;
420 const char *PS2;
421#endif
422#if ENABLE_FEATURE_EDITING
423 line_input_t *line_input_state;
424#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000425 pid_t root_pid;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000426#if ENABLE_HUSH_JOB
427 int run_list_level;
428 pid_t saved_task_pgrp;
429 pid_t saved_tty_pgrp;
430 int last_jobid;
431 struct pipe *job_list;
432 struct pipe *toplevel_list;
433 smallint ctrl_z_flag;
434#endif
435 smallint fake_mode;
436 /* these three support $?, $#, and $1 */
437 char **global_argv;
438 int global_argc;
439 int last_return_code;
440 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000441 const char *cwd;
442 unsigned last_bg_pid;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +0000443 struct variable *top_var; /* = &shell_ver (set in main()) */
444 struct variable shell_ver;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000445#if ENABLE_FEATURE_SH_STANDALONE
446 struct nofork_save_area nofork_save;
447#endif
448#if ENABLE_HUSH_JOB
449 sigjmp_buf toplevel_jb;
450#endif
451 unsigned char charmap[256];
452 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
453};
454
455#define G (*ptr_to_globals)
456
457#if !ENABLE_HUSH_INTERACTIVE
458enum { interactive_fd = 0 };
459#endif
460#if !ENABLE_HUSH_JOB
461enum { run_list_level = 0 };
462#endif
463
464#if ENABLE_HUSH_INTERACTIVE
465#define interactive_fd (G.interactive_fd )
466#define PS1 (G.PS1 )
467#define PS2 (G.PS2 )
468#endif
469#if ENABLE_FEATURE_EDITING
470#define line_input_state (G.line_input_state)
471#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000472#define root_pid (G.root_pid )
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000473#if ENABLE_HUSH_JOB
474#define run_list_level (G.run_list_level )
475#define saved_task_pgrp (G.saved_task_pgrp )
476#define saved_tty_pgrp (G.saved_tty_pgrp )
477#define last_jobid (G.last_jobid )
478#define job_list (G.job_list )
479#define toplevel_list (G.toplevel_list )
480#define toplevel_jb (G.toplevel_jb )
481#define ctrl_z_flag (G.ctrl_z_flag )
482#endif /* JOB */
483#define global_argv (G.global_argv )
484#define global_argc (G.global_argc )
485#define last_return_code (G.last_return_code)
486#define ifs (G.ifs )
487#define fake_mode (G.fake_mode )
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000488#define cwd (G.cwd )
489#define last_bg_pid (G.last_bg_pid )
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000490#define top_var (G.top_var )
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000491#define shell_ver (G.shell_ver )
492#if ENABLE_FEATURE_SH_STANDALONE
493#define nofork_save (G.nofork_save )
Denis Vlasenko4b924f32007-05-30 00:29:55 +0000494#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000495#if ENABLE_HUSH_JOB
496#define toplevel_jb (G.toplevel_jb )
497#endif
498#define charmap (G.charmap )
499#define user_input_buf (G.user_input_buf )
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000500#define INIT_G() do { \
501 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
502} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000503
504
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000505#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
506
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000507#if 1
508/* Normal */
509static void syntax(const char *msg)
510{
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000511 /* Was using fancy stuff:
512 * (interactive_fd ? bb_error_msg : bb_error_msg_and_die)(...params...)
513 * but it SEGVs. ?! Oh well... explicit temp ptr works around that */
Denis Vlasenkodefc1ea2008-06-27 02:52:20 +0000514 void FAST_FUNC (*fp)(const char *s, ...);
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000515
516 fp = (interactive_fd ? bb_error_msg : bb_error_msg_and_die);
517 fp(msg ? "%s: %s" : "syntax error", "syntax error", msg);
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000518}
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000519
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000520#else
521/* Debug */
522static void syntax_lineno(int line)
Denis Vlasenkob6aae0f2007-01-29 22:51:25 +0000523{
Denis Vlasenkoff182a32008-07-05 20:29:59 +0000524 void FAST_FUNC (*fp)(const char *s, ...);
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000525
526 fp = (interactive_fd ? bb_error_msg : bb_error_msg_and_die);
527 fp("syntax error hush.c:%d", line);
Eric Andersen25f27032001-04-26 23:22:31 +0000528}
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000529#define syntax(str) syntax_lineno(__LINE__)
530#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000531
532/* Index of subroutines: */
Eric Andersen25f27032001-04-26 23:22:31 +0000533/* in_str manipulations: */
534static int static_get(struct in_str *i);
535static int static_peek(struct in_str *i);
536static int file_get(struct in_str *i);
537static int file_peek(struct in_str *i);
538static void setup_file_in_str(struct in_str *i, FILE *f);
539static void setup_string_in_str(struct in_str *i, const char *s);
Eric Andersen25f27032001-04-26 23:22:31 +0000540/* "run" the final data structures: */
Denis Vlasenkoc666f712007-05-16 22:18:54 +0000541#if !defined(DEBUG_CLEAN)
542#define free_pipe_list(head, indent) free_pipe_list(head)
543#define free_pipe(pi, indent) free_pipe(pi)
544#endif
Eric Andersenbf7df042001-05-23 22:18:35 +0000545static int free_pipe_list(struct pipe *head, int indent);
546static int free_pipe(struct pipe *pi, int indent);
Eric Andersen25f27032001-04-26 23:22:31 +0000547/* really run the final data structures: */
548static int setup_redirects(struct child_prog *prog, int squirrel[]);
Denis Vlasenko05743d72008-02-10 12:10:08 +0000549static int run_list(struct pipe *pi);
Denis Vlasenko76d50412008-06-10 16:19:39 +0000550#if BB_MMU
551#define pseudo_exec_argv(ptrs2free, argv) pseudo_exec_argv(argv)
552#define pseudo_exec(ptrs2free, child) pseudo_exec(child)
553#endif
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000554static void pseudo_exec_argv(char **ptrs2free, char **argv) NORETURN;
555static void pseudo_exec(char **ptrs2free, struct child_prog *child) NORETURN;
Denis Vlasenko05743d72008-02-10 12:10:08 +0000556static int run_pipe(struct pipe *pi);
Eric Andersen25f27032001-04-26 23:22:31 +0000557/* data structure manipulation: */
558static int setup_redirect(struct p_context *ctx, int fd, redir_type style, struct in_str *input);
559static void initialize_context(struct p_context *ctx);
560static int done_word(o_string *dest, struct p_context *ctx);
561static int done_command(struct p_context *ctx);
Denis Vlasenkoa8442002008-06-14 11:00:17 +0000562static void done_pipe(struct p_context *ctx, pipe_style type);
Eric Andersen25f27032001-04-26 23:22:31 +0000563/* primary string parsing: */
564static int redirect_dup_num(struct in_str *input);
565static int redirect_opt_num(o_string *o);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +0000566#if ENABLE_HUSH_TICK
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000567static int process_command_subs(o_string *dest,
Denis Vlasenko68404f12008-03-17 09:00:54 +0000568 struct in_str *input, const char *subst_end);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +0000569#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000570static int parse_group(o_string *dest, struct p_context *ctx, struct in_str *input, int ch);
Denis Vlasenko15d78fb2007-01-30 22:28:21 +0000571static const char *lookup_param(const char *src);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000572static int handle_dollar(o_string *dest,
Denis Vlasenko68404f12008-03-17 09:00:54 +0000573 struct in_str *input);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +0000574static 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 +0000575/* setup: */
Denis Vlasenko170435c2007-05-23 13:01:10 +0000576static int parse_and_run_stream(struct in_str *inp, int parse_flag);
577static int parse_and_run_string(const char *s, int parse_flag);
578static int parse_and_run_file(FILE *f);
Eric Andersenbafd94f2001-05-02 16:11:59 +0000579/* job management: */
Eric Andersenc798b072001-06-22 06:23:03 +0000580static int checkjobs(struct pipe* fg_pipe);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000581#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +0000582static int checkjobs_and_fg_shell(struct pipe* fg_pipe);
Eric Andersenbafd94f2001-05-02 16:11:59 +0000583static void insert_bg_job(struct pipe *pi);
584static void remove_bg_job(struct pipe *pi);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000585static void delete_finished_bg_job(struct pipe *pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000586#else
587int checkjobs_and_fg_shell(struct pipe* fg_pipe); /* never called */
588#endif
Eric Andersenf72f5622001-05-15 23:21:41 +0000589/* local variable support */
Denis Vlasenko170435c2007-05-23 13:01:10 +0000590static char **expand_strvec_to_strvec(char **argv);
591/* used for eval */
592static char *expand_strvec_to_string(char **argv);
Denis Vlasenkob6a741f2007-05-17 14:38:17 +0000593/* used for expansion of right hand of assignments */
Denis Vlasenko170435c2007-05-23 13:01:10 +0000594static char *expand_string_to_string(const char *str);
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000595static struct variable *get_local_var(const char *name);
596static int set_local_var(char *str, int flg_export);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +0000597static void unset_local_var(const char *name);
Eric Andersen25f27032001-04-26 23:22:31 +0000598
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000599
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000600static int glob_needed(const char *s)
601{
602 while (*s) {
603 if (*s == '\\')
604 s++;
605 if (*s == '*' || *s == '[' || *s == '?')
606 return 1;
607 s++;
608 }
609 return 0;
610}
611
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000612static int is_assignment(const char *s)
613{
614 if (!s || !isalpha(*s))
615 return 0;
616 s++;
617 while (isalnum(*s) || *s == '_')
618 s++;
619 return *s == '=';
620}
621
Denis Vlasenko55789c62008-06-18 16:30:42 +0000622/* Replace each \x with x in place, return ptr past NUL. */
623static char *unbackslash(char *src)
624{
625 char *dst = src;
626 while (1) {
627 if (*src == '\\')
628 src++;
629 if ((*dst++ = *src++) == '\0')
630 break;
631 }
632 return dst;
633}
634
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000635static char **add_malloced_strings_to_strings(char **strings, char **add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000636{
637 int i;
638 unsigned count1;
639 unsigned count2;
640 char **v;
641
642 v = strings;
643 count1 = 0;
644 if (v) {
645 while (*v) {
646 count1++;
647 v++;
648 }
649 }
650 count2 = 0;
651 v = add;
652 while (*v) {
653 count2++;
654 v++;
655 }
656 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
657 v[count1 + count2] = NULL;
658 i = count2;
659 while (--i >= 0)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000660 v[count1 + i] = add[i];
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000661 return v;
662}
663
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000664static char **add_malloced_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000665{
666 char *v[2];
667
668 v[0] = add;
669 v[1] = NULL;
670
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000671 return add_malloced_strings_to_strings(strings, v);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000672}
673
674static void free_strings(char **strings)
675{
676 if (strings) {
677 char **v = strings;
678 while (*v)
679 free(*v++);
680 free(strings);
681 }
682}
683
Denis Vlasenko76d50412008-06-10 16:19:39 +0000684#if !BB_MMU
685#define EXTRA_PTRS 5 /* 1 for NULL, 1 for args, 3 for paranoid reasons */
686static char **alloc_ptrs(char **argv)
687{
688 char **v = argv;
689 while (*v)
690 v++;
691 return xzalloc((v - argv + EXTRA_PTRS) * sizeof(v[0]));
692}
693#endif
694
695
Denis Vlasenko83506862007-11-23 13:11:42 +0000696/* Function prototypes for builtins */
697static int builtin_cd(char **argv);
Denis Vlasenko5bc593c2007-11-23 21:20:21 +0000698static int builtin_echo(char **argv);
Denis Vlasenko83506862007-11-23 13:11:42 +0000699static int builtin_eval(char **argv);
700static int builtin_exec(char **argv);
701static int builtin_exit(char **argv);
702static int builtin_export(char **argv);
703#if ENABLE_HUSH_JOB
704static int builtin_fg_bg(char **argv);
705static int builtin_jobs(char **argv);
706#endif
707#if ENABLE_HUSH_HELP
708static int builtin_help(char **argv);
709#endif
710static int builtin_pwd(char **argv);
711static int builtin_read(char **argv);
712static int builtin_test(char **argv);
Denis Vlasenkodd316dd2008-06-14 15:50:55 +0000713static int builtin_true(char **argv);
Denis Vlasenko83506862007-11-23 13:11:42 +0000714static int builtin_set(char **argv);
715static int builtin_shift(char **argv);
716static int builtin_source(char **argv);
717static int builtin_umask(char **argv);
718static int builtin_unset(char **argv);
719//static int builtin_not_written(char **argv);
720
Eric Andersen25f27032001-04-26 23:22:31 +0000721/* Table of built-in functions. They can be forked or not, depending on
722 * context: within pipes, they fork. As simple commands, they do not.
723 * When used in non-forking context, they can change global variables
Denis Vlasenkoe1a0d482006-10-20 13:28:22 +0000724 * in the parent shell process. If forked, of course they cannot.
Eric Andersen25f27032001-04-26 23:22:31 +0000725 * For example, 'unset foo | whatever' will parse and run, but foo will
726 * still be set at the end. */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000727struct built_in_command {
Denis Vlasenkodd316dd2008-06-14 15:50:55 +0000728 const char *cmd;
729 int (*function)(char **argv);
Denis Vlasenko06810332007-05-21 23:30:54 +0000730#if ENABLE_HUSH_HELP
Denis Vlasenkodd316dd2008-06-14 15:50:55 +0000731 const char *descr;
Denis Vlasenko06810332007-05-21 23:30:54 +0000732#define BLTIN(cmd, func, help) { cmd, func, help }
733#else
734#define BLTIN(cmd, func, help) { cmd, func }
735#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000736};
737
Denis Vlasenko5bc593c2007-11-23 21:20:21 +0000738/* For now, echo and test are unconditionally enabled.
739 * Maybe make it configurable? */
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +0000740static const struct built_in_command bltins[] = {
Denis Vlasenkodd316dd2008-06-14 15:50:55 +0000741 BLTIN("." , builtin_source, "Run commands in a file"),
742 BLTIN(":" , builtin_true, "No-op"),
Denis Vlasenko83506862007-11-23 13:11:42 +0000743 BLTIN("[" , builtin_test, "Test condition"),
744 BLTIN("[[" , builtin_test, "Test condition"),
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000745#if ENABLE_HUSH_JOB
Denis Vlasenko06810332007-05-21 23:30:54 +0000746 BLTIN("bg" , builtin_fg_bg, "Resume a job in the background"),
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000747#endif
Denis Vlasenko06810332007-05-21 23:30:54 +0000748// BLTIN("break" , builtin_not_written, "Exit for, while or until loop"),
Denis Vlasenkodd316dd2008-06-14 15:50:55 +0000749 BLTIN("cd" , builtin_cd, "Change directory"),
Denis Vlasenko06810332007-05-21 23:30:54 +0000750// BLTIN("continue", builtin_not_written, "Continue for, while or until loop"),
Denis Vlasenko5bc593c2007-11-23 21:20:21 +0000751 BLTIN("echo" , builtin_echo, "Write strings to stdout"),
Denis Vlasenko06810332007-05-21 23:30:54 +0000752 BLTIN("eval" , builtin_eval, "Construct and run shell command"),
Denis Vlasenkodd316dd2008-06-14 15:50:55 +0000753 BLTIN("exec" , builtin_exec, "Execute command, don't return to shell"),
754 BLTIN("exit" , builtin_exit, "Exit"),
Denis Vlasenko06810332007-05-21 23:30:54 +0000755 BLTIN("export", builtin_export, "Set environment variable"),
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000756#if ENABLE_HUSH_JOB
Denis Vlasenko06810332007-05-21 23:30:54 +0000757 BLTIN("fg" , builtin_fg_bg, "Bring job into the foreground"),
Denis Vlasenkodd316dd2008-06-14 15:50:55 +0000758 BLTIN("jobs" , builtin_jobs, "List active jobs"),
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000759#endif
Denis Vlasenko06810332007-05-21 23:30:54 +0000760 BLTIN("pwd" , builtin_pwd, "Print current directory"),
761 BLTIN("read" , builtin_read, "Input environment variable"),
762// BLTIN("return", builtin_not_written, "Return from a function"),
763 BLTIN("set" , builtin_set, "Set/unset shell local variables"),
764 BLTIN("shift" , builtin_shift, "Shift positional parameters"),
765// BLTIN("trap" , builtin_not_written, "Trap signals"),
Denis Vlasenko83506862007-11-23 13:11:42 +0000766 BLTIN("test" , builtin_test, "Test condition"),
Denis Vlasenkodd316dd2008-06-14 15:50:55 +0000767// BLTIN("ulimit", builtin_not_written, "Control resource limits"),
768 BLTIN("umask" , builtin_umask, "Set file creation mask"),
Denis Vlasenko06810332007-05-21 23:30:54 +0000769 BLTIN("unset" , builtin_unset, "Unset environment variable"),
Denis Vlasenko06810332007-05-21 23:30:54 +0000770#if ENABLE_HUSH_HELP
771 BLTIN("help" , builtin_help, "List shell built-in commands"),
772#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000773};
774
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000775
Denis Vlasenko4830fc52008-05-25 21:50:55 +0000776/* Signals are grouped, we handle them in batches */
777static void set_misc_sighandler(void (*handler)(int))
778{
779 bb_signals(0
780 + (1 << SIGINT)
781 + (1 << SIGQUIT)
782 + (1 << SIGTERM)
783 , handler);
784}
785
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000786#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000787
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000788static void set_fatal_sighandler(void (*handler)(int))
789{
Denis Vlasenko25591c32008-02-16 22:58:56 +0000790 bb_signals(0
791 + (1 << SIGILL)
792 + (1 << SIGTRAP)
793 + (1 << SIGABRT)
794 + (1 << SIGFPE)
795 + (1 << SIGBUS)
796 + (1 << SIGSEGV)
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000797 /* bash 3.2 seems to handle these just like 'fatal' ones */
Denis Vlasenko25591c32008-02-16 22:58:56 +0000798 + (1 << SIGHUP)
799 + (1 << SIGPIPE)
800 + (1 << SIGALRM)
801 , handler);
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000802}
803static void set_jobctrl_sighandler(void (*handler)(int))
804{
Denis Vlasenko25591c32008-02-16 22:58:56 +0000805 bb_signals(0
806 + (1 << SIGTSTP)
807 + (1 << SIGTTIN)
808 + (1 << SIGTTOU)
809 , handler);
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000810}
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000811/* SIGCHLD is special and handled separately */
812
813static void set_every_sighandler(void (*handler)(int))
814{
815 set_fatal_sighandler(handler);
816 set_jobctrl_sighandler(handler);
817 set_misc_sighandler(handler);
818 signal(SIGCHLD, handler);
819}
820
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000821static void handler_ctrl_c(int sig UNUSED_PARAM)
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000822{
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000823 debug_printf_jobs("got sig %d\n", sig);
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000824// as usual we can have all kinds of nasty problems with leaked malloc data here
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000825 siglongjmp(toplevel_jb, 1);
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000826}
827
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000828static void handler_ctrl_z(int sig UNUSED_PARAM)
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000829{
830 pid_t pid;
831
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000832 debug_printf_jobs("got tty sig %d in pid %d\n", sig, getpid());
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000833 pid = fork();
Denis Vlasenkoc2990322007-05-16 12:57:12 +0000834 if (pid < 0) /* can't fork. Pretend there was no ctrl-Z */
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000835 return;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000836 ctrl_z_flag = 1;
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000837 if (!pid) { /* child */
Denis Vlasenko83177992008-02-11 08:44:36 +0000838 if (ENABLE_HUSH_JOB)
839 die_sleep = 0; /* let nofork's xfuncs die */
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000840 setpgrp();
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000841 debug_printf_jobs("set pgrp for child %d ok\n", getpid());
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000842 set_every_sighandler(SIG_DFL);
Denis Vlasenko18e19f22007-04-28 16:43:18 +0000843 raise(SIGTSTP); /* resend TSTP so that child will be stopped */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000844 debug_printf_jobs("returning in child\n");
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000845 /* return to nofork, it will eventually exit now,
846 * not return back to shell */
847 return;
848 }
849 /* parent */
850 /* finish filling up pipe info */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000851 toplevel_list->pgrp = pid; /* child is in its own pgrp */
852 toplevel_list->progs[0].pid = pid;
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000853 /* parent needs to longjmp out of running nofork.
854 * we will "return" exitcode 0, with child put in background */
855// as usual we can have all kinds of nasty problems with leaked malloc data here
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000856 debug_printf_jobs("siglongjmp in parent\n");
857 siglongjmp(toplevel_jb, 1);
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000858}
859
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000860/* Restores tty foreground process group, and exits.
861 * May be called as signal handler for fatal signal
862 * (will faithfully resend signal to itself, producing correct exit state)
863 * or called directly with -EXITCODE.
864 * We also call it if xfunc is exiting. */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000865static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000866static void sigexit(int sig)
867{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000868 /* Disable all signals: job control, SIGPIPE, etc. */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +0000869 sigprocmask_allsigs(SIG_BLOCK);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000870
Denis Vlasenko87cb2db2007-04-21 10:00:01 +0000871 if (interactive_fd)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000872 tcsetpgrp(interactive_fd, saved_tty_pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000873
874 /* Not a signal, just exit */
875 if (sig <= 0)
876 _exit(- sig);
877
Denis Vlasenko400d8bb2008-02-24 13:36:01 +0000878 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000879}
880
881/* Restores tty foreground process group, and exits. */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000882static void hush_exit(int exitcode) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000883static void hush_exit(int exitcode)
884{
885 fflush(NULL); /* flush all streams */
886 sigexit(- (exitcode & 0xff));
887}
888
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000889#else /* !JOB */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000890
891#define set_fatal_sighandler(handler) ((void)0)
892#define set_jobctrl_sighandler(handler) ((void)0)
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000893#define hush_exit(e) exit(e)
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000894
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000895#endif /* JOB */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000896
897
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000898static const char *set_cwd(void)
899{
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000900 if (cwd == bb_msg_unknown)
Denis Vlasenko7cced6e2007-04-12 17:08:53 +0000901 cwd = NULL; /* xrealloc_getcwd_or_warn(arg) calls free(arg)! */
Denis Vlasenko6ca04442007-02-11 16:19:28 +0000902 cwd = xrealloc_getcwd_or_warn((char *)cwd);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000903 if (!cwd)
Manuel Novoa III cad53642003-03-19 09:13:01 +0000904 cwd = bb_msg_unknown;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000905 return cwd;
906}
907
Denis Vlasenko83506862007-11-23 13:11:42 +0000908
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000909/*
910 * o_string support
911 */
912#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +0000913
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000914static void o_reset(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +0000915{
916 o->length = 0;
917 o->nonnull = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000918 if (o->data)
919 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +0000920}
921
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000922static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +0000923{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +0000924 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000925 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +0000926}
927
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000928static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000929{
930 if (o->length + len > o->maxlen) {
931 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
932 o->data = xrealloc(o->data, 1 + o->maxlen);
933 }
934}
935
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000936static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000937{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000938 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
939 o_grow_by(o, 1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000940 o->data[o->length] = ch;
941 o->length++;
942 o->data[o->length] = '\0';
943}
944
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000945static void o_addstr(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000946{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000947 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000948 memcpy(&o->data[o->length], str, len);
949 o->length += len;
950 o->data[o->length] = '\0';
951}
952
Denis Vlasenko55789c62008-06-18 16:30:42 +0000953static void o_addstr_duplicate_backslash(o_string *o, const char *str, int len)
954{
955 while (len) {
956 o_addchr(o, *str);
957 if (*str++ == '\\'
958 && (*str != '*' && *str != '?' && *str != '[')
959 ) {
960 o_addchr(o, '\\');
961 }
962 len--;
963 }
964}
965
Eric Andersen25f27032001-04-26 23:22:31 +0000966/* My analysis of quoting semantics tells me that state information
967 * is associated with a destination, not a source.
968 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +0000969static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +0000970{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +0000971 int sz = 1;
972 if (strchr("*?[\\", ch)) {
973 sz++;
974 o->data[o->length] = '\\';
975 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +0000976 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +0000977 o_grow_by(o, sz);
978 o->data[o->length] = ch;
979 o->length++;
980 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +0000981}
982
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +0000983static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +0000984{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +0000985 int sz = 1;
986 if (o->o_quote && strchr("*?[\\", ch)) {
987 sz++;
988 o->data[o->length] = '\\';
989 o->length++;
990 }
991 o_grow_by(o, sz);
992 o->data[o->length] = ch;
993 o->length++;
994 o->data[o->length] = '\0';
995}
996
997static void o_addQstr(o_string *o, const char *str, int len)
998{
999 if (!o->o_quote) {
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001000 o_addstr(o, str, len);
1001 return;
1002 }
1003 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001004 char ch;
1005 int sz;
1006 int ordinary_cnt = strcspn(str, "*?[\\");
1007 if (ordinary_cnt > len) /* paranoia */
1008 ordinary_cnt = len;
1009 o_addstr(o, str, ordinary_cnt);
1010 if (ordinary_cnt == len)
1011 return;
1012 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001013 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001014
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001015 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001016 sz = 1;
1017 if (ch) { /* it is necessarily one of "*?[\\" */
1018 sz++;
1019 o->data[o->length] = '\\';
1020 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001021 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001022 o_grow_by(o, sz);
1023 o->data[o->length] = ch;
1024 o->length++;
1025 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001026 }
1027}
1028
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001029/* A special kind of o_string for $VAR and `cmd` expansion.
1030 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001031 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001032 * list[i] contains an INDEX (int!) into this string data.
1033 * It means that if list[] needs to grow, data needs to be moved higher up
1034 * but list[i]'s need not be modified.
1035 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001036 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001037 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1038 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001039#if DEBUG_EXPAND || DEBUG_GLOB
1040static void debug_print_list(const char *prefix, o_string *o, int n)
1041{
1042 char **list = (char**)o->data;
1043 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1044 int i = 0;
1045 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1046 prefix, list, n, string_start, o->length, o->maxlen);
1047 while (i < n) {
1048 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1049 o->data + (int)list[i] + string_start,
1050 o->data + (int)list[i] + string_start);
1051 i++;
1052 }
1053 if (n) {
1054 const char *p = o->data + (int)list[n - 1] + string_start;
1055 fprintf(stderr, " total_sz:%d\n", (p + strlen(p) + 1) - o->data);
1056 }
1057}
1058#else
1059#define debug_print_list(prefix, o, n) ((void)0)
1060#endif
1061
1062/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1063 * in list[n] so that it points past last stored byte so far.
1064 * It returns n+1. */
1065static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001066{
1067 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00001068 int string_start;
1069 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001070
1071 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00001072 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1073 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001074 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001075 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001076 /* list[n] points to string_start, make space for 16 more pointers */
1077 o->maxlen += 0x10 * sizeof(list[0]);
1078 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00001079 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001080 memmove(list + n + 0x10, list + n, string_len);
1081 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001082 } else
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001083 debug_printf_list("list[%d]=%d string_start=%d\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001084 } else {
1085 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00001086 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1087 string_len = o->length - string_start;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001088 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001089 o->has_empty_slot = 0;
1090 }
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001091 list[n] = (char*)(ptrdiff_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001092 return n + 1;
1093}
1094
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001095/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001096static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001097{
1098 char **list = (char**)o->data;
1099 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1100
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001101 return ((int)(ptrdiff_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001102}
1103
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001104/* o_glob performs globbing on last list[], saving each result
Denis Vlasenko55789c62008-06-18 16:30:42 +00001105 * as a new list[]. */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001106static int o_glob(o_string *o, int n)
1107{
1108 glob_t globdata;
1109 int gr;
1110 char *pattern;
1111
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001112 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001113 if (!o->data)
1114 return o_save_ptr_helper(o, n);
1115 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001116 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001117 if (!glob_needed(pattern)) {
1118 literal:
1119 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001120 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001121 return o_save_ptr_helper(o, n);
1122 }
1123
1124 memset(&globdata, 0, sizeof(globdata));
1125 gr = glob(pattern, 0, NULL, &globdata);
1126 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
1127 if (gr == GLOB_NOSPACE)
1128 bb_error_msg_and_die("out of memory during glob");
1129 if (gr == GLOB_NOMATCH) {
1130 globfree(&globdata);
1131 goto literal;
1132 }
1133 if (gr != 0) { /* GLOB_ABORTED ? */
1134//TODO: testcase for bad glob pattern behavior
1135 bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
1136 }
1137 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
1138 char **argv = globdata.gl_pathv;
1139 o->length = pattern - o->data; /* "forget" pattern */
1140 while (1) {
1141 o_addstr(o, *argv, strlen(*argv) + 1);
1142 n = o_save_ptr_helper(o, n);
1143 argv++;
1144 if (!*argv)
1145 break;
1146 }
1147 }
1148 globfree(&globdata);
1149 if (DEBUG_GLOB)
1150 debug_print_list("o_glob returning", o, n);
1151 return n;
1152}
1153
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001154/* If o->o_glob == 1, glob the string so far remembered.
1155 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001156static int o_save_ptr(o_string *o, int n)
1157{
1158 if (o->o_glob)
1159 return o_glob(o, n); /* o_save_ptr_helper is inside */
1160 return o_save_ptr_helper(o, n);
1161}
1162
1163/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001164static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001165{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001166 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001167 int string_start;
1168
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001169 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
1170 if (DEBUG_EXPAND)
1171 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001172 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001173 list = (char**)o->data;
1174 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1175 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001176 while (n) {
1177 n--;
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001178 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001179 }
1180 return list;
1181}
1182
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001183
1184/*
1185 * in_str support
1186 */
Eric Andersen25f27032001-04-26 23:22:31 +00001187static int static_get(struct in_str *i)
1188{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001189 int ch = *i->p++;
1190 if (ch == '\0') return EOF;
Eric Andersen25f27032001-04-26 23:22:31 +00001191 return ch;
1192}
1193
1194static int static_peek(struct in_str *i)
1195{
1196 return *i->p;
1197}
1198
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001199#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001200
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001201#if ENABLE_FEATURE_EDITING
Rob Landley88621d72006-08-29 19:41:06 +00001202static void cmdedit_set_initial_prompt(void)
Eric Andersen25f27032001-04-26 23:22:31 +00001203{
Denis Vlasenko38f63192007-01-22 09:03:07 +00001204#if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
Eric Andersen25f27032001-04-26 23:22:31 +00001205 PS1 = NULL;
1206#else
1207 PS1 = getenv("PS1");
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001208 if (PS1 == NULL)
Eric Andersen25f27032001-04-26 23:22:31 +00001209 PS1 = "\\w \\$ ";
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001210#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001211}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001212#endif /* EDITING */
Eric Andersen25f27032001-04-26 23:22:31 +00001213
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001214static const char* setup_prompt_string(int promptmode)
Eric Andersen25f27032001-04-26 23:22:31 +00001215{
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001216 const char *prompt_str;
1217 debug_printf("setup_prompt_string %d ", promptmode);
Denis Vlasenko38f63192007-01-22 09:03:07 +00001218#if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
Eric Andersen25f27032001-04-26 23:22:31 +00001219 /* Set up the prompt */
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001220 if (promptmode == 0) { /* PS1 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001221 free((char*)PS1);
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001222 PS1 = xasprintf("%s %c ", cwd, (geteuid() != 0) ? '$' : '#');
1223 prompt_str = PS1;
Eric Andersen25f27032001-04-26 23:22:31 +00001224 } else {
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001225 prompt_str = PS2;
Eric Andersen25f27032001-04-26 23:22:31 +00001226 }
1227#else
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001228 prompt_str = (promptmode == 0) ? PS1 : PS2;
Eric Andersenaf44a0e2001-04-27 07:26:12 +00001229#endif
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001230 debug_printf("result '%s'\n", prompt_str);
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001231 return prompt_str;
Eric Andersen25f27032001-04-26 23:22:31 +00001232}
1233
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001234static void get_user_input(struct in_str *i)
Eric Andersen25f27032001-04-26 23:22:31 +00001235{
Denis Vlasenko0937be52007-04-28 16:47:08 +00001236 int r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001237 const char *prompt_str;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001238
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001239 prompt_str = setup_prompt_string(i->promptmode);
Denis Vlasenko38f63192007-01-22 09:03:07 +00001240#if ENABLE_FEATURE_EDITING
Denis Vlasenko170435c2007-05-23 13:01:10 +00001241 /* Enable command line editing only while a command line
Denis Vlasenkoe376d452008-02-20 22:23:24 +00001242 * is actually being read */
1243 do {
1244 r = read_line_input(prompt_str, user_input_buf, BUFSIZ-1, line_input_state);
1245 } while (r == 0); /* repeat if Ctrl-C */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001246 i->eof_flag = (r < 0);
1247 if (i->eof_flag) { /* EOF/error detected */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001248 user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1249 user_input_buf[1] = '\0';
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001250 }
Eric Andersen25f27032001-04-26 23:22:31 +00001251#else
1252 fputs(prompt_str, stdout);
1253 fflush(stdout);
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001254 user_input_buf[0] = r = fgetc(i->file);
1255 /*user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001256 i->eof_flag = (r == EOF);
Eric Andersen25f27032001-04-26 23:22:31 +00001257#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001258 i->p = user_input_buf;
Eric Andersen25f27032001-04-26 23:22:31 +00001259}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001260
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001261#endif /* INTERACTIVE */
Eric Andersen25f27032001-04-26 23:22:31 +00001262
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001263/* This is the magic location that prints prompts
Eric Andersen25f27032001-04-26 23:22:31 +00001264 * and gets data back from the user */
1265static int file_get(struct in_str *i)
1266{
1267 int ch;
1268
Eric Andersen25f27032001-04-26 23:22:31 +00001269 /* If there is data waiting, eat it up */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001270 if (i->p && *i->p) {
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001271#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001272 take_cached:
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001273#endif
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001274 ch = *i->p++;
1275 if (i->eof_flag && !*i->p)
1276 ch = EOF;
Eric Andersen25f27032001-04-26 23:22:31 +00001277 } else {
1278 /* need to double check i->file because we might be doing something
1279 * more complicated by now, like sourcing or substituting. */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001280#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001281 if (interactive_fd && i->promptme && i->file == stdin) {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001282 do {
1283 get_user_input(i);
1284 } while (!*i->p); /* need non-empty line */
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001285 i->promptmode = 1; /* PS2 */
1286 i->promptme = 0;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001287 goto take_cached;
Eric Andersen25f27032001-04-26 23:22:31 +00001288 }
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001289#endif
1290 ch = fgetc(i->file);
Eric Andersen25f27032001-04-26 23:22:31 +00001291 }
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001292 debug_printf("file_get: got a '%c' %d\n", ch, ch);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001293#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001294 if (ch == '\n')
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001295 i->promptme = 1;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001296#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001297 return ch;
1298}
1299
1300/* All the callers guarantee this routine will never be
1301 * used right after a newline, so prompting is not needed.
1302 */
1303static int file_peek(struct in_str *i)
1304{
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00001305 int ch;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001306 if (i->p && *i->p) {
1307 if (i->eof_flag && !i->p[1])
1308 return EOF;
1309 return *i->p;
Eric Andersen25f27032001-04-26 23:22:31 +00001310 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00001311 ch = fgetc(i->file);
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001312 i->eof_flag = (ch == EOF);
1313 i->peek_buf[0] = ch;
1314 i->peek_buf[1] = '\0';
1315 i->p = i->peek_buf;
1316 debug_printf("file_peek: got a '%c' %d\n", *i->p, *i->p);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00001317 return ch;
Eric Andersen25f27032001-04-26 23:22:31 +00001318}
1319
1320static void setup_file_in_str(struct in_str *i, FILE *f)
1321{
1322 i->peek = file_peek;
1323 i->get = file_get;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001324#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001325 i->promptme = 1;
1326 i->promptmode = 0; /* PS1 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001327#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001328 i->file = f;
1329 i->p = NULL;
1330}
1331
1332static void setup_string_in_str(struct in_str *i, const char *s)
1333{
1334 i->peek = static_peek;
1335 i->get = static_get;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001336#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001337 i->promptme = 1;
1338 i->promptmode = 0; /* PS1 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001339#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001340 i->p = s;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001341 i->eof_flag = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00001342}
1343
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001344
Eric Andersen25f27032001-04-26 23:22:31 +00001345/* squirrel != NULL means we squirrel away copies of stdin, stdout,
1346 * and stderr if they are redirected. */
1347static int setup_redirects(struct child_prog *prog, int squirrel[])
1348{
1349 int openfd, mode;
1350 struct redir_struct *redir;
1351
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001352 for (redir = prog->redirects; redir; redir = redir->next) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00001353 if (redir->dup == -1 && redir->rd_filename == NULL) {
Eric Andersen817e73c2001-06-06 17:56:09 +00001354 /* something went wrong in the parse. Pretend it didn't happen */
1355 continue;
1356 }
Eric Andersen25f27032001-04-26 23:22:31 +00001357 if (redir->dup == -1) {
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00001358 char *p;
Denis Vlasenko55789c62008-06-18 16:30:42 +00001359 mode = redir_table[redir->rd_type].mode;
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00001360//TODO: check redir for names like '\\'
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00001361 p = expand_string_to_string(redir->rd_filename);
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00001362 openfd = open_or_warn(p, mode);
1363 free(p);
Eric Andersen25f27032001-04-26 23:22:31 +00001364 if (openfd < 0) {
1365 /* this could get lost if stderr has been redirected, but
1366 bash and ash both lose it as well (though zsh doesn't!) */
Eric Andersen25f27032001-04-26 23:22:31 +00001367 return 1;
1368 }
1369 } else {
1370 openfd = redir->dup;
1371 }
1372
1373 if (openfd != redir->fd) {
1374 if (squirrel && redir->fd < 3) {
1375 squirrel[redir->fd] = dup(redir->fd);
1376 }
Eric Andersen83a2ae22001-05-07 17:59:25 +00001377 if (openfd == -3) {
Denis Vlasenko8412d792007-10-01 09:59:47 +00001378 //close(openfd); // close(-3) ??!
Eric Andersen83a2ae22001-05-07 17:59:25 +00001379 } else {
1380 dup2(openfd, redir->fd);
Matt Kraaic616e532001-06-05 16:50:08 +00001381 if (redir->dup == -1)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001382 close(openfd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00001383 }
Eric Andersen25f27032001-04-26 23:22:31 +00001384 }
1385 }
1386 return 0;
1387}
1388
1389static void restore_redirects(int squirrel[])
1390{
1391 int i, fd;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001392 for (i = 0; i < 3; i++) {
Eric Andersen25f27032001-04-26 23:22:31 +00001393 fd = squirrel[i];
1394 if (fd != -1) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00001395 /* We simply die on error */
1396 xmove_fd(fd, i);
Eric Andersen25f27032001-04-26 23:22:31 +00001397 }
1398 }
1399}
1400
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001401
Denis Vlasenko05743d72008-02-10 12:10:08 +00001402/* Called after [v]fork() in run_pipe(), or from builtin_exec().
Denis Vlasenko8412d792007-10-01 09:59:47 +00001403 * Never returns.
1404 * XXX no exit() here. If you don't exec, use _exit instead.
Eric Andersen94ac2442001-05-22 19:05:18 +00001405 * The at_exit handlers apparently confuse the calling process,
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001406 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
Denis Vlasenko76d50412008-06-10 16:19:39 +00001407static void pseudo_exec_argv(char **ptrs2free, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00001408{
Eric Andersen78a7c992001-05-15 16:30:25 +00001409 int i, rcode;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001410 char *p;
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +00001411 const struct built_in_command *x;
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001412
Denis Vlasenko1359da62007-04-21 23:27:30 +00001413 for (i = 0; is_assignment(argv[i]); i++) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001414 debug_printf_exec("pid %d environment modification: %s\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001415 getpid(), argv[i]);
Denis Vlasenko170435c2007-05-23 13:01:10 +00001416 p = expand_string_to_string(argv[i]);
Denis Vlasenko76d50412008-06-10 16:19:39 +00001417#if !BB_MMU
1418 *ptrs2free++ = p;
1419#endif
Denis Vlasenko170435c2007-05-23 13:01:10 +00001420 putenv(p);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001421 }
1422 argv += i;
1423 /* If a variable is assigned in a forest, and nobody listens,
1424 * was it ever really set?
1425 */
Denis Vlasenko05743d72008-02-10 12:10:08 +00001426 if (!argv[0])
Denis Vlasenko1359da62007-04-21 23:27:30 +00001427 _exit(EXIT_SUCCESS);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001428
Denis Vlasenko170435c2007-05-23 13:01:10 +00001429 argv = expand_strvec_to_strvec(argv);
Denis Vlasenko76d50412008-06-10 16:19:39 +00001430#if !BB_MMU
1431 *ptrs2free++ = (char*) argv;
1432#endif
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001433
Denis Vlasenko1359da62007-04-21 23:27:30 +00001434 /*
1435 * Check if the command matches any of the builtins.
1436 * Depending on context, this might be redundant. But it's
1437 * easier to waste a few CPU cycles than it is to figure out
1438 * if this is one of those cases.
1439 */
Denis Vlasenkodd316dd2008-06-14 15:50:55 +00001440 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
Denis Vlasenko1359da62007-04-21 23:27:30 +00001441 if (strcmp(argv[0], x->cmd) == 0) {
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001442 debug_printf_exec("running builtin '%s'\n", argv[0]);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001443 rcode = x->function(argv);
1444 fflush(stdout);
1445 _exit(rcode);
Eric Andersen94ac2442001-05-22 19:05:18 +00001446 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00001447 }
Eric Andersen78a7c992001-05-15 16:30:25 +00001448
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001449 /* Check if the command matches any busybox applets */
Denis Vlasenko80d14be2007-04-10 23:03:30 +00001450#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001451 if (strchr(argv[0], '/') == NULL) {
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00001452 int a = find_applet_by_name(argv[0]);
1453 if (a >= 0) {
1454 if (APPLET_IS_NOEXEC(a)) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001455 debug_printf_exec("running applet '%s'\n", argv[0]);
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00001456// is it ok that run_applet_no_and_exit() does exit(), not _exit()?
1457 run_applet_no_and_exit(a, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001458 }
1459 /* re-exec ourselves with the new arguments */
1460 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denis Vlasenkobdbbb7e2007-06-08 15:02:55 +00001461 execvp(bb_busybox_exec_path, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001462 /* If they called chroot or otherwise made the binary no longer
1463 * executable, fall through */
1464 }
1465 }
Eric Andersenaac75e52001-04-30 18:18:45 +00001466#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001467
1468 debug_printf_exec("execing '%s'\n", argv[0]);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001469 execvp(argv[0], argv);
1470 bb_perror_msg("cannot exec '%s'", argv[0]);
Bernhard Reutner-Fischer636a1f82008-05-19 09:29:47 +00001471 _exit(EXIT_FAILURE);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001472}
1473
Denis Vlasenko05743d72008-02-10 12:10:08 +00001474/* Called after [v]fork() in run_pipe()
Denis Vlasenko8412d792007-10-01 09:59:47 +00001475 */
Denis Vlasenko76d50412008-06-10 16:19:39 +00001476static void pseudo_exec(char **ptrs2free, struct child_prog *child)
Denis Vlasenko1359da62007-04-21 23:27:30 +00001477{
Denis Vlasenko05743d72008-02-10 12:10:08 +00001478 if (child->argv)
Denis Vlasenko76d50412008-06-10 16:19:39 +00001479 pseudo_exec_argv(ptrs2free, child->argv);
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001480
1481 if (child->group) {
Denis Vlasenko8412d792007-10-01 09:59:47 +00001482#if !BB_MMU
Denis Vlasenko3b492162007-12-24 14:26:57 +00001483 bb_error_msg_and_die("nested lists are not supported on NOMMU");
Denis Vlasenko8412d792007-10-01 09:59:47 +00001484#else
Denis Vlasenko3b492162007-12-24 14:26:57 +00001485 int rcode;
Denis Vlasenko05743d72008-02-10 12:10:08 +00001486 debug_printf_exec("pseudo_exec: run_list\n");
1487 rcode = run_list(child->group);
Eric Andersenbf7df042001-05-23 22:18:35 +00001488 /* OK to leak memory by not calling free_pipe_list,
Eric Andersen25f27032001-04-26 23:22:31 +00001489 * since this process is about to exit */
Eric Andersen94ac2442001-05-22 19:05:18 +00001490 _exit(rcode);
Denis Vlasenko8412d792007-10-01 09:59:47 +00001491#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001492 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001493
1494 /* Can happen. See what bash does with ">foo" by itself. */
1495 debug_printf("trying to pseudo_exec null command\n");
1496 _exit(EXIT_SUCCESS);
Eric Andersen25f27032001-04-26 23:22:31 +00001497}
1498
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001499#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001500static const char *get_cmdtext(struct pipe *pi)
1501{
1502 char **argv;
1503 char *p;
1504 int len;
1505
1506 /* This is subtle. ->cmdtext is created only on first backgrounding.
1507 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001508 * On subsequent bg argv is trashed, but we won't use it */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001509 if (pi->cmdtext)
1510 return pi->cmdtext;
1511 argv = pi->progs[0].argv;
Denis Vlasenkoa8442002008-06-14 11:00:17 +00001512 if (!argv || !argv[0]) {
1513 pi->cmdtext = xzalloc(1);
1514 return pi->cmdtext;
1515 }
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001516
1517 len = 0;
1518 do len += strlen(*argv) + 1; while (*++argv);
1519 pi->cmdtext = p = xmalloc(len);
1520 argv = pi->progs[0].argv;
1521 do {
1522 len = strlen(*argv);
1523 memcpy(p, *argv, len);
1524 p += len;
1525 *p++ = ' ';
1526 } while (*++argv);
1527 p[-1] = '\0';
1528 return pi->cmdtext;
1529}
1530
Eric Andersenbafd94f2001-05-02 16:11:59 +00001531static void insert_bg_job(struct pipe *pi)
1532{
1533 struct pipe *thejob;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001534 int i;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001535
1536 /* Linear search for the ID of the job to use */
1537 pi->jobid = 1;
Eric Andersenc798b072001-06-22 06:23:03 +00001538 for (thejob = job_list; thejob; thejob = thejob->next)
Eric Andersenbafd94f2001-05-02 16:11:59 +00001539 if (thejob->jobid >= pi->jobid)
1540 pi->jobid = thejob->jobid + 1;
1541
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001542 /* Add thejob to the list of running jobs */
Eric Andersenc798b072001-06-22 06:23:03 +00001543 if (!job_list) {
Eric Andersen52a97ca2001-06-22 06:49:26 +00001544 thejob = job_list = xmalloc(sizeof(*thejob));
Eric Andersenbafd94f2001-05-02 16:11:59 +00001545 } else {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001546 for (thejob = job_list; thejob->next; thejob = thejob->next)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001547 continue;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001548 thejob->next = xmalloc(sizeof(*thejob));
1549 thejob = thejob->next;
1550 }
1551
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001552 /* Physically copy the struct job */
Eric Andersen0fcd4472001-05-02 20:12:03 +00001553 memcpy(thejob, pi, sizeof(struct pipe));
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001554 thejob->progs = xzalloc(sizeof(pi->progs[0]) * pi->num_progs);
1555 /* We cannot copy entire pi->progs[] vector! Double free()s will happen */
1556 for (i = 0; i < pi->num_progs; i++) {
1557// TODO: do we really need to have so many fields which are just dead weight
1558// at execution stage?
1559 thejob->progs[i].pid = pi->progs[i].pid;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001560 /* all other fields are not used and stay zero */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001561 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00001562 thejob->next = NULL;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001563 thejob->cmdtext = xstrdup(get_cmdtext(pi));
Eric Andersenbafd94f2001-05-02 16:11:59 +00001564
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001565 /* We don't wait for background thejobs to return -- append it
Eric Andersenbafd94f2001-05-02 16:11:59 +00001566 to the list of backgrounded thejobs and leave it alone */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001567 printf("[%d] %d %s\n", thejob->jobid, thejob->progs[0].pid, thejob->cmdtext);
Eric Andersen1a6d39b2001-05-08 05:11:54 +00001568 last_bg_pid = thejob->progs[0].pid;
Eric Andersenc798b072001-06-22 06:23:03 +00001569 last_jobid = thejob->jobid;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001570}
1571
Eric Andersenbafd94f2001-05-02 16:11:59 +00001572static void remove_bg_job(struct pipe *pi)
1573{
1574 struct pipe *prev_pipe;
1575
Eric Andersenc798b072001-06-22 06:23:03 +00001576 if (pi == job_list) {
Eric Andersen52a97ca2001-06-22 06:49:26 +00001577 job_list = pi->next;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001578 } else {
Eric Andersenc798b072001-06-22 06:23:03 +00001579 prev_pipe = job_list;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001580 while (prev_pipe->next != pi)
1581 prev_pipe = prev_pipe->next;
1582 prev_pipe->next = pi->next;
1583 }
Eric Andersen028b65b2001-06-28 01:10:11 +00001584 if (job_list)
1585 last_jobid = job_list->jobid;
1586 else
1587 last_jobid = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001588}
Eric Andersen028b65b2001-06-28 01:10:11 +00001589
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001590/* Remove a backgrounded job */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001591static void delete_finished_bg_job(struct pipe *pi)
1592{
1593 remove_bg_job(pi);
Eric Andersen52a97ca2001-06-22 06:49:26 +00001594 pi->stopped_progs = 0;
Eric Andersenbf7df042001-05-23 22:18:35 +00001595 free_pipe(pi, 0);
Eric Andersenbafd94f2001-05-02 16:11:59 +00001596 free(pi);
1597}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001598#endif /* JOB */
Eric Andersenbafd94f2001-05-02 16:11:59 +00001599
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001600/* Check to see if any processes have exited -- if they
1601 * have, figure out why and see if a job has completed */
Eric Andersenc798b072001-06-22 06:23:03 +00001602static int checkjobs(struct pipe* fg_pipe)
Eric Andersenbafd94f2001-05-02 16:11:59 +00001603{
Eric Andersenc798b072001-06-22 06:23:03 +00001604 int attributes;
1605 int status;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001606#if ENABLE_HUSH_JOB
Eric Andersenbafd94f2001-05-02 16:11:59 +00001607 struct pipe *pi;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001608#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00001609 pid_t childpid;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001610 int rcode = 0;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001611
Eric Andersenc798b072001-06-22 06:23:03 +00001612 attributes = WUNTRACED;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001613 if (fg_pipe == NULL)
Eric Andersenc798b072001-06-22 06:23:03 +00001614 attributes |= WNOHANG;
Eric Andersenc798b072001-06-22 06:23:03 +00001615
Denis Vlasenko1359da62007-04-21 23:27:30 +00001616/* Do we do this right?
1617 * bash-3.00# sleep 20 | false
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001618 * <ctrl-Z pressed>
Denis Vlasenko1359da62007-04-21 23:27:30 +00001619 * [3]+ Stopped sleep 20 | false
1620 * bash-3.00# echo $?
1621 * 1 <========== bg pipe is not fully done, but exitcode is already known!
1622 */
1623
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001624//FIXME: non-interactive bash does not continue even if all processes in fg pipe
1625//are stopped. Testcase: "cat | cat" in a script (not on command line)
1626// + killall -STOP cat
1627
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001628 wait_more:
Denis Vlasenkofb0eba72008-01-02 19:55:04 +00001629// TODO: safe_waitpid?
Eric Andersenc798b072001-06-22 06:23:03 +00001630 while ((childpid = waitpid(-1, &status, attributes)) > 0) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001631 int i;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001632 const int dead = WIFEXITED(status) || WIFSIGNALED(status);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001633#if DEBUG_JOBS
Denis Vlasenko1359da62007-04-21 23:27:30 +00001634 if (WIFSTOPPED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001635 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001636 childpid, WSTOPSIG(status), WEXITSTATUS(status));
1637 if (WIFSIGNALED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001638 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001639 childpid, WTERMSIG(status), WEXITSTATUS(status));
1640 if (WIFEXITED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001641 debug_printf_jobs("pid %d exited, exitcode %d\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001642 childpid, WEXITSTATUS(status));
1643#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001644 /* Were we asked to wait for fg pipe? */
Eric Andersenc798b072001-06-22 06:23:03 +00001645 if (fg_pipe) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001646 for (i = 0; i < fg_pipe->num_progs; i++) {
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001647 debug_printf_jobs("check pid %d\n", fg_pipe->progs[i].pid);
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001648 if (fg_pipe->progs[i].pid != childpid)
1649 continue;
1650 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
1651 if (dead) {
1652 fg_pipe->progs[i].pid = 0;
1653 fg_pipe->alive_progs--;
1654 if (i == fg_pipe->num_progs - 1) {
1655 /* last process gives overall exitstatus */
1656 rcode = WEXITSTATUS(status);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00001657 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
Denis Vlasenko1359da62007-04-21 23:27:30 +00001658 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001659 } else {
1660 fg_pipe->progs[i].is_stopped = 1;
1661 fg_pipe->stopped_progs++;
Eric Andersenc798b072001-06-22 06:23:03 +00001662 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001663 debug_printf_jobs("fg_pipe: alive_progs %d stopped_progs %d\n",
1664 fg_pipe->alive_progs, fg_pipe->stopped_progs);
1665 if (fg_pipe->alive_progs - fg_pipe->stopped_progs <= 0) {
1666 /* All processes in fg pipe have exited/stopped */
1667#if ENABLE_HUSH_JOB
1668 if (fg_pipe->alive_progs)
1669 insert_bg_job(fg_pipe);
1670#endif
1671 return rcode;
1672 }
1673 /* There are still running processes in the fg pipe */
1674 goto wait_more; /* do waitpid again */
Eric Andersenc798b072001-06-22 06:23:03 +00001675 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001676 /* it wasnt fg_pipe, look for process in bg pipes */
Eric Andersenc798b072001-06-22 06:23:03 +00001677 }
1678
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001679#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001680 /* We asked to wait for bg or orphaned children */
1681 /* No need to remember exitcode in this case */
Eric Andersenc798b072001-06-22 06:23:03 +00001682 for (pi = job_list; pi; pi = pi->next) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001683 for (i = 0; i < pi->num_progs; i++) {
1684 if (pi->progs[i].pid == childpid)
Denis Vlasenko5f786c22007-04-20 08:35:45 +00001685 goto found_pi_and_prognum;
Eric Andersen52a97ca2001-06-22 06:49:26 +00001686 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00001687 }
Denis Vlasenko5f786c22007-04-20 08:35:45 +00001688 /* Happens when shell is used as init process (init=/bin/sh) */
1689 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001690 continue; /* do waitpid again */
Eric Andersenaeb44c42001-05-22 20:29:00 +00001691
Denis Vlasenko5f786c22007-04-20 08:35:45 +00001692 found_pi_and_prognum:
Denis Vlasenko1359da62007-04-21 23:27:30 +00001693 if (dead) {
Eric Andersenbafd94f2001-05-02 16:11:59 +00001694 /* child exited */
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001695 pi->progs[i].pid = 0;
1696 pi->alive_progs--;
1697 if (!pi->alive_progs) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001698 printf(JOB_STATUS_FORMAT, pi->jobid,
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001699 "Done", pi->cmdtext);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001700 delete_finished_bg_job(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00001701 }
1702 } else {
1703 /* child stopped */
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001704 pi->progs[i].is_stopped = 1;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001705 pi->stopped_progs++;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001706 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001707#endif
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001708 } /* while (waitpid succeeds)... */
Eric Andersenbafd94f2001-05-02 16:11:59 +00001709
Denis Vlasenko1359da62007-04-21 23:27:30 +00001710 /* wait found no children or failed */
1711
1712 if (childpid && errno != ECHILD)
Manuel Novoa III cad53642003-03-19 09:13:01 +00001713 bb_perror_msg("waitpid");
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001714 return rcode;
Eric Andersenada18ff2001-05-21 16:18:22 +00001715}
1716
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001717#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +00001718static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
1719{
1720 pid_t p;
1721 int rcode = checkjobs(fg_pipe);
1722 /* Job finished, move the shell to the foreground */
Denis Vlasenko170435c2007-05-23 13:01:10 +00001723 p = getpgid(0); /* pgid of our process */
1724 debug_printf_jobs("fg'ing ourself: getpgid(0)=%d\n", (int)p);
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001725 tcsetpgrp(interactive_fd, p);
1726// if (tcsetpgrp(interactive_fd, p) && errno != ENOTTY)
1727// bb_perror_msg("tcsetpgrp-4a");
Denis Vlasenko52881e92007-04-21 13:42:52 +00001728 return rcode;
1729}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001730#endif
Denis Vlasenko52881e92007-04-21 13:42:52 +00001731
Denis Vlasenko05743d72008-02-10 12:10:08 +00001732/* run_pipe() starts all the jobs, but doesn't wait for anything
Eric Andersenc798b072001-06-22 06:23:03 +00001733 * to finish. See checkjobs().
Eric Andersen25f27032001-04-26 23:22:31 +00001734 *
1735 * return code is normally -1, when the caller has to wait for children
1736 * to finish to determine the exit status of the pipe. If the pipe
1737 * is a simple builtin command, however, the action is done by the
Denis Vlasenko05743d72008-02-10 12:10:08 +00001738 * time run_pipe returns, and the exit code is provided as the
Eric Andersen25f27032001-04-26 23:22:31 +00001739 * return value.
1740 *
1741 * The input of the pipe is always stdin, the output is always
1742 * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
1743 * because it tries to avoid running the command substitution in
1744 * subshell, when that is in fact necessary. The subshell process
1745 * now has its stdout directed to the input of the appropriate pipe,
1746 * so this routine is noticeably simpler.
Denis Vlasenko170435c2007-05-23 13:01:10 +00001747 *
1748 * Returns -1 only if started some children. IOW: we have to
1749 * mask out retvals of builtins etc with 0xff!
Eric Andersen25f27032001-04-26 23:22:31 +00001750 */
Denis Vlasenko05743d72008-02-10 12:10:08 +00001751static int run_pipe(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00001752{
1753 int i;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001754 int nextin;
1755 int pipefds[2]; /* pipefds[0] is for reading */
Rob Landley53702e52006-07-19 21:43:53 +00001756 struct child_prog *child;
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +00001757 const struct built_in_command *x;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001758 char *p;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001759 /* it is not always needed, but we aim to smaller code */
1760 int squirrel[] = { -1, -1, -1 };
1761 int rcode;
Denis Vlasenko52881e92007-04-21 13:42:52 +00001762 const int single_fg = (pi->num_progs == 1 && pi->followup != PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00001763
Denis Vlasenko05743d72008-02-10 12:10:08 +00001764 debug_printf_exec("run_pipe start: single_fg=%d\n", single_fg);
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00001765
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001766#if ENABLE_HUSH_JOB
Eric Andersenada18ff2001-05-21 16:18:22 +00001767 pi->pgrp = -1;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001768#endif
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001769 pi->alive_progs = 1;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001770 pi->stopped_progs = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00001771
1772 /* Check if this is a simple builtin (not part of a pipe).
1773 * Builtins within pipes have to fork anyway, and are handled in
1774 * pseudo_exec. "echo foo | read bar" doesn't work on bash, either.
1775 */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001776 child = &(pi->progs[0]);
Denis Vlasenko52881e92007-04-21 13:42:52 +00001777 if (single_fg && child->group && child->subshell == 0) {
Eric Andersen04407e52001-06-07 16:42:05 +00001778 debug_printf("non-subshell grouping\n");
1779 setup_redirects(child, squirrel);
Denis Vlasenko05743d72008-02-10 12:10:08 +00001780 debug_printf_exec(": run_list\n");
1781 rcode = run_list(child->group) & 0xff;
Eric Andersen04407e52001-06-07 16:42:05 +00001782 restore_redirects(squirrel);
Denis Vlasenko05743d72008-02-10 12:10:08 +00001783 debug_printf_exec("run_pipe return %d\n", rcode);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00001784 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko05743d72008-02-10 12:10:08 +00001785 return rcode;
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001786 }
1787
Denis Vlasenko1359da62007-04-21 23:27:30 +00001788 if (single_fg && child->argv != NULL) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001789 char **argv_expanded;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001790 char **argv = child->argv;
1791
1792 for (i = 0; is_assignment(argv[i]); i++)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001793 continue;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001794 if (i != 0 && argv[i] == NULL) {
Eric Andersen78a7c992001-05-15 16:30:25 +00001795 /* assignments, but no command: set the local environment */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001796 for (i = 0; argv[i] != NULL; i++) {
Denis Vlasenkod76c0492007-05-25 02:16:25 +00001797 debug_printf("local environment set: %s\n", argv[i]);
Denis Vlasenko170435c2007-05-23 13:01:10 +00001798 p = expand_string_to_string(argv[i]);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00001799 set_local_var(p, 0);
Eric Andersen78a7c992001-05-15 16:30:25 +00001800 }
1801 return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
1802 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00001803 for (i = 0; is_assignment(argv[i]); i++) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00001804 p = expand_string_to_string(argv[i]);
Denis Vlasenko170435c2007-05-23 13:01:10 +00001805 putenv(p);
Denis Vlasenko55789c62008-06-18 16:30:42 +00001806//FIXME: do we leak p?!
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001807 }
Denis Vlasenkodd316dd2008-06-14 15:50:55 +00001808 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
Denis Vlasenko1359da62007-04-21 23:27:30 +00001809 if (strcmp(argv[i], x->cmd) == 0) {
1810 if (x->function == builtin_exec && argv[i+1] == NULL) {
Eric Andersen83a2ae22001-05-07 17:59:25 +00001811 debug_printf("magic exec\n");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001812 setup_redirects(child, NULL);
Eric Andersen83a2ae22001-05-07 17:59:25 +00001813 return EXIT_SUCCESS;
1814 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00001815 debug_printf("builtin inline %s\n", argv[0]);
Eric Andersen25f27032001-04-26 23:22:31 +00001816 /* XXX setup_redirects acts on file descriptors, not FILEs.
1817 * This is perfect for work that comes after exec().
1818 * Is it really safe for inline use? Experimentally,
1819 * things seem to work with glibc. */
1820 setup_redirects(child, squirrel);
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001821 debug_printf_exec(": builtin '%s' '%s'...\n", x->cmd, argv[i+1]);
Denis Vlasenko170435c2007-05-23 13:01:10 +00001822 argv_expanded = expand_strvec_to_strvec(argv + i);
1823 rcode = x->function(argv_expanded) & 0xff;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001824 free(argv_expanded);
Eric Andersen25f27032001-04-26 23:22:31 +00001825 restore_redirects(squirrel);
Denis Vlasenko05743d72008-02-10 12:10:08 +00001826 debug_printf_exec("run_pipe return %d\n", rcode);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00001827 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Eric Andersen25f27032001-04-26 23:22:31 +00001828 return rcode;
1829 }
1830 }
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001831#if ENABLE_FEATURE_SH_STANDALONE
1832 {
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00001833 int a = find_applet_by_name(argv[i]);
1834 if (a >= 0 && APPLET_IS_NOFORK(a)) {
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001835 setup_redirects(child, squirrel);
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001836 save_nofork_data(&nofork_save);
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001837 argv_expanded = argv + i;
Denis Vlasenko170435c2007-05-23 13:01:10 +00001838 argv_expanded = expand_strvec_to_strvec(argv + i);
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001839 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n", argv_expanded[0], argv_expanded[1]);
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00001840 rcode = run_nofork_applet_prime(&nofork_save, a, argv_expanded);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001841 free(argv_expanded);
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001842 restore_redirects(squirrel);
Denis Vlasenko05743d72008-02-10 12:10:08 +00001843 debug_printf_exec("run_pipe return %d\n", rcode);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00001844 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001845 return rcode;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001846 }
1847 }
1848#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001849 }
1850
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001851 /* Disable job control signals for shell (parent) and
1852 * for initial child code after fork */
1853 set_jobctrl_sighandler(SIG_IGN);
1854
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001855 /* Going to fork a child per each pipe member */
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001856 pi->alive_progs = 0;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001857 nextin = 0;
1858
Eric Andersen25f27032001-04-26 23:22:31 +00001859 for (i = 0; i < pi->num_progs; i++) {
Denis Vlasenko76d50412008-06-10 16:19:39 +00001860#if !BB_MMU
1861 char **ptrs2free = NULL;
1862#endif
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001863 child = &(pi->progs[i]);
Denis Vlasenko76d50412008-06-10 16:19:39 +00001864 if (child->argv) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001865 debug_printf_exec(": pipe member '%s' '%s'...\n", child->argv[0], child->argv[1]);
Denis Vlasenko76d50412008-06-10 16:19:39 +00001866#if !BB_MMU
1867 ptrs2free = alloc_ptrs(child->argv);
1868#endif
1869 } else
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001870 debug_printf_exec(": pipe member with no argv\n");
Eric Andersen25f27032001-04-26 23:22:31 +00001871
1872 /* pipes are inserted between pairs of commands */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001873 pipefds[0] = 0;
1874 pipefds[1] = 1;
1875 if ((i + 1) < pi->num_progs)
1876 xpipe(pipefds);
Eric Andersen25f27032001-04-26 23:22:31 +00001877
Denis Vlasenko05743d72008-02-10 12:10:08 +00001878 child->pid = BB_MMU ? fork() : vfork();
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001879 if (!child->pid) { /* child */
Denis Vlasenko83177992008-02-11 08:44:36 +00001880 if (ENABLE_HUSH_JOB)
1881 die_sleep = 0; /* let nofork's xfuncs die */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001882#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001883 /* Every child adds itself to new process group
Denis Vlasenko05743d72008-02-10 12:10:08 +00001884 * with pgid == pid_of_first_child_in_pipe */
Denis Vlasenko170435c2007-05-23 13:01:10 +00001885 if (run_list_level == 1 && interactive_fd) {
Denis Vlasenko05743d72008-02-10 12:10:08 +00001886 pid_t pgrp;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001887 /* Don't do pgrp restore anymore on fatal signals */
1888 set_fatal_sighandler(SIG_DFL);
Denis Vlasenko05743d72008-02-10 12:10:08 +00001889 pgrp = pi->pgrp;
1890 if (pgrp < 0) /* true for 1st process only */
1891 pgrp = getpid();
1892 if (setpgid(0, pgrp) == 0 && pi->followup != PIPE_BG) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001893 /* We do it in *every* child, not just first,
1894 * to avoid races */
Denis Vlasenko05743d72008-02-10 12:10:08 +00001895 tcsetpgrp(interactive_fd, pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001896 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001897 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001898#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +00001899 xmove_fd(nextin, 0);
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001900 xmove_fd(pipefds[1], 1); /* write end */
1901 if (pipefds[0] > 1)
1902 close(pipefds[0]); /* read end */
Eric Andersen25f27032001-04-26 23:22:31 +00001903 /* Like bash, explicit redirects override pipes,
1904 * and the pipe fd is available for dup'ing. */
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001905 setup_redirects(child, NULL);
Eric Andersen52a97ca2001-06-22 06:49:26 +00001906
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001907 /* Restore default handlers just prior to exec */
1908 set_jobctrl_sighandler(SIG_DFL);
1909 set_misc_sighandler(SIG_DFL);
1910 signal(SIGCHLD, SIG_DFL);
Denis Vlasenko76d50412008-06-10 16:19:39 +00001911 pseudo_exec(ptrs2free, child); /* does not return */
Eric Andersen25f27032001-04-26 23:22:31 +00001912 }
Denis Vlasenko76d50412008-06-10 16:19:39 +00001913#if !BB_MMU
1914 free_strings(ptrs2free);
1915#endif
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001916 if (child->pid < 0) { /* [v]fork failed */
1917 /* Clearly indicate, was it fork or vfork */
Denis Vlasenko82604e92008-07-01 15:59:42 +00001918 bb_perror_msg(BB_MMU ? "fork" : "vfork");
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001919 } else {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001920 pi->alive_progs++;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001921#if ENABLE_HUSH_JOB
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001922 /* Second and next children need to know pid of first one */
1923 if (pi->pgrp < 0)
1924 pi->pgrp = child->pid;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001925#endif
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001926 }
Eric Andersen25f27032001-04-26 23:22:31 +00001927
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001928 if (i)
1929 close(nextin);
1930 if ((i + 1) < pi->num_progs)
1931 close(pipefds[1]); /* write end */
1932 /* Pass read (output) pipe end to next iteration */
Eric Andersen25f27032001-04-26 23:22:31 +00001933 nextin = pipefds[0];
1934 }
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001935
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001936 if (!pi->alive_progs) {
Denis Vlasenko05743d72008-02-10 12:10:08 +00001937 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
1938 return 1;
1939 }
1940
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001941 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_progs);
Eric Andersen25f27032001-04-26 23:22:31 +00001942 return -1;
1943}
1944
Denis Vlasenko4b924f32007-05-30 00:29:55 +00001945#ifndef debug_print_tree
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001946static void debug_print_tree(struct pipe *pi, int lvl)
1947{
1948 static const char *PIPE[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001949 [PIPE_SEQ] = "SEQ",
1950 [PIPE_AND] = "AND",
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001951 [PIPE_OR ] = "OR" ,
1952 [PIPE_BG ] = "BG" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001953 };
1954 static const char *RES[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001955 [RES_NONE ] = "NONE" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00001956#if ENABLE_HUSH_IF
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001957 [RES_IF ] = "IF" ,
1958 [RES_THEN ] = "THEN" ,
1959 [RES_ELIF ] = "ELIF" ,
1960 [RES_ELSE ] = "ELSE" ,
1961 [RES_FI ] = "FI" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00001962#endif
1963#if ENABLE_HUSH_LOOPS
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001964 [RES_FOR ] = "FOR" ,
1965 [RES_WHILE] = "WHILE",
1966 [RES_UNTIL] = "UNTIL",
1967 [RES_DO ] = "DO" ,
1968 [RES_DONE ] = "DONE" ,
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001969 [RES_IN ] = "IN" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00001970#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00001971#if ENABLE_HUSH_CASE
1972 [RES_CASE ] = "CASE" ,
1973 [RES_MATCH] = "MATCH",
1974 [RES_CASEI] = "CASEI",
1975 [RES_ESAC ] = "ESAC" ,
1976#endif
Denis Vlasenko06810332007-05-21 23:30:54 +00001977 [RES_XXXX ] = "XXXX" ,
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001978 [RES_SNTX ] = "SNTX" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001979 };
1980
1981 int pin, prn;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00001982
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001983 pin = 0;
1984 while (pi) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00001985 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
1986 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001987 prn = 0;
1988 while (prn < pi->num_progs) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00001989 struct child_prog *child = &pi->progs[prn];
1990 char **argv = child->argv;
1991
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001992 fprintf(stderr, "%*s prog %d", lvl*2, "", prn);
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00001993 if (child->group) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001994 fprintf(stderr, " group %s: (argv=%p)\n",
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00001995 (child->subshell ? "()" : "{}"),
1996 argv);
1997 debug_print_tree(child->group, lvl+1);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001998 prn++;
1999 continue;
2000 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002001 if (argv) while (*argv) {
2002 fprintf(stderr, " '%s'", *argv);
2003 argv++;
Denis Vlasenko4b924f32007-05-30 00:29:55 +00002004 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002005 fprintf(stderr, "\n");
2006 prn++;
2007 }
2008 pi = pi->next;
2009 pin++;
2010 }
2011}
2012#endif
2013
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002014/* NB: called by pseudo_exec, and therefore must not modify any
2015 * global data until exec/_exit (we can be a child after vfork!) */
Denis Vlasenko05743d72008-02-10 12:10:08 +00002016static int run_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00002017{
Denis Vlasenko06810332007-05-21 23:30:54 +00002018 struct pipe *rpipe;
2019#if ENABLE_HUSH_LOOPS
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002020 char *for_varname = NULL;
2021 char **for_lcur = NULL;
2022 char **for_list = NULL;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002023 int flag_rep = 0;
Denis Vlasenko06810332007-05-21 23:30:54 +00002024#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002025#if ENABLE_HUSH_CASE
2026 char *case_word = NULL;
2027#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002028 int flag_skip = 1;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002029 int rcode = 0; /* probably for gcc only */
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002030 int flag_restore = 0;
Denis Vlasenko06810332007-05-21 23:30:54 +00002031#if ENABLE_HUSH_IF
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002032 int if_code = 0, next_if_code = 0; /* need double-buffer to handle elif */
Denis Vlasenko06810332007-05-21 23:30:54 +00002033#else
2034 enum { if_code = 0, next_if_code = 0 };
2035#endif
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002036 reserved_style rword IF_HAS_NO_KEYWORDS(= RES_NONE);
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002037 reserved_style skip_more_for_this_rword = RES_XXXX;
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00002038
Denis Vlasenko05743d72008-02-10 12:10:08 +00002039 debug_printf_exec("run_list start lvl %d\n", run_list_level + 1);
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00002040
Denis Vlasenko06810332007-05-21 23:30:54 +00002041#if ENABLE_HUSH_LOOPS
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002042 /* check syntax for "for" */
2043 for (rpipe = pi; rpipe; rpipe = rpipe->next) {
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002044 if (rpipe->res_word != RES_FOR && rpipe->res_word != RES_IN)
2045 continue;
2046 /* current word is FOR or IN (BOLD in comments below) */
2047 if (rpipe->next == NULL) {
2048 syntax("malformed for");
Denis Vlasenko05743d72008-02-10 12:10:08 +00002049 debug_printf_exec("run_list lvl %d return 1\n", run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002050 return 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002051 }
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002052 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
2053 if (rpipe->next->res_word == RES_DO)
2054 continue;
2055 /* next word is not "do". It must be "in" then ("FOR v in ...") */
2056 if (rpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
2057 || rpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002058 ) {
Denis Vlasenkoff182a32008-07-05 20:29:59 +00002059 syntax("malformed for");
Denis Vlasenko05743d72008-02-10 12:10:08 +00002060 debug_printf_exec("run_list lvl %d return 1\n", run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002061 return 1;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002062 }
2063 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002064#else
2065 rpipe = NULL;
2066#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002067
2068#if ENABLE_HUSH_JOB
2069 /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
2070 * We are saving state before entering outermost list ("while...done")
2071 * so that ctrl-Z will correctly background _entire_ outermost list,
2072 * not just a part of it (like "sleep 1 | exit 2") */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00002073 if (++run_list_level == 1 && interactive_fd) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002074 if (sigsetjmp(toplevel_jb, 1)) {
2075 /* ctrl-Z forked and we are parent; or ctrl-C.
2076 * Sighandler has longjmped us here */
2077 signal(SIGINT, SIG_IGN);
2078 signal(SIGTSTP, SIG_IGN);
2079 /* Restore level (we can be coming from deep inside
2080 * nested levels) */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00002081 run_list_level = 1;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002082#if ENABLE_FEATURE_SH_STANDALONE
2083 if (nofork_save.saved) { /* if save area is valid */
2084 debug_printf_jobs("exiting nofork early\n");
2085 restore_nofork_data(&nofork_save);
2086 }
2087#endif
2088 if (ctrl_z_flag) {
2089 /* ctrl-Z has forked and stored pid of the child in pi->pid.
2090 * Remember this child as background job */
2091 insert_bg_job(pi);
2092 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002093 /* ctrl-C. We just stop doing whatever we were doing */
Denis Vlasenko4daad902007-09-27 10:20:47 +00002094 bb_putchar('\n');
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002095 }
2096 rcode = 0;
2097 goto ret;
2098 }
2099 /* ctrl-Z handler will store pid etc in pi */
2100 toplevel_list = pi;
2101 ctrl_z_flag = 0;
2102#if ENABLE_FEATURE_SH_STANDALONE
2103 nofork_save.saved = 0; /* in case we will run a nofork later */
2104#endif
Denis Vlasenko8e2cfec2008-03-12 23:19:35 +00002105 signal_SA_RESTART_empty_mask(SIGTSTP, handler_ctrl_z);
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002106 signal(SIGINT, handler_ctrl_c);
2107 }
Denis Vlasenko05743d72008-02-10 12:10:08 +00002108#endif /* JOB */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002109
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002110 for (; pi; pi = flag_restore ? rpipe : pi->next) {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002111 IF_HAS_KEYWORDS(rword = pi->res_word;)
2112 IF_HAS_NO_KEYWORDS(rword = RES_NONE;)
Denis Vlasenko06810332007-05-21 23:30:54 +00002113#if ENABLE_HUSH_LOOPS
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002114 if (rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002115 flag_restore = 0;
2116 if (!rpipe) {
2117 flag_rep = 0;
2118 rpipe = pi;
2119 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002120 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002121#endif
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002122 debug_printf_exec(": rword=%d if_code=%d next_if_code=%d skip_more=%d\n",
2123 rword, if_code, next_if_code, skip_more_for_this_rword);
2124 if (rword == skip_more_for_this_rword && flag_skip) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002125 if (pi->followup == PIPE_SEQ)
2126 flag_skip = 0;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002127 continue;
2128 }
2129 flag_skip = 1;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002130 skip_more_for_this_rword = RES_XXXX;
Denis Vlasenko06810332007-05-21 23:30:54 +00002131#if ENABLE_HUSH_IF
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002132 if (rword == RES_THEN || rword == RES_ELSE)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002133 if_code = next_if_code;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002134 if (rword == RES_THEN && if_code)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002135 continue;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002136 if (rword == RES_ELSE && !if_code)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002137 continue;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002138 if (rword == RES_ELIF && !if_code)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002139 break;
Denis Vlasenko06810332007-05-21 23:30:54 +00002140#endif
2141#if ENABLE_HUSH_LOOPS
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002142 if (rword == RES_FOR && pi->num_progs) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002143 if (!for_lcur) {
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002144 /* first loop through for */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00002145
2146 static const char encoded_dollar_at[] ALIGN1 = {
2147 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
2148 }; /* encoded representation of "$@" */
2149 static const char *const encoded_dollar_at_argv[] = {
2150 encoded_dollar_at, NULL
2151 }; /* argv list with one element: "$@" */
2152 char **vals;
2153
2154 vals = (char**)encoded_dollar_at_argv;
2155 if (rpipe->next->res_word == RES_IN) {
2156 /* if no variable values after "in" we skip "for" */
2157 if (!pi->next->progs->argv)
2158 continue;
2159 vals = pi->next->progs->argv;
2160 } /* else: "for var; do..." -> assume "$@" list */
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002161 /* create list of variable values */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00002162 debug_print_strings("for_list made from", vals);
2163 for_list = expand_strvec_to_strvec(vals);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002164 for_lcur = for_list;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002165 debug_print_strings("for_list", for_list);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002166 for_varname = pi->progs->argv[0];
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002167 pi->progs->argv[0] = NULL;
2168 flag_rep = 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002169 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002170 free(pi->progs->argv[0]);
2171 if (!*for_lcur) {
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002172 /* for loop is over, clean up */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002173 free(for_list);
2174 for_lcur = NULL;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002175 flag_rep = 0;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002176 pi->progs->argv[0] = for_varname;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002177 continue;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002178 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002179 /* insert next value from for_lcur */
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002180 /* vda: does it need escaping? */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002181 pi->progs->argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002182 }
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002183 if (rword == RES_IN)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002184 continue;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002185 if (rword == RES_DO) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002186 if (!flag_rep)
2187 continue;
Tim Rikerc1ef7bd2006-01-25 00:08:53 +00002188 }
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002189 if (rword == RES_DONE) {
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002190 if (flag_rep) {
2191 flag_restore = 1;
2192 } else {
2193 rpipe = NULL;
2194 }
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002195 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002196#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002197#if ENABLE_HUSH_CASE
2198 if (rword == RES_CASE) {
2199 case_word = pi->progs->argv[0];
2200 continue;
2201 }
2202 if (rword == RES_MATCH) {
2203 if (case_word) {
2204 next_if_code = strcmp(case_word, pi->progs->argv[0]);
2205 if (next_if_code == 0)
2206 case_word = NULL;
2207 continue;
2208 }
2209 break;
2210 }
2211 if (rword == RES_CASEI) {
2212 if (next_if_code != 0)
2213 continue;
2214 }
2215#endif
2216
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002217 if (pi->num_progs == 0)
2218 continue;
Denis Vlasenko05743d72008-02-10 12:10:08 +00002219 debug_printf_exec(": run_pipe with %d members\n", pi->num_progs);
2220 rcode = run_pipe(pi);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002221 if (rcode != -1) {
Eric Andersen25f27032001-04-26 23:22:31 +00002222 /* We only ran a builtin: rcode was set by the return value
Denis Vlasenko05743d72008-02-10 12:10:08 +00002223 * of run_pipe(), and we don't need to wait for anything. */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002224 } else if (pi->followup == PIPE_BG) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002225 /* What does bash do with attempts to background builtins? */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002226 /* Even bash 3.2 doesn't do that well with nested bg:
2227 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
Denis Vlasenko170435c2007-05-23 13:01:10 +00002228 * I'm NOT treating inner &'s as jobs */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002229#if ENABLE_HUSH_JOB
Denis Vlasenko4b924f32007-05-30 00:29:55 +00002230 if (run_list_level == 1)
Denis Vlasenko170435c2007-05-23 13:01:10 +00002231 insert_bg_job(pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002232#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002233 rcode = EXIT_SUCCESS;
2234 } else {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002235#if ENABLE_HUSH_JOB
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00002236 if (run_list_level == 1 && interactive_fd) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00002237 /* waits for completion, then fg's main shell */
Denis Vlasenko52881e92007-04-21 13:42:52 +00002238 rcode = checkjobs_and_fg_shell(pi);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002239 } else
2240#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002241 { /* this one just waits for completion */
Eric Andersenc798b072001-06-22 06:23:03 +00002242 rcode = checkjobs(pi);
Eric Andersen25f27032001-04-26 23:22:31 +00002243 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002244 debug_printf_exec(": checkjobs returned %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00002245 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002246 debug_printf_exec(": setting last_return_code=%d\n", rcode);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002247 last_return_code = rcode;
Denis Vlasenko06810332007-05-21 23:30:54 +00002248#if ENABLE_HUSH_IF
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002249 if (rword == RES_IF || rword == RES_ELIF)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002250 next_if_code = rcode; /* can be overwritten a number of times */
Denis Vlasenko06810332007-05-21 23:30:54 +00002251#endif
2252#if ENABLE_HUSH_LOOPS
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002253 if (rword == RES_WHILE)
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002254 flag_rep = !last_return_code;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002255 if (rword == RES_UNTIL)
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002256 flag_rep = last_return_code;
Denis Vlasenko06810332007-05-21 23:30:54 +00002257#endif
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002258 if ((rcode == EXIT_SUCCESS && pi->followup == PIPE_OR)
2259 || (rcode != EXIT_SUCCESS && pi->followup == PIPE_AND)
2260 ) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002261 skip_more_for_this_rword = rword;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002262 }
Eric Andersen028b65b2001-06-28 01:10:11 +00002263 checkjobs(NULL);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002264 } /* for (pi) */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002265
2266#if ENABLE_HUSH_JOB
2267 if (ctrl_z_flag) {
2268 /* ctrl-Z forked somewhere in the past, we are the child,
2269 * and now we completed running the list. Exit. */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002270//TODO: _exit?
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002271 exit(rcode);
2272 }
2273 ret:
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00002274 if (!--run_list_level && interactive_fd) {
2275 signal(SIGTSTP, SIG_IGN);
2276 signal(SIGINT, SIG_IGN);
2277 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002278#endif
Denis Vlasenko05743d72008-02-10 12:10:08 +00002279 debug_printf_exec("run_list lvl %d return %d\n", run_list_level + 1, rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00002280 return rcode;
2281}
2282
Eric Andersen25f27032001-04-26 23:22:31 +00002283/* return code is the exit status of the pipe */
Eric Andersenbf7df042001-05-23 22:18:35 +00002284static int free_pipe(struct pipe *pi, int indent)
Eric Andersen25f27032001-04-26 23:22:31 +00002285{
2286 char **p;
2287 struct child_prog *child;
2288 struct redir_struct *r, *rnext;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002289 int a, i, ret_code = 0;
Eric Andersen52a97ca2001-06-22 06:49:26 +00002290
2291 if (pi->stopped_progs > 0)
2292 return ret_code;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002293 debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002294 for (i = 0; i < pi->num_progs; i++) {
Eric Andersen25f27032001-04-26 23:22:31 +00002295 child = &pi->progs[i];
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002296 debug_printf_clean("%s command %d:\n", indenter(indent), i);
Eric Andersen25f27032001-04-26 23:22:31 +00002297 if (child->argv) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002298 for (a = 0, p = child->argv; *p; a++, p++) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002299 debug_printf_clean("%s argv[%d] = %s\n", indenter(indent), a, *p);
Eric Andersen25f27032001-04-26 23:22:31 +00002300 }
Denis Vlasenkof962a032007-11-23 12:50:54 +00002301 free_strings(child->argv);
2302 child->argv = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002303 } else if (child->group) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002304 debug_printf_clean("%s begin group (subshell:%d)\n", indenter(indent), child->subshell);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002305 ret_code = free_pipe_list(child->group, indent+3);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002306 debug_printf_clean("%s end group\n", indenter(indent));
Eric Andersen25f27032001-04-26 23:22:31 +00002307 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002308 debug_printf_clean("%s (nil)\n", indenter(indent));
Eric Andersen25f27032001-04-26 23:22:31 +00002309 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002310 for (r = child->redirects; r; r = rnext) {
Denis Vlasenko211b59b2008-06-23 16:28:53 +00002311 debug_printf_clean("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->rd_type].descrip);
Eric Andersen25f27032001-04-26 23:22:31 +00002312 if (r->dup == -1) {
Eric Andersen817e73c2001-06-06 17:56:09 +00002313 /* guard against the case >$FOO, where foo is unset or blank */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002314 if (r->rd_filename) {
2315 debug_printf_clean(" %s\n", r->rd_filename);
2316 free(r->rd_filename);
2317 r->rd_filename = NULL;
Eric Andersen817e73c2001-06-06 17:56:09 +00002318 }
Eric Andersen25f27032001-04-26 23:22:31 +00002319 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002320 debug_printf_clean("&%d\n", r->dup);
Eric Andersen25f27032001-04-26 23:22:31 +00002321 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002322 rnext = r->next;
Eric Andersen25f27032001-04-26 23:22:31 +00002323 free(r);
2324 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002325 child->redirects = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002326 }
2327 free(pi->progs); /* children are an array, they get freed all at once */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002328 pi->progs = NULL;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002329#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002330 free(pi->cmdtext);
2331 pi->cmdtext = NULL;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002332#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002333 return ret_code;
2334}
2335
Eric Andersenbf7df042001-05-23 22:18:35 +00002336static int free_pipe_list(struct pipe *head, int indent)
Eric Andersen25f27032001-04-26 23:22:31 +00002337{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002338 int rcode = 0; /* if list has no members */
Eric Andersen25f27032001-04-26 23:22:31 +00002339 struct pipe *pi, *next;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002340
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002341 for (pi = head; pi; pi = next) {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002342#if HAS_KEYWORDS
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002343 debug_printf_clean("%s pipe reserved mode %d\n", indenter(indent), pi->res_word);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002344#endif
Eric Andersenbf7df042001-05-23 22:18:35 +00002345 rcode = free_pipe(pi, indent);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002346 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002347 next = pi->next;
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002348 /*pi->next = NULL;*/
Eric Andersen25f27032001-04-26 23:22:31 +00002349 free(pi);
2350 }
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002351 return rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00002352}
2353
2354/* Select which version we will use */
Denis Vlasenko05743d72008-02-10 12:10:08 +00002355static int run_and_free_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00002356{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002357 int rcode = 0;
Denis Vlasenko05743d72008-02-10 12:10:08 +00002358 debug_printf_exec("run_and_free_list entered\n");
2359 if (!fake_mode) {
2360 debug_printf_exec(": run_list with %d members\n", pi->num_progs);
2361 rcode = run_list(pi);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002362 }
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002363 /* free_pipe_list has the side effect of clearing memory.
Denis Vlasenko05743d72008-02-10 12:10:08 +00002364 * In the long run that function can be merged with run_list,
Eric Andersen25f27032001-04-26 23:22:31 +00002365 * but doing that now would hobble the debugging effort. */
Denis Vlasenko05743d72008-02-10 12:10:08 +00002366 free_pipe_list(pi, /* indent: */ 0);
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002367 debug_printf_exec("run_and_free_list return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00002368 return rcode;
2369}
2370
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002371
Denis Vlasenko170435c2007-05-23 13:01:10 +00002372/* expand_strvec_to_strvec() takes a list of strings, expands
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002373 * all variable references within and returns a pointer to
2374 * a list of expanded strings, possibly with larger number
2375 * of strings. (Think VAR="a b"; echo $VAR).
2376 * This new list is allocated as a single malloc block.
2377 * NULL-terminated list of char* pointers is at the beginning of it,
2378 * followed by strings themself.
2379 * Caller can deallocate entire list by single free(list). */
2380
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002381/* Store given string, finalizing the word and starting new one whenever
2382 * we encounter ifs char(s). This is used for expanding variable values.
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002383 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002384static int expand_on_ifs(o_string *output, int n, const char *str)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002385{
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002386 while (1) {
2387 int word_len = strcspn(str, ifs);
2388 if (word_len) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00002389 if (output->o_quote || !output->o_glob)
2390 o_addQstr(output, str, word_len);
2391 else /* protect backslashes against globbing up :) */
2392 o_addstr_duplicate_backslash(output, str, word_len);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002393 str += word_len;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002394 }
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002395 if (!*str) /* EOL - do not finalize word */
2396 break;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002397 o_addchr(output, '\0');
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002398 debug_print_list("expand_on_ifs", output, n);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002399 n = o_save_ptr(output, n);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002400 str += strspn(str, ifs); /* skip ifs chars */
2401 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002402 debug_print_list("expand_on_ifs[1]", output, n);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002403 return n;
2404}
2405
2406/* Expand all variable references in given string, adding words to list[]
2407 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2408 * to be filled). This routine is extremely tricky: has to deal with
2409 * variables/parameters with whitespace, $* and $@, and constructs like
2410 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002411/* NB: another bug is that we cannot detect empty strings yet:
2412 * "" or $empty"" expands to zero words, has to expand to empty word */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002413static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002414{
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002415 /* or_mask is either 0 (normal case) or 0x80
Denis Vlasenko55789c62008-06-18 16:30:42 +00002416 * (expansion of right-hand side of assignment == 1-element expand.
2417 * It will also do no globbing, and thus we must not backslash-quote!) */
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002418
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002419 char first_ch, ored_ch;
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002420 int i;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002421 const char *val;
2422 char *p;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002423
2424 ored_ch = 0;
2425
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002426 debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002427 debug_print_list("expand_vars_to_list", output, n);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002428 n = o_save_ptr(output, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002429 debug_print_list("expand_vars_to_list[0]", output, n);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002430
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002431 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
Denis Vlasenkoccce59d2008-06-16 14:35:57 +00002432#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002433 o_string subst_result = NULL_O_STRING;
Denis Vlasenkoccce59d2008-06-16 14:35:57 +00002434#endif
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002435
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002436 o_addstr(output, arg, p - arg);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002437 debug_print_list("expand_vars_to_list[1]", output, n);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002438 arg = ++p;
2439 p = strchr(p, SPECIAL_VAR_SYMBOL);
2440
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002441 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00002442 /* "$@" is special. Even if quoted, it can still
2443 * expand to nothing (not even an empty string) */
2444 if ((first_ch & 0x7f) != '@')
2445 ored_ch |= first_ch;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002446 val = NULL;
2447 switch (first_ch & 0x7f) {
2448 /* Highest bit in first_ch indicates that var is double-quoted */
2449 case '$': /* pid */
Denis Vlasenko16c2fea2008-06-17 12:28:44 +00002450 val = utoa(root_pid);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002451 break;
2452 case '!': /* bg pid */
2453 val = last_bg_pid ? utoa(last_bg_pid) : (char*)"";
2454 break;
2455 case '?': /* exitcode */
2456 val = utoa(last_return_code);
2457 break;
2458 case '#': /* argc */
2459 val = utoa(global_argc ? global_argc-1 : 0);
2460 break;
2461 case '*':
2462 case '@':
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002463 i = 1;
Denis Vlasenkoc3c66592007-11-24 00:22:42 +00002464 if (!global_argv[i])
2465 break;
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00002466 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002467 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denis Vlasenko324a3fd2008-06-18 17:49:58 +00002468 smallint sv = output->o_quote;
2469 /* unquoted var's contents should be globbed, so don't quote */
2470 output->o_quote = 0;
Denis Vlasenkoc3c66592007-11-24 00:22:42 +00002471 while (global_argv[i]) {
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002472 n = expand_on_ifs(output, n, global_argv[i]);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002473 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, global_argc-1);
Denis Vlasenkoc3c66592007-11-24 00:22:42 +00002474 if (global_argv[i++][0] && global_argv[i]) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002475 /* this argv[] is not empty and not last:
2476 * put terminating NUL, start new word */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002477 o_addchr(output, '\0');
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002478 debug_print_list("expand_vars_to_list[2]", output, n);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002479 n = o_save_ptr(output, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002480 debug_print_list("expand_vars_to_list[3]", output, n);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002481 }
2482 }
Denis Vlasenko324a3fd2008-06-18 17:49:58 +00002483 output->o_quote = sv;
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002484 } else
2485 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00002486 * and in this case should treat it like '$*' - see 'else...' below */
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002487 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002488 while (1) {
Denis Vlasenko324a3fd2008-06-18 17:49:58 +00002489 o_addQstr(output, global_argv[i], strlen(global_argv[i]));
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002490 if (++i >= global_argc)
2491 break;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002492 o_addchr(output, '\0');
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002493 debug_print_list("expand_vars_to_list[4]", output, n);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002494 n = o_save_ptr(output, n);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002495 }
2496 } else { /* quoted $*: add as one word */
Denis Vlasenkoc3c66592007-11-24 00:22:42 +00002497 while (1) {
Denis Vlasenko324a3fd2008-06-18 17:49:58 +00002498 o_addQstr(output, global_argv[i], strlen(global_argv[i]));
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00002499 if (!global_argv[++i])
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002500 break;
2501 if (ifs[0])
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002502 o_addchr(output, ifs[0]);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002503 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002504 }
2505 break;
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00002506 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
2507 /* "Empty variable", used to make "" etc to not disappear */
2508 arg++;
2509 ored_ch = 0x80;
2510 break;
Denis Vlasenkoccce59d2008-06-16 14:35:57 +00002511#if ENABLE_HUSH_TICK
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00002512 case '`': { /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002513 struct in_str input;
2514 *p = '\0';
2515 arg++;
Denis Vlasenkoccce59d2008-06-16 14:35:57 +00002516//TODO: can we just stuff it into "output" directly?
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002517 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002518 setup_string_in_str(&input, arg);
2519 process_command_subs(&subst_result, &input, NULL);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002520 debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002521 val = subst_result.data;
2522 goto store_val;
2523 }
Denis Vlasenkoccce59d2008-06-16 14:35:57 +00002524#endif
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00002525 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002526 *p = '\0';
2527 arg[0] = first_ch & 0x7f;
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002528 if (isdigit(arg[0])) {
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002529 i = xatoi_u(arg);
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002530 if (i < global_argc)
2531 val = global_argv[i];
Denis Vlasenko55789c62008-06-18 16:30:42 +00002532 /* else val remains NULL: $N with too big N */
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002533 } else
2534 val = lookup_param(arg);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002535 arg[0] = first_ch;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002536#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002537 store_val:
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002538#endif
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002539 *p = SPECIAL_VAR_SYMBOL;
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002540 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002541 debug_printf_expand("unquoted '%s', output->o_quote:%d\n", val, output->o_quote);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002542 if (val) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00002543 /* unquoted var's contents should be globbed, so don't quote */
2544 smallint sv = output->o_quote;
2545 output->o_quote = 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002546 n = expand_on_ifs(output, n, val);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002547 val = NULL;
Denis Vlasenko55789c62008-06-18 16:30:42 +00002548 output->o_quote = sv;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002549 }
Denis Vlasenko55789c62008-06-18 16:30:42 +00002550 } else { /* quoted $VAR, val will be appended below */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002551 debug_printf_expand("quoted '%s', output->o_quote:%d\n", val, output->o_quote);
Denis Vlasenko55789c62008-06-18 16:30:42 +00002552 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002553 }
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002554 if (val) {
Denis Vlasenko324a3fd2008-06-18 17:49:58 +00002555 o_addQstr(output, val, strlen(val));
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002556 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002557
Denis Vlasenkoccce59d2008-06-16 14:35:57 +00002558#if ENABLE_HUSH_TICK
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002559 o_free(&subst_result);
Denis Vlasenkoccce59d2008-06-16 14:35:57 +00002560#endif
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002561 arg = ++p;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002562 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
2563
Denis Vlasenko2e76c3f2008-06-10 18:27:50 +00002564 if (arg[0]) {
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002565 debug_print_list("expand_vars_to_list[a]", output, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002566 /* this part is literal, and it was already pre-quoted
2567 * if needed (much earlier), do not use o_addQstr here! */
2568 o_addstr(output, arg, strlen(arg) + 1);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002569 debug_print_list("expand_vars_to_list[b]", output, n);
Denis Vlasenko2e76c3f2008-06-10 18:27:50 +00002570 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
2571 && !(ored_ch & 0x80) /* and all vars were not quoted. */
2572 ) {
2573 n--;
2574 /* allow to reuse list[n] later without re-growth */
2575 output->has_empty_slot = 1;
2576 } else {
2577 o_addchr(output, '\0');
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002578 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002579 return n;
2580}
2581
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002582static char **expand_variables(char **argv, int or_mask)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002583{
2584 int n;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002585 char **list;
2586 char **v;
2587 o_string output = NULL_O_STRING;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002588
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002589 if (or_mask & 0x100) {
Denis Vlasenko324a3fd2008-06-18 17:49:58 +00002590 output.o_quote = 1; /* protect against globbing for "$var" */
2591 /* (unquoted $var will temporarily switch it off) */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002592 output.o_glob = 1;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002593 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002594
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002595 n = 0;
2596 v = argv;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002597 while (*v) {
2598 n = expand_vars_to_list(&output, n, *v, (char)or_mask);
2599 v++;
2600 }
2601 debug_print_list("expand_variables", &output, n);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002602
Denis Vlasenko82dfec32008-06-16 12:47:11 +00002603 /* output.data (malloced in one block) gets returned in "list" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002604 list = o_finalize_list(&output, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002605 debug_print_strings("expand_variables[1]", list);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002606 return list;
2607}
2608
Denis Vlasenko170435c2007-05-23 13:01:10 +00002609static char **expand_strvec_to_strvec(char **argv)
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002610{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002611 return expand_variables(argv, 0x100);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002612}
2613
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002614/* Used for expansion of right hand of assignments */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00002615/* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
2616 * "v=/bin/c*" */
Denis Vlasenko170435c2007-05-23 13:01:10 +00002617static char *expand_string_to_string(const char *str)
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002618{
2619 char *argv[2], **list;
2620
2621 argv[0] = (char*)str;
2622 argv[1] = NULL;
2623 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002624 if (HUSH_DEBUG)
Denis Vlasenko170435c2007-05-23 13:01:10 +00002625 if (!list[0] || list[1])
2626 bb_error_msg_and_die("BUG in varexp2");
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002627 /* actually, just move string 2*sizeof(char*) bytes back */
2628 strcpy((char*)list, list[0]);
Denis Vlasenko170435c2007-05-23 13:01:10 +00002629 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2630 return (char*)list;
2631}
2632
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002633/* Used for "eval" builtin */
Denis Vlasenko170435c2007-05-23 13:01:10 +00002634static char* expand_strvec_to_string(char **argv)
2635{
2636 char **list;
2637
2638 list = expand_variables(argv, 0x80);
2639 /* Convert all NULs to spaces */
2640 if (list[0]) {
2641 int n = 1;
2642 while (list[n]) {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002643 if (HUSH_DEBUG)
Denis Vlasenko170435c2007-05-23 13:01:10 +00002644 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2645 bb_error_msg_and_die("BUG in varexp3");
2646 list[n][-1] = ' '; /* TODO: or to ifs[0]? */
2647 n++;
2648 }
2649 }
2650 strcpy((char*)list, list[0]);
2651 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002652 return (char*)list;
2653}
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002654
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002655
2656/* Used to get/check local shell variables */
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002657static struct variable *get_local_var(const char *name)
Eric Andersenf72f5622001-05-15 23:21:41 +00002658{
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002659 struct variable *cur;
2660 int len;
Eric Andersenf72f5622001-05-15 23:21:41 +00002661
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002662 if (!name)
Eric Andersenf72f5622001-05-15 23:21:41 +00002663 return NULL;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002664 len = strlen(name);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002665 for (cur = top_var; cur; cur = cur->next) {
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002666 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002667 return cur;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00002668 }
Eric Andersenf72f5622001-05-15 23:21:41 +00002669 return NULL;
2670}
2671
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002672/* str holds "NAME=VAL" and is expected to be malloced.
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002673 * We take ownership of it. */
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002674static int set_local_var(char *str, int flg_export)
Eric Andersen78a7c992001-05-15 16:30:25 +00002675{
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002676 struct variable *cur;
2677 char *value;
2678 int name_len;
Eric Andersen20a69a72001-05-15 17:24:44 +00002679
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002680 value = strchr(str, '=');
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002681 if (!value) { /* not expected to ever happen? */
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002682 free(str);
Eric Andersen99785762001-05-22 21:37:48 +00002683 return -1;
2684 }
Eric Andersen20a69a72001-05-15 17:24:44 +00002685
Denis Vlasenko201c72a2007-05-25 10:00:36 +00002686 name_len = value - str + 1; /* including '=' */
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002687 cur = top_var; /* cannot be NULL (we have HUSH_VERSION and it's RO) */
2688 while (1) {
Denis Vlasenko201c72a2007-05-25 10:00:36 +00002689 if (strncmp(cur->varstr, str, name_len) != 0) {
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002690 if (!cur->next) {
Denis Vlasenko201c72a2007-05-25 10:00:36 +00002691 /* Bail out. Note that now cur points
2692 * to last var in linked list */
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002693 break;
Eric Andersen20a69a72001-05-15 17:24:44 +00002694 }
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002695 cur = cur->next;
2696 continue;
Eric Andersen20a69a72001-05-15 17:24:44 +00002697 }
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002698 /* We found an existing var with this name */
2699 *value = '\0';
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002700 if (cur->flg_read_only) {
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002701 bb_error_msg("%s: readonly variable", str);
2702 free(str);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002703 return -1;
2704 }
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002705 unsetenv(str); /* just in case */
2706 *value = '=';
2707 if (strcmp(cur->varstr, str) == 0) {
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002708 free_and_exp:
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002709 free(str);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002710 goto exp;
2711 }
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002712 if (cur->max_len >= strlen(str)) {
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002713 /* This one is from startup env, reuse space */
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002714 strcpy(cur->varstr, str);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002715 goto free_and_exp;
2716 }
2717 /* max_len == 0 signifies "malloced" var, which we can
2718 * (and has to) free */
2719 if (!cur->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002720 free(cur->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002721 cur->max_len = 0;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002722 goto set_str_and_exp;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002723 }
Eric Andersen20a69a72001-05-15 17:24:44 +00002724
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002725 /* Not found - create next variable struct */
2726 cur->next = xzalloc(sizeof(*cur));
2727 cur = cur->next;
2728
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002729 set_str_and_exp:
2730 cur->varstr = str;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002731 exp:
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002732 if (flg_export)
2733 cur->flg_export = 1;
2734 if (cur->flg_export)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002735 return putenv(cur->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002736 return 0;
Eric Andersen20a69a72001-05-15 17:24:44 +00002737}
2738
Eric Andersenf72f5622001-05-15 23:21:41 +00002739static void unset_local_var(const char *name)
Eric Andersen20a69a72001-05-15 17:24:44 +00002740{
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002741 struct variable *cur;
2742 struct variable *prev = prev; /* for gcc */
2743 int name_len;
Eric Andersen20a69a72001-05-15 17:24:44 +00002744
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002745 if (!name)
2746 return;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002747 name_len = strlen(name);
2748 cur = top_var;
2749 while (cur) {
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002750 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002751 if (cur->flg_read_only) {
Manuel Novoa III cad53642003-03-19 09:13:01 +00002752 bb_error_msg("%s: readonly variable", name);
Eric Andersen94ac2442001-05-22 19:05:18 +00002753 return;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002754 }
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002755 /* prev is ok to use here because 1st variable, HUSH_VERSION,
2756 * is ro, and we cannot reach this code on the 1st pass */
2757 prev->next = cur->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002758 unsetenv(cur->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002759 if (!cur->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002760 free(cur->varstr);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002761 free(cur);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002762 return;
Eric Andersenf72f5622001-05-15 23:21:41 +00002763 }
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002764 prev = cur;
2765 cur = cur->next;
Eric Andersen20a69a72001-05-15 17:24:44 +00002766 }
Eric Andersen78a7c992001-05-15 16:30:25 +00002767}
2768
Denis Vlasenkoff182a32008-07-05 20:29:59 +00002769/* The src parameter allows us to peek forward to a possible &n syntax
Eric Andersen25f27032001-04-26 23:22:31 +00002770 * for file descriptor duplication, e.g., "2>&1".
2771 * Return code is 0 normally, 1 if a syntax error is detected in src.
2772 * Resource errors (in xmalloc) cause the process to exit */
2773static int setup_redirect(struct p_context *ctx, int fd, redir_type style,
2774 struct in_str *input)
2775{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002776 struct child_prog *child = ctx->child;
Eric Andersen25f27032001-04-26 23:22:31 +00002777 struct redir_struct *redir = child->redirects;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002778 struct redir_struct *last_redir = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002779
2780 /* Create a new redir_struct and drop it onto the end of the linked list */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002781 while (redir) {
2782 last_redir = redir;
2783 redir = redir->next;
Eric Andersen25f27032001-04-26 23:22:31 +00002784 }
Denis Vlasenkoff097622007-10-01 10:00:45 +00002785 redir = xzalloc(sizeof(struct redir_struct));
2786 /* redir->next = NULL; */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002787 /* redir->rd_filename = NULL; */
Eric Andersen25f27032001-04-26 23:22:31 +00002788 if (last_redir) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002789 last_redir->next = redir;
Eric Andersen25f27032001-04-26 23:22:31 +00002790 } else {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002791 child->redirects = redir;
Eric Andersen25f27032001-04-26 23:22:31 +00002792 }
2793
Denis Vlasenko55789c62008-06-18 16:30:42 +00002794 redir->rd_type = style;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002795 redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
Eric Andersen25f27032001-04-26 23:22:31 +00002796
2797 debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
2798
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002799 /* Check for a '2>&1' type redirect */
Eric Andersen25f27032001-04-26 23:22:31 +00002800 redir->dup = redirect_dup_num(input);
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002801 if (redir->dup == -2)
2802 return 1; /* syntax error */
Eric Andersen25f27032001-04-26 23:22:31 +00002803 if (redir->dup != -1) {
2804 /* Erik had a check here that the file descriptor in question
Eric Andersen83a2ae22001-05-07 17:59:25 +00002805 * is legit; I postpone that to "run time"
2806 * A "-" representation of "close me" shows up as a -3 here */
Eric Andersen25f27032001-04-26 23:22:31 +00002807 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
2808 } else {
2809 /* We do _not_ try to open the file that src points to,
2810 * since we need to return and let src be expanded first.
2811 * Set ctx->pending_redirect, so we know what to do at the
Denis Vlasenko201c72a2007-05-25 10:00:36 +00002812 * end of the next parsed word. */
Eric Andersen25f27032001-04-26 23:22:31 +00002813 ctx->pending_redirect = redir;
2814 }
2815 return 0;
2816}
2817
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00002818static struct pipe *new_pipe(void)
2819{
Eric Andersen25f27032001-04-26 23:22:31 +00002820 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002821 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002822 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002823 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00002824 return pi;
2825}
2826
2827static void initialize_context(struct p_context *ctx)
2828{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002829 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00002830 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002831 /* Create the memory for child, roughly:
2832 * ctx->pipe->progs = new struct child_prog;
2833 * ctx->pipe->progs[0].family = ctx->pipe;
2834 * ctx->child = &ctx->pipe->progs[0];
2835 */
2836 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00002837}
2838
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002839/* If a reserved word is found and processed, parse context is modified
2840 * and 1 is returned.
2841 * Handles if, then, elif, else, fi, for, while, until, do, done.
Eric Andersen25f27032001-04-26 23:22:31 +00002842 * case, function, and select are obnoxious, save those for later.
2843 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002844#if HAS_KEYWORDS
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002845static int reserved_word(const o_string *word, struct p_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00002846{
2847 struct reserved_combo {
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002848 char literal[7];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002849 unsigned char res;
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002850 int flag;
Eric Andersen25f27032001-04-26 23:22:31 +00002851 };
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002852 enum {
2853 FLAG_END = (1 << RES_NONE ),
2854#if ENABLE_HUSH_IF
2855 FLAG_IF = (1 << RES_IF ),
2856 FLAG_THEN = (1 << RES_THEN ),
2857 FLAG_ELIF = (1 << RES_ELIF ),
2858 FLAG_ELSE = (1 << RES_ELSE ),
2859 FLAG_FI = (1 << RES_FI ),
2860#endif
2861#if ENABLE_HUSH_LOOPS
2862 FLAG_FOR = (1 << RES_FOR ),
2863 FLAG_WHILE = (1 << RES_WHILE),
2864 FLAG_UNTIL = (1 << RES_UNTIL),
2865 FLAG_DO = (1 << RES_DO ),
2866 FLAG_DONE = (1 << RES_DONE ),
2867 FLAG_IN = (1 << RES_IN ),
2868#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002869#if ENABLE_HUSH_CASE
2870 FLAG_MATCH = (1 << RES_MATCH),
2871 FLAG_ESAC = (1 << RES_ESAC ),
2872#endif
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002873 FLAG_START = (1 << RES_XXXX ),
2874 };
Eric Andersen25f27032001-04-26 23:22:31 +00002875 /* Mostly a list of accepted follow-up reserved words.
2876 * FLAG_END means we are done with the sequence, and are ready
2877 * to turn the compound list into a command.
2878 * FLAG_START means the word must start a new compound list.
2879 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002880 static const struct reserved_combo reserved_list[] = {
Denis Vlasenko06810332007-05-21 23:30:54 +00002881#if ENABLE_HUSH_IF
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002882 { "!", RES_NONE, 0 },
Eric Andersen25f27032001-04-26 23:22:31 +00002883 { "if", RES_IF, FLAG_THEN | FLAG_START },
2884 { "then", RES_THEN, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2885 { "elif", RES_ELIF, FLAG_THEN },
2886 { "else", RES_ELSE, FLAG_FI },
2887 { "fi", RES_FI, FLAG_END },
Denis Vlasenko06810332007-05-21 23:30:54 +00002888#endif
2889#if ENABLE_HUSH_LOOPS
Denis Vlasenkoff182a32008-07-05 20:29:59 +00002890 { "for", RES_FOR, FLAG_IN | FLAG_DO | FLAG_START },
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002891 { "while", RES_WHILE, FLAG_DO | FLAG_START },
2892 { "until", RES_UNTIL, FLAG_DO | FLAG_START },
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002893 { "in", RES_IN, FLAG_DO },
Eric Andersen25f27032001-04-26 23:22:31 +00002894 { "do", RES_DO, FLAG_DONE },
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002895 { "done", RES_DONE, FLAG_END },
2896#endif
2897#if ENABLE_HUSH_CASE
2898 { "case", RES_CASE, FLAG_MATCH | FLAG_START },
2899 { "esac", RES_ESAC, FLAG_END },
Denis Vlasenko06810332007-05-21 23:30:54 +00002900#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002901 };
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002902#if ENABLE_HUSH_CASE
2903 static const struct reserved_combo reserved_match = {
2904 "" /* "match" */, RES_MATCH, FLAG_MATCH | FLAG_ESAC
2905 };
2906#endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002907 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002908
Denis Vlasenko80b8b392007-06-25 10:55:35 +00002909 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002910 if (strcmp(word->data, r->literal) != 0)
Denis Vlasenko1a735862007-05-23 00:32:25 +00002911 continue;
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002912 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002913#if ENABLE_HUSH_CASE
2914 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE)
2915 /* "case word IN ..." - IN part starts first match part */
2916 r = &reserved_match;
2917 else
2918#endif
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002919 if (r->flag == 0) { /* '!' */
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00002920 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002921 syntax(NULL);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002922 IF_HAS_KEYWORDS(ctx->ctx_res_w = RES_SNTX;)
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002923 }
2924 ctx->ctx_inverted = 1;
2925 return 1;
2926 }
Denis Vlasenko1a735862007-05-23 00:32:25 +00002927 if (r->flag & FLAG_START) {
2928 struct p_context *new;
2929 debug_printf("push stack\n");
Denis Vlasenko1a735862007-05-23 00:32:25 +00002930 new = xmalloc(sizeof(*new));
2931 *new = *ctx; /* physical copy */
2932 initialize_context(ctx);
2933 ctx->stack = new;
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00002934 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00002935 syntax(NULL);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002936 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00002937 return 1;
2938 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002939 ctx->ctx_res_w = r->res;
Denis Vlasenko1a735862007-05-23 00:32:25 +00002940 ctx->old_flag = r->flag;
2941 if (ctx->old_flag & FLAG_END) {
2942 struct p_context *old;
2943 debug_printf("pop stack\n");
2944 done_pipe(ctx, PIPE_SEQ);
2945 old = ctx->stack;
2946 old->child->group = ctx->list_head;
2947 old->child->subshell = 0;
2948 *ctx = *old; /* physical copy */
2949 free(old);
2950 }
Denis Vlasenko1a735862007-05-23 00:32:25 +00002951 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002952 }
2953 return 0;
2954}
Denis Vlasenko06810332007-05-21 23:30:54 +00002955#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002956
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002957/* Word is complete, look at it and update parsing context.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002958 * Normal return is 0. Syntax errors return 1. */
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002959static int done_word(o_string *word, struct p_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00002960{
Denis Vlasenkobb81c582007-01-30 22:32:09 +00002961 struct child_prog *child = ctx->child;
Eric Andersen25f27032001-04-26 23:22:31 +00002962
Denis Vlasenko55789c62008-06-18 16:30:42 +00002963 /* If this word wasn't an assignment, next ones definitely
2964 * can't be assignments. Even if they look like ones. */
2965 if (word->o_assignment != DEFINITELY_ASSIGNMENT) {
2966 word->o_assignment = NOT_ASSIGNMENT;
2967 } else {
2968 word->o_assignment = MAYBE_ASSIGNMENT;
2969 }
2970
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002971 debug_printf_parse("done_word entered: '%s' %p\n", word->data, child);
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002972 if (word->length == 0 && word->nonnull == 0) {
2973 debug_printf_parse("done_word return 0: true null, ignored\n");
2974 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00002975 }
2976 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002977 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
2978 * only if run as "bash", not "sh" */
2979 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenko55789c62008-06-18 16:30:42 +00002980 word->o_assignment = NOT_ASSIGNMENT;
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002981 debug_printf("word stored in rd_filename: '%s'\n", word->data);
Eric Andersen25f27032001-04-26 23:22:31 +00002982 } else {
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002983// if (child->group) { /* TODO: example how to trigger? */
2984// syntax(NULL);
2985// debug_printf_parse("done_word return 1: syntax error, groups and arglists don't mix\n");
2986// return 1;
2987// }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002988#if HAS_KEYWORDS
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002989#if ENABLE_HUSH_CASE
2990 if (ctx->ctx_dsemicolon) {
2991 /* already done when ctx_dsemicolon was set to 1 */
2992 /* ctx->ctx_res_w = RES_MATCH; */
2993 ctx->ctx_dsemicolon = 0;
2994 } else
2995#endif
2996
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00002997 if (!child->argv /* if it's the first word... */
Denis Vlasenko6bdff082008-07-09 20:14:53 +00002998#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00002999 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3000 && ctx->ctx_res_w != RES_IN
Denis Vlasenko6bdff082008-07-09 20:14:53 +00003001#endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003002 ) {
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003003 debug_printf_parse(": checking '%s' for reserved-ness\n", word->data);
3004 if (reserved_word(word, ctx)) {
3005 o_reset(word);
Denis Vlasenko55789c62008-06-18 16:30:42 +00003006 word->o_assignment = NOT_ASSIGNMENT;
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003007 debug_printf_parse("done_word return %d\n", (ctx->ctx_res_w == RES_SNTX));
3008 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003009 }
Eric Andersen25f27032001-04-26 23:22:31 +00003010 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003011#endif
Denis Vlasenkoff182a32008-07-05 20:29:59 +00003012 if (word->nonnull /* word had "xx" or 'xx' at least as part of it. */
Denis Vlasenko55789c62008-06-18 16:30:42 +00003013 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3014 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003015 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003016 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003017 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00003018 char *p = word->data;
3019 while (p[0] == SPECIAL_VAR_SYMBOL
3020 && (p[1] & 0x7f) == '@'
3021 && p[2] == SPECIAL_VAR_SYMBOL
3022 ) {
3023 p += 3;
3024 }
3025 if (p == word->data || p[0] != '\0') {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003026 /* saw no "$@", or not only "$@" but some
3027 * real text is there too */
3028 /* insert "empty variable" reference, this makes
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00003029 * e.g. "", $empty"" etc to not disappear */
3030 o_addchr(word, SPECIAL_VAR_SYMBOL);
3031 o_addchr(word, SPECIAL_VAR_SYMBOL);
3032 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00003033 }
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003034 child->argv = add_malloced_string_to_strings(child->argv, xstrdup(word->data));
3035 debug_print_strings("word appended to argv", child->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003036 }
Eric Andersen25f27032001-04-26 23:22:31 +00003037
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003038 o_reset(word);
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003039 ctx->pending_redirect = NULL;
3040
Denis Vlasenko06810332007-05-21 23:30:54 +00003041#if ENABLE_HUSH_LOOPS
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003042 /* Force FOR to have just one word (variable name) */
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003043 /* NB: basically, this makes hush see "for v in ..." syntax as if
3044 * as it is "for v; in ...". FOR and IN become two pipe structs
3045 * in parse tree. */
3046 if (ctx->ctx_res_w == RES_FOR) {
3047//TODO: check that child->argv[0] is a valid variable name!
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003048 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003049 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003050#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003051#if ENABLE_HUSH_CASE
3052 /* Force CASE to have just one word */
3053 if (ctx->ctx_res_w == RES_CASE) {
3054 done_pipe(ctx, PIPE_SEQ);
3055 }
3056#endif
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003057 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003058 return 0;
3059}
3060
Denis Vlasenko6eaf8de2008-06-17 12:09:21 +00003061/* Command (member of a pipe) is complete. The only possible error here
3062 * is out of memory, in which case xmalloc exits. */
Eric Andersen25f27032001-04-26 23:22:31 +00003063static int done_command(struct p_context *ctx)
3064{
3065 /* The child is really already in the pipe structure, so
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003066 * advance the pipe counter and make a new, null child. */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003067 struct pipe *pi = ctx->pipe;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003068 struct child_prog *child = ctx->child;
Eric Andersen25f27032001-04-26 23:22:31 +00003069
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003070 if (child) {
3071 if (child->group == NULL
3072 && child->argv == NULL
3073 && child->redirects == NULL
3074 ) {
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003075 debug_printf_parse("done_command: skipping null cmd, num_progs=%d\n", pi->num_progs);
3076 return pi->num_progs;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003077 }
Eric Andersen25f27032001-04-26 23:22:31 +00003078 pi->num_progs++;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003079 debug_printf_parse("done_command: ++num_progs=%d\n", pi->num_progs);
Eric Andersen25f27032001-04-26 23:22:31 +00003080 } else {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003081 debug_printf_parse("done_command: initializing, num_progs=%d\n", pi->num_progs);
Eric Andersen25f27032001-04-26 23:22:31 +00003082 }
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003083
3084 /* Only real trickiness here is that the uncommitted
3085 * child structure is not counted in pi->num_progs. */
Eric Andersen25f27032001-04-26 23:22:31 +00003086 pi->progs = xrealloc(pi->progs, sizeof(*pi->progs) * (pi->num_progs+1));
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003087 child = &pi->progs[pi->num_progs];
Eric Andersen25f27032001-04-26 23:22:31 +00003088
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003089 memset(child, 0, sizeof(*child));
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003090 child->family = pi;
Eric Andersen25f27032001-04-26 23:22:31 +00003091
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003092 ctx->child = child;
Eric Andersen25f27032001-04-26 23:22:31 +00003093 /* but ctx->pipe and ctx->list_head remain unchanged */
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003094
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003095 return pi->num_progs; /* used only for 0/nonzero check */
Eric Andersen25f27032001-04-26 23:22:31 +00003096}
3097
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003098static void done_pipe(struct p_context *ctx, pipe_style type)
Eric Andersen25f27032001-04-26 23:22:31 +00003099{
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003100 int not_null;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003101
3102 debug_printf_parse("done_pipe entered, followup %d\n", type);
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003103 not_null = done_command(ctx); /* implicit closure of previous command */
Eric Andersen25f27032001-04-26 23:22:31 +00003104 ctx->pipe->followup = type;
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003105 IF_HAS_KEYWORDS(ctx->pipe->pi_inverted = ctx->ctx_inverted;)
3106 IF_HAS_KEYWORDS(ctx->ctx_inverted = 0;)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003107 IF_HAS_KEYWORDS(ctx->pipe->res_word = ctx->ctx_res_w;)
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003108 /* Without this check, even just <enter> on command line generates
3109 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenko6eaf8de2008-06-17 12:09:21 +00003110 * IOW: it is safe to do it unconditionally.
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003111 * RES_NONE case is for "for a in; do ..." (empty IN set)
3112 * to work, possibly other cases too. */
3113 if (not_null IF_HAS_KEYWORDS(|| ctx->ctx_res_w != RES_NONE)) {
Denis Vlasenko6eaf8de2008-06-17 12:09:21 +00003114 struct pipe *new_p = new_pipe();
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003115 ctx->pipe->next = new_p;
3116 ctx->pipe = new_p;
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003117 ctx->child = NULL; /* needed! */
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003118 /* RES_IF, RES_WHILE etc are "sticky" -
3119 * they remain set for commands inside if/while.
3120 * This is used to control execution.
3121 * RES_FOR and RES_IN are NOT sticky (needed to support
3122 * cases where variable or value happens to match a keyword):
3123 */
Denis Vlasenko6bdff082008-07-09 20:14:53 +00003124#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003125 if (ctx->ctx_res_w == RES_FOR
3126 || ctx->ctx_res_w == RES_IN)
3127 ctx->ctx_res_w = RES_NONE;
Denis Vlasenko6bdff082008-07-09 20:14:53 +00003128#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003129#if ENABLE_HUSH_CASE
3130 if (ctx->ctx_res_w == RES_MATCH)
3131 ctx->ctx_res_w = RES_CASEI;
3132#endif
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003133 /* Create the memory for child, roughly:
3134 * ctx->pipe->progs = new struct child_prog;
3135 * ctx->pipe->progs[0].family = ctx->pipe;
Denis Vlasenko7049ff82008-06-25 09:53:17 +00003136 * ctx->child = &ctx->pipe->progs[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003137 */
3138 done_command(ctx);
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003139 }
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003140 debug_printf_parse("done_pipe return\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003141}
3142
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003143/* Peek ahead in the in_str to find out if we have a "&n" construct,
Eric Andersen25f27032001-04-26 23:22:31 +00003144 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003145 * Return either -2 (syntax error), -1 (no &), or the number found.
Eric Andersen25f27032001-04-26 23:22:31 +00003146 */
3147static int redirect_dup_num(struct in_str *input)
3148{
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003149 int ch, d = 0, ok = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003150 ch = i_peek(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003151 if (ch != '&') return -1;
3152
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003153 i_getch(input); /* get the & */
3154 ch = i_peek(input);
Eric Andersen83a2ae22001-05-07 17:59:25 +00003155 if (ch == '-') {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003156 i_getch(input);
Eric Andersen83a2ae22001-05-07 17:59:25 +00003157 return -3; /* "-" represents "close me" */
3158 }
3159 while (isdigit(ch)) {
Denis Vlasenko7d4c44e2007-04-16 22:34:39 +00003160 d = d*10 + (ch-'0');
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003161 ok = 1;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003162 i_getch(input);
3163 ch = i_peek(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003164 }
3165 if (ok) return d;
3166
Manuel Novoa III cad53642003-03-19 09:13:01 +00003167 bb_error_msg("ambiguous redirect");
Eric Andersen25f27032001-04-26 23:22:31 +00003168 return -2;
3169}
3170
3171/* If a redirect is immediately preceded by a number, that number is
3172 * supposed to tell which file descriptor to redirect. This routine
3173 * looks for such preceding numbers. In an ideal world this routine
3174 * needs to handle all the following classes of redirects...
3175 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3176 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3177 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3178 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3179 * A -1 output from this program means no valid number was found, so the
3180 * caller should use the appropriate default for this redirection.
3181 */
3182static int redirect_opt_num(o_string *o)
3183{
3184 int num;
3185
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003186 if (o->length == 0)
3187 return -1;
3188 for (num = 0; num < o->length; num++) {
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00003189 if (!isdigit(o->data[num])) {
Eric Andersen25f27032001-04-26 23:22:31 +00003190 return -1;
3191 }
3192 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003193 num = atoi(o->data);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003194 o_reset(o);
Eric Andersen25f27032001-04-26 23:22:31 +00003195 return num;
3196}
3197
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003198#if ENABLE_HUSH_TICK
"Vladimir N. Oleynik"19c37012005-09-22 14:33:15 +00003199static FILE *generate_stream_from_list(struct pipe *head)
Eric Andersen25f27032001-04-26 23:22:31 +00003200{
3201 FILE *pf;
Eric Andersen25f27032001-04-26 23:22:31 +00003202 int pid, channel[2];
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003203
Denis Vlasenko5a6aedd2007-05-26 16:44:20 +00003204 xpipe(channel);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003205/* *** NOMMU WARNING *** */
3206/* By using vfork here, we suspend parent till child exits or execs.
3207 * If child will not do it before it fills the pipe, it can block forever
3208 * in write(STDOUT_FILENO), and parent (shell) will be also stuck.
Denis Vlasenko3fe4f982008-06-09 16:02:39 +00003209 * Try this script:
3210 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >TESTFILE
3211 * huge=`cat TESTFILE` # will block here forever
3212 * echo OK
Denis Vlasenko05743d72008-02-10 12:10:08 +00003213 */
Denis Vlasenko82604e92008-07-01 15:59:42 +00003214 pid = BB_MMU ? fork() : vfork();
3215 if (pid < 0)
3216 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
Denis Vlasenko05743d72008-02-10 12:10:08 +00003217 if (pid == 0) { /* child */
Denis Vlasenko83177992008-02-11 08:44:36 +00003218 if (ENABLE_HUSH_JOB)
3219 die_sleep = 0; /* let nofork's xfuncs die */
Denis Vlasenko284d0fa2008-02-16 13:18:17 +00003220 close(channel[0]); /* NB: close _first_, then move fd! */
Denis Vlasenko05743d72008-02-10 12:10:08 +00003221 xmove_fd(channel[1], 1);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003222 /* Prevent it from trying to handle ctrl-z etc */
Denis Vlasenko27f79ff2007-05-30 00:55:52 +00003223#if ENABLE_HUSH_JOB
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003224 run_list_level = 1;
Denis Vlasenko27f79ff2007-05-30 00:55:52 +00003225#endif
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003226 /* Process substitution is not considered to be usual
3227 * 'command execution'.
3228 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not. */
3229 /* Not needed, we are relying on it being disabled
3230 * everywhere outside actual command execution. */
3231 /*set_jobctrl_sighandler(SIG_IGN);*/
3232 set_misc_sighandler(SIG_DFL);
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00003233 /* Freeing 'head' here would break NOMMU. */
3234 _exit(run_list(head));
Eric Andersen25f27032001-04-26 23:22:31 +00003235 }
Eric Andersen25f27032001-04-26 23:22:31 +00003236 close(channel[1]);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003237 pf = fdopen(channel[0], "r");
Eric Andersen25f27032001-04-26 23:22:31 +00003238 return pf;
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00003239 /* 'head' is freed by the caller */
Eric Andersen25f27032001-04-26 23:22:31 +00003240}
3241
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003242/* Return code is exit status of the process that is run. */
Denis Vlasenko68404f12008-03-17 09:00:54 +00003243static int process_command_subs(o_string *dest,
Denis Vlasenko68404f12008-03-17 09:00:54 +00003244 struct in_str *input,
3245 const char *subst_end)
Eric Andersen25f27032001-04-26 23:22:31 +00003246{
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003247 int retcode, ch, eol_cnt;
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003248 o_string result = NULL_O_STRING;
Eric Andersen25f27032001-04-26 23:22:31 +00003249 struct p_context inner;
3250 FILE *p;
3251 struct in_str pipe_str;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003252
Eric Andersen25f27032001-04-26 23:22:31 +00003253 initialize_context(&inner);
3254
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003255 /* Recursion to generate command */
Eric Andersen25f27032001-04-26 23:22:31 +00003256 retcode = parse_stream(&result, &inner, input, subst_end);
Denis Vlasenko1a735862007-05-23 00:32:25 +00003257 if (retcode != 0)
3258 return retcode; /* syntax error or EOF */
Eric Andersen25f27032001-04-26 23:22:31 +00003259 done_word(&result, &inner);
3260 done_pipe(&inner, PIPE_SEQ);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003261 o_free(&result);
Eric Andersen25f27032001-04-26 23:22:31 +00003262
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003263 p = generate_stream_from_list(inner.list_head);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003264 if (p == NULL)
3265 return 1;
Denis Vlasenkoa0898172007-10-01 09:59:01 +00003266 close_on_exec_on(fileno(p));
Eric Andersen25f27032001-04-26 23:22:31 +00003267 setup_file_in_str(&pipe_str, p);
3268
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003269 /* Now send results of command back into original context */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003270 eol_cnt = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003271 while ((ch = i_getch(&pipe_str)) != EOF) {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003272 if (ch == '\n') {
3273 eol_cnt++;
3274 continue;
3275 }
3276 while (eol_cnt) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00003277 o_addchr(dest, '\n');
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003278 eol_cnt--;
3279 }
Denis Vlasenko55789c62008-06-18 16:30:42 +00003280// /* Even unquoted `echo '\'` results in two backslashes
3281// * (which are converted into one by globbing later) */
3282// if (!dest->o_quote && ch == '\\') {
3283// o_addchr(dest, ch);
3284// }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003285 o_addQchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003286 }
3287
3288 debug_printf("done reading from pipe, pclose()ing\n");
3289 /* This is the step that wait()s for the child. Should be pretty
3290 * safe, since we just read an EOF from its stdout. We could try
Denis Vlasenko262d7652007-05-20 21:52:49 +00003291 * to do better, by using wait(), and keeping track of background jobs
Eric Andersen25f27032001-04-26 23:22:31 +00003292 * at the same time. That would be a lot of work, and contrary
3293 * to the KISS philosophy of this program. */
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003294 retcode = fclose(p);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003295 free_pipe_list(inner.list_head, /* indent: */ 0);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003296 debug_printf("closed FILE from child, retcode=%d\n", retcode);
Eric Andersen25f27032001-04-26 23:22:31 +00003297 return retcode;
3298}
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003299#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003300
3301static int parse_group(o_string *dest, struct p_context *ctx,
3302 struct in_str *input, int ch)
3303{
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003304 int rcode;
3305 const char *endch = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003306 struct p_context sub;
3307 struct child_prog *child = ctx->child;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003308
3309 debug_printf_parse("parse_group entered\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003310 if (child->argv) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003311 syntax(NULL);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003312 debug_printf_parse("parse_group return 1: syntax error, groups and arglists don't mix\n");
3313 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003314 }
3315 initialize_context(&sub);
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003316 endch = "}";
3317 if (ch == '(') {
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003318 endch = ")";
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003319 child->subshell = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003320 }
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003321 rcode = parse_stream(dest, &sub, input, endch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003322 if (rcode == 0) {
3323 done_word(dest, &sub); /* finish off the final word in the subcontext */
3324 done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */
3325 child->group = sub.list_head;
3326 }
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003327 debug_printf_parse("parse_group return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00003328 return rcode;
3329 /* child remains "open", available for possible redirects */
3330}
3331
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003332/* Basically useful version until someone wants to get fancier,
Eric Andersen25f27032001-04-26 23:22:31 +00003333 * see the bash man page under "Parameter Expansion" */
Denis Vlasenko15d78fb2007-01-30 22:28:21 +00003334static const char *lookup_param(const char *src)
Eric Andersen25f27032001-04-26 23:22:31 +00003335{
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003336 struct variable *var = get_local_var(src);
3337 if (var)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00003338 return strchr(var->varstr, '=') + 1;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003339 return NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003340}
3341
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003342#if ENABLE_HUSH_TICK
3343/* Subroutines for copying $(...) and `...` things */
3344static void add_till_backquote(o_string *dest, struct in_str *input);
3345/* '...' */
3346static void add_till_single_quote(o_string *dest, struct in_str *input)
3347{
3348 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003349 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003350 if (ch == EOF)
3351 break;
3352 if (ch == '\'')
3353 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003354 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003355 }
3356}
3357/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
3358static void add_till_double_quote(o_string *dest, struct in_str *input)
3359{
3360 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003361 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003362 if (ch == '"')
3363 break;
3364 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003365 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003366 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003367 }
3368 if (ch == EOF)
3369 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003370 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003371 if (ch == '`') {
3372 add_till_backquote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003373 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003374 continue;
3375 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00003376 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003377 }
3378}
3379/* Process `cmd` - copy contents until "`" is seen. Complicated by
3380 * \` quoting.
3381 * "Within the backquoted style of command substitution, backslash
3382 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3383 * The search for the matching backquote shall be satisfied by the first
3384 * backquote found without a preceding backslash; during this search,
3385 * if a non-escaped backquote is encountered within a shell comment,
3386 * a here-document, an embedded command substitution of the $(command)
3387 * form, or a quoted string, undefined results occur. A single-quoted
3388 * or double-quoted string that begins, but does not end, within the
3389 * "`...`" sequence produces undefined results."
3390 * Example Output
3391 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3392 */
3393static void add_till_backquote(o_string *dest, struct in_str *input)
3394{
3395 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003396 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003397 if (ch == '`')
3398 break;
3399 if (ch == '\\') { /* \x. Copy both chars unless it is \` */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003400 int ch2 = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003401 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003402 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003403 ch = ch2;
3404 }
3405 if (ch == EOF)
3406 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003407 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003408 }
3409}
3410/* Process $(cmd) - copy contents until ")" is seen. Complicated by
3411 * quoting and nested ()s.
3412 * "With the $(command) style of command substitution, all characters
3413 * following the open parenthesis to the matching closing parenthesis
3414 * constitute the command. Any valid shell script can be used for command,
3415 * except a script consisting solely of redirections which produces
3416 * unspecified results."
3417 * Example Output
3418 * echo $(echo '(TEST)' BEST) (TEST) BEST
3419 * echo $(echo 'TEST)' BEST) TEST) BEST
3420 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
3421 */
3422static void add_till_closing_curly_brace(o_string *dest, struct in_str *input)
3423{
3424 int count = 0;
3425 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003426 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003427 if (ch == EOF)
3428 break;
3429 if (ch == '(')
3430 count++;
3431 if (ch == ')')
3432 if (--count < 0)
3433 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003434 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003435 if (ch == '\'') {
3436 add_till_single_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003437 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003438 continue;
3439 }
3440 if (ch == '"') {
3441 add_till_double_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003442 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003443 continue;
3444 }
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003445 if (ch == '\\') { /* \x. Copy verbatim. Important for \(, \) */
3446 ch = i_getch(input);
3447 if (ch == EOF)
3448 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003449 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003450 continue;
3451 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003452 }
3453}
3454#endif /* ENABLE_HUSH_TICK */
3455
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003456/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003457static int handle_dollar(o_string *dest, struct in_str *input)
Eric Andersen25f27032001-04-26 23:22:31 +00003458{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003459 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkoff097622007-10-01 10:00:45 +00003460 unsigned char quote_mask = dest->o_quote ? 0x80 : 0;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003461
3462 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003463 if (isalpha(ch)) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003464 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003465 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003466 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003467 i_getch(input);
3468 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003469 quote_mask = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003470 ch = i_peek(input);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003471 if (!isalnum(ch) && ch != '_')
3472 break;
Eric Andersen25f27032001-04-26 23:22:31 +00003473 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003474 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003475 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003476 make_one_char_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003477 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003478 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003479 i_getch(input);
3480 o_addchr(dest, ch | quote_mask);
3481 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003482 } else switch (ch) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003483 case '$': /* pid */
3484 case '!': /* last bg pid */
3485 case '?': /* last exit code */
3486 case '#': /* number of args */
3487 case '*': /* args */
3488 case '@': /* args */
3489 goto make_one_char_var;
Eric Andersen25f27032001-04-26 23:22:31 +00003490 case '{':
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003491 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3492 i_getch(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003493 /* XXX maybe someone will try to escape the '}' */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003494 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003495 ch = i_getch(input);
Denis Vlasenkob0550012007-05-24 12:18:16 +00003496 if (ch == '}')
3497 break;
3498 if (!isalnum(ch) && ch != '_') {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003499 syntax("unterminated ${name}");
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003500 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
3501 return 1;
3502 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003503 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003504 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003505 quote_mask = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003506 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003507 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003508 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003509#if ENABLE_HUSH_TICK
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003510 case '(': {
3511 //int pos = dest->length;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003512 i_getch(input);
3513 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3514 o_addchr(dest, quote_mask | '`');
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003515 add_till_closing_curly_brace(dest, input);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003516 //debug_printf_subst("SUBST RES2 '%s'\n", dest->data + pos);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003517 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003518 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003519 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003520#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003521 case '-':
3522 case '_':
3523 /* still unhandled, but should be eventually */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003524 bb_error_msg("unhandled syntax: $%c", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003525 return 1;
3526 break;
3527 default:
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003528 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00003529 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003530 debug_printf_parse("handle_dollar return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003531 return 0;
3532}
3533
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003534/* Scan input, call done_word() whenever full IFS delimited word was seen.
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003535 * Call done_pipe if '\n' was seen (and end_trigger != NULL).
3536 * Return code is 0 if end_trigger char is met,
3537 * -1 on EOF (but if end_trigger == NULL then return 0),
Denis Vlasenko55789c62008-06-18 16:30:42 +00003538 * 1 for syntax error */
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003539static int parse_stream(o_string *dest, struct p_context *ctx,
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003540 struct in_str *input, const char *end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00003541{
"Vladimir N. Oleynik"4ccd2b42006-01-31 09:27:48 +00003542 int ch, m;
Eric Andersen25f27032001-04-26 23:22:31 +00003543 int redir_fd;
3544 redir_type redir_style;
Denis Vlasenko55789c62008-06-18 16:30:42 +00003545 int shadow_quote = dest->o_quote;
Eric Andersen25f27032001-04-26 23:22:31 +00003546 int next;
3547
Denis Vlasenkoff097622007-10-01 10:00:45 +00003548 /* Only double-quote state is handled in the state variable dest->o_quote.
Eric Andersen25f27032001-04-26 23:22:31 +00003549 * A single-quote triggers a bypass of the main loop until its mate is
Denis Vlasenkoff097622007-10-01 10:00:45 +00003550 * found. When recursing, quote state is passed in via dest->o_quote. */
Eric Andersen25f27032001-04-26 23:22:31 +00003551
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003552 debug_printf_parse("parse_stream entered, end_trigger='%s'\n", end_trigger);
3553
Denis Vlasenko1a735862007-05-23 00:32:25 +00003554 while (1) {
Denis Vlasenko1a735862007-05-23 00:32:25 +00003555 m = CHAR_IFS;
3556 next = '\0';
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003557 ch = i_getch(input);
Denis Vlasenko1a735862007-05-23 00:32:25 +00003558 if (ch != EOF) {
3559 m = charmap[ch];
Denis Vlasenko55789c62008-06-18 16:30:42 +00003560 if (ch != '\n') {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003561 next = i_peek(input);
Denis Vlasenko55789c62008-06-18 16:30:42 +00003562 }
Denis Vlasenko1a735862007-05-23 00:32:25 +00003563 }
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003564 debug_printf_parse(": ch=%c (%d) m=%d quote=%d\n",
Denis Vlasenkoff097622007-10-01 10:00:45 +00003565 ch, ch, m, dest->o_quote);
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003566 if (m == CHAR_ORDINARY
Denis Vlasenko55789c62008-06-18 16:30:42 +00003567 || (m != CHAR_SPECIAL && shadow_quote)
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003568 ) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00003569 if (ch == EOF) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003570 syntax("unterminated \"");
Denis Vlasenko170435c2007-05-23 13:01:10 +00003571 debug_printf_parse("parse_stream return 1: unterminated \"\n");
3572 return 1;
3573 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003574 o_addQchr(dest, ch);
Denis Vlasenko55789c62008-06-18 16:30:42 +00003575 if (dest->o_assignment == MAYBE_ASSIGNMENT
3576 && ch == '='
3577 && is_assignment(dest->data)
3578 ) {
3579 dest->o_assignment = DEFINITELY_ASSIGNMENT;
3580 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003581 continue;
3582 }
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003583 if (m == CHAR_IFS) {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003584 if (done_word(dest, ctx)) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003585 debug_printf_parse("parse_stream return 1: done_word!=0\n");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003586 return 1;
Eric Andersenaac75e52001-04-30 18:18:45 +00003587 }
Denis Vlasenko1a735862007-05-23 00:32:25 +00003588 if (ch == EOF)
3589 break;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003590 /* If we aren't performing a substitution, treat
3591 * a newline as a command separator.
3592 * [why we don't handle it exactly like ';'? --vda] */
3593 if (end_trigger && ch == '\n') {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003594 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003595 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003596 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003597 if (end_trigger) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00003598 if (!shadow_quote && strchr(end_trigger, ch)) {
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003599 /* Special case: (...word) makes last word terminate,
3600 * as if ';' is seen */
3601 if (ch == ')') {
3602 done_word(dest, ctx);
Denis Vlasenko55789c62008-06-18 16:30:42 +00003603//err chk?
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003604 done_pipe(ctx, PIPE_SEQ);
3605 }
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003606 if (!HAS_KEYWORDS
3607 IF_HAS_KEYWORDS(|| (ctx->ctx_res_w == RES_NONE && ctx->old_flag == 0))
3608 ) {
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003609 debug_printf_parse("parse_stream return 0: end_trigger char found\n");
3610 return 0;
3611 }
3612 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003613 }
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003614 if (m == CHAR_IFS)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003615 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00003616
3617 if (dest->o_assignment == MAYBE_ASSIGNMENT) {
3618 /* ch is a special char and thus this word
3619 * cannot be an assignment: */
3620 dest->o_assignment = NOT_ASSIGNMENT;
3621 }
3622
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003623 switch (ch) {
Eric Andersen25f27032001-04-26 23:22:31 +00003624 case '#':
Denis Vlasenko55789c62008-06-18 16:30:42 +00003625 if (dest->length == 0 && !shadow_quote) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003626 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003627 ch = i_peek(input);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003628 if (ch == EOF || ch == '\n')
3629 break;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003630 i_getch(input);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003631 }
Eric Andersen25f27032001-04-26 23:22:31 +00003632 } else {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003633 o_addQchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003634 }
3635 break;
3636 case '\\':
3637 if (next == EOF) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003638 syntax("\\<eof>");
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003639 debug_printf_parse("parse_stream return 1: \\<eof>\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003640 return 1;
3641 }
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003642 /* bash:
3643 * "The backslash retains its special meaning [in "..."]
3644 * only when followed by one of the following characters:
3645 * $, `, ", \, or <newline>. A double quote may be quoted
3646 * within double quotes by preceding it with a backslash.
3647 * If enabled, history expansion will be performed unless
3648 * an ! appearing in double quotes is escaped using
3649 * a backslash. The backslash preceding the ! is not removed."
3650 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00003651 if (shadow_quote) { //NOT SURE dest->o_quote) {
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003652 if (strchr("$`\"\\", next) != NULL) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003653 o_addqchr(dest, i_getch(input));
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003654 } else {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003655 o_addqchr(dest, '\\');
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003656 }
3657 } else {
3658 o_addchr(dest, '\\');
3659 o_addchr(dest, i_getch(input));
3660 }
Eric Andersen25f27032001-04-26 23:22:31 +00003661 break;
3662 case '$':
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003663 if (handle_dollar(dest, input) != 0) {
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003664 debug_printf_parse("parse_stream return 1: handle_dollar returned non-0\n");
3665 return 1;
3666 }
Eric Andersen25f27032001-04-26 23:22:31 +00003667 break;
3668 case '\'':
3669 dest->nonnull = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003670 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003671 ch = i_getch(input);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003672 if (ch == EOF) {
3673 syntax("unterminated '");
3674 debug_printf_parse("parse_stream return 1: unterminated '\n");
3675 return 1;
3676 }
3677 if (ch == '\'')
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003678 break;
Denis Vlasenko55789c62008-06-18 16:30:42 +00003679 if (dest->o_assignment == NOT_ASSIGNMENT)
3680 o_addqchr(dest, ch);
3681 else
3682 o_addchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003683 }
Eric Andersen25f27032001-04-26 23:22:31 +00003684 break;
3685 case '"':
3686 dest->nonnull = 1;
Denis Vlasenko55789c62008-06-18 16:30:42 +00003687 shadow_quote ^= 1; /* invert */
3688 if (dest->o_assignment == NOT_ASSIGNMENT)
3689 dest->o_quote ^= 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003690 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003691#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003692 case '`': {
3693 //int pos = dest->length;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003694 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko55789c62008-06-18 16:30:42 +00003695 o_addchr(dest, shadow_quote /*or dest->o_quote??*/ ? 0x80 | '`' : '`');
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003696 add_till_backquote(dest, input);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003697 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003698 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00003699 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003700 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003701#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003702 case '>':
3703 redir_fd = redirect_opt_num(dest);
3704 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003705 redir_style = REDIRECT_OVERWRITE;
Eric Andersen25f27032001-04-26 23:22:31 +00003706 if (next == '>') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003707 redir_style = REDIRECT_APPEND;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003708 i_getch(input);
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003709 }
3710#if 0
3711 else if (next == '(') {
3712 syntax(">(process) not supported");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003713 debug_printf_parse("parse_stream return 1: >(process) not supported\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003714 return 1;
3715 }
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003716#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003717 setup_redirect(ctx, redir_fd, redir_style, input);
3718 break;
3719 case '<':
3720 redir_fd = redirect_opt_num(dest);
3721 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003722 redir_style = REDIRECT_INPUT;
Eric Andersen25f27032001-04-26 23:22:31 +00003723 if (next == '<') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003724 redir_style = REDIRECT_HEREIS;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003725 i_getch(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003726 } else if (next == '>') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003727 redir_style = REDIRECT_IO;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003728 i_getch(input);
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003729 }
3730#if 0
3731 else if (next == '(') {
3732 syntax("<(process) not supported");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003733 debug_printf_parse("parse_stream return 1: <(process) not supported\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003734 return 1;
3735 }
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003736#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003737 setup_redirect(ctx, redir_fd, redir_style, input);
3738 break;
3739 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003740#if ENABLE_HUSH_CASE
3741 case_semi:
3742#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003743 done_word(dest, ctx);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003744 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003745#if ENABLE_HUSH_CASE
3746 /* Eat multiple semicolons, detect
3747 * whether it means something special */
3748 while (1) {
3749 ch = i_peek(input);
3750 if (ch != ';')
3751 break;
3752 i_getch(input);
3753 if (ctx->ctx_res_w == RES_CASEI) {
3754 ctx->ctx_dsemicolon = 1;
3755 ctx->ctx_res_w = RES_MATCH;
3756 break;
3757 }
3758 }
3759#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003760 break;
3761 case '&':
3762 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003763 if (next == '&') {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003764 i_getch(input);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003765 done_pipe(ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00003766 } else {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003767 done_pipe(ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00003768 }
3769 break;
3770 case '|':
3771 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003772 if (next == '|') {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003773 i_getch(input);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003774 done_pipe(ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00003775 } else {
3776 /* we could pick up a file descriptor choice here
3777 * with redirect_opt_num(), but bash doesn't do it.
3778 * "echo foo 2| cat" yields "foo 2". */
3779 done_command(ctx);
3780 }
3781 break;
3782 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003783#if ENABLE_HUSH_CASE
3784 if (dest->length == 0 // && argv[0] == NULL
3785 && ctx->ctx_res_w == RES_MATCH
3786 ) {
3787 continue;
3788 }
3789#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003790 case '{':
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003791 if (parse_group(dest, ctx, input, ch) != 0) {
3792 debug_printf_parse("parse_stream return 1: parse_group returned non-0\n");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003793 return 1;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003794 }
Eric Andersen25f27032001-04-26 23:22:31 +00003795 break;
3796 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003797#if ENABLE_HUSH_CASE
3798 if (ctx->ctx_res_w == RES_MATCH)
3799 goto case_semi;
3800#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003801 case '}':
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003802 /* proper use of this character is caught by end_trigger */
3803 syntax("unexpected } or )");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003804 debug_printf_parse("parse_stream return 1: unexpected '}'\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003805 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003806 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003807 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003808 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003809 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003810 } /* while (1) */
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003811 debug_printf_parse("parse_stream return %d\n", -(end_trigger != NULL));
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003812 if (end_trigger)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003813 return -1;
Eric Andersen25f27032001-04-26 23:22:31 +00003814 return 0;
3815}
3816
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003817static void set_in_charmap(const char *set, int code)
Eric Andersen25f27032001-04-26 23:22:31 +00003818{
Denis Vlasenkof5294e12007-04-14 10:09:57 +00003819 while (*set)
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003820 charmap[(unsigned char)*set++] = code;
Eric Andersen25f27032001-04-26 23:22:31 +00003821}
3822
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003823static void update_charmap(void)
Eric Andersen25f27032001-04-26 23:22:31 +00003824{
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003825 /* char *ifs and char charmap[256] are both globals. */
Eric Andersen25f27032001-04-26 23:22:31 +00003826 ifs = getenv("IFS");
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003827 if (ifs == NULL)
3828 ifs = " \t\n";
Eric Andersen25f27032001-04-26 23:22:31 +00003829 /* Precompute a list of 'flow through' behavior so it can be treated
3830 * quickly up front. Computation is necessary because of IFS.
3831 * Special case handling of IFS == " \t\n" is not implemented.
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003832 * The charmap[] array only really needs two bits each,
3833 * and on most machines that would be faster (reduced L1 cache use).
Eric Andersen25f27032001-04-26 23:22:31 +00003834 */
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003835 memset(charmap, CHAR_ORDINARY, sizeof(charmap));
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003836#if ENABLE_HUSH_TICK
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003837 set_in_charmap("\\$\"`", CHAR_SPECIAL);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003838#else
3839 set_in_charmap("\\$\"", CHAR_SPECIAL);
3840#endif
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003841 set_in_charmap("<>;&|(){}#'", CHAR_ORDINARY_IF_QUOTED);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003842 set_in_charmap(ifs, CHAR_IFS); /* are ordinary if quoted */
Eric Andersen25f27032001-04-26 23:22:31 +00003843}
3844
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003845/* Most recursion does not come through here, the exception is
Denis Vlasenko170435c2007-05-23 13:01:10 +00003846 * from builtin_source() and builtin_eval() */
3847static int parse_and_run_stream(struct in_str *inp, int parse_flag)
Eric Andersen25f27032001-04-26 23:22:31 +00003848{
Eric Andersen25f27032001-04-26 23:22:31 +00003849 struct p_context ctx;
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003850 o_string temp = NULL_O_STRING;
Eric Andersen25f27032001-04-26 23:22:31 +00003851 int rcode;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003852
Eric Andersen25f27032001-04-26 23:22:31 +00003853 do {
3854 initialize_context(&ctx);
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003855 update_charmap();
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003856#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00003857 inp->promptmode = 0; /* PS1 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003858#endif
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003859 /* We will stop & execute after each ';' or '\n'.
3860 * Example: "sleep 9999; echo TEST" + ctrl-C:
3861 * TEST should be printed */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003862 rcode = parse_stream(&temp, &ctx, inp, ";\n");
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003863#if HAS_KEYWORDS
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003864 if (rcode != 1 && ctx.old_flag != 0) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003865 syntax(NULL);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003866 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003867#endif
3868 if (rcode != 1 IF_HAS_KEYWORDS(&& ctx.old_flag == 0)) {
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003869 done_word(&temp, &ctx);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003870 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003871 debug_print_tree(ctx.list_head, 0);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003872 debug_printf_exec("parse_stream_outer: run_and_free_list\n");
3873 run_and_free_list(ctx.list_head);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003874 } else {
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003875 /* We arrive here also if rcode == 1 (error in parse_stream) */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003876#if HAS_KEYWORDS
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003877 if (ctx.old_flag != 0) {
3878 free(ctx.stack);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003879 o_reset(&temp);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003880 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003881#endif
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00003882 /*temp.nonnull = 0; - o_free does it below */
3883 /*temp.o_quote = 0; - o_free does it below */
Denis Vlasenko05743d72008-02-10 12:10:08 +00003884 free_pipe_list(ctx.list_head, /* indent: */ 0);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003885 /* Discard all unprocessed line input, force prompt on */
3886 inp->p = NULL;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003887#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003888 inp->promptme = 1;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003889#endif
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003890 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003891 o_free(&temp);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003892 /* loop on syntax errors, return on EOF: */
3893 } while (rcode != -1 && !(parse_flag & PARSEFLAG_EXIT_FROM_LOOP));
Eric Andersen25f27032001-04-26 23:22:31 +00003894 return 0;
3895}
3896
Denis Vlasenko170435c2007-05-23 13:01:10 +00003897static int parse_and_run_string(const char *s, int parse_flag)
Eric Andersen25f27032001-04-26 23:22:31 +00003898{
3899 struct in_str input;
3900 setup_string_in_str(&input, s);
Denis Vlasenko170435c2007-05-23 13:01:10 +00003901 return parse_and_run_stream(&input, parse_flag);
Eric Andersen25f27032001-04-26 23:22:31 +00003902}
3903
Denis Vlasenko170435c2007-05-23 13:01:10 +00003904static int parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00003905{
3906 int rcode;
3907 struct in_str input;
3908 setup_file_in_str(&input, f);
Denis Vlasenko5703c222008-06-15 11:49:42 +00003909 rcode = parse_and_run_stream(&input, 0 /* parse_flag */);
Eric Andersen25f27032001-04-26 23:22:31 +00003910 return rcode;
3911}
3912
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003913#if ENABLE_HUSH_JOB
Eric Andersen6c947d22001-06-25 22:24:38 +00003914/* Make sure we have a controlling tty. If we get started under a job
3915 * aware app (like bash for example), make sure we are now in charge so
3916 * we don't fight over who gets the foreground */
Eric Anderseneaecbf32001-10-31 10:41:31 +00003917static void setup_job_control(void)
Eric Andersen52a97ca2001-06-22 06:49:26 +00003918{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003919 pid_t shell_pgrp;
3920
Denis Vlasenkoa6a17852007-04-28 16:42:11 +00003921 saved_task_pgrp = shell_pgrp = getpgrp();
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003922 debug_printf_jobs("saved_task_pgrp=%d\n", saved_task_pgrp);
Denis Vlasenko96e1b382007-09-30 23:50:48 +00003923 close_on_exec_on(interactive_fd);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003924
Denis Vlasenkoa6a17852007-04-28 16:42:11 +00003925 /* If we were ran as 'hush &',
3926 * sleep until we are in the foreground. */
3927 while (tcgetpgrp(interactive_fd) != shell_pgrp) {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003928 /* Send TTIN to ourself (should stop us) */
Denis Vlasenkoff131b92007-04-10 15:42:06 +00003929 kill(- shell_pgrp, SIGTTIN);
Denis Vlasenkoa6a17852007-04-28 16:42:11 +00003930 shell_pgrp = getpgrp();
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003931 }
Eric Andersen52a97ca2001-06-22 06:49:26 +00003932
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003933 /* Ignore job-control and misc signals. */
3934 set_jobctrl_sighandler(SIG_IGN);
3935 set_misc_sighandler(SIG_IGN);
3936//huh? signal(SIGCHLD, SIG_IGN);
3937
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003938 /* We _must_ restore tty pgrp on fatal signals */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003939 set_fatal_sighandler(sigexit);
Eric Andersen6c947d22001-06-25 22:24:38 +00003940
3941 /* Put ourselves in our own process group. */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003942 setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
Eric Andersen6c947d22001-06-25 22:24:38 +00003943 /* Grab control of the terminal. */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003944 tcsetpgrp(interactive_fd, getpid());
Eric Andersen6c947d22001-06-25 22:24:38 +00003945}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003946#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00003947
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003948
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00003949int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00003950int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00003951{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00003952 static const char version_str[] ALIGN1 = "HUSH_VERSION="HUSH_VER_STR;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00003953 static const struct variable const_shell_ver = {
3954 .next = NULL,
3955 .varstr = (char*)version_str,
3956 .max_len = 1, /* 0 can provoke free(name) */
3957 .flg_export = 1,
3958 .flg_read_only = 1,
3959 };
3960
Eric Andersen25f27032001-04-26 23:22:31 +00003961 int opt;
3962 FILE *input;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003963 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003964 struct variable *cur_var;
Eric Andersenbc604a22001-05-16 05:24:03 +00003965
Denis Vlasenko574f2f42008-02-27 18:41:59 +00003966 INIT_G();
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003967
Denis Vlasenko16c2fea2008-06-17 12:28:44 +00003968 root_pid = getpid();
3969
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00003970 /* Deal with HUSH_VERSION */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00003971 shell_ver = const_shell_ver; /* copying struct here */
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003972 top_var = &shell_ver;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00003973 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
3974 /* Initialize our shell local variables with the values
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003975 * currently living in the environment */
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003976 cur_var = top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00003977 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003978 if (e) while (*e) {
3979 char *value = strchr(*e, '=');
3980 if (value) { /* paranoia */
3981 cur_var->next = xzalloc(sizeof(*cur_var));
3982 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00003983 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003984 cur_var->max_len = strlen(*e);
3985 cur_var->flg_export = 1;
3986 }
3987 e++;
3988 }
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00003989 putenv((char *)version_str); /* reinstate HUSH_VERSION */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00003990
Denis Vlasenko38f63192007-01-22 09:03:07 +00003991#if ENABLE_FEATURE_EDITING
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00003992 line_input_state = new_line_input_t(FOR_SHELL);
3993#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003994 /* XXX what should these be while sourcing /etc/profile? */
3995 global_argc = argc;
3996 global_argv = argv;
Eric Andersen94ac2442001-05-22 19:05:18 +00003997 /* Initialize some more globals to non-zero values */
3998 set_cwd();
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003999#if ENABLE_HUSH_INTERACTIVE
4000#if ENABLE_FEATURE_EDITING
4001 cmdedit_set_initial_prompt();
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004002#endif
Eric Andersen94ac2442001-05-22 19:05:18 +00004003 PS2 = "> ";
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004004#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00004005
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004006 if (EXIT_SUCCESS) /* otherwise is already done */
4007 last_return_code = EXIT_SUCCESS;
Eric Andersen25f27032001-04-26 23:22:31 +00004008
4009 if (argv[0] && argv[0][0] == '-') {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004010 debug_printf("sourcing /etc/profile\n");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00004011 input = fopen("/etc/profile", "r");
4012 if (input != NULL) {
Denis Vlasenkoa0898172007-10-01 09:59:01 +00004013 close_on_exec_on(fileno(input));
Denis Vlasenko170435c2007-05-23 13:01:10 +00004014 parse_and_run_file(input);
Eric Andersena90f20b2001-06-26 23:00:21 +00004015 fclose(input);
4016 }
Eric Andersen25f27032001-04-26 23:22:31 +00004017 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004018 input = stdin;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004019
Eric Andersen25f27032001-04-26 23:22:31 +00004020 while ((opt = getopt(argc, argv, "c:xif")) > 0) {
4021 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004022 case 'c':
Denis Vlasenko5f786c22007-04-20 08:35:45 +00004023 global_argv = argv + optind;
4024 global_argc = argc - optind;
Denis Vlasenko5703c222008-06-15 11:49:42 +00004025 opt = parse_and_run_string(optarg, 0 /* parse_flag */);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004026 goto final_return;
4027 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00004028 /* Well, we cannot just declare interactiveness,
4029 * we have to have some stuff (ctty, etc) */
4030 /* interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004031 break;
4032 case 'f':
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00004033 fake_mode = 1;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004034 break;
4035 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00004036#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004037 fprintf(stderr, "Usage: sh [FILE]...\n"
4038 " or: sh -c command [args]...\n\n");
4039 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00004040#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004041 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00004042#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004043 }
4044 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004045#if ENABLE_HUSH_JOB
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004046 /* A shell is interactive if the '-i' flag was given, or if all of
Eric Andersen25f27032001-04-26 23:22:31 +00004047 * the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00004048 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00004049 * no arguments remaining or the -s flag given
4050 * standard input is a terminal
4051 * standard output is a terminal
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004052 * Refer to Posix.2, the description of the 'sh' utility. */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004053 if (argv[optind] == NULL && input == stdin
4054 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
4055 ) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004056 saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
4057 debug_printf("saved_tty_pgrp=%d\n", saved_tty_pgrp);
4058 if (saved_tty_pgrp >= 0) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004059 /* try to dup to high fd#, >= 255 */
4060 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
4061 if (interactive_fd < 0) {
4062 /* try to dup to any fd */
4063 interactive_fd = dup(STDIN_FILENO);
4064 if (interactive_fd < 0)
4065 /* give up */
4066 interactive_fd = 0;
4067 }
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00004068 // TODO: track & disallow any attempts of user
4069 // to (inadvertently) close/redirect it
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004070 }
Eric Andersen25f27032001-04-26 23:22:31 +00004071 }
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004072 debug_printf("interactive_fd=%d\n", interactive_fd);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004073 if (interactive_fd) {
Denis Vlasenko08126f62008-02-11 08:39:11 +00004074 fcntl(interactive_fd, F_SETFD, FD_CLOEXEC);
Eric Andersen25f27032001-04-26 23:22:31 +00004075 /* Looks like they want an interactive shell */
Eric Andersen52a97ca2001-06-22 06:49:26 +00004076 setup_job_control();
Denis Vlasenko4ecfcdc2008-02-11 08:32:31 +00004077 /* -1 is special - makes xfuncs longjmp, not exit
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00004078 * (we reset die_sleep = 0 whereever we [v]fork) */
4079 die_sleep = -1;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004080 if (setjmp(die_jmp)) {
4081 /* xfunc has failed! die die die */
4082 hush_exit(xfunc_error_retval);
4083 }
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00004084#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denis Vlasenkoca525b42007-06-13 12:27:17 +00004085 printf("\n\n%s hush - the humble shell v"HUSH_VER_STR"\n", bb_banner);
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00004086 printf("Enter 'help' for a list of built-in commands.\n\n");
4087#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00004088 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004089#elif ENABLE_HUSH_INTERACTIVE
4090/* no job control compiled, only prompt/line editing */
4091 if (argv[optind] == NULL && input == stdin
4092 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
4093 ) {
4094 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
4095 if (interactive_fd < 0) {
4096 /* try to dup to any fd */
4097 interactive_fd = dup(STDIN_FILENO);
4098 if (interactive_fd < 0)
4099 /* give up */
4100 interactive_fd = 0;
4101 }
Denis Vlasenko4830fc52008-05-25 21:50:55 +00004102 if (interactive_fd) {
Denis Vlasenko08126f62008-02-11 08:39:11 +00004103 fcntl(interactive_fd, F_SETFD, FD_CLOEXEC);
Denis Vlasenko4830fc52008-05-25 21:50:55 +00004104 set_misc_sighandler(SIG_IGN);
4105 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004106 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004107#endif
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004108
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004109 if (argv[optind] == NULL) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00004110 opt = parse_and_run_file(stdin);
Denis Vlasenko05743d72008-02-10 12:10:08 +00004111 } else {
4112 debug_printf("\nrunning script '%s'\n", argv[optind]);
4113 global_argv = argv + optind;
4114 global_argc = argc - optind;
4115 input = xfopen(argv[optind], "r");
Denis Vlasenko459a5ad2008-02-11 08:35:03 +00004116 fcntl(fileno(input), F_SETFD, FD_CLOEXEC);
Denis Vlasenko05743d72008-02-10 12:10:08 +00004117 opt = parse_and_run_file(input);
Eric Andersen25f27032001-04-26 23:22:31 +00004118 }
Eric Andersen25f27032001-04-26 23:22:31 +00004119
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004120 final_return:
4121
Denis Vlasenko38f63192007-01-22 09:03:07 +00004122#if ENABLE_FEATURE_CLEAN_UP
Eric Andersenaeb44c42001-05-22 20:29:00 +00004123 fclose(input);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004124 if (cwd != bb_msg_unknown)
Eric Andersenaeb44c42001-05-22 20:29:00 +00004125 free((char*)cwd);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004126 cur_var = top_var->next;
4127 while (cur_var) {
4128 struct variable *tmp = cur_var;
4129 if (!cur_var->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00004130 free(cur_var->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004131 cur_var = cur_var->next;
4132 free(tmp);
Eric Andersenaeb44c42001-05-22 20:29:00 +00004133 }
Eric Andersen25f27032001-04-26 23:22:31 +00004134#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004135 hush_exit(opt ? opt : last_return_code);
Eric Andersen25f27032001-04-26 23:22:31 +00004136}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00004137
4138
4139#if ENABLE_LASH
4140int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
4141int lash_main(int argc, char **argv)
4142{
4143 //bb_error_msg("lash is deprecated, please use hush instead");
4144 return hush_main(argc, argv);
4145}
4146#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004147
4148
4149/*
4150 * Built-ins
4151 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004152static int builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004153{
4154 return 0;
4155}
4156
4157static int builtin_test(char **argv)
4158{
4159 int argc = 0;
4160 while (*argv) {
4161 argc++;
4162 argv++;
4163 }
4164 return test_main(argc, argv - argc);
4165}
4166
4167static int builtin_echo(char **argv)
4168{
4169 int argc = 0;
4170 while (*argv) {
4171 argc++;
4172 argv++;
4173 }
4174 return echo_main(argc, argv - argc);
4175}
4176
4177static int builtin_eval(char **argv)
4178{
4179 int rcode = EXIT_SUCCESS;
4180
4181 if (argv[1]) {
4182 char *str = expand_strvec_to_string(argv + 1);
4183 parse_and_run_string(str, PARSEFLAG_EXIT_FROM_LOOP);
4184 free(str);
4185 rcode = last_return_code;
4186 }
4187 return rcode;
4188}
4189
4190static int builtin_cd(char **argv)
4191{
4192 const char *newdir;
4193 if (argv[1] == NULL) {
4194 // bash does nothing (exitcode 0) if HOME is ""; if it's unset,
4195 // bash says "bash: cd: HOME not set" and does nothing (exitcode 1)
4196 newdir = getenv("HOME") ? : "/";
4197 } else
4198 newdir = argv[1];
4199 if (chdir(newdir)) {
4200 printf("cd: %s: %s\n", newdir, strerror(errno));
4201 return EXIT_FAILURE;
4202 }
4203 set_cwd();
4204 return EXIT_SUCCESS;
4205}
4206
4207static int builtin_exec(char **argv)
4208{
4209 if (argv[1] == NULL)
4210 return EXIT_SUCCESS; /* bash does this */
4211 {
4212#if !BB_MMU
4213 char **ptrs2free = alloc_ptrs(argv);
4214#endif
4215// FIXME: if exec fails, bash does NOT exit! We do...
4216 pseudo_exec_argv(ptrs2free, argv + 1);
4217 /* never returns */
4218 }
4219}
4220
4221static int builtin_exit(char **argv)
4222{
4223// TODO: bash does it ONLY on top-level sh exit (+interacive only?)
4224 //puts("exit"); /* bash does it */
4225// TODO: warn if we have background jobs: "There are stopped jobs"
4226// On second consecutive 'exit', exit anyway.
4227 if (argv[1] == NULL)
4228 hush_exit(last_return_code);
4229 /* mimic bash: exit 123abc == exit 255 + error msg */
4230 xfunc_error_retval = 255;
4231 /* bash: exit -2 == exit 254, no error msg */
4232 hush_exit(xatoi(argv[1]) & 0xff);
4233}
4234
4235static int builtin_export(char **argv)
4236{
4237 const char *value;
4238 char *name = argv[1];
4239
4240 if (name == NULL) {
4241 // TODO:
4242 // ash emits: export VAR='VAL'
4243 // bash: declare -x VAR="VAL"
4244 // (both also escape as needed (quotes, $, etc))
4245 char **e = environ;
4246 if (e)
4247 while (*e)
4248 puts(*e++);
4249 return EXIT_SUCCESS;
4250 }
4251
4252 value = strchr(name, '=');
4253 if (!value) {
4254 /* They are exporting something without a =VALUE */
4255 struct variable *var;
4256
4257 var = get_local_var(name);
4258 if (var) {
4259 var->flg_export = 1;
4260 putenv(var->varstr);
4261 }
4262 /* bash does not return an error when trying to export
4263 * an undefined variable. Do likewise. */
4264 return EXIT_SUCCESS;
4265 }
4266
4267 set_local_var(xstrdup(name), 1);
4268 return EXIT_SUCCESS;
4269}
4270
4271#if ENABLE_HUSH_JOB
4272/* built-in 'fg' and 'bg' handler */
4273static int builtin_fg_bg(char **argv)
4274{
4275 int i, jobnum;
4276 struct pipe *pi;
4277
4278 if (!interactive_fd)
4279 return EXIT_FAILURE;
4280 /* If they gave us no args, assume they want the last backgrounded task */
4281 if (!argv[1]) {
4282 for (pi = job_list; pi; pi = pi->next) {
4283 if (pi->jobid == last_jobid) {
4284 goto found;
4285 }
4286 }
4287 bb_error_msg("%s: no current job", argv[0]);
4288 return EXIT_FAILURE;
4289 }
4290 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
4291 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
4292 return EXIT_FAILURE;
4293 }
4294 for (pi = job_list; pi; pi = pi->next) {
4295 if (pi->jobid == jobnum) {
4296 goto found;
4297 }
4298 }
4299 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
4300 return EXIT_FAILURE;
4301 found:
4302 // TODO: bash prints a string representation
4303 // of job being foregrounded (like "sleep 1 | cat")
4304 if (*argv[0] == 'f') {
4305 /* Put the job into the foreground. */
4306 tcsetpgrp(interactive_fd, pi->pgrp);
4307 }
4308
4309 /* Restart the processes in the job */
4310 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_progs, pi->pgrp);
4311 for (i = 0; i < pi->num_progs; i++) {
4312 debug_printf_jobs("reviving pid %d\n", pi->progs[i].pid);
4313 pi->progs[i].is_stopped = 0;
4314 }
4315 pi->stopped_progs = 0;
4316
4317 i = kill(- pi->pgrp, SIGCONT);
4318 if (i < 0) {
4319 if (errno == ESRCH) {
4320 delete_finished_bg_job(pi);
4321 return EXIT_SUCCESS;
4322 } else {
4323 bb_perror_msg("kill (SIGCONT)");
4324 }
4325 }
4326
4327 if (*argv[0] == 'f') {
4328 remove_bg_job(pi);
4329 return checkjobs_and_fg_shell(pi);
4330 }
4331 return EXIT_SUCCESS;
4332}
4333#endif
4334
4335#if ENABLE_HUSH_HELP
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004336static int builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004337{
4338 const struct built_in_command *x;
4339
4340 printf("\nBuilt-in commands:\n");
4341 printf("-------------------\n");
4342 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
4343 printf("%s\t%s\n", x->cmd, x->descr);
4344 }
4345 printf("\n\n");
4346 return EXIT_SUCCESS;
4347}
4348#endif
4349
4350#if ENABLE_HUSH_JOB
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004351static int builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004352{
4353 struct pipe *job;
4354 const char *status_string;
4355
4356 for (job = job_list; job; job = job->next) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004357 if (job->alive_progs == job->stopped_progs)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004358 status_string = "Stopped";
4359 else
4360 status_string = "Running";
4361
4362 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
4363 }
4364 return EXIT_SUCCESS;
4365}
4366#endif
4367
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004368static int builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004369{
4370 puts(set_cwd());
4371 return EXIT_SUCCESS;
4372}
4373
4374static int builtin_read(char **argv)
4375{
4376 char *string;
4377 const char *name = argv[1] ? argv[1] : "REPLY";
4378
4379 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
4380 return set_local_var(string, 0);
4381}
4382
4383/* built-in 'set [VAR=value]' handler */
4384static int builtin_set(char **argv)
4385{
4386 char *temp = argv[1];
4387 struct variable *e;
4388
4389 if (temp == NULL)
4390 for (e = top_var; e; e = e->next)
4391 puts(e->varstr);
4392 else
4393 set_local_var(xstrdup(temp), 0);
4394
4395 return EXIT_SUCCESS;
4396}
4397
4398static int builtin_shift(char **argv)
4399{
4400 int n = 1;
4401 if (argv[1]) {
4402 n = atoi(argv[1]);
4403 }
4404 if (n >= 0 && n < global_argc) {
4405 global_argv[n] = global_argv[0];
4406 global_argc -= n;
4407 global_argv += n;
4408 return EXIT_SUCCESS;
4409 }
4410 return EXIT_FAILURE;
4411}
4412
4413static int builtin_source(char **argv)
4414{
4415 FILE *input;
4416 int status;
4417
4418 if (argv[1] == NULL)
4419 return EXIT_FAILURE;
4420
4421 /* XXX search through $PATH is missing */
4422 input = fopen(argv[1], "r");
4423 if (!input) {
4424 bb_error_msg("cannot open '%s'", argv[1]);
4425 return EXIT_FAILURE;
4426 }
4427 close_on_exec_on(fileno(input));
4428
4429 /* Now run the file */
4430 /* XXX argv and argc are broken; need to save old global_argv
4431 * (pointer only is OK!) on this stack frame,
4432 * set global_argv=argv+1, recurse, and restore. */
4433 status = parse_and_run_file(input);
4434 fclose(input);
4435 return status;
4436}
4437
4438static int builtin_umask(char **argv)
4439{
4440 mode_t new_umask;
4441 const char *arg = argv[1];
4442 char *end;
4443 if (arg) {
4444 new_umask = strtoul(arg, &end, 8);
4445 if (*end != '\0' || end == arg) {
4446 return EXIT_FAILURE;
4447 }
4448 } else {
4449 new_umask = umask(0);
4450 printf("%.3o\n", (unsigned) new_umask);
4451 }
4452 umask(new_umask);
4453 return EXIT_SUCCESS;
4454}
4455
4456static int builtin_unset(char **argv)
4457{
4458 /* bash always returns true */
4459 unset_local_var(argv[1]);
4460 return EXIT_SUCCESS;
4461}