blob: 800b0f9709d66129bbc8c456c0be8f609269047b [file] [log] [blame]
Eric Andersen25f27032001-04-26 23:22:31 +00001/* vi: set sw=4 ts=4: */
2/*
3 * sh.c -- a prototype Bourne shell grammar parser
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
7 *
8 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
9 *
10 * Credits:
11 * The parser routines proper are all original material, first
Eric Andersencb81e642003-07-14 21:21:08 +000012 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
13 * execution engine, the builtins, and much of the underlying
14 * support has been adapted from busybox-0.49pre's lash, which is
Eric Andersenc7bda1c2004-03-15 08:29:22 +000015 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
Eric Andersencb81e642003-07-14 21:21:08 +000016 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
17 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
18 * Troan, which they placed in the public domain. I don't know
19 * how much of the Johnson/Troan code has survived the repeated
20 * rewrites.
21 *
Eric Andersen25f27032001-04-26 23:22:31 +000022 * Other credits:
Eric Andersen25f27032001-04-26 23:22:31 +000023 * b_addchr() derived from similar w_addchar function in glibc-2.2
24 * setup_redirect(), redirect_opt_num(), and big chunks of main()
Denis Vlasenko55b2de72007-04-18 17:21:28 +000025 * and many builtins derived from contributions by Erik Andersen
Eric Andersen25f27032001-04-26 23:22:31 +000026 * miscellaneous bugfixes from Matt Kraai
27 *
28 * There are two big (and related) architecture differences between
29 * this parser and the lash parser. One is that this version is
30 * actually designed from the ground up to understand nearly all
31 * of the Bourne grammar. The second, consequential change is that
32 * the parser and input reader have been turned inside out. Now,
33 * the parser is in control, and asks for input as needed. The old
34 * way had the input reader in control, and it asked for parsing to
35 * take place as needed. The new way makes it much easier to properly
36 * handle the recursion implicit in the various substitutions, especially
37 * across continuation lines.
38 *
39 * Bash grammar not implemented: (how many of these were in original sh?)
Eric Andersen25f27032001-04-26 23:22:31 +000040 * $_
41 * ! negation operator for pipes
42 * &> and >& redirection of stdout+stderr
43 * Brace Expansion
44 * Tilde Expansion
45 * fancy forms of Parameter Expansion
Eric Andersen78a7c992001-05-15 16:30:25 +000046 * aliases
Eric Andersen25f27032001-04-26 23:22:31 +000047 * Arithmetic Expansion
48 * <(list) and >(list) Process Substitution
Eric Andersen83a2ae22001-05-07 17:59:25 +000049 * reserved words: case, esac, select, function
Eric Andersen25f27032001-04-26 23:22:31 +000050 * Here Documents ( << word )
51 * Functions
52 * Major bugs:
Denis Vlasenkob81b3df2007-04-28 16:48:04 +000053 * job handling woefully incomplete and buggy (improved --vda)
Eric Andersen25f27032001-04-26 23:22:31 +000054 * reserved word execution woefully incomplete and buggy
Eric Andersen25f27032001-04-26 23:22:31 +000055 * to-do:
Eric Andersen83a2ae22001-05-07 17:59:25 +000056 * port selected bugfixes from post-0.49 busybox lash - done?
57 * finish implementing reserved words: for, while, until, do, done
58 * change { and } from special chars to reserved words
59 * builtins: break, continue, eval, return, set, trap, ulimit
60 * test magic exec
Eric Andersen25f27032001-04-26 23:22:31 +000061 * handle children going into background
62 * clean up recognition of null pipes
Eric Andersen25f27032001-04-26 23:22:31 +000063 * check setting of global_argc and global_argv
64 * control-C handling, probably with longjmp
Eric Andersen25f27032001-04-26 23:22:31 +000065 * follow IFS rules more precisely, including update semantics
Eric Andersen25f27032001-04-26 23:22:31 +000066 * figure out what to do with backslash-newline
67 * explain why we use signal instead of sigaction
68 * propagate syntax errors, die on resource errors?
69 * continuation lines, both explicit and implicit - done?
70 * memory leak finding and plugging - done?
71 * more testing, especially quoting rules and redirection
Eric Andersen78a7c992001-05-15 16:30:25 +000072 * document how quoting rules not precisely followed for variable assignments
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +000073 * maybe change charmap[] to use 2-bit entries
Eric Andersen25f27032001-04-26 23:22:31 +000074 * (eventually) remove all the printf's
Eric Andersen25f27032001-04-26 23:22:31 +000075 *
Bernhard Reutner-Fischer86f5c992006-01-22 22:55:11 +000076 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
Eric Andersen25f27032001-04-26 23:22:31 +000077 */
Bernhard Reutner-Fischere15d7572006-06-02 20:56:16 +000078
79#include "busybox.h"
Eric Andersen25f27032001-04-26 23:22:31 +000080#include <glob.h> /* glob, of course */
Eric Andersen25f27032001-04-26 23:22:31 +000081#include <getopt.h> /* should be pretty obvious */
Eric Andersen25f27032001-04-26 23:22:31 +000082/* #include <dmalloc.h> */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +000083extern char **environ; /* This is in <unistd.h>, but protected with __USE_GNU */
Denis Vlasenkod01ff132007-05-02 21:40:23 +000084
85
86/* If you comment out one of these below, it will be #defined later
87 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +000088#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +000089/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +000090#define debug_printf_parse(...) do {} while (0)
91#define debug_print_tree(a, b) do {} while (0)
92#define debug_printf_exec(...) do {} while (0)
93#define debug_printf_jobs(...) do {} while (0)
94#define debug_printf_expand(...) do {} while (0)
95#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +000096
97#ifndef debug_printf
98#define debug_printf(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkod01ff132007-05-02 21:40:23 +000099#endif
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000100
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000101#ifndef debug_printf_parse
102#define debug_printf_parse(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000103#endif
104
105#ifndef debug_printf_exec
106#define debug_printf_exec(...) fprintf(stderr, __VA_ARGS__)
107#endif
108
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000109#ifndef debug_printf_jobs
110#define debug_printf_jobs(...) fprintf(stderr, __VA_ARGS__)
111#define DEBUG_SHELL_JOBS 1
112#endif
113
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000114#ifndef debug_printf_expand
115#define debug_printf_expand(...) fprintf(stderr, __VA_ARGS__)
116#define DEBUG_EXPAND 1
117#endif
118
Denis Vlasenko170435c2007-05-23 13:01:10 +0000119/* Keep unconditionally on for now */
120#define ENABLE_HUSH_DEBUG 1
121
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000122#ifndef debug_printf_clean
123/* broken, of course, but OK for testing */
124static const char *indenter(int i)
125{
126 static const char blanks[] = " ";
127 return &blanks[sizeof(blanks) - i - 1];
128}
129#define debug_printf_clean(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkoc666f712007-05-16 22:18:54 +0000130#define DEBUG_CLEAN 1
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +0000131#endif
132
Eric Andersen25f27032001-04-26 23:22:31 +0000133
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000134#if !ENABLE_HUSH_INTERACTIVE
135#undef ENABLE_FEATURE_EDITING
136#define ENABLE_FEATURE_EDITING 0
137#undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
138#define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
139#endif
"Robert P. J. Day"f3501602006-07-01 12:19:39 +0000140
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +0000141#define SPECIAL_VAR_SYMBOL 3
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000142
143#define PARSEFLAG_EXIT_FROM_LOOP 1
144#define PARSEFLAG_SEMICOLON (1 << 1) /* symbol ';' is special for parser */
145#define PARSEFLAG_REPARSING (1 << 2) /* >= 2nd pass */
Eric Andersen25f27032001-04-26 23:22:31 +0000146
147typedef enum {
148 REDIRECT_INPUT = 1,
149 REDIRECT_OVERWRITE = 2,
150 REDIRECT_APPEND = 3,
151 REDIRECT_HEREIS = 4,
152 REDIRECT_IO = 5
153} redir_type;
154
155/* The descrip member of this structure is only used to make debugging
156 * output pretty */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +0000157static const struct {
158 int mode;
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000159 signed char default_fd;
160 char descrip[3];
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +0000161} redir_table[] = {
Eric Andersen25f27032001-04-26 23:22:31 +0000162 { 0, 0, "()" },
163 { O_RDONLY, 0, "<" },
164 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
165 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
166 { O_RDONLY, -1, "<<" },
167 { O_RDWR, 1, "<>" }
168};
169
170typedef enum {
171 PIPE_SEQ = 1,
172 PIPE_AND = 2,
173 PIPE_OR = 3,
174 PIPE_BG = 4,
175} pipe_style;
176
177/* might eventually control execution */
178typedef enum {
179 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000180#if ENABLE_HUSH_IF
Eric Andersen25f27032001-04-26 23:22:31 +0000181 RES_IF = 1,
182 RES_THEN = 2,
183 RES_ELIF = 3,
184 RES_ELSE = 4,
185 RES_FI = 5,
Denis Vlasenko06810332007-05-21 23:30:54 +0000186#endif
187#if ENABLE_HUSH_LOOPS
Eric Andersen25f27032001-04-26 23:22:31 +0000188 RES_FOR = 6,
189 RES_WHILE = 7,
190 RES_UNTIL = 8,
191 RES_DO = 9,
192 RES_DONE = 10,
Denis Vlasenko06810332007-05-21 23:30:54 +0000193 RES_IN = 11,
194#endif
195 RES_XXXX = 12,
Eric Andersen4c9b68f2002-04-13 12:33:41 +0000196 RES_SNTX = 13
Eric Andersen25f27032001-04-26 23:22:31 +0000197} reserved_style;
Denis Vlasenko5f786c22007-04-20 08:35:45 +0000198enum {
199 FLAG_END = (1 << RES_NONE ),
Denis Vlasenko06810332007-05-21 23:30:54 +0000200#if ENABLE_HUSH_IF
Denis Vlasenko5f786c22007-04-20 08:35:45 +0000201 FLAG_IF = (1 << RES_IF ),
202 FLAG_THEN = (1 << RES_THEN ),
203 FLAG_ELIF = (1 << RES_ELIF ),
204 FLAG_ELSE = (1 << RES_ELSE ),
205 FLAG_FI = (1 << RES_FI ),
Denis Vlasenko06810332007-05-21 23:30:54 +0000206#endif
207#if ENABLE_HUSH_LOOPS
Denis Vlasenko5f786c22007-04-20 08:35:45 +0000208 FLAG_FOR = (1 << RES_FOR ),
209 FLAG_WHILE = (1 << RES_WHILE),
210 FLAG_UNTIL = (1 << RES_UNTIL),
211 FLAG_DO = (1 << RES_DO ),
212 FLAG_DONE = (1 << RES_DONE ),
213 FLAG_IN = (1 << RES_IN ),
Denis Vlasenko06810332007-05-21 23:30:54 +0000214#endif
Denis Vlasenko5f786c22007-04-20 08:35:45 +0000215 FLAG_START = (1 << RES_XXXX ),
216};
Eric Andersen25f27032001-04-26 23:22:31 +0000217
218/* This holds pointers to the various results of parsing */
219struct p_context {
220 struct child_prog *child;
221 struct pipe *list_head;
222 struct pipe *pipe;
223 struct redir_struct *pending_redirect;
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000224 smallint res_w;
225 smallint parse_type; /* bitmask of PARSEFLAG_xxx, defines type of parser : ";$" common or special symbol */
226 int old_flag; /* bitmask of FLAG_xxx, for figuring out valid reserved words */
Eric Andersen25f27032001-04-26 23:22:31 +0000227 struct p_context *stack;
228 /* How about quoting status? */
229};
230
231struct redir_struct {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000232 struct redir_struct *next; /* pointer to the next redirect in the list */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000233 redir_type type; /* type of redirection */
234 int fd; /* file descriptor being redirected */
235 int dup; /* -1, or file descriptor being duplicated */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000236 glob_t word; /* *word.gl_pathv is the filename */
Eric Andersen25f27032001-04-26 23:22:31 +0000237};
238
239struct child_prog {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000240 pid_t pid; /* 0 if exited */
241 char **argv; /* program name and arguments */
242 struct pipe *group; /* if non-NULL, first in group or subshell */
Denis Vlasenko262d7652007-05-20 21:52:49 +0000243 smallint subshell; /* flag, non-zero if group must be forked */
244 smallint is_stopped; /* is the program currently running? */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000245 struct redir_struct *redirects; /* I/O redirections */
246 glob_t glob_result; /* result of parameter globbing */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000247 struct pipe *family; /* pointer back to the child's parent pipe */
Denis Vlasenkoc666f712007-05-16 22:18:54 +0000248 //sp counting seems to be broken... so commented out, grep for '//sp:'
249 //sp: int sp; /* number of SPECIAL_VAR_SYMBOL */
Denis Vlasenko262d7652007-05-20 21:52:49 +0000250 //seems to be unused, grep for '//pt:'
251 //pt: int parse_type;
Eric Andersen25f27032001-04-26 23:22:31 +0000252};
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000253/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
254 * and on execution these are substituted with their values.
255 * Substitution can make _several_ words out of one argv[n]!
256 * Example: argv[0]=='.^C*^C.' here: echo .$*.
257 */
Eric Andersen25f27032001-04-26 23:22:31 +0000258
259struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000260 struct pipe *next;
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000261 int num_progs; /* total number of programs in job */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000262 int running_progs; /* number of programs running (not exited) */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000263 int stopped_progs; /* number of programs alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000264#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000265 int jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000266 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000267 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000268#endif
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000269 char *cmdbuf; /* buffer various argv's point into */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000270 struct child_prog *progs; /* array of commands in pipe */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000271 int job_context; /* bitmask defining current context */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000272 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
273 smallint res_word; /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000274};
275
Eric Andersen25f27032001-04-26 23:22:31 +0000276struct close_me {
Eric Andersen25f27032001-04-26 23:22:31 +0000277 struct close_me *next;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000278 int fd;
Eric Andersen25f27032001-04-26 23:22:31 +0000279};
280
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000281/* On program start, environ points to initial environment.
282 * putenv adds new pointers into it, unsetenv removes them.
283 * Neither of these (de)allocates the strings.
284 * setenv allocates new strings in malloc space and does putenv,
285 * and thus setenv is unusable (leaky) for shell's purposes */
286#define setenv(...) setenv_is_leaky_dont_use()
287struct variable {
288 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000289 char *varstr; /* points to "name=" portion */
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000290 int max_len; /* if > 0, name is part of initial env; else name is malloced */
291 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000292 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000293};
294
Eric Andersen25f27032001-04-26 23:22:31 +0000295typedef struct {
296 char *data;
297 int length;
298 int maxlen;
299 int quote;
300 int nonnull;
301} o_string;
302#define NULL_O_STRING {NULL,0,0,0,0}
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000303/* used for initialization: o_string foo = NULL_O_STRING; */
Eric Andersen25f27032001-04-26 23:22:31 +0000304
305/* I can almost use ordinary FILE *. Is open_memstream() universally
306 * available? Where is it documented? */
307struct in_str {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +0000308 const char *p;
309 /* eof_flag=1: last char in ->p is really an EOF */
310 char eof_flag; /* meaningless if ->p == NULL */
311 char peek_buf[2];
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000312#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000313 smallint promptme;
314 smallint promptmode; /* 0: PS1, 1: PS2 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000315#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000316 FILE *file;
317 int (*get) (struct in_str *);
318 int (*peek) (struct in_str *);
319};
320#define b_getch(input) ((input)->get(input))
321#define b_peek(input) ((input)->peek(input))
322
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000323enum {
324 CHAR_ORDINARY = 0,
325 CHAR_ORDINARY_IF_QUOTED = 1, /* example: *, # */
326 CHAR_IFS = 2, /* treated as ordinary if quoted */
327 CHAR_SPECIAL = 3, /* example: $ */
Eric Andersen25f27032001-04-26 23:22:31 +0000328};
329
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000330#define HUSH_VER_STR "0.02"
331
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000332/* "Globals" within this file */
333
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000334/* Sorted roughly by size (smaller offsets == smaller code) */
335struct globals {
336#if ENABLE_HUSH_INTERACTIVE
337 /* 'interactive_fd' is a fd# open to ctty, if we have one
338 * _AND_ if we decided to act interactively */
339 int interactive_fd;
340 const char *PS1;
341 const char *PS2;
342#endif
343#if ENABLE_FEATURE_EDITING
344 line_input_t *line_input_state;
345#endif
346#if ENABLE_HUSH_JOB
347 int run_list_level;
348 pid_t saved_task_pgrp;
349 pid_t saved_tty_pgrp;
350 int last_jobid;
351 struct pipe *job_list;
352 struct pipe *toplevel_list;
353 smallint ctrl_z_flag;
354#endif
355 smallint fake_mode;
356 /* these three support $?, $#, and $1 */
357 char **global_argv;
358 int global_argc;
359 int last_return_code;
360 const char *ifs;
361 struct close_me *close_me_head;
362 const char *cwd;
363 unsigned last_bg_pid;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +0000364 struct variable *top_var; /* = &shell_ver (set in main()) */
365 struct variable shell_ver;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000366#if ENABLE_FEATURE_SH_STANDALONE
367 struct nofork_save_area nofork_save;
368#endif
369#if ENABLE_HUSH_JOB
370 sigjmp_buf toplevel_jb;
371#endif
372 unsigned char charmap[256];
373 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
374};
375
376#define G (*ptr_to_globals)
377
378#if !ENABLE_HUSH_INTERACTIVE
379enum { interactive_fd = 0 };
380#endif
381#if !ENABLE_HUSH_JOB
382enum { run_list_level = 0 };
383#endif
384
385#if ENABLE_HUSH_INTERACTIVE
386#define interactive_fd (G.interactive_fd )
387#define PS1 (G.PS1 )
388#define PS2 (G.PS2 )
389#endif
390#if ENABLE_FEATURE_EDITING
391#define line_input_state (G.line_input_state)
392#endif
393#if ENABLE_HUSH_JOB
394#define run_list_level (G.run_list_level )
395#define saved_task_pgrp (G.saved_task_pgrp )
396#define saved_tty_pgrp (G.saved_tty_pgrp )
397#define last_jobid (G.last_jobid )
398#define job_list (G.job_list )
399#define toplevel_list (G.toplevel_list )
400#define toplevel_jb (G.toplevel_jb )
401#define ctrl_z_flag (G.ctrl_z_flag )
402#endif /* JOB */
403#define global_argv (G.global_argv )
404#define global_argc (G.global_argc )
405#define last_return_code (G.last_return_code)
406#define ifs (G.ifs )
407#define fake_mode (G.fake_mode )
408#define close_me_head (G.close_me_head )
409#define cwd (G.cwd )
410#define last_bg_pid (G.last_bg_pid )
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000411#define top_var (G.top_var )
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000412#define shell_ver (G.shell_ver )
413#if ENABLE_FEATURE_SH_STANDALONE
414#define nofork_save (G.nofork_save )
415#endif
416#if ENABLE_HUSH_JOB
417#define toplevel_jb (G.toplevel_jb )
418#endif
419#define charmap (G.charmap )
420#define user_input_buf (G.user_input_buf )
421
422
423#define B_CHUNK 100
424#define B_NOSPAC 1
425#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
426
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000427#if 1
428/* Normal */
429static void syntax(const char *msg)
430{
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000431 /* Was using fancy stuff:
432 * (interactive_fd ? bb_error_msg : bb_error_msg_and_die)(...params...)
433 * but it SEGVs. ?! Oh well... explicit temp ptr works around that */
434 void (*fp)(const char *s, ...);
435
436 fp = (interactive_fd ? bb_error_msg : bb_error_msg_and_die);
437 fp(msg ? "%s: %s" : "syntax error", "syntax error", msg);
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000438}
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000439
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000440#else
441/* Debug */
442static void syntax_lineno(int line)
Denis Vlasenkob6aae0f2007-01-29 22:51:25 +0000443{
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000444 void (*fp)(const char *s, ...);
445
446 fp = (interactive_fd ? bb_error_msg : bb_error_msg_and_die);
447 fp("syntax error hush.c:%d", line);
Eric Andersen25f27032001-04-26 23:22:31 +0000448}
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000449#define syntax(str) syntax_lineno(__LINE__)
450#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000451
452/* Index of subroutines: */
453/* function prototypes for builtins */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000454static int builtin_cd(char **argv);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000455static int builtin_eval(char **argv);
456static int builtin_exec(char **argv);
457static int builtin_exit(char **argv);
458static int builtin_export(char **argv);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000459#if ENABLE_HUSH_JOB
Denis Vlasenko1359da62007-04-21 23:27:30 +0000460static int builtin_fg_bg(char **argv);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000461static int builtin_jobs(char **argv);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000462#endif
Denis Vlasenko06810332007-05-21 23:30:54 +0000463#if ENABLE_HUSH_HELP
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000464static int builtin_help(char **argv);
Denis Vlasenko06810332007-05-21 23:30:54 +0000465#endif
Denis Vlasenko1359da62007-04-21 23:27:30 +0000466static int builtin_pwd(char **argv);
467static int builtin_read(char **argv);
468static int builtin_set(char **argv);
469static int builtin_shift(char **argv);
470static int builtin_source(char **argv);
471static int builtin_umask(char **argv);
472static int builtin_unset(char **argv);
Denis Vlasenko06810332007-05-21 23:30:54 +0000473//static int builtin_not_written(char **argv);
Eric Andersen25f27032001-04-26 23:22:31 +0000474/* o_string manipulation: */
475static int b_check_space(o_string *o, int len);
476static int b_addchr(o_string *o, int ch);
477static void b_reset(o_string *o);
478static int b_addqchr(o_string *o, int ch, int quote);
Eric Andersen25f27032001-04-26 23:22:31 +0000479/* in_str manipulations: */
480static int static_get(struct in_str *i);
481static int static_peek(struct in_str *i);
482static int file_get(struct in_str *i);
483static int file_peek(struct in_str *i);
484static void setup_file_in_str(struct in_str *i, FILE *f);
485static void setup_string_in_str(struct in_str *i, const char *s);
486/* close_me manipulations: */
487static void mark_open(int fd);
488static void mark_closed(int fd);
Eric Anderseneaecbf32001-10-31 10:41:31 +0000489static void close_all(void);
Eric Andersen25f27032001-04-26 23:22:31 +0000490/* "run" the final data structures: */
Denis Vlasenkoc666f712007-05-16 22:18:54 +0000491#if !defined(DEBUG_CLEAN)
492#define free_pipe_list(head, indent) free_pipe_list(head)
493#define free_pipe(pi, indent) free_pipe(pi)
494#endif
Eric Andersenbf7df042001-05-23 22:18:35 +0000495static int free_pipe_list(struct pipe *head, int indent);
496static int free_pipe(struct pipe *pi, int indent);
Eric Andersen25f27032001-04-26 23:22:31 +0000497/* really run the final data structures: */
498static int setup_redirects(struct child_prog *prog, int squirrel[]);
Eric Andersen25f27032001-04-26 23:22:31 +0000499static int run_list_real(struct pipe *pi);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000500static void pseudo_exec_argv(char **argv) ATTRIBUTE_NORETURN;
Bernhard Reutner-Fischer86f5c992006-01-22 22:55:11 +0000501static void pseudo_exec(struct child_prog *child) ATTRIBUTE_NORETURN;
Eric Andersen25f27032001-04-26 23:22:31 +0000502static int run_pipe_real(struct pipe *pi);
503/* extended glob support: */
504static int globhack(const char *src, int flags, glob_t *pglob);
505static int glob_needed(const char *s);
506static int xglob(o_string *dest, int flags, glob_t *pglob);
Eric Andersen78a7c992001-05-15 16:30:25 +0000507/* variable assignment: */
Eric Andersen78a7c992001-05-15 16:30:25 +0000508static int is_assignment(const char *s);
Eric Andersen25f27032001-04-26 23:22:31 +0000509/* data structure manipulation: */
510static int setup_redirect(struct p_context *ctx, int fd, redir_type style, struct in_str *input);
511static void initialize_context(struct p_context *ctx);
512static int done_word(o_string *dest, struct p_context *ctx);
513static int done_command(struct p_context *ctx);
514static int done_pipe(struct p_context *ctx, pipe_style type);
515/* primary string parsing: */
516static int redirect_dup_num(struct in_str *input);
517static int redirect_opt_num(o_string *o);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +0000518#if ENABLE_HUSH_TICK
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +0000519static int process_command_subs(o_string *dest, struct p_context *ctx, struct in_str *input, const char *subst_end);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +0000520#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000521static int parse_group(o_string *dest, struct p_context *ctx, struct in_str *input, int ch);
Denis Vlasenko15d78fb2007-01-30 22:28:21 +0000522static const char *lookup_param(const char *src);
Eric Andersen25f27032001-04-26 23:22:31 +0000523static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +0000524static 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 +0000525/* setup: */
Denis Vlasenko170435c2007-05-23 13:01:10 +0000526static int parse_and_run_stream(struct in_str *inp, int parse_flag);
527static int parse_and_run_string(const char *s, int parse_flag);
528static int parse_and_run_file(FILE *f);
Eric Andersenbafd94f2001-05-02 16:11:59 +0000529/* job management: */
Eric Andersenc798b072001-06-22 06:23:03 +0000530static int checkjobs(struct pipe* fg_pipe);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000531#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +0000532static int checkjobs_and_fg_shell(struct pipe* fg_pipe);
Eric Andersenbafd94f2001-05-02 16:11:59 +0000533static void insert_bg_job(struct pipe *pi);
534static void remove_bg_job(struct pipe *pi);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000535static void delete_finished_bg_job(struct pipe *pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000536#else
537int checkjobs_and_fg_shell(struct pipe* fg_pipe); /* never called */
538#endif
Eric Andersenf72f5622001-05-15 23:21:41 +0000539/* local variable support */
Denis Vlasenko170435c2007-05-23 13:01:10 +0000540static char **expand_strvec_to_strvec(char **argv);
541/* used for eval */
542static char *expand_strvec_to_string(char **argv);
Denis Vlasenkob6a741f2007-05-17 14:38:17 +0000543/* used for expansion of right hand of assignments */
Denis Vlasenko170435c2007-05-23 13:01:10 +0000544static char *expand_string_to_string(const char *str);
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000545static struct variable *get_local_var(const char *name);
546static int set_local_var(char *str, int flg_export);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +0000547static void unset_local_var(const char *name);
Eric Andersen25f27032001-04-26 23:22:31 +0000548
549/* Table of built-in functions. They can be forked or not, depending on
550 * context: within pipes, they fork. As simple commands, they do not.
551 * When used in non-forking context, they can change global variables
Denis Vlasenkoe1a0d482006-10-20 13:28:22 +0000552 * in the parent shell process. If forked, of course they cannot.
Eric Andersen25f27032001-04-26 23:22:31 +0000553 * For example, 'unset foo | whatever' will parse and run, but foo will
554 * still be set at the end. */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000555struct built_in_command {
556 const char *cmd; /* name */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000557 int (*function) (char **argv); /* function ptr */
Denis Vlasenko06810332007-05-21 23:30:54 +0000558#if ENABLE_HUSH_HELP
559 const char *descr; /* description */
560#define BLTIN(cmd, func, help) { cmd, func, help }
561#else
562#define BLTIN(cmd, func, help) { cmd, func }
563#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000564};
565
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +0000566static const struct built_in_command bltins[] = {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000567#if ENABLE_HUSH_JOB
Denis Vlasenko06810332007-05-21 23:30:54 +0000568 BLTIN("bg" , builtin_fg_bg, "Resume a job in the background"),
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000569#endif
Denis Vlasenko06810332007-05-21 23:30:54 +0000570// BLTIN("break" , builtin_not_written, "Exit for, while or until loop"),
571 BLTIN("cd" , builtin_cd, "Change working directory"),
572// BLTIN("continue", builtin_not_written, "Continue for, while or until loop"),
573 BLTIN("eval" , builtin_eval, "Construct and run shell command"),
574 BLTIN("exec" , builtin_exec, "Exec command, replacing this shell with the exec'd process"),
575 BLTIN("exit" , builtin_exit, "Exit from shell"),
576 BLTIN("export", builtin_export, "Set environment variable"),
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000577#if ENABLE_HUSH_JOB
Denis Vlasenko06810332007-05-21 23:30:54 +0000578 BLTIN("fg" , builtin_fg_bg, "Bring job into the foreground"),
579 BLTIN("jobs" , builtin_jobs, "Lists the active jobs"),
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000580#endif
Denis Vlasenko06810332007-05-21 23:30:54 +0000581// TODO: remove pwd? we have it as an applet...
582 BLTIN("pwd" , builtin_pwd, "Print current directory"),
583 BLTIN("read" , builtin_read, "Input environment variable"),
584// BLTIN("return", builtin_not_written, "Return from a function"),
585 BLTIN("set" , builtin_set, "Set/unset shell local variables"),
586 BLTIN("shift" , builtin_shift, "Shift positional parameters"),
587// BLTIN("trap" , builtin_not_written, "Trap signals"),
588// BLTIN("ulimit", builtin_not_written, "Controls resource limits"),
589 BLTIN("umask" , builtin_umask, "Sets file creation mask"),
590 BLTIN("unset" , builtin_unset, "Unset environment variable"),
591 BLTIN("." , builtin_source, "Source-in and run commands in a file"),
592#if ENABLE_HUSH_HELP
593 BLTIN("help" , builtin_help, "List shell built-in commands"),
594#endif
595 BLTIN(NULL, NULL, NULL)
Eric Andersen25f27032001-04-26 23:22:31 +0000596};
597
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000598#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000599
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000600/* move to libbb? */
601static void signal_SA_RESTART(int sig, void (*handler)(int))
602{
603 struct sigaction sa;
604 sa.sa_handler = handler;
605 sa.sa_flags = SA_RESTART;
606 sigemptyset(&sa.sa_mask);
607 sigaction(sig, &sa, NULL);
608}
609
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000610/* Signals are grouped, we handle them in batches */
611static void set_fatal_sighandler(void (*handler)(int))
612{
613 signal(SIGILL , handler);
614 signal(SIGTRAP, handler);
615 signal(SIGABRT, handler);
616 signal(SIGFPE , handler);
617 signal(SIGBUS , handler);
618 signal(SIGSEGV, handler);
619 /* bash 3.2 seems to handle these just like 'fatal' ones */
620 signal(SIGHUP , handler);
621 signal(SIGPIPE, handler);
622 signal(SIGALRM, handler);
623}
624static void set_jobctrl_sighandler(void (*handler)(int))
625{
626 signal(SIGTSTP, handler);
627 signal(SIGTTIN, handler);
628 signal(SIGTTOU, handler);
629}
630static void set_misc_sighandler(void (*handler)(int))
631{
632 signal(SIGINT , handler);
633 signal(SIGQUIT, handler);
634 signal(SIGTERM, handler);
635}
636/* SIGCHLD is special and handled separately */
637
638static void set_every_sighandler(void (*handler)(int))
639{
640 set_fatal_sighandler(handler);
641 set_jobctrl_sighandler(handler);
642 set_misc_sighandler(handler);
643 signal(SIGCHLD, handler);
644}
645
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000646static void handler_ctrl_c(int sig)
647{
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000648 debug_printf_jobs("got sig %d\n", sig);
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000649// as usual we can have all kinds of nasty problems with leaked malloc data here
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000650 siglongjmp(toplevel_jb, 1);
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000651}
652
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000653static void handler_ctrl_z(int sig)
654{
655 pid_t pid;
656
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000657 debug_printf_jobs("got tty sig %d in pid %d\n", sig, getpid());
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000658 pid = fork();
Denis Vlasenkoc2990322007-05-16 12:57:12 +0000659 if (pid < 0) /* can't fork. Pretend there was no ctrl-Z */
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000660 return;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000661 ctrl_z_flag = 1;
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000662 if (!pid) { /* child */
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000663 setpgrp();
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000664 debug_printf_jobs("set pgrp for child %d ok\n", getpid());
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000665 set_every_sighandler(SIG_DFL);
Denis Vlasenko18e19f22007-04-28 16:43:18 +0000666 raise(SIGTSTP); /* resend TSTP so that child will be stopped */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000667 debug_printf_jobs("returning in child\n");
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000668 /* return to nofork, it will eventually exit now,
669 * not return back to shell */
670 return;
671 }
672 /* parent */
673 /* finish filling up pipe info */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000674 toplevel_list->pgrp = pid; /* child is in its own pgrp */
675 toplevel_list->progs[0].pid = pid;
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000676 /* parent needs to longjmp out of running nofork.
677 * we will "return" exitcode 0, with child put in background */
678// as usual we can have all kinds of nasty problems with leaked malloc data here
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000679 debug_printf_jobs("siglongjmp in parent\n");
680 siglongjmp(toplevel_jb, 1);
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000681}
682
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000683/* Restores tty foreground process group, and exits.
684 * May be called as signal handler for fatal signal
685 * (will faithfully resend signal to itself, producing correct exit state)
686 * or called directly with -EXITCODE.
687 * We also call it if xfunc is exiting. */
688static void sigexit(int sig) ATTRIBUTE_NORETURN;
689static void sigexit(int sig)
690{
691 sigset_t block_all;
692
693 /* Disable all signals: job control, SIGPIPE, etc. */
694 sigfillset(&block_all);
695 sigprocmask(SIG_SETMASK, &block_all, NULL);
696
Denis Vlasenko87cb2db2007-04-21 10:00:01 +0000697 if (interactive_fd)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000698 tcsetpgrp(interactive_fd, saved_tty_pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000699
700 /* Not a signal, just exit */
701 if (sig <= 0)
702 _exit(- sig);
703
704 /* Enable only this sig and kill ourself with it */
705 signal(sig, SIG_DFL);
706 sigdelset(&block_all, sig);
707 sigprocmask(SIG_SETMASK, &block_all, NULL);
708 raise(sig);
709 _exit(1); /* Should not reach it */
710}
711
712/* Restores tty foreground process group, and exits. */
713static void hush_exit(int exitcode) ATTRIBUTE_NORETURN;
714static void hush_exit(int exitcode)
715{
716 fflush(NULL); /* flush all streams */
717 sigexit(- (exitcode & 0xff));
718}
719
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000720#else /* !JOB */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000721
722#define set_fatal_sighandler(handler) ((void)0)
723#define set_jobctrl_sighandler(handler) ((void)0)
724#define set_misc_sighandler(handler) ((void)0)
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000725#define hush_exit(e) exit(e)
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000726
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000727#endif /* JOB */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000728
729
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000730static const char *set_cwd(void)
731{
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000732 if (cwd == bb_msg_unknown)
Denis Vlasenko7cced6e2007-04-12 17:08:53 +0000733 cwd = NULL; /* xrealloc_getcwd_or_warn(arg) calls free(arg)! */
Denis Vlasenko6ca04442007-02-11 16:19:28 +0000734 cwd = xrealloc_getcwd_or_warn((char *)cwd);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000735 if (!cwd)
Manuel Novoa III cad53642003-03-19 09:13:01 +0000736 cwd = bb_msg_unknown;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000737 return cwd;
738}
739
Eric Andersen4c9b68f2002-04-13 12:33:41 +0000740/* built-in 'eval' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000741static int builtin_eval(char **argv)
Eric Andersen4c9b68f2002-04-13 12:33:41 +0000742{
Eric Andersen4c9b68f2002-04-13 12:33:41 +0000743 int rcode = EXIT_SUCCESS;
Eric Andersenc7bda1c2004-03-15 08:29:22 +0000744
Denis Vlasenko1359da62007-04-21 23:27:30 +0000745 if (argv[1]) {
Denis Vlasenko170435c2007-05-23 13:01:10 +0000746 char *str = expand_strvec_to_string(argv + 1);
747 parse_and_run_string(str, PARSEFLAG_EXIT_FROM_LOOP |
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000748 PARSEFLAG_SEMICOLON);
Eric Andersen4c9b68f2002-04-13 12:33:41 +0000749 free(str);
750 rcode = last_return_code;
751 }
752 return rcode;
753}
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000754
Eric Andersen25f27032001-04-26 23:22:31 +0000755/* built-in 'cd <path>' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000756static int builtin_cd(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000757{
Denis Vlasenko170435c2007-05-23 13:01:10 +0000758 const char *newdir;
Denis Vlasenko1359da62007-04-21 23:27:30 +0000759 if (argv[1] == NULL)
Denis Vlasenko170435c2007-05-23 13:01:10 +0000760 newdir = getenv("HOME") ? : "/";
Eric Andersen25f27032001-04-26 23:22:31 +0000761 else
Denis Vlasenko1359da62007-04-21 23:27:30 +0000762 newdir = argv[1];
Eric Andersen25f27032001-04-26 23:22:31 +0000763 if (chdir(newdir)) {
764 printf("cd: %s: %s\n", newdir, strerror(errno));
765 return EXIT_FAILURE;
766 }
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000767 set_cwd();
Eric Andersen25f27032001-04-26 23:22:31 +0000768 return EXIT_SUCCESS;
769}
770
Eric Andersen25f27032001-04-26 23:22:31 +0000771/* built-in 'exec' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000772static int builtin_exec(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000773{
Denis Vlasenko1359da62007-04-21 23:27:30 +0000774 if (argv[1] == NULL)
Eric Andersen25f27032001-04-26 23:22:31 +0000775 return EXIT_SUCCESS; /* Really? */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000776 pseudo_exec_argv(argv + 1);
Eric Andersen25f27032001-04-26 23:22:31 +0000777 /* never returns */
778}
779
780/* built-in 'exit' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000781static int builtin_exit(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000782{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000783// TODO: bash does it ONLY on top-level sh exit (+interacive only?)
784 //puts("exit"); /* bash does it */
Denis Vlasenkof2fffd02007-05-02 23:39:04 +0000785// TODO: warn if we have background jobs: "There are stopped jobs"
786// On second consecutive 'exit', exit anyway.
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000787
Denis Vlasenko1359da62007-04-21 23:27:30 +0000788 if (argv[1] == NULL)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000789 hush_exit(last_return_code);
Denis Vlasenko5f786c22007-04-20 08:35:45 +0000790 /* mimic bash: exit 123abc == exit 255 + error msg */
791 xfunc_error_retval = 255;
792 /* bash: exit -2 == exit 254, no error msg */
Denis Vlasenkof2fffd02007-05-02 23:39:04 +0000793 hush_exit(xatoi(argv[1]) & 0xff);
Eric Andersen25f27032001-04-26 23:22:31 +0000794}
795
796/* built-in 'export VAR=value' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000797static int builtin_export(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000798{
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000799 const char *value;
Denis Vlasenko1359da62007-04-21 23:27:30 +0000800 char *name = argv[1];
Eric Andersen25f27032001-04-26 23:22:31 +0000801
Eric Andersenf72f5622001-05-15 23:21:41 +0000802 if (name == NULL) {
Denis Vlasenkof2fffd02007-05-02 23:39:04 +0000803 // TODO:
804 // ash emits: export VAR='VAL'
805 // bash: declare -x VAR="VAL"
806 // (both also escape as needed (quotes, $, etc))
807 char **e = environ;
808 if (e)
809 while (*e)
810 puts(*e++);
811 return EXIT_SUCCESS;
Eric Andersen25f27032001-04-26 23:22:31 +0000812 }
Eric Andersenf72f5622001-05-15 23:21:41 +0000813
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000814 value = strchr(name, '=');
815 if (!value) {
816 /* They are exporting something without a =VALUE */
817 struct variable *var;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000818
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000819 var = get_local_var(name);
820 if (var) {
821 var->flg_export = 1;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000822 putenv(var->varstr);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000823 }
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000824 /* bash does not return an error when trying to export
825 * an undefined variable. Do likewise. */
826 return EXIT_SUCCESS;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000827 }
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000828
829 set_local_var(xstrdup(name), 1);
830 return EXIT_SUCCESS;
Eric Andersen25f27032001-04-26 23:22:31 +0000831}
832
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000833#if ENABLE_HUSH_JOB
Eric Andersen25f27032001-04-26 23:22:31 +0000834/* built-in 'fg' and 'bg' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000835static int builtin_fg_bg(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000836{
Eric Andersen0fcd4472001-05-02 20:12:03 +0000837 int i, jobnum;
Denis Vlasenko8a28e622007-04-14 11:16:29 +0000838 struct pipe *pi;
Eric Andersen25f27032001-04-26 23:22:31 +0000839
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000840 if (!interactive_fd)
Eric Andersenc798b072001-06-22 06:23:03 +0000841 return EXIT_FAILURE;
Eric Andersen0fcd4472001-05-02 20:12:03 +0000842 /* If they gave us no args, assume they want the last backgrounded task */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000843 if (!argv[1]) {
Eric Andersenc798b072001-06-22 06:23:03 +0000844 for (pi = job_list; pi; pi = pi->next) {
845 if (pi->jobid == last_jobid) {
Denis Vlasenko8a28e622007-04-14 11:16:29 +0000846 goto found;
Eric Andersen0fcd4472001-05-02 20:12:03 +0000847 }
848 }
Denis Vlasenko1359da62007-04-21 23:27:30 +0000849 bb_error_msg("%s: no current job", argv[0]);
Denis Vlasenko8a28e622007-04-14 11:16:29 +0000850 return EXIT_FAILURE;
851 }
Denis Vlasenko1359da62007-04-21 23:27:30 +0000852 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
853 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
Denis Vlasenko8a28e622007-04-14 11:16:29 +0000854 return EXIT_FAILURE;
855 }
856 for (pi = job_list; pi; pi = pi->next) {
857 if (pi->jobid == jobnum) {
858 goto found;
Eric Andersen25f27032001-04-26 23:22:31 +0000859 }
860 }
Denis Vlasenko1359da62007-04-21 23:27:30 +0000861 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
Denis Vlasenko8a28e622007-04-14 11:16:29 +0000862 return EXIT_FAILURE;
863 found:
Denis Vlasenko52881e92007-04-21 13:42:52 +0000864 // TODO: bash prints a string representation
865 // of job being foregrounded (like "sleep 1 | cat")
Denis Vlasenko1359da62007-04-21 23:27:30 +0000866 if (*argv[0] == 'f') {
Eric Andersen028b65b2001-06-28 01:10:11 +0000867 /* Put the job into the foreground. */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000868 tcsetpgrp(interactive_fd, pi->pgrp);
Eric Andersen25f27032001-04-26 23:22:31 +0000869 }
870
871 /* Restart the processes in the job */
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000872 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_progs, pi->pgrp);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000873 for (i = 0; i < pi->num_progs; i++) {
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000874 debug_printf_jobs("reviving pid %d\n", pi->progs[i].pid);
Eric Andersen0fcd4472001-05-02 20:12:03 +0000875 pi->progs[i].is_stopped = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +0000876 }
877 pi->stopped_progs = 0;
Eric Andersen25f27032001-04-26 23:22:31 +0000878
Denis Vlasenkobb81c582007-01-30 22:32:09 +0000879 i = kill(- pi->pgrp, SIGCONT);
880 if (i < 0) {
Denis Vlasenko8a28e622007-04-14 11:16:29 +0000881 if (errno == ESRCH) {
Denis Vlasenko1359da62007-04-21 23:27:30 +0000882 delete_finished_bg_job(pi);
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000883 return EXIT_SUCCESS;
Eric Andersen028b65b2001-06-28 01:10:11 +0000884 } else {
Manuel Novoa III cad53642003-03-19 09:13:01 +0000885 bb_perror_msg("kill (SIGCONT)");
Eric Andersen028b65b2001-06-28 01:10:11 +0000886 }
887 }
Eric Andersen25f27032001-04-26 23:22:31 +0000888
Denis Vlasenko1359da62007-04-21 23:27:30 +0000889 if (*argv[0] == 'f') {
890 remove_bg_job(pi);
Denis Vlasenko52881e92007-04-21 13:42:52 +0000891 return checkjobs_and_fg_shell(pi);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000892 }
Eric Andersen25f27032001-04-26 23:22:31 +0000893 return EXIT_SUCCESS;
894}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000895#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000896
897/* built-in 'help' handler */
Denis Vlasenko06810332007-05-21 23:30:54 +0000898#if ENABLE_HUSH_HELP
Denis Vlasenko1359da62007-04-21 23:27:30 +0000899static int builtin_help(char **argv ATTRIBUTE_UNUSED)
Eric Andersen25f27032001-04-26 23:22:31 +0000900{
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +0000901 const struct built_in_command *x;
Eric Andersen25f27032001-04-26 23:22:31 +0000902
903 printf("\nBuilt-in commands:\n");
904 printf("-------------------\n");
905 for (x = bltins; x->cmd; x++) {
Eric Andersen25f27032001-04-26 23:22:31 +0000906 printf("%s\t%s\n", x->cmd, x->descr);
907 }
908 printf("\n\n");
909 return EXIT_SUCCESS;
910}
Denis Vlasenko06810332007-05-21 23:30:54 +0000911#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000912
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000913#if ENABLE_HUSH_JOB
Eric Andersen25f27032001-04-26 23:22:31 +0000914/* built-in 'jobs' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000915static int builtin_jobs(char **argv ATTRIBUTE_UNUSED)
Eric Andersen25f27032001-04-26 23:22:31 +0000916{
917 struct pipe *job;
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000918 const char *status_string;
Eric Andersen25f27032001-04-26 23:22:31 +0000919
Eric Andersenc798b072001-06-22 06:23:03 +0000920 for (job = job_list; job; job = job->next) {
Eric Andersen25f27032001-04-26 23:22:31 +0000921 if (job->running_progs == job->stopped_progs)
922 status_string = "Stopped";
923 else
924 status_string = "Running";
Eric Andersen52a97ca2001-06-22 06:49:26 +0000925
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000926 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
Eric Andersen25f27032001-04-26 23:22:31 +0000927 }
928 return EXIT_SUCCESS;
929}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000930#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000931
Eric Andersen25f27032001-04-26 23:22:31 +0000932/* built-in 'pwd' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000933static int builtin_pwd(char **argv ATTRIBUTE_UNUSED)
Eric Andersen25f27032001-04-26 23:22:31 +0000934{
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000935 puts(set_cwd());
Eric Andersen25f27032001-04-26 23:22:31 +0000936 return EXIT_SUCCESS;
937}
938
939/* built-in 'read VAR' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000940static int builtin_read(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000941{
Denis Vlasenko3e7b0e62007-05-16 12:52:15 +0000942 char string[BUFSIZ];
943 char *p;
944 const char *name = argv[1] ? argv[1] : "REPLY";
945 int name_len = strlen(name);
Eric Andersen25f27032001-04-26 23:22:31 +0000946
Denis Vlasenko3e7b0e62007-05-16 12:52:15 +0000947 if (name_len >= sizeof(string) - 2)
948 return EXIT_FAILURE;
949 strcpy(string, name);
950 p = string + name_len;
951 *p++ = '=';
952 *p = '\0'; /* In case stdin has only EOF */
953 /* read string. name_len+1 chars are already used by 'name=' */
954 fgets(p, sizeof(string) - 1 - name_len, stdin);
955 chomp(p);
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000956 return set_local_var(xstrdup(string), 0);
Eric Andersen25f27032001-04-26 23:22:31 +0000957}
958
Denis Vlasenko3e7b0e62007-05-16 12:52:15 +0000959/* built-in 'set [VAR=value]' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000960static int builtin_set(char **argv)
Eric Andersenf72f5622001-05-15 23:21:41 +0000961{
Denis Vlasenko1359da62007-04-21 23:27:30 +0000962 char *temp = argv[1];
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000963 struct variable *e;
Eric Andersenf72f5622001-05-15 23:21:41 +0000964
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000965 if (temp == NULL)
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000966 for (e = top_var; e; e = e->next)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000967 puts(e->varstr);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000968 else
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000969 set_local_var(xstrdup(temp), 0);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000970
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000971 return EXIT_SUCCESS;
Eric Andersenf72f5622001-05-15 23:21:41 +0000972}
973
974
Eric Andersen25f27032001-04-26 23:22:31 +0000975/* Built-in 'shift' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000976static int builtin_shift(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000977{
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000978 int n = 1;
Denis Vlasenko1359da62007-04-21 23:27:30 +0000979 if (argv[1]) {
980 n = atoi(argv[1]);
Eric Andersen25f27032001-04-26 23:22:31 +0000981 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000982 if (n >= 0 && n < global_argc) {
Denis Vlasenko004baba2007-05-20 22:22:18 +0000983 global_argv[n] = global_argv[0];
Eric Andersen25f27032001-04-26 23:22:31 +0000984 global_argc -= n;
985 global_argv += n;
986 return EXIT_SUCCESS;
Eric Andersen25f27032001-04-26 23:22:31 +0000987 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +0000988 return EXIT_FAILURE;
Eric Andersen25f27032001-04-26 23:22:31 +0000989}
990
991/* Built-in '.' handler (read-in and execute commands from file) */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000992static int builtin_source(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000993{
994 FILE *input;
995 int status;
996
Denis Vlasenko1359da62007-04-21 23:27:30 +0000997 if (argv[1] == NULL)
Eric Andersen25f27032001-04-26 23:22:31 +0000998 return EXIT_FAILURE;
999
1000 /* XXX search through $PATH is missing */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001001 input = fopen(argv[1], "r");
Eric Andersen25f27032001-04-26 23:22:31 +00001002 if (!input) {
Denis Vlasenko1359da62007-04-21 23:27:30 +00001003 bb_error_msg("cannot open '%s'", argv[1]);
Eric Andersen25f27032001-04-26 23:22:31 +00001004 return EXIT_FAILURE;
1005 }
1006
1007 /* Now run the file */
1008 /* XXX argv and argc are broken; need to save old global_argv
1009 * (pointer only is OK!) on this stack frame,
Denis Vlasenko1359da62007-04-21 23:27:30 +00001010 * set global_argv=argv+1, recurse, and restore. */
Eric Andersen25f27032001-04-26 23:22:31 +00001011 mark_open(fileno(input));
Denis Vlasenko170435c2007-05-23 13:01:10 +00001012 status = parse_and_run_file(input);
Eric Andersen25f27032001-04-26 23:22:31 +00001013 mark_closed(fileno(input));
1014 fclose(input);
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00001015 return status;
Eric Andersen25f27032001-04-26 23:22:31 +00001016}
1017
Denis Vlasenko1359da62007-04-21 23:27:30 +00001018static int builtin_umask(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00001019{
Eric Andersen83a2ae22001-05-07 17:59:25 +00001020 mode_t new_umask;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001021 const char *arg = argv[1];
Eric Andersen83a2ae22001-05-07 17:59:25 +00001022 char *end;
1023 if (arg) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001024 new_umask = strtoul(arg, &end, 8);
1025 if (*end != '\0' || end == arg) {
Eric Andersen83a2ae22001-05-07 17:59:25 +00001026 return EXIT_FAILURE;
1027 }
1028 } else {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001029 new_umask = umask(0);
1030 printf("%.3o\n", (unsigned) new_umask);
Eric Andersen83a2ae22001-05-07 17:59:25 +00001031 }
1032 umask(new_umask);
1033 return EXIT_SUCCESS;
Eric Andersen25f27032001-04-26 23:22:31 +00001034}
1035
1036/* built-in 'unset VAR' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001037static int builtin_unset(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00001038{
Denis Vlasenko3e7b0e62007-05-16 12:52:15 +00001039 /* bash always returns true */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001040 unset_local_var(argv[1]);
Eric Andersen25f27032001-04-26 23:22:31 +00001041 return EXIT_SUCCESS;
1042}
1043
Denis Vlasenko06810332007-05-21 23:30:54 +00001044//static int builtin_not_written(char **argv)
1045//{
1046// printf("builtin_%s not written\n", argv[0]);
1047// return EXIT_FAILURE;
1048//}
Eric Andersen83a2ae22001-05-07 17:59:25 +00001049
Eric Andersen25f27032001-04-26 23:22:31 +00001050static int b_check_space(o_string *o, int len)
1051{
1052 /* It would be easy to drop a more restrictive policy
1053 * in here, such as setting a maximum string length */
1054 if (o->length + len > o->maxlen) {
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001055 /* assert(data == NULL || o->maxlen != 0); */
Denis Vlasenkoef36ead2007-05-02 15:34:47 +00001056 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001057 o->data = xrealloc(o->data, 1 + o->maxlen);
Eric Andersen25f27032001-04-26 23:22:31 +00001058 }
1059 return o->data == NULL;
1060}
1061
1062static int b_addchr(o_string *o, int ch)
1063{
Denis Vlasenko831dcc42007-05-16 15:05:36 +00001064 debug_printf("b_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001065 if (b_check_space(o, 1))
1066 return B_NOSPAC;
Eric Andersen25f27032001-04-26 23:22:31 +00001067 o->data[o->length] = ch;
1068 o->length++;
1069 o->data[o->length] = '\0';
1070 return 0;
1071}
1072
1073static void b_reset(o_string *o)
1074{
1075 o->length = 0;
1076 o->nonnull = 0;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001077 if (o->data != NULL)
1078 *o->data = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001079}
1080
1081static void b_free(o_string *o)
1082{
1083 b_reset(o);
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00001084 free(o->data);
Eric Andersen25f27032001-04-26 23:22:31 +00001085 o->data = NULL;
1086 o->maxlen = 0;
1087}
1088
1089/* My analysis of quoting semantics tells me that state information
1090 * is associated with a destination, not a source.
1091 */
1092static int b_addqchr(o_string *o, int ch, int quote)
1093{
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00001094 if (quote && strchr("*?[\\", ch)) {
Eric Andersen25f27032001-04-26 23:22:31 +00001095 int rc;
1096 rc = b_addchr(o, '\\');
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001097 if (rc)
1098 return rc;
Eric Andersen25f27032001-04-26 23:22:31 +00001099 }
1100 return b_addchr(o, ch);
1101}
1102
Eric Andersen25f27032001-04-26 23:22:31 +00001103static int static_get(struct in_str *i)
1104{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001105 int ch = *i->p++;
1106 if (ch == '\0') return EOF;
Eric Andersen25f27032001-04-26 23:22:31 +00001107 return ch;
1108}
1109
1110static int static_peek(struct in_str *i)
1111{
1112 return *i->p;
1113}
1114
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001115#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001116#if ENABLE_FEATURE_EDITING
Rob Landley88621d72006-08-29 19:41:06 +00001117static void cmdedit_set_initial_prompt(void)
Eric Andersen25f27032001-04-26 23:22:31 +00001118{
Denis Vlasenko38f63192007-01-22 09:03:07 +00001119#if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
Eric Andersen25f27032001-04-26 23:22:31 +00001120 PS1 = NULL;
1121#else
1122 PS1 = getenv("PS1");
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001123 if (PS1 == NULL)
Eric Andersen25f27032001-04-26 23:22:31 +00001124 PS1 = "\\w \\$ ";
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001125#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001126}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001127#endif /* EDITING */
Eric Andersen25f27032001-04-26 23:22:31 +00001128
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001129static const char* setup_prompt_string(int promptmode)
Eric Andersen25f27032001-04-26 23:22:31 +00001130{
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001131 const char *prompt_str;
1132 debug_printf("setup_prompt_string %d ", promptmode);
Denis Vlasenko38f63192007-01-22 09:03:07 +00001133#if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
Eric Andersen25f27032001-04-26 23:22:31 +00001134 /* Set up the prompt */
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001135 if (promptmode == 0) { /* PS1 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001136 free((char*)PS1);
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001137 PS1 = xasprintf("%s %c ", cwd, (geteuid() != 0) ? '$' : '#');
1138 prompt_str = PS1;
Eric Andersen25f27032001-04-26 23:22:31 +00001139 } else {
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001140 prompt_str = PS2;
Eric Andersen25f27032001-04-26 23:22:31 +00001141 }
1142#else
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001143 prompt_str = (promptmode == 0) ? PS1 : PS2;
Eric Andersenaf44a0e2001-04-27 07:26:12 +00001144#endif
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001145 debug_printf("result '%s'\n", prompt_str);
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001146 return prompt_str;
Eric Andersen25f27032001-04-26 23:22:31 +00001147}
1148
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001149static void get_user_input(struct in_str *i)
Eric Andersen25f27032001-04-26 23:22:31 +00001150{
Denis Vlasenko0937be52007-04-28 16:47:08 +00001151 int r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001152 const char *prompt_str;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001153
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001154 prompt_str = setup_prompt_string(i->promptmode);
Denis Vlasenko38f63192007-01-22 09:03:07 +00001155#if ENABLE_FEATURE_EDITING
Denis Vlasenko170435c2007-05-23 13:01:10 +00001156 /* Enable command line editing only while a command line
1157 * is actually being read; otherwise, we'll end up bequeathing
1158 * atexit() handlers and other unwanted stuff to our
1159 * child processes (rob@sysgo.de) */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001160 r = read_line_input(prompt_str, user_input_buf, BUFSIZ-1, line_input_state);
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001161 i->eof_flag = (r < 0);
1162 if (i->eof_flag) { /* EOF/error detected */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001163 user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1164 user_input_buf[1] = '\0';
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001165 }
Eric Andersen25f27032001-04-26 23:22:31 +00001166#else
1167 fputs(prompt_str, stdout);
1168 fflush(stdout);
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001169 user_input_buf[0] = r = fgetc(i->file);
1170 /*user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001171 i->eof_flag = (r == EOF);
Eric Andersen25f27032001-04-26 23:22:31 +00001172#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001173 i->p = user_input_buf;
Eric Andersen25f27032001-04-26 23:22:31 +00001174}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001175#endif /* INTERACTIVE */
Eric Andersen25f27032001-04-26 23:22:31 +00001176
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001177/* This is the magic location that prints prompts
Eric Andersen25f27032001-04-26 23:22:31 +00001178 * and gets data back from the user */
1179static int file_get(struct in_str *i)
1180{
1181 int ch;
1182
Eric Andersen25f27032001-04-26 23:22:31 +00001183 /* If there is data waiting, eat it up */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001184 if (i->p && *i->p) {
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001185#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001186 take_cached:
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001187#endif
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001188 ch = *i->p++;
1189 if (i->eof_flag && !*i->p)
1190 ch = EOF;
Eric Andersen25f27032001-04-26 23:22:31 +00001191 } else {
1192 /* need to double check i->file because we might be doing something
1193 * more complicated by now, like sourcing or substituting. */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001194#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001195 if (interactive_fd && i->promptme && i->file == stdin) {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001196 do {
1197 get_user_input(i);
1198 } while (!*i->p); /* need non-empty line */
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001199 i->promptmode = 1; /* PS2 */
1200 i->promptme = 0;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001201 goto take_cached;
Eric Andersen25f27032001-04-26 23:22:31 +00001202 }
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001203#endif
1204 ch = fgetc(i->file);
Eric Andersen25f27032001-04-26 23:22:31 +00001205 }
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001206 debug_printf("file_get: got a '%c' %d\n", ch, ch);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001207#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001208 if (ch == '\n')
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001209 i->promptme = 1;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001210#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001211 return ch;
1212}
1213
1214/* All the callers guarantee this routine will never be
1215 * used right after a newline, so prompting is not needed.
1216 */
1217static int file_peek(struct in_str *i)
1218{
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00001219 int ch;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001220 if (i->p && *i->p) {
1221 if (i->eof_flag && !i->p[1])
1222 return EOF;
1223 return *i->p;
Eric Andersen25f27032001-04-26 23:22:31 +00001224 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00001225 ch = fgetc(i->file);
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001226 i->eof_flag = (ch == EOF);
1227 i->peek_buf[0] = ch;
1228 i->peek_buf[1] = '\0';
1229 i->p = i->peek_buf;
1230 debug_printf("file_peek: got a '%c' %d\n", *i->p, *i->p);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00001231 return ch;
Eric Andersen25f27032001-04-26 23:22:31 +00001232}
1233
1234static void setup_file_in_str(struct in_str *i, FILE *f)
1235{
1236 i->peek = file_peek;
1237 i->get = file_get;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001238#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001239 i->promptme = 1;
1240 i->promptmode = 0; /* PS1 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001241#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001242 i->file = f;
1243 i->p = NULL;
1244}
1245
1246static void setup_string_in_str(struct in_str *i, const char *s)
1247{
1248 i->peek = static_peek;
1249 i->get = static_get;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001250#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001251 i->promptme = 1;
1252 i->promptmode = 0; /* PS1 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001253#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001254 i->p = s;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001255 i->eof_flag = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00001256}
1257
1258static void mark_open(int fd)
1259{
1260 struct close_me *new = xmalloc(sizeof(struct close_me));
1261 new->fd = fd;
1262 new->next = close_me_head;
1263 close_me_head = new;
1264}
1265
1266static void mark_closed(int fd)
1267{
1268 struct close_me *tmp;
1269 if (close_me_head == NULL || close_me_head->fd != fd)
Manuel Novoa III cad53642003-03-19 09:13:01 +00001270 bb_error_msg_and_die("corrupt close_me");
Eric Andersen25f27032001-04-26 23:22:31 +00001271 tmp = close_me_head;
1272 close_me_head = close_me_head->next;
1273 free(tmp);
1274}
1275
Eric Anderseneaecbf32001-10-31 10:41:31 +00001276static void close_all(void)
Eric Andersen25f27032001-04-26 23:22:31 +00001277{
1278 struct close_me *c;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001279 for (c = close_me_head; c; c = c->next) {
Eric Andersen25f27032001-04-26 23:22:31 +00001280 close(c->fd);
1281 }
1282 close_me_head = NULL;
1283}
1284
1285/* squirrel != NULL means we squirrel away copies of stdin, stdout,
1286 * and stderr if they are redirected. */
1287static int setup_redirects(struct child_prog *prog, int squirrel[])
1288{
1289 int openfd, mode;
1290 struct redir_struct *redir;
1291
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001292 for (redir = prog->redirects; redir; redir = redir->next) {
Eric Andersen817e73c2001-06-06 17:56:09 +00001293 if (redir->dup == -1 && redir->word.gl_pathv == NULL) {
1294 /* something went wrong in the parse. Pretend it didn't happen */
1295 continue;
1296 }
Eric Andersen25f27032001-04-26 23:22:31 +00001297 if (redir->dup == -1) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001298 mode = redir_table[redir->type].mode;
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001299 openfd = open_or_warn(redir->word.gl_pathv[0], mode);
Eric Andersen25f27032001-04-26 23:22:31 +00001300 if (openfd < 0) {
1301 /* this could get lost if stderr has been redirected, but
1302 bash and ash both lose it as well (though zsh doesn't!) */
Eric Andersen25f27032001-04-26 23:22:31 +00001303 return 1;
1304 }
1305 } else {
1306 openfd = redir->dup;
1307 }
1308
1309 if (openfd != redir->fd) {
1310 if (squirrel && redir->fd < 3) {
1311 squirrel[redir->fd] = dup(redir->fd);
1312 }
Eric Andersen83a2ae22001-05-07 17:59:25 +00001313 if (openfd == -3) {
1314 close(openfd);
1315 } else {
1316 dup2(openfd, redir->fd);
Matt Kraaic616e532001-06-05 16:50:08 +00001317 if (redir->dup == -1)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001318 close(openfd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00001319 }
Eric Andersen25f27032001-04-26 23:22:31 +00001320 }
1321 }
1322 return 0;
1323}
1324
1325static void restore_redirects(int squirrel[])
1326{
1327 int i, fd;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001328 for (i = 0; i < 3; i++) {
Eric Andersen25f27032001-04-26 23:22:31 +00001329 fd = squirrel[i];
1330 if (fd != -1) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00001331 /* We simply die on error */
1332 xmove_fd(fd, i);
Eric Andersen25f27032001-04-26 23:22:31 +00001333 }
1334 }
1335}
1336
Eric Andersenada18ff2001-05-21 16:18:22 +00001337/* never returns */
Eric Andersen94ac2442001-05-22 19:05:18 +00001338/* XXX no exit() here. If you don't exec, use _exit instead.
1339 * The at_exit handlers apparently confuse the calling process,
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001340 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001341static void pseudo_exec_argv(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00001342{
Eric Andersen78a7c992001-05-15 16:30:25 +00001343 int i, rcode;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001344 char *p;
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +00001345 const struct built_in_command *x;
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001346
Denis Vlasenko1359da62007-04-21 23:27:30 +00001347 for (i = 0; is_assignment(argv[i]); i++) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001348 debug_printf_exec("pid %d environment modification: %s\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001349 getpid(), argv[i]);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001350// FIXME: vfork case??
Denis Vlasenko170435c2007-05-23 13:01:10 +00001351 p = expand_string_to_string(argv[i]);
1352 putenv(p);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001353 }
1354 argv += i;
1355 /* If a variable is assigned in a forest, and nobody listens,
1356 * was it ever really set?
1357 */
1358 if (argv[0] == NULL) {
1359 _exit(EXIT_SUCCESS);
1360 }
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001361
Denis Vlasenko170435c2007-05-23 13:01:10 +00001362 argv = expand_strvec_to_strvec(argv);
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001363
Denis Vlasenko1359da62007-04-21 23:27:30 +00001364 /*
1365 * Check if the command matches any of the builtins.
1366 * Depending on context, this might be redundant. But it's
1367 * easier to waste a few CPU cycles than it is to figure out
1368 * if this is one of those cases.
1369 */
1370 for (x = bltins; x->cmd; x++) {
1371 if (strcmp(argv[0], x->cmd) == 0) {
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001372 debug_printf_exec("running builtin '%s'\n", argv[0]);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001373 rcode = x->function(argv);
1374 fflush(stdout);
1375 _exit(rcode);
Eric Andersen94ac2442001-05-22 19:05:18 +00001376 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00001377 }
Eric Andersen78a7c992001-05-15 16:30:25 +00001378
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001379 /* Check if the command matches any busybox applets */
Denis Vlasenko80d14be2007-04-10 23:03:30 +00001380#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001381 if (strchr(argv[0], '/') == NULL) {
1382 const struct bb_applet *a = find_applet_by_name(argv[0]);
1383 if (a) {
1384 if (a->noexec) {
1385 current_applet = a;
1386 debug_printf_exec("running applet '%s'\n", argv[0]);
1387// is it ok that run_current_applet_and_exit() does exit(), not _exit()?
1388 run_current_applet_and_exit(argv);
1389 }
1390 /* re-exec ourselves with the new arguments */
1391 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
1392 execvp(CONFIG_BUSYBOX_EXEC_PATH, argv);
1393 /* If they called chroot or otherwise made the binary no longer
1394 * executable, fall through */
1395 }
1396 }
Eric Andersenaac75e52001-04-30 18:18:45 +00001397#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001398
1399 debug_printf_exec("execing '%s'\n", argv[0]);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001400 execvp(argv[0], argv);
1401 bb_perror_msg("cannot exec '%s'", argv[0]);
1402 _exit(1);
1403}
1404
1405static void pseudo_exec(struct child_prog *child)
1406{
Denis Vlasenkof2fffd02007-05-02 23:39:04 +00001407// FIXME: buggy wrt NOMMU! Must not modify any global data
1408// until it does exec/_exit, but currently it does.
Denis Vlasenko1359da62007-04-21 23:27:30 +00001409 int rcode;
1410
1411 if (child->argv) {
1412 pseudo_exec_argv(child->argv);
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001413 }
1414
1415 if (child->group) {
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001416 // FIXME: do not modify globals! Think vfork!
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001417#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001418 debug_printf_exec("pseudo_exec: setting interactive_fd=0\n");
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001419 interactive_fd = 0; /* crucial!!!! */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001420#endif
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001421 debug_printf_exec("pseudo_exec: run_list_real\n");
Eric Andersen25f27032001-04-26 23:22:31 +00001422 rcode = run_list_real(child->group);
Eric Andersenbf7df042001-05-23 22:18:35 +00001423 /* OK to leak memory by not calling free_pipe_list,
Eric Andersen25f27032001-04-26 23:22:31 +00001424 * since this process is about to exit */
Eric Andersen94ac2442001-05-22 19:05:18 +00001425 _exit(rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00001426 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001427
1428 /* Can happen. See what bash does with ">foo" by itself. */
1429 debug_printf("trying to pseudo_exec null command\n");
1430 _exit(EXIT_SUCCESS);
Eric Andersen25f27032001-04-26 23:22:31 +00001431}
1432
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001433#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001434static const char *get_cmdtext(struct pipe *pi)
1435{
1436 char **argv;
1437 char *p;
1438 int len;
1439
1440 /* This is subtle. ->cmdtext is created only on first backgrounding.
1441 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001442 * On subsequent bg argv is trashed, but we won't use it */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001443 if (pi->cmdtext)
1444 return pi->cmdtext;
1445 argv = pi->progs[0].argv;
1446 if (!argv || !argv[0])
1447 return (pi->cmdtext = xzalloc(1));
1448
1449 len = 0;
1450 do len += strlen(*argv) + 1; while (*++argv);
1451 pi->cmdtext = p = xmalloc(len);
1452 argv = pi->progs[0].argv;
1453 do {
1454 len = strlen(*argv);
1455 memcpy(p, *argv, len);
1456 p += len;
1457 *p++ = ' ';
1458 } while (*++argv);
1459 p[-1] = '\0';
1460 return pi->cmdtext;
1461}
1462
Eric Andersenbafd94f2001-05-02 16:11:59 +00001463static void insert_bg_job(struct pipe *pi)
1464{
1465 struct pipe *thejob;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001466 int i;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001467
1468 /* Linear search for the ID of the job to use */
1469 pi->jobid = 1;
Eric Andersenc798b072001-06-22 06:23:03 +00001470 for (thejob = job_list; thejob; thejob = thejob->next)
Eric Andersenbafd94f2001-05-02 16:11:59 +00001471 if (thejob->jobid >= pi->jobid)
1472 pi->jobid = thejob->jobid + 1;
1473
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001474 /* Add thejob to the list of running jobs */
Eric Andersenc798b072001-06-22 06:23:03 +00001475 if (!job_list) {
Eric Andersen52a97ca2001-06-22 06:49:26 +00001476 thejob = job_list = xmalloc(sizeof(*thejob));
Eric Andersenbafd94f2001-05-02 16:11:59 +00001477 } else {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001478 for (thejob = job_list; thejob->next; thejob = thejob->next)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001479 continue;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001480 thejob->next = xmalloc(sizeof(*thejob));
1481 thejob = thejob->next;
1482 }
1483
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001484 /* Physically copy the struct job */
Eric Andersen0fcd4472001-05-02 20:12:03 +00001485 memcpy(thejob, pi, sizeof(struct pipe));
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001486 thejob->progs = xzalloc(sizeof(pi->progs[0]) * pi->num_progs);
1487 /* We cannot copy entire pi->progs[] vector! Double free()s will happen */
1488 for (i = 0; i < pi->num_progs; i++) {
1489// TODO: do we really need to have so many fields which are just dead weight
1490// at execution stage?
1491 thejob->progs[i].pid = pi->progs[i].pid;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001492 /* all other fields are not used and stay zero */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001493 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00001494 thejob->next = NULL;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001495 thejob->cmdtext = xstrdup(get_cmdtext(pi));
Eric Andersenbafd94f2001-05-02 16:11:59 +00001496
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001497 /* We don't wait for background thejobs to return -- append it
Eric Andersenbafd94f2001-05-02 16:11:59 +00001498 to the list of backgrounded thejobs and leave it alone */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001499 printf("[%d] %d %s\n", thejob->jobid, thejob->progs[0].pid, thejob->cmdtext);
Eric Andersen1a6d39b2001-05-08 05:11:54 +00001500 last_bg_pid = thejob->progs[0].pid;
Eric Andersenc798b072001-06-22 06:23:03 +00001501 last_jobid = thejob->jobid;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001502}
1503
Eric Andersenbafd94f2001-05-02 16:11:59 +00001504static void remove_bg_job(struct pipe *pi)
1505{
1506 struct pipe *prev_pipe;
1507
Eric Andersenc798b072001-06-22 06:23:03 +00001508 if (pi == job_list) {
Eric Andersen52a97ca2001-06-22 06:49:26 +00001509 job_list = pi->next;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001510 } else {
Eric Andersenc798b072001-06-22 06:23:03 +00001511 prev_pipe = job_list;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001512 while (prev_pipe->next != pi)
1513 prev_pipe = prev_pipe->next;
1514 prev_pipe->next = pi->next;
1515 }
Eric Andersen028b65b2001-06-28 01:10:11 +00001516 if (job_list)
1517 last_jobid = job_list->jobid;
1518 else
1519 last_jobid = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001520}
Eric Andersen028b65b2001-06-28 01:10:11 +00001521
Denis Vlasenko1359da62007-04-21 23:27:30 +00001522/* remove a backgrounded job */
1523static void delete_finished_bg_job(struct pipe *pi)
1524{
1525 remove_bg_job(pi);
Eric Andersen52a97ca2001-06-22 06:49:26 +00001526 pi->stopped_progs = 0;
Eric Andersenbf7df042001-05-23 22:18:35 +00001527 free_pipe(pi, 0);
Eric Andersenbafd94f2001-05-02 16:11:59 +00001528 free(pi);
1529}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001530#endif /* JOB */
Eric Andersenbafd94f2001-05-02 16:11:59 +00001531
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001532/* Checks to see if any processes have exited -- if they
Eric Andersenbafd94f2001-05-02 16:11:59 +00001533 have, figure out why and see if a job has completed */
Eric Andersenc798b072001-06-22 06:23:03 +00001534static int checkjobs(struct pipe* fg_pipe)
Eric Andersenbafd94f2001-05-02 16:11:59 +00001535{
Eric Andersenc798b072001-06-22 06:23:03 +00001536 int attributes;
1537 int status;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001538#if ENABLE_HUSH_JOB
Eric Andersenbafd94f2001-05-02 16:11:59 +00001539 int prognum = 0;
1540 struct pipe *pi;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001541#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00001542 pid_t childpid;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001543 int rcode = 0;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001544
Eric Andersenc798b072001-06-22 06:23:03 +00001545 attributes = WUNTRACED;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001546 if (fg_pipe == NULL) {
Eric Andersenc798b072001-06-22 06:23:03 +00001547 attributes |= WNOHANG;
1548 }
1549
Denis Vlasenko1359da62007-04-21 23:27:30 +00001550/* Do we do this right?
1551 * bash-3.00# sleep 20 | false
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001552 * <ctrl-Z pressed>
Denis Vlasenko1359da62007-04-21 23:27:30 +00001553 * [3]+ Stopped sleep 20 | false
1554 * bash-3.00# echo $?
1555 * 1 <========== bg pipe is not fully done, but exitcode is already known!
1556 */
1557
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001558//FIXME: non-interactive bash does not continue even if all processes in fg pipe
1559//are stopped. Testcase: "cat | cat" in a script (not on command line)
1560// + killall -STOP cat
1561
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001562 wait_more:
Eric Andersenc798b072001-06-22 06:23:03 +00001563 while ((childpid = waitpid(-1, &status, attributes)) > 0) {
Denis Vlasenko1359da62007-04-21 23:27:30 +00001564 const int dead = WIFEXITED(status) || WIFSIGNALED(status);
1565
1566#ifdef DEBUG_SHELL_JOBS
1567 if (WIFSTOPPED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001568 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001569 childpid, WSTOPSIG(status), WEXITSTATUS(status));
1570 if (WIFSIGNALED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001571 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001572 childpid, WTERMSIG(status), WEXITSTATUS(status));
1573 if (WIFEXITED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001574 debug_printf_jobs("pid %d exited, exitcode %d\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001575 childpid, WEXITSTATUS(status));
1576#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001577 /* Were we asked to wait for fg pipe? */
Eric Andersenc798b072001-06-22 06:23:03 +00001578 if (fg_pipe) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001579 int i;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001580 for (i = 0; i < fg_pipe->num_progs; i++) {
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001581 debug_printf_jobs("check pid %d\n", fg_pipe->progs[i].pid);
Eric Andersenc798b072001-06-22 06:23:03 +00001582 if (fg_pipe->progs[i].pid == childpid) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001583 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001584 if (dead) {
1585 fg_pipe->progs[i].pid = 0;
1586 fg_pipe->running_progs--;
1587 if (i == fg_pipe->num_progs-1)
1588 /* last process gives overall exitstatus */
1589 rcode = WEXITSTATUS(status);
1590 } else {
1591 fg_pipe->progs[i].is_stopped = 1;
1592 fg_pipe->stopped_progs++;
1593 }
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001594 debug_printf_jobs("fg_pipe: running_progs %d stopped_progs %d\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001595 fg_pipe->running_progs, fg_pipe->stopped_progs);
1596 if (fg_pipe->running_progs - fg_pipe->stopped_progs <= 0) {
1597 /* All processes in fg pipe have exited/stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001598#if ENABLE_HUSH_JOB
Denis Vlasenko1359da62007-04-21 23:27:30 +00001599 if (fg_pipe->running_progs)
1600 insert_bg_job(fg_pipe);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001601#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001602 return rcode;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001603 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001604 /* There are still running processes in the fg pipe */
1605 goto wait_more;
Eric Andersenc798b072001-06-22 06:23:03 +00001606 }
1607 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00001608 /* fall through to searching process in bg pipes */
Eric Andersenc798b072001-06-22 06:23:03 +00001609 }
1610
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001611#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001612 /* We asked to wait for bg or orphaned children */
1613 /* No need to remember exitcode in this case */
Eric Andersenc798b072001-06-22 06:23:03 +00001614 for (pi = job_list; pi; pi = pi->next) {
Eric Andersenbafd94f2001-05-02 16:11:59 +00001615 prognum = 0;
Denis Vlasenko5f786c22007-04-20 08:35:45 +00001616 while (prognum < pi->num_progs) {
1617 if (pi->progs[prognum].pid == childpid)
1618 goto found_pi_and_prognum;
Eric Andersen52a97ca2001-06-22 06:49:26 +00001619 prognum++;
1620 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00001621 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001622#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00001623
Denis Vlasenko5f786c22007-04-20 08:35:45 +00001624 /* Happens when shell is used as init process (init=/bin/sh) */
1625 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001626 goto wait_more;
Eric Andersenaeb44c42001-05-22 20:29:00 +00001627
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001628#if ENABLE_HUSH_JOB
Denis Vlasenko5f786c22007-04-20 08:35:45 +00001629 found_pi_and_prognum:
Denis Vlasenko1359da62007-04-21 23:27:30 +00001630 if (dead) {
Eric Andersenbafd94f2001-05-02 16:11:59 +00001631 /* child exited */
Eric Andersenbafd94f2001-05-02 16:11:59 +00001632 pi->progs[prognum].pid = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001633 pi->running_progs--;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001634 if (!pi->running_progs) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001635 printf(JOB_STATUS_FORMAT, pi->jobid,
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001636 "Done", pi->cmdtext);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001637 delete_finished_bg_job(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00001638 }
1639 } else {
1640 /* child stopped */
1641 pi->stopped_progs++;
1642 pi->progs[prognum].is_stopped = 1;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001643 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001644#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00001645 }
1646
Denis Vlasenko1359da62007-04-21 23:27:30 +00001647 /* wait found no children or failed */
1648
1649 if (childpid && errno != ECHILD)
Manuel Novoa III cad53642003-03-19 09:13:01 +00001650 bb_perror_msg("waitpid");
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001651 return rcode;
Eric Andersenada18ff2001-05-21 16:18:22 +00001652}
1653
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001654#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +00001655static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
1656{
1657 pid_t p;
1658 int rcode = checkjobs(fg_pipe);
1659 /* Job finished, move the shell to the foreground */
Denis Vlasenko170435c2007-05-23 13:01:10 +00001660 p = getpgid(0); /* pgid of our process */
1661 debug_printf_jobs("fg'ing ourself: getpgid(0)=%d\n", (int)p);
Denis Vlasenko52881e92007-04-21 13:42:52 +00001662 if (tcsetpgrp(interactive_fd, p) && errno != ENOTTY)
1663 bb_perror_msg("tcsetpgrp-4a");
1664 return rcode;
1665}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001666#endif
Denis Vlasenko52881e92007-04-21 13:42:52 +00001667
Eric Andersen25f27032001-04-26 23:22:31 +00001668/* run_pipe_real() starts all the jobs, but doesn't wait for anything
Eric Andersenc798b072001-06-22 06:23:03 +00001669 * to finish. See checkjobs().
Eric Andersen25f27032001-04-26 23:22:31 +00001670 *
1671 * return code is normally -1, when the caller has to wait for children
1672 * to finish to determine the exit status of the pipe. If the pipe
1673 * is a simple builtin command, however, the action is done by the
1674 * time run_pipe_real returns, and the exit code is provided as the
1675 * return value.
1676 *
1677 * The input of the pipe is always stdin, the output is always
1678 * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
1679 * because it tries to avoid running the command substitution in
1680 * subshell, when that is in fact necessary. The subshell process
1681 * now has its stdout directed to the input of the appropriate pipe,
1682 * so this routine is noticeably simpler.
Denis Vlasenko170435c2007-05-23 13:01:10 +00001683 *
1684 * Returns -1 only if started some children. IOW: we have to
1685 * mask out retvals of builtins etc with 0xff!
Eric Andersen25f27032001-04-26 23:22:31 +00001686 */
1687static int run_pipe_real(struct pipe *pi)
1688{
1689 int i;
1690 int nextin, nextout;
1691 int pipefds[2]; /* pipefds[0] is for reading */
Rob Landley53702e52006-07-19 21:43:53 +00001692 struct child_prog *child;
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +00001693 const struct built_in_command *x;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001694 char *p;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001695 /* it is not always needed, but we aim to smaller code */
1696 int squirrel[] = { -1, -1, -1 };
1697 int rcode;
Denis Vlasenko52881e92007-04-21 13:42:52 +00001698 const int single_fg = (pi->num_progs == 1 && pi->followup != PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00001699
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001700 debug_printf_exec("run_pipe_real start: single_fg=%d\n", single_fg);
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00001701
Eric Andersen25f27032001-04-26 23:22:31 +00001702 nextin = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001703#if ENABLE_HUSH_JOB
Eric Andersenada18ff2001-05-21 16:18:22 +00001704 pi->pgrp = -1;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001705#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001706 pi->running_progs = 1;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001707 pi->stopped_progs = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00001708
1709 /* Check if this is a simple builtin (not part of a pipe).
1710 * Builtins within pipes have to fork anyway, and are handled in
1711 * pseudo_exec. "echo foo | read bar" doesn't work on bash, either.
1712 */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001713 child = &(pi->progs[0]);
Denis Vlasenko52881e92007-04-21 13:42:52 +00001714 if (single_fg && child->group && child->subshell == 0) {
Eric Andersen04407e52001-06-07 16:42:05 +00001715 debug_printf("non-subshell grouping\n");
1716 setup_redirects(child, squirrel);
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001717 debug_printf_exec(": run_list_real\n");
Eric Andersen04407e52001-06-07 16:42:05 +00001718 rcode = run_list_real(child->group);
1719 restore_redirects(squirrel);
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001720 debug_printf_exec("run_pipe_real return %d\n", rcode);
Denis Vlasenko170435c2007-05-23 13:01:10 +00001721 return rcode; // do we need to add '... & 0xff' ?
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001722 }
1723
Denis Vlasenko1359da62007-04-21 23:27:30 +00001724 if (single_fg && child->argv != NULL) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001725 char **argv_expanded;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001726 char **argv = child->argv;
1727
1728 for (i = 0; is_assignment(argv[i]); i++)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001729 continue;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001730 if (i != 0 && argv[i] == NULL) {
Eric Andersen78a7c992001-05-15 16:30:25 +00001731 /* assignments, but no command: set the local environment */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001732 for (i = 0; argv[i] != NULL; i++) {
Denis Vlasenkod76c0492007-05-25 02:16:25 +00001733 debug_printf("local environment set: %s\n", argv[i]);
Denis Vlasenko170435c2007-05-23 13:01:10 +00001734 p = expand_string_to_string(argv[i]);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00001735 set_local_var(p, 0);
Eric Andersen78a7c992001-05-15 16:30:25 +00001736 }
1737 return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
1738 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00001739 for (i = 0; is_assignment(argv[i]); i++) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00001740 p = expand_string_to_string(argv[i]);
1741 //sp: child->sp--;
1742 putenv(p);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001743 }
Eric Andersen25f27032001-04-26 23:22:31 +00001744 for (x = bltins; x->cmd; x++) {
Denis Vlasenko1359da62007-04-21 23:27:30 +00001745 if (strcmp(argv[i], x->cmd) == 0) {
1746 if (x->function == builtin_exec && argv[i+1] == NULL) {
Eric Andersen83a2ae22001-05-07 17:59:25 +00001747 debug_printf("magic exec\n");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001748 setup_redirects(child, NULL);
Eric Andersen83a2ae22001-05-07 17:59:25 +00001749 return EXIT_SUCCESS;
1750 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00001751 debug_printf("builtin inline %s\n", argv[0]);
Eric Andersen25f27032001-04-26 23:22:31 +00001752 /* XXX setup_redirects acts on file descriptors, not FILEs.
1753 * This is perfect for work that comes after exec().
1754 * Is it really safe for inline use? Experimentally,
1755 * things seem to work with glibc. */
1756 setup_redirects(child, squirrel);
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001757 debug_printf_exec(": builtin '%s' '%s'...\n", x->cmd, argv[i+1]);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001758 //sp: if (child->sp) /* btw we can do it unconditionally... */
Denis Vlasenko170435c2007-05-23 13:01:10 +00001759 argv_expanded = expand_strvec_to_strvec(argv + i);
1760 rcode = x->function(argv_expanded) & 0xff;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001761 free(argv_expanded);
Eric Andersen25f27032001-04-26 23:22:31 +00001762 restore_redirects(squirrel);
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001763 debug_printf_exec("run_pipe_real return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00001764 return rcode;
1765 }
1766 }
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001767#if ENABLE_FEATURE_SH_STANDALONE
1768 {
Denis Vlasenko1359da62007-04-21 23:27:30 +00001769 const struct bb_applet *a = find_applet_by_name(argv[i]);
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001770 if (a && a->nofork) {
1771 setup_redirects(child, squirrel);
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001772 save_nofork_data(&nofork_save);
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001773 argv_expanded = argv + i;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001774 //sp: if (child->sp)
Denis Vlasenko170435c2007-05-23 13:01:10 +00001775 argv_expanded = expand_strvec_to_strvec(argv + i);
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001776 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n", argv_expanded[0], argv_expanded[1]);
Denis Vlasenko170435c2007-05-23 13:01:10 +00001777 rcode = run_nofork_applet_prime(&nofork_save, a, argv_expanded) & 0xff;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001778 free(argv_expanded);
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001779 restore_redirects(squirrel);
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001780 debug_printf_exec("run_pipe_real return %d\n", rcode);
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001781 return rcode;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001782 }
1783 }
1784#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001785 }
1786
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001787 /* Going to fork a child per each pipe member */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001788 pi->running_progs = 0;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001789
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001790 /* Disable job control signals for shell (parent) and
1791 * for initial child code after fork */
1792 set_jobctrl_sighandler(SIG_IGN);
1793
Eric Andersen25f27032001-04-26 23:22:31 +00001794 for (i = 0; i < pi->num_progs; i++) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001795 child = &(pi->progs[i]);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001796 if (child->argv)
1797 debug_printf_exec(": pipe member '%s' '%s'...\n", child->argv[0], child->argv[1]);
1798 else
1799 debug_printf_exec(": pipe member with no argv\n");
Eric Andersen25f27032001-04-26 23:22:31 +00001800
1801 /* pipes are inserted between pairs of commands */
1802 if ((i + 1) < pi->num_progs) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001803 if (pipe(pipefds) < 0)
1804 bb_perror_msg_and_die("pipe");
Eric Andersen25f27032001-04-26 23:22:31 +00001805 nextout = pipefds[1];
1806 } else {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001807 nextout = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00001808 pipefds[0] = -1;
1809 }
1810
1811 /* XXX test for failed fork()? */
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001812#if BB_MMU
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001813 child->pid = fork();
Eric Andersen72f9a422001-10-28 05:12:20 +00001814#else
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001815 child->pid = vfork();
Eric Andersen72f9a422001-10-28 05:12:20 +00001816#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001817 if (!child->pid) { /* child */
1818 /* Every child adds itself to new process group
1819 * with pgid == pid of first child in pipe */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001820#if ENABLE_HUSH_JOB
Denis Vlasenko170435c2007-05-23 13:01:10 +00001821 if (run_list_level == 1 && interactive_fd) {
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001822 /* Don't do pgrp restore anymore on fatal signals */
1823 set_fatal_sighandler(SIG_DFL);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001824 if (pi->pgrp < 0) /* true for 1st process only */
1825 pi->pgrp = getpid();
1826 if (setpgid(0, pi->pgrp) == 0 && pi->followup != PIPE_BG) {
1827 /* We do it in *every* child, not just first,
1828 * to avoid races */
1829 tcsetpgrp(interactive_fd, pi->pgrp);
1830 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001831 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001832#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001833 /* in non-interactive case fatal sigs are already SIG_DFL */
Eric Andersen25f27032001-04-26 23:22:31 +00001834 close_all();
Eric Andersen25f27032001-04-26 23:22:31 +00001835 if (nextin != 0) {
1836 dup2(nextin, 0);
1837 close(nextin);
1838 }
1839 if (nextout != 1) {
1840 dup2(nextout, 1);
1841 close(nextout);
1842 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00001843 if (pipefds[0] != -1) {
Eric Andersen25f27032001-04-26 23:22:31 +00001844 close(pipefds[0]); /* opposite end of our output pipe */
1845 }
Eric Andersen25f27032001-04-26 23:22:31 +00001846 /* Like bash, explicit redirects override pipes,
1847 * and the pipe fd is available for dup'ing. */
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001848 setup_redirects(child, NULL);
Eric Andersen52a97ca2001-06-22 06:49:26 +00001849
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001850 /* Restore default handlers just prior to exec */
1851 set_jobctrl_sighandler(SIG_DFL);
1852 set_misc_sighandler(SIG_DFL);
1853 signal(SIGCHLD, SIG_DFL);
Eric Andersen25f27032001-04-26 23:22:31 +00001854 pseudo_exec(child);
1855 }
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001856
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001857 pi->running_progs++;
1858
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001859#if ENABLE_HUSH_JOB
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00001860 /* Second and next children need to know pid of first one */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001861 if (pi->pgrp < 0)
Eric Andersen0fcd4472001-05-02 20:12:03 +00001862 pi->pgrp = child->pid;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001863#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001864 if (nextin != 0)
1865 close(nextin);
1866 if (nextout != 1)
1867 close(nextout);
1868
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001869 /* If there isn't another process, nextin is garbage
Eric Andersen25f27032001-04-26 23:22:31 +00001870 but it doesn't matter */
1871 nextin = pipefds[0];
1872 }
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001873 debug_printf_exec("run_pipe_real return -1\n");
Eric Andersen25f27032001-04-26 23:22:31 +00001874 return -1;
1875}
1876
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001877#ifndef debug_print_tree
1878static void debug_print_tree(struct pipe *pi, int lvl)
1879{
1880 static const char *PIPE[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001881 [PIPE_SEQ] = "SEQ",
1882 [PIPE_AND] = "AND",
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001883 [PIPE_OR ] = "OR" ,
1884 [PIPE_BG ] = "BG" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001885 };
1886 static const char *RES[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001887 [RES_NONE ] = "NONE" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00001888#if ENABLE_HUSH_IF
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001889 [RES_IF ] = "IF" ,
1890 [RES_THEN ] = "THEN" ,
1891 [RES_ELIF ] = "ELIF" ,
1892 [RES_ELSE ] = "ELSE" ,
1893 [RES_FI ] = "FI" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00001894#endif
1895#if ENABLE_HUSH_LOOPS
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001896 [RES_FOR ] = "FOR" ,
1897 [RES_WHILE] = "WHILE",
1898 [RES_UNTIL] = "UNTIL",
1899 [RES_DO ] = "DO" ,
1900 [RES_DONE ] = "DONE" ,
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001901 [RES_IN ] = "IN" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00001902#endif
1903 [RES_XXXX ] = "XXXX" ,
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001904 [RES_SNTX ] = "SNTX" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001905 };
1906
1907 int pin, prn;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00001908
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001909 pin = 0;
1910 while (pi) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00001911 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
1912 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001913 prn = 0;
1914 while (prn < pi->num_progs) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00001915 struct child_prog *child = &pi->progs[prn];
1916 char **argv = child->argv;
1917
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001918 fprintf(stderr, "%*s prog %d", lvl*2, "", prn);
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00001919 if (child->group) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001920 fprintf(stderr, " group %s: (argv=%p)\n",
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00001921 (child->subshell ? "()" : "{}"),
1922 argv);
1923 debug_print_tree(child->group, lvl+1);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001924 prn++;
1925 continue;
1926 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001927 if (argv) while (*argv) {
1928 fprintf(stderr, " '%s'", *argv);
1929 argv++;
1930 }
1931 fprintf(stderr, "\n");
1932 prn++;
1933 }
1934 pi = pi->next;
1935 pin++;
1936 }
1937}
1938#endif
1939
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001940/* NB: called by pseudo_exec, and therefore must not modify any
1941 * global data until exec/_exit (we can be a child after vfork!) */
Eric Andersen25f27032001-04-26 23:22:31 +00001942static int run_list_real(struct pipe *pi)
1943{
Denis Vlasenko06810332007-05-21 23:30:54 +00001944 struct pipe *rpipe;
1945#if ENABLE_HUSH_LOOPS
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00001946 char *for_varname = NULL;
1947 char **for_lcur = NULL;
1948 char **for_list = NULL;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001949 int flag_rep = 0;
Denis Vlasenko06810332007-05-21 23:30:54 +00001950#endif
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001951 int save_num_progs;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001952 int flag_skip = 1;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00001953 int rcode = 0; /* probably for gcc only */
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001954 int flag_restore = 0;
Denis Vlasenko06810332007-05-21 23:30:54 +00001955#if ENABLE_HUSH_IF
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001956 int if_code = 0, next_if_code = 0; /* need double-buffer to handle elif */
Denis Vlasenko06810332007-05-21 23:30:54 +00001957#else
1958 enum { if_code = 0, next_if_code = 0 };
1959#endif
Denis Vlasenko219e88d2007-05-21 10:18:23 +00001960 reserved_style rword;
1961 reserved_style skip_more_for_this_rword = RES_XXXX;
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00001962
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001963 debug_printf_exec("run_list_real start lvl %d\n", run_list_level + 1);
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00001964
Denis Vlasenko06810332007-05-21 23:30:54 +00001965#if ENABLE_HUSH_LOOPS
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001966 /* check syntax for "for" */
1967 for (rpipe = pi; rpipe; rpipe = rpipe->next) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00001968 if ((rpipe->res_word == RES_IN || rpipe->res_word == RES_FOR)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001969 && (rpipe->next == NULL)
1970 ) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001971 syntax("malformed for"); /* no IN or no commands after IN */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001972 debug_printf_exec("run_list_real lvl %d return 1\n", run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001973 return 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001974 }
Denis Vlasenko219e88d2007-05-21 10:18:23 +00001975 if ((rpipe->res_word == RES_IN && rpipe->next->res_word == RES_IN && rpipe->next->progs[0].argv != NULL)
1976 || (rpipe->res_word == RES_FOR && rpipe->next->res_word != RES_IN)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001977 ) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001978 /* TODO: what is tested in the first condition? */
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001979 syntax("malformed for"); /* 2nd condition: not followed by IN */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001980 debug_printf_exec("run_list_real lvl %d return 1\n", run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001981 return 1;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001982 }
1983 }
Denis Vlasenko06810332007-05-21 23:30:54 +00001984#else
1985 rpipe = NULL;
1986#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001987
1988#if ENABLE_HUSH_JOB
1989 /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
1990 * We are saving state before entering outermost list ("while...done")
1991 * so that ctrl-Z will correctly background _entire_ outermost list,
1992 * not just a part of it (like "sleep 1 | exit 2") */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001993 if (++run_list_level == 1 && interactive_fd) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001994 if (sigsetjmp(toplevel_jb, 1)) {
1995 /* ctrl-Z forked and we are parent; or ctrl-C.
1996 * Sighandler has longjmped us here */
1997 signal(SIGINT, SIG_IGN);
1998 signal(SIGTSTP, SIG_IGN);
1999 /* Restore level (we can be coming from deep inside
2000 * nested levels) */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00002001 run_list_level = 1;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002002#if ENABLE_FEATURE_SH_STANDALONE
2003 if (nofork_save.saved) { /* if save area is valid */
2004 debug_printf_jobs("exiting nofork early\n");
2005 restore_nofork_data(&nofork_save);
2006 }
2007#endif
2008 if (ctrl_z_flag) {
2009 /* ctrl-Z has forked and stored pid of the child in pi->pid.
2010 * Remember this child as background job */
2011 insert_bg_job(pi);
2012 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002013 /* ctrl-C. We just stop doing whatever we were doing */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002014 putchar('\n');
2015 }
2016 rcode = 0;
2017 goto ret;
2018 }
2019 /* ctrl-Z handler will store pid etc in pi */
2020 toplevel_list = pi;
2021 ctrl_z_flag = 0;
2022#if ENABLE_FEATURE_SH_STANDALONE
2023 nofork_save.saved = 0; /* in case we will run a nofork later */
2024#endif
2025 signal_SA_RESTART(SIGTSTP, handler_ctrl_z);
2026 signal(SIGINT, handler_ctrl_c);
2027 }
2028#endif
2029
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002030 for (; pi; pi = flag_restore ? rpipe : pi->next) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002031 rword = pi->res_word;
Denis Vlasenko06810332007-05-21 23:30:54 +00002032#if ENABLE_HUSH_LOOPS
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002033 if (rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002034 flag_restore = 0;
2035 if (!rpipe) {
2036 flag_rep = 0;
2037 rpipe = pi;
2038 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002039 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002040#endif
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002041 debug_printf_exec(": rword=%d if_code=%d next_if_code=%d skip_more=%d\n",
2042 rword, if_code, next_if_code, skip_more_for_this_rword);
2043 if (rword == skip_more_for_this_rword && flag_skip) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002044 if (pi->followup == PIPE_SEQ)
2045 flag_skip = 0;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002046 continue;
2047 }
2048 flag_skip = 1;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002049 skip_more_for_this_rword = RES_XXXX;
Denis Vlasenko06810332007-05-21 23:30:54 +00002050#if ENABLE_HUSH_IF
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002051 if (rword == RES_THEN || rword == RES_ELSE)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002052 if_code = next_if_code;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002053 if (rword == RES_THEN && if_code)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002054 continue;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002055 if (rword == RES_ELSE && !if_code)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002056 continue;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002057 if (rword == RES_ELIF && !if_code)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002058 break;
Denis Vlasenko06810332007-05-21 23:30:54 +00002059#endif
2060#if ENABLE_HUSH_LOOPS
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002061 if (rword == RES_FOR && pi->num_progs) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002062 if (!for_lcur) {
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002063 /* if no variable values after "in" we skip "for" */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002064 if (!pi->next->progs->argv)
2065 continue;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002066 /* create list of variable values */
Denis Vlasenko170435c2007-05-23 13:01:10 +00002067 for_list = expand_strvec_to_strvec(pi->next->progs->argv);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002068 for_lcur = for_list;
2069 for_varname = pi->progs->argv[0];
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002070 pi->progs->argv[0] = NULL;
2071 flag_rep = 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002072 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002073 free(pi->progs->argv[0]);
2074 if (!*for_lcur) {
2075 free(for_list);
2076 for_lcur = NULL;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002077 flag_rep = 0;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002078 pi->progs->argv[0] = for_varname;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002079 pi->progs->glob_result.gl_pathv[0] = pi->progs->argv[0];
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002080 continue;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002081 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002082 /* insert next value from for_lcur */
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002083 /* vda: does it need escaping? */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002084 pi->progs->argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002085 pi->progs->glob_result.gl_pathv[0] = pi->progs->argv[0];
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002086 }
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002087 if (rword == RES_IN)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002088 continue;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002089 if (rword == RES_DO) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002090 if (!flag_rep)
2091 continue;
Tim Rikerc1ef7bd2006-01-25 00:08:53 +00002092 }
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002093 if (rword == RES_DONE) {
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002094 if (flag_rep) {
2095 flag_restore = 1;
2096 } else {
2097 rpipe = NULL;
2098 }
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002099 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002100#endif
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002101 if (pi->num_progs == 0)
2102 continue;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002103 save_num_progs = pi->num_progs; /* save number of programs */
Denis Vlasenkod01ff132007-05-02 21:40:23 +00002104 debug_printf_exec(": run_pipe_real with %d members\n", pi->num_progs);
Eric Andersen25f27032001-04-26 23:22:31 +00002105 rcode = run_pipe_real(pi);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002106 if (rcode != -1) {
Eric Andersen25f27032001-04-26 23:22:31 +00002107 /* We only ran a builtin: rcode was set by the return value
2108 * of run_pipe_real(), and we don't need to wait for anything. */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002109 } else if (pi->followup == PIPE_BG) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002110 /* What does bash do with attempts to background builtins? */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002111 /* Even bash 3.2 doesn't do that well with nested bg:
2112 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
Denis Vlasenko170435c2007-05-23 13:01:10 +00002113 * I'm NOT treating inner &'s as jobs */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002114#if ENABLE_HUSH_JOB
Denis Vlasenko170435c2007-05-23 13:01:10 +00002115 if (run_list_level == 1)
2116 insert_bg_job(pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002117#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002118 rcode = EXIT_SUCCESS;
2119 } else {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002120#if ENABLE_HUSH_JOB
Denis Vlasenko170435c2007-05-23 13:01:10 +00002121 /* Paranoia, just "interactive_fd" should be enough? */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00002122 if (run_list_level == 1 && interactive_fd) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00002123 /* waits for completion, then fg's main shell */
Denis Vlasenko52881e92007-04-21 13:42:52 +00002124 rcode = checkjobs_and_fg_shell(pi);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002125 } else
2126#endif
2127 {
Denis Vlasenko170435c2007-05-23 13:01:10 +00002128 /* this one just waits for completion */
Eric Andersenc798b072001-06-22 06:23:03 +00002129 rcode = checkjobs(pi);
Eric Andersen25f27032001-04-26 23:22:31 +00002130 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002131 debug_printf_exec(": checkjobs returned %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00002132 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002133 debug_printf_exec(": setting last_return_code=%d\n", rcode);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002134 last_return_code = rcode;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002135 pi->num_progs = save_num_progs; /* restore number of programs */
Denis Vlasenko06810332007-05-21 23:30:54 +00002136#if ENABLE_HUSH_IF
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002137 if (rword == RES_IF || rword == RES_ELIF)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002138 next_if_code = rcode; /* can be overwritten a number of times */
Denis Vlasenko06810332007-05-21 23:30:54 +00002139#endif
2140#if ENABLE_HUSH_LOOPS
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002141 if (rword == RES_WHILE)
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002142 flag_rep = !last_return_code;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002143 if (rword == RES_UNTIL)
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002144 flag_rep = last_return_code;
Denis Vlasenko06810332007-05-21 23:30:54 +00002145#endif
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002146 if ((rcode == EXIT_SUCCESS && pi->followup == PIPE_OR)
2147 || (rcode != EXIT_SUCCESS && pi->followup == PIPE_AND)
2148 ) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002149 skip_more_for_this_rword = rword;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002150 }
Eric Andersen028b65b2001-06-28 01:10:11 +00002151 checkjobs(NULL);
Eric Andersen25f27032001-04-26 23:22:31 +00002152 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002153
2154#if ENABLE_HUSH_JOB
2155 if (ctrl_z_flag) {
2156 /* ctrl-Z forked somewhere in the past, we are the child,
2157 * and now we completed running the list. Exit. */
2158 exit(rcode);
2159 }
2160 ret:
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00002161 if (!--run_list_level && interactive_fd) {
2162 signal(SIGTSTP, SIG_IGN);
2163 signal(SIGINT, SIG_IGN);
2164 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002165#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00002166 debug_printf_exec("run_list_real lvl %d return %d\n", run_list_level + 1, rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00002167 return rcode;
2168}
2169
Eric Andersen25f27032001-04-26 23:22:31 +00002170/* return code is the exit status of the pipe */
Eric Andersenbf7df042001-05-23 22:18:35 +00002171static int free_pipe(struct pipe *pi, int indent)
Eric Andersen25f27032001-04-26 23:22:31 +00002172{
2173 char **p;
2174 struct child_prog *child;
2175 struct redir_struct *r, *rnext;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002176 int a, i, ret_code = 0;
Eric Andersen52a97ca2001-06-22 06:49:26 +00002177
2178 if (pi->stopped_progs > 0)
2179 return ret_code;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002180 debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002181 for (i = 0; i < pi->num_progs; i++) {
Eric Andersen25f27032001-04-26 23:22:31 +00002182 child = &pi->progs[i];
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002183 debug_printf_clean("%s command %d:\n", indenter(indent), i);
Eric Andersen25f27032001-04-26 23:22:31 +00002184 if (child->argv) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002185 for (a = 0, p = child->argv; *p; a++, p++) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002186 debug_printf_clean("%s argv[%d] = %s\n", indenter(indent), a, *p);
Eric Andersen25f27032001-04-26 23:22:31 +00002187 }
2188 globfree(&child->glob_result);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002189 child->argv = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002190 } else if (child->group) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002191 debug_printf_clean("%s begin group (subshell:%d)\n", indenter(indent), child->subshell);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002192 ret_code = free_pipe_list(child->group, indent+3);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002193 debug_printf_clean("%s end group\n", indenter(indent));
Eric Andersen25f27032001-04-26 23:22:31 +00002194 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002195 debug_printf_clean("%s (nil)\n", indenter(indent));
Eric Andersen25f27032001-04-26 23:22:31 +00002196 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002197 for (r = child->redirects; r; r = rnext) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002198 debug_printf_clean("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->type].descrip);
Eric Andersen25f27032001-04-26 23:22:31 +00002199 if (r->dup == -1) {
Eric Andersen817e73c2001-06-06 17:56:09 +00002200 /* guard against the case >$FOO, where foo is unset or blank */
2201 if (r->word.gl_pathv) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002202 debug_printf_clean(" %s\n", *r->word.gl_pathv);
Eric Andersen817e73c2001-06-06 17:56:09 +00002203 globfree(&r->word);
2204 }
Eric Andersen25f27032001-04-26 23:22:31 +00002205 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002206 debug_printf_clean("&%d\n", r->dup);
Eric Andersen25f27032001-04-26 23:22:31 +00002207 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002208 rnext = r->next;
Eric Andersen25f27032001-04-26 23:22:31 +00002209 free(r);
2210 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002211 child->redirects = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002212 }
2213 free(pi->progs); /* children are an array, they get freed all at once */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002214 pi->progs = NULL;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002215#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002216 free(pi->cmdtext);
2217 pi->cmdtext = NULL;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002218#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002219 return ret_code;
2220}
2221
Eric Andersenbf7df042001-05-23 22:18:35 +00002222static int free_pipe_list(struct pipe *head, int indent)
Eric Andersen25f27032001-04-26 23:22:31 +00002223{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002224 int rcode = 0; /* if list has no members */
Eric Andersen25f27032001-04-26 23:22:31 +00002225 struct pipe *pi, *next;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002226
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002227 for (pi = head; pi; pi = next) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002228 debug_printf_clean("%s pipe reserved mode %d\n", indenter(indent), pi->res_word);
Eric Andersenbf7df042001-05-23 22:18:35 +00002229 rcode = free_pipe(pi, indent);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002230 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002231 next = pi->next;
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002232 /*pi->next = NULL;*/
Eric Andersen25f27032001-04-26 23:22:31 +00002233 free(pi);
2234 }
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002235 return rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00002236}
2237
2238/* Select which version we will use */
2239static int run_list(struct pipe *pi)
2240{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002241 int rcode = 0;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002242 debug_printf_exec("run_list entered\n");
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002243 if (fake_mode == 0) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002244 debug_printf_exec(": run_list_real with %d members\n", pi->num_progs);
Eric Andersen25f27032001-04-26 23:22:31 +00002245 rcode = run_list_real(pi);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002246 }
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002247 /* free_pipe_list has the side effect of clearing memory.
Eric Andersen25f27032001-04-26 23:22:31 +00002248 * In the long run that function can be merged with run_list_real,
2249 * but doing that now would hobble the debugging effort. */
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002250 free_pipe_list(pi, 0);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002251 debug_printf_exec("run_list return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00002252 return rcode;
2253}
2254
2255/* The API for glob is arguably broken. This routine pushes a non-matching
2256 * string into the output structure, removing non-backslashed backslashes.
2257 * If someone can prove me wrong, by performing this function within the
2258 * original glob(3) api, feel free to rewrite this routine into oblivion.
2259 * Return code (0 vs. GLOB_NOSPACE) matches glob(3).
2260 * XXX broken if the last character is '\\', check that before calling.
2261 */
2262static int globhack(const char *src, int flags, glob_t *pglob)
2263{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002264 int cnt = 0, pathc;
Eric Andersen25f27032001-04-26 23:22:31 +00002265 const char *s;
2266 char *dest;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002267 for (cnt = 1, s = src; s && *s; s++) {
Eric Andersen25f27032001-04-26 23:22:31 +00002268 if (*s == '\\') s++;
2269 cnt++;
2270 }
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002271 dest = xmalloc(cnt);
Eric Andersen25f27032001-04-26 23:22:31 +00002272 if (!(flags & GLOB_APPEND)) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002273 pglob->gl_pathv = NULL;
2274 pglob->gl_pathc = 0;
2275 pglob->gl_offs = 0;
2276 pglob->gl_offs = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00002277 }
2278 pathc = ++pglob->gl_pathc;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002279 pglob->gl_pathv = xrealloc(pglob->gl_pathv, (pathc+1) * sizeof(*pglob->gl_pathv));
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002280 pglob->gl_pathv[pathc-1] = dest;
2281 pglob->gl_pathv[pathc] = NULL;
2282 for (s = src; s && *s; s++, dest++) {
Eric Andersen25f27032001-04-26 23:22:31 +00002283 if (*s == '\\') s++;
2284 *dest = *s;
2285 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002286 *dest = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002287 return 0;
2288}
2289
2290/* XXX broken if the last character is '\\', check that before calling */
2291static int glob_needed(const char *s)
2292{
2293 for (; *s; s++) {
2294 if (*s == '\\') s++;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002295 if (strchr("*[?", *s)) return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002296 }
2297 return 0;
2298}
2299
Eric Andersen25f27032001-04-26 23:22:31 +00002300static int xglob(o_string *dest, int flags, glob_t *pglob)
2301{
2302 int gr;
2303
Tim Rikerc1ef7bd2006-01-25 00:08:53 +00002304 /* short-circuit for null word */
Eric Andersen25f27032001-04-26 23:22:31 +00002305 /* we can code this better when the debug_printf's are gone */
Tim Rikerc1ef7bd2006-01-25 00:08:53 +00002306 if (dest->length == 0) {
2307 if (dest->nonnull) {
2308 /* bash man page calls this an "explicit" null */
2309 gr = globhack(dest->data, flags, pglob);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002310 debug_printf("globhack returned %d\n", gr);
Tim Rikerc1ef7bd2006-01-25 00:08:53 +00002311 } else {
Eric Andersen25f27032001-04-26 23:22:31 +00002312 return 0;
2313 }
Tim Rikerc1ef7bd2006-01-25 00:08:53 +00002314 } else if (glob_needed(dest->data)) {
Eric Andersen25f27032001-04-26 23:22:31 +00002315 gr = glob(dest->data, flags, NULL, pglob);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002316 debug_printf("glob returned %d\n", gr);
Eric Andersen25f27032001-04-26 23:22:31 +00002317 if (gr == GLOB_NOMATCH) {
2318 /* quote removal, or more accurately, backslash removal */
2319 gr = globhack(dest->data, flags, pglob);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002320 debug_printf("globhack returned %d\n", gr);
Eric Andersen25f27032001-04-26 23:22:31 +00002321 }
2322 } else {
2323 gr = globhack(dest->data, flags, pglob);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002324 debug_printf("globhack returned %d\n", gr);
Eric Andersen25f27032001-04-26 23:22:31 +00002325 }
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002326 if (gr == GLOB_NOSPACE)
Manuel Novoa III cad53642003-03-19 09:13:01 +00002327 bb_error_msg_and_die("out of memory during glob");
Eric Andersen25f27032001-04-26 23:22:31 +00002328 if (gr != 0) { /* GLOB_ABORTED ? */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002329 bb_error_msg("glob(3) error %d", gr);
Eric Andersen25f27032001-04-26 23:22:31 +00002330 }
2331 /* globprint(glob_target); */
2332 return gr;
2333}
2334
Denis Vlasenko170435c2007-05-23 13:01:10 +00002335/* expand_strvec_to_strvec() takes a list of strings, expands
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002336 * all variable references within and returns a pointer to
2337 * a list of expanded strings, possibly with larger number
2338 * of strings. (Think VAR="a b"; echo $VAR).
2339 * This new list is allocated as a single malloc block.
2340 * NULL-terminated list of char* pointers is at the beginning of it,
2341 * followed by strings themself.
2342 * Caller can deallocate entire list by single free(list). */
2343
2344/* Helpers first:
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00002345 * count_XXX estimates size of the block we need. It's okay
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002346 * to over-estimate sizes a bit, if it makes code simpler */
2347static int count_ifs(const char *str)
2348{
2349 int cnt = 0;
2350 debug_printf_expand("count_ifs('%s') ifs='%s'", str, ifs);
2351 while (1) {
2352 str += strcspn(str, ifs);
2353 if (!*str) break;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002354 str++; /* str += strspn(str, ifs); */
2355 cnt++; /* cnt += strspn(str, ifs); - but this code is larger */
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002356 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002357 debug_printf_expand(" return %d\n", cnt);
2358 return cnt;
2359}
2360
2361static void count_var_expansion_space(int *countp, int *lenp, char *arg)
2362{
2363 char first_ch;
2364 int i;
2365 int len = *lenp;
2366 int count = *countp;
2367 const char *val;
2368 char *p;
2369
2370 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL))) {
2371 len += p - arg;
2372 arg = ++p;
2373 p = strchr(p, SPECIAL_VAR_SYMBOL);
2374 first_ch = arg[0];
2375
2376 switch (first_ch & 0x7f) {
2377 /* high bit in 1st_ch indicates that var is double-quoted */
2378 case '$': /* pid */
2379 case '!': /* bg pid */
2380 case '?': /* exitcode */
2381 case '#': /* argc */
2382 len += sizeof(int)*3 + 1; /* enough for int */
2383 break;
2384 case '*':
2385 case '@':
2386 for (i = 1; i < global_argc; i++) {
2387 len += strlen(global_argv[i]) + 1;
2388 count++;
2389 if (!(first_ch & 0x80))
2390 count += count_ifs(global_argv[i]);
2391 }
2392 break;
2393 default:
2394 *p = '\0';
2395 arg[0] = first_ch & 0x7f;
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002396 if (isdigit(arg[0])) {
2397 i = xatoi_u(arg);
2398 val = NULL;
2399 if (i < global_argc)
2400 val = global_argv[i];
2401 } else
2402 val = lookup_param(arg);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002403 arg[0] = first_ch;
2404 *p = SPECIAL_VAR_SYMBOL;
2405
2406 if (val) {
2407 len += strlen(val) + 1;
2408 if (!(first_ch & 0x80))
2409 count += count_ifs(val);
2410 }
2411 }
2412 arg = ++p;
2413 }
2414
2415 len += strlen(arg) + 1;
2416 count++;
2417 *lenp = len;
2418 *countp = count;
2419}
2420
2421/* Store given string, finalizing the word and starting new one whenever
2422 * we encounter ifs char(s). This is used for expanding variable values.
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002423 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002424static int expand_on_ifs(char **list, int n, char **posp, const char *str)
2425{
2426 char *pos = *posp;
2427 while (1) {
2428 int word_len = strcspn(str, ifs);
2429 if (word_len) {
2430 memcpy(pos, str, word_len); /* store non-ifs chars */
2431 pos += word_len;
2432 str += word_len;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002433 }
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002434 if (!*str) /* EOL - do not finalize word */
2435 break;
2436 *pos++ = '\0';
2437 if (n) debug_printf_expand("expand_on_ifs finalized list[%d]=%p '%s' "
2438 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2439 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2440 list[n++] = pos;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002441 str += strspn(str, ifs); /* skip ifs chars */
2442 }
2443 *posp = pos;
2444 return n;
2445}
2446
2447/* Expand all variable references in given string, adding words to list[]
2448 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2449 * to be filled). This routine is extremely tricky: has to deal with
2450 * variables/parameters with whitespace, $* and $@, and constructs like
2451 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002452/* NB: another bug is that we cannot detect empty strings yet:
2453 * "" or $empty"" expands to zero words, has to expand to empty word */
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002454static int expand_vars_to_list(char **list, int n, char **posp, char *arg, char or_mask)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002455{
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002456 /* or_mask is either 0 (normal case) or 0x80
2457 * (expansion of right-hand side of assignment == 1-element expand) */
2458
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002459 char first_ch, ored_ch;
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002460 int i;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002461 const char *val;
2462 char *p;
2463 char *pos = *posp;
2464
2465 ored_ch = 0;
2466
2467 if (n) debug_printf_expand("expand_vars_to_list finalized list[%d]=%p '%s' "
2468 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2469 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2470 list[n++] = pos;
2471
2472 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL))) {
2473 memcpy(pos, arg, p - arg);
2474 pos += (p - arg);
2475 arg = ++p;
2476 p = strchr(p, SPECIAL_VAR_SYMBOL);
2477
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002478 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002479 ored_ch |= first_ch;
2480 val = NULL;
2481 switch (first_ch & 0x7f) {
2482 /* Highest bit in first_ch indicates that var is double-quoted */
2483 case '$': /* pid */
2484 /* FIXME: (echo $$) should still print pid of main shell */
2485 val = utoa(getpid());
2486 break;
2487 case '!': /* bg pid */
2488 val = last_bg_pid ? utoa(last_bg_pid) : (char*)"";
2489 break;
2490 case '?': /* exitcode */
2491 val = utoa(last_return_code);
2492 break;
2493 case '#': /* argc */
2494 val = utoa(global_argc ? global_argc-1 : 0);
2495 break;
2496 case '*':
2497 case '@':
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002498 i = 1;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002499 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002500 while (i < global_argc) {
2501 n = expand_on_ifs(list, n, &pos, global_argv[i]);
2502 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, global_argc-1);
2503 if (global_argv[i++][0] && i < global_argc) {
2504 /* this argv[] is not empty and not last:
2505 * put terminating NUL, start new word */
2506 *pos++ = '\0';
2507 if (n) debug_printf_expand("expand_vars_to_list 2 finalized list[%d]=%p '%s' "
2508 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2509 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2510 list[n++] = pos;
2511 }
2512 }
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002513 } else
2514 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2515 * and in this case should theat it like '$*' */
2516 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002517 while (1) {
2518 strcpy(pos, global_argv[i]);
2519 pos += strlen(global_argv[i]);
2520 if (++i >= global_argc)
2521 break;
2522 *pos++ = '\0';
2523 if (n) debug_printf_expand("expand_vars_to_list 3 finalized list[%d]=%p '%s' "
2524 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2525 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2526 list[n++] = pos;
2527 }
2528 } else { /* quoted $*: add as one word */
2529 while (1) {
2530 strcpy(pos, global_argv[i]);
2531 pos += strlen(global_argv[i]);
2532 if (++i >= global_argc)
2533 break;
2534 if (ifs[0])
2535 *pos++ = ifs[0];
2536 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002537 }
2538 break;
2539 default:
2540 *p = '\0';
2541 arg[0] = first_ch & 0x7f;
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002542 if (isdigit(arg[0])) {
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002543 i = xatoi_u(arg);
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002544 val = NULL;
2545 if (i < global_argc)
2546 val = global_argv[i];
2547 } else
2548 val = lookup_param(arg);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002549 arg[0] = first_ch;
2550 *p = SPECIAL_VAR_SYMBOL;
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002551 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002552 if (val) {
2553 n = expand_on_ifs(list, n, &pos, val);
2554 val = NULL;
2555 }
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002556 } /* else: quoted $VAR, val will be appended at pos */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002557 }
2558 if (val) {
2559 strcpy(pos, val);
2560 pos += strlen(val);
2561 }
2562 arg = ++p;
2563 }
2564 debug_printf_expand("expand_vars_to_list adding tail '%s' at %p\n", arg, pos);
2565 strcpy(pos, arg);
2566 pos += strlen(arg) + 1;
2567 if (pos == list[n-1] + 1) { /* expansion is empty */
2568 if (!(ored_ch & 0x80)) { /* all vars were not quoted... */
2569 debug_printf_expand("expand_vars_to_list list[%d] empty, going back\n", n);
2570 pos--;
2571 n--;
2572 }
2573 }
2574
2575 *posp = pos;
2576 return n;
2577}
2578
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002579static char **expand_variables(char **argv, char or_mask)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002580{
2581 int n;
2582 int count = 1;
2583 int len = 0;
2584 char *pos, **v, **list;
2585
2586 v = argv;
2587 if (!*v) debug_printf_expand("count_var_expansion_space: "
2588 "argv[0]=NULL count=%d len=%d alloc_space=%d\n",
2589 count, len, sizeof(char*) * count + len);
2590 while (*v) {
2591 count_var_expansion_space(&count, &len, *v);
2592 debug_printf_expand("count_var_expansion_space: "
2593 "'%s' count=%d len=%d alloc_space=%d\n",
2594 *v, count, len, sizeof(char*) * count + len);
2595 v++;
2596 }
2597 len += sizeof(char*) * count; /* total to alloc */
2598 list = xmalloc(len);
2599 pos = (char*)(list + count);
2600 debug_printf_expand("list=%p, list[0] should be %p\n", list, pos);
2601 n = 0;
2602 v = argv;
2603 while (*v)
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002604 n = expand_vars_to_list(list, n, &pos, *v++, or_mask);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002605
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002606 if (n) debug_printf_expand("finalized list[%d]=%p '%s' "
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002607 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2608 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002609 list[n] = NULL;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002610
2611#ifdef DEBUG_EXPAND
2612 {
2613 int m = 0;
2614 while (m <= n) {
2615 debug_printf_expand("list[%d]=%p '%s'\n", m, list[m], list[m]);
2616 m++;
2617 }
2618 debug_printf_expand("used_space=%d\n", pos - (char*)list);
2619 }
2620#endif
Denis Vlasenko170435c2007-05-23 13:01:10 +00002621 if (ENABLE_HUSH_DEBUG)
2622 if (pos - (char*)list > len)
2623 bb_error_msg_and_die("BUG in varexp");
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002624 return list;
2625}
2626
Denis Vlasenko170435c2007-05-23 13:01:10 +00002627static char **expand_strvec_to_strvec(char **argv)
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002628{
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002629 return expand_variables(argv, 0);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002630}
2631
Denis Vlasenko170435c2007-05-23 13:01:10 +00002632static char *expand_string_to_string(const char *str)
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002633{
2634 char *argv[2], **list;
2635
2636 argv[0] = (char*)str;
2637 argv[1] = NULL;
2638 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
Denis Vlasenko170435c2007-05-23 13:01:10 +00002639 if (ENABLE_HUSH_DEBUG)
2640 if (!list[0] || list[1])
2641 bb_error_msg_and_die("BUG in varexp2");
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002642 /* actually, just move string 2*sizeof(char*) bytes back */
2643 strcpy((char*)list, list[0]);
Denis Vlasenko170435c2007-05-23 13:01:10 +00002644 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2645 return (char*)list;
2646}
2647
2648static char* expand_strvec_to_string(char **argv)
2649{
2650 char **list;
2651
2652 list = expand_variables(argv, 0x80);
2653 /* Convert all NULs to spaces */
2654 if (list[0]) {
2655 int n = 1;
2656 while (list[n]) {
2657 if (ENABLE_HUSH_DEBUG)
2658 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2659 bb_error_msg_and_die("BUG in varexp3");
2660 list[n][-1] = ' '; /* TODO: or to ifs[0]? */
2661 n++;
2662 }
2663 }
2664 strcpy((char*)list, list[0]);
2665 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002666 return (char*)list;
2667}
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002668
Eric Andersenf72f5622001-05-15 23:21:41 +00002669/* This is used to get/check local shell variables */
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002670static struct variable *get_local_var(const char *name)
Eric Andersenf72f5622001-05-15 23:21:41 +00002671{
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002672 struct variable *cur;
2673 int len;
Eric Andersenf72f5622001-05-15 23:21:41 +00002674
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002675 if (!name)
Eric Andersenf72f5622001-05-15 23:21:41 +00002676 return NULL;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002677 len = strlen(name);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002678 for (cur = top_var; cur; cur = cur->next) {
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002679 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002680 return cur;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00002681 }
Eric Andersenf72f5622001-05-15 23:21:41 +00002682 return NULL;
2683}
2684
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002685/* str holds "NAME=VAL" and is expected to be malloced.
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002686 * We take ownership of it. */
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002687static int set_local_var(char *str, int flg_export)
Eric Andersen78a7c992001-05-15 16:30:25 +00002688{
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002689 struct variable *cur;
2690 char *value;
2691 int name_len;
Eric Andersen20a69a72001-05-15 17:24:44 +00002692
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002693 value = strchr(str, '=');
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002694 if (!value) { /* not expected to ever happen? */
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002695 free(str);
Eric Andersen99785762001-05-22 21:37:48 +00002696 return -1;
2697 }
Eric Andersen20a69a72001-05-15 17:24:44 +00002698
Denis Vlasenko201c72a2007-05-25 10:00:36 +00002699 name_len = value - str + 1; /* including '=' */
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002700 cur = top_var; /* cannot be NULL (we have HUSH_VERSION and it's RO) */
2701 while (1) {
Denis Vlasenko201c72a2007-05-25 10:00:36 +00002702 if (strncmp(cur->varstr, str, name_len) != 0) {
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002703 if (!cur->next) {
Denis Vlasenko201c72a2007-05-25 10:00:36 +00002704 /* Bail out. Note that now cur points
2705 * to last var in linked list */
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002706 break;
Eric Andersen20a69a72001-05-15 17:24:44 +00002707 }
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002708 cur = cur->next;
2709 continue;
Eric Andersen20a69a72001-05-15 17:24:44 +00002710 }
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002711 /* We found an existing var with this name */
2712 *value = '\0';
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002713 if (cur->flg_read_only) {
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002714 bb_error_msg("%s: readonly variable", str);
2715 free(str);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002716 return -1;
2717 }
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002718 unsetenv(str); /* just in case */
2719 *value = '=';
2720 if (strcmp(cur->varstr, str) == 0) {
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002721 free_and_exp:
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002722 free(str);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002723 goto exp;
2724 }
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002725 if (cur->max_len >= strlen(str)) {
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002726 /* This one is from startup env, reuse space */
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002727 strcpy(cur->varstr, str);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002728 goto free_and_exp;
2729 }
2730 /* max_len == 0 signifies "malloced" var, which we can
2731 * (and has to) free */
2732 if (!cur->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002733 free(cur->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002734 cur->max_len = 0;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002735 goto set_str_and_exp;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002736 }
Eric Andersen20a69a72001-05-15 17:24:44 +00002737
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002738 /* Not found - create next variable struct */
2739 cur->next = xzalloc(sizeof(*cur));
2740 cur = cur->next;
2741
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002742 set_str_and_exp:
2743 cur->varstr = str;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002744 exp:
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002745 if (flg_export)
2746 cur->flg_export = 1;
2747 if (cur->flg_export)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002748 return putenv(cur->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002749 return 0;
Eric Andersen20a69a72001-05-15 17:24:44 +00002750}
2751
Eric Andersenf72f5622001-05-15 23:21:41 +00002752static void unset_local_var(const char *name)
Eric Andersen20a69a72001-05-15 17:24:44 +00002753{
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002754 struct variable *cur;
2755 struct variable *prev = prev; /* for gcc */
2756 int name_len;
Eric Andersen20a69a72001-05-15 17:24:44 +00002757
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002758 if (!name)
2759 return;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002760 name_len = strlen(name);
2761 cur = top_var;
2762 while (cur) {
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002763 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002764 if (cur->flg_read_only) {
Manuel Novoa III cad53642003-03-19 09:13:01 +00002765 bb_error_msg("%s: readonly variable", name);
Eric Andersen94ac2442001-05-22 19:05:18 +00002766 return;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002767 }
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002768 /* prev is ok to use here because 1st variable, HUSH_VERSION,
2769 * is ro, and we cannot reach this code on the 1st pass */
2770 prev->next = cur->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002771 unsetenv(cur->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002772 if (!cur->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002773 free(cur->varstr);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002774 free(cur);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002775 return;
Eric Andersenf72f5622001-05-15 23:21:41 +00002776 }
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002777 prev = cur;
2778 cur = cur->next;
Eric Andersen20a69a72001-05-15 17:24:44 +00002779 }
Eric Andersen78a7c992001-05-15 16:30:25 +00002780}
2781
2782static int is_assignment(const char *s)
2783{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002784 if (!s || !isalpha(*s))
2785 return 0;
2786 s++;
2787 while (isalnum(*s) || *s == '_')
2788 s++;
2789 return *s == '=';
Eric Andersen78a7c992001-05-15 16:30:25 +00002790}
2791
Eric Andersen25f27032001-04-26 23:22:31 +00002792/* the src parameter allows us to peek forward to a possible &n syntax
2793 * for file descriptor duplication, e.g., "2>&1".
2794 * Return code is 0 normally, 1 if a syntax error is detected in src.
2795 * Resource errors (in xmalloc) cause the process to exit */
2796static int setup_redirect(struct p_context *ctx, int fd, redir_type style,
2797 struct in_str *input)
2798{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002799 struct child_prog *child = ctx->child;
Eric Andersen25f27032001-04-26 23:22:31 +00002800 struct redir_struct *redir = child->redirects;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002801 struct redir_struct *last_redir = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002802
2803 /* Create a new redir_struct and drop it onto the end of the linked list */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002804 while (redir) {
2805 last_redir = redir;
2806 redir = redir->next;
Eric Andersen25f27032001-04-26 23:22:31 +00002807 }
2808 redir = xmalloc(sizeof(struct redir_struct));
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002809 redir->next = NULL;
2810 redir->word.gl_pathv = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002811 if (last_redir) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002812 last_redir->next = redir;
Eric Andersen25f27032001-04-26 23:22:31 +00002813 } else {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002814 child->redirects = redir;
Eric Andersen25f27032001-04-26 23:22:31 +00002815 }
2816
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002817 redir->type = style;
2818 redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
Eric Andersen25f27032001-04-26 23:22:31 +00002819
2820 debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
2821
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002822 /* Check for a '2>&1' type redirect */
Eric Andersen25f27032001-04-26 23:22:31 +00002823 redir->dup = redirect_dup_num(input);
2824 if (redir->dup == -2) return 1; /* syntax error */
2825 if (redir->dup != -1) {
2826 /* Erik had a check here that the file descriptor in question
Eric Andersen83a2ae22001-05-07 17:59:25 +00002827 * is legit; I postpone that to "run time"
2828 * A "-" representation of "close me" shows up as a -3 here */
Eric Andersen25f27032001-04-26 23:22:31 +00002829 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
2830 } else {
2831 /* We do _not_ try to open the file that src points to,
2832 * since we need to return and let src be expanded first.
2833 * Set ctx->pending_redirect, so we know what to do at the
Denis Vlasenko201c72a2007-05-25 10:00:36 +00002834 * end of the next parsed word. */
Eric Andersen25f27032001-04-26 23:22:31 +00002835 ctx->pending_redirect = redir;
2836 }
2837 return 0;
2838}
2839
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00002840static struct pipe *new_pipe(void)
2841{
Eric Andersen25f27032001-04-26 23:22:31 +00002842 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002843 pi = xzalloc(sizeof(struct pipe));
2844 /*pi->num_progs = 0;*/
2845 /*pi->progs = NULL;*/
2846 /*pi->next = NULL;*/
2847 /*pi->followup = 0; invalid */
2848 if (RES_NONE)
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002849 pi->res_word = RES_NONE;
Eric Andersen25f27032001-04-26 23:22:31 +00002850 return pi;
2851}
2852
2853static void initialize_context(struct p_context *ctx)
2854{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002855 ctx->child = NULL;
Denis Vlasenko1a735862007-05-23 00:32:25 +00002856 ctx->pipe = ctx->list_head = new_pipe();
2857 ctx->pending_redirect = NULL;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002858 ctx->res_w = RES_NONE;
Denis Vlasenko1a735862007-05-23 00:32:25 +00002859 //only ctx->parse_type is not touched... is this intentional?
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002860 ctx->old_flag = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00002861 ctx->stack = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002862 done_command(ctx); /* creates the memory for working child */
2863}
2864
2865/* normal return is 0
2866 * if a reserved word is found, and processed, return 1
2867 * should handle if, then, elif, else, fi, for, while, until, do, done.
2868 * case, function, and select are obnoxious, save those for later.
2869 */
Denis Vlasenko06810332007-05-21 23:30:54 +00002870#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS
"Vladimir N. Oleynik"19c37012005-09-22 14:33:15 +00002871static int reserved_word(o_string *dest, struct p_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00002872{
2873 struct reserved_combo {
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002874 char literal[7];
2875 unsigned char code;
2876 int flag;
Eric Andersen25f27032001-04-26 23:22:31 +00002877 };
2878 /* Mostly a list of accepted follow-up reserved words.
2879 * FLAG_END means we are done with the sequence, and are ready
2880 * to turn the compound list into a command.
2881 * FLAG_START means the word must start a new compound list.
2882 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002883 static const struct reserved_combo reserved_list[] = {
Denis Vlasenko06810332007-05-21 23:30:54 +00002884#if ENABLE_HUSH_IF
Eric Andersen25f27032001-04-26 23:22:31 +00002885 { "if", RES_IF, FLAG_THEN | FLAG_START },
2886 { "then", RES_THEN, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2887 { "elif", RES_ELIF, FLAG_THEN },
2888 { "else", RES_ELSE, FLAG_FI },
2889 { "fi", RES_FI, FLAG_END },
Denis Vlasenko06810332007-05-21 23:30:54 +00002890#endif
2891#if ENABLE_HUSH_LOOPS
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002892 { "for", RES_FOR, FLAG_IN | FLAG_START },
Eric Andersen25f27032001-04-26 23:22:31 +00002893 { "while", RES_WHILE, FLAG_DO | FLAG_START },
2894 { "until", RES_UNTIL, FLAG_DO | FLAG_START },
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002895 { "in", RES_IN, FLAG_DO },
Eric Andersen25f27032001-04-26 23:22:31 +00002896 { "do", RES_DO, FLAG_DONE },
2897 { "done", RES_DONE, FLAG_END }
Denis Vlasenko06810332007-05-21 23:30:54 +00002898#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002899 };
Denis Vlasenko7d4c44e2007-04-16 22:34:39 +00002900 enum { NRES = sizeof(reserved_list)/sizeof(reserved_list[0]) };
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002901 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002902
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002903 for (r = reserved_list; r < reserved_list + NRES; r++) {
Denis Vlasenko1a735862007-05-23 00:32:25 +00002904 if (strcmp(dest->data, r->literal) != 0)
2905 continue;
2906 debug_printf("found reserved word %s, code %d\n", r->literal, r->code);
2907 if (r->flag & FLAG_START) {
2908 struct p_context *new;
2909 debug_printf("push stack\n");
Denis Vlasenko06810332007-05-21 23:30:54 +00002910#if ENABLE_HUSH_LOOPS
Denis Vlasenko1a735862007-05-23 00:32:25 +00002911 if (ctx->res_w == RES_IN || ctx->res_w == RES_FOR) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00002912 syntax("malformed for"); /* example: 'for if' */
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002913 ctx->res_w = RES_SNTX;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002914 b_reset(dest);
Eric Andersenaf44a0e2001-04-27 07:26:12 +00002915 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002916 }
Denis Vlasenko1a735862007-05-23 00:32:25 +00002917#endif
2918 new = xmalloc(sizeof(*new));
2919 *new = *ctx; /* physical copy */
2920 initialize_context(ctx);
2921 ctx->stack = new;
2922 } else if (ctx->res_w == RES_NONE || !(ctx->old_flag & (1 << r->code))) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00002923 syntax(NULL);
Denis Vlasenko1a735862007-05-23 00:32:25 +00002924 ctx->res_w = RES_SNTX;
Denis Vlasenkoff131b92007-04-10 15:42:06 +00002925 b_reset(dest);
Eric Andersen25f27032001-04-26 23:22:31 +00002926 return 1;
2927 }
Denis Vlasenko1a735862007-05-23 00:32:25 +00002928 ctx->res_w = r->code;
2929 ctx->old_flag = r->flag;
2930 if (ctx->old_flag & FLAG_END) {
2931 struct p_context *old;
2932 debug_printf("pop stack\n");
2933 done_pipe(ctx, PIPE_SEQ);
2934 old = ctx->stack;
2935 old->child->group = ctx->list_head;
2936 old->child->subshell = 0;
2937 *ctx = *old; /* physical copy */
2938 free(old);
2939 }
2940 b_reset(dest);
2941 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002942 }
2943 return 0;
2944}
Denis Vlasenko06810332007-05-21 23:30:54 +00002945#else
2946#define reserved_word(dest, ctx) ((int)0)
2947#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002948
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002949/* Normal return is 0.
Eric Andersen25f27032001-04-26 23:22:31 +00002950 * Syntax or xglob errors return 1. */
2951static int done_word(o_string *dest, struct p_context *ctx)
2952{
Denis Vlasenkobb81c582007-01-30 22:32:09 +00002953 struct child_prog *child = ctx->child;
Eric Andersen25f27032001-04-26 23:22:31 +00002954 glob_t *glob_target;
2955 int gr, flags = 0;
2956
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002957 debug_printf_parse("done_word entered: '%s' %p\n", dest->data, child);
Eric Andersen25f27032001-04-26 23:22:31 +00002958 if (dest->length == 0 && !dest->nonnull) {
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002959 debug_printf_parse("done_word return 0: true null, ignored\n");
Eric Andersen25f27032001-04-26 23:22:31 +00002960 return 0;
2961 }
2962 if (ctx->pending_redirect) {
2963 glob_target = &ctx->pending_redirect->word;
2964 } else {
2965 if (child->group) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00002966 syntax(NULL);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002967 debug_printf_parse("done_word return 1: syntax error, groups and arglists don't mix\n");
2968 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002969 }
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002970 if (!child->argv && (ctx->parse_type & PARSEFLAG_SEMICOLON)) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002971 debug_printf_parse(": checking '%s' for reserved-ness\n", dest->data);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002972 if (reserved_word(dest, ctx)) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002973 debug_printf_parse("done_word return %d\n", (ctx->res_w == RES_SNTX));
2974 return (ctx->res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002975 }
Eric Andersen25f27032001-04-26 23:22:31 +00002976 }
2977 glob_target = &child->glob_result;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002978 if (child->argv)
2979 flags |= GLOB_APPEND;
Eric Andersen25f27032001-04-26 23:22:31 +00002980 }
2981 gr = xglob(dest, flags, glob_target);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002982 if (gr != 0) {
2983 debug_printf_parse("done_word return 1: xglob returned %d\n", gr);
2984 return 1;
2985 }
Eric Andersen25f27032001-04-26 23:22:31 +00002986
2987 b_reset(dest);
2988 if (ctx->pending_redirect) {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00002989 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002990 if (glob_target->gl_pathc != 1) {
Manuel Novoa III cad53642003-03-19 09:13:01 +00002991 bb_error_msg("ambiguous redirect");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002992 debug_printf_parse("done_word return 1: ambiguous redirect\n");
Eric Andersen25f27032001-04-26 23:22:31 +00002993 return 1;
2994 }
2995 } else {
2996 child->argv = glob_target->gl_pathv;
2997 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002998#if ENABLE_HUSH_LOOPS
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002999 if (ctx->res_w == RES_FOR) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003000 done_word(dest, ctx);
3001 done_pipe(ctx, PIPE_SEQ);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003002 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003003#endif
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003004 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003005 return 0;
3006}
3007
3008/* The only possible error here is out of memory, in which case
3009 * xmalloc exits. */
3010static int done_command(struct p_context *ctx)
3011{
3012 /* The child is really already in the pipe structure, so
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003013 * advance the pipe counter and make a new, null child. */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003014 struct pipe *pi = ctx->pipe;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003015 struct child_prog *child = ctx->child;
Eric Andersen25f27032001-04-26 23:22:31 +00003016
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003017 if (child) {
3018 if (child->group == NULL
3019 && child->argv == NULL
3020 && child->redirects == NULL
3021 ) {
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003022 debug_printf_parse("done_command: skipping null cmd, num_progs=%d\n", pi->num_progs);
3023 return pi->num_progs;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003024 }
Eric Andersen25f27032001-04-26 23:22:31 +00003025 pi->num_progs++;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003026 debug_printf_parse("done_command: ++num_progs=%d\n", pi->num_progs);
Eric Andersen25f27032001-04-26 23:22:31 +00003027 } else {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003028 debug_printf_parse("done_command: initializing, num_progs=%d\n", pi->num_progs);
Eric Andersen25f27032001-04-26 23:22:31 +00003029 }
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003030
3031 /* Only real trickiness here is that the uncommitted
3032 * child structure is not counted in pi->num_progs. */
Eric Andersen25f27032001-04-26 23:22:31 +00003033 pi->progs = xrealloc(pi->progs, sizeof(*pi->progs) * (pi->num_progs+1));
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003034 child = &pi->progs[pi->num_progs];
Eric Andersen25f27032001-04-26 23:22:31 +00003035
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003036 memset(child, 0, sizeof(*child));
3037 /*child->redirects = NULL;*/
3038 /*child->argv = NULL;*/
3039 /*child->is_stopped = 0;*/
3040 /*child->group = NULL;*/
3041 /*child->glob_result.gl_pathv = NULL;*/
3042 child->family = pi;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003043 //sp: /*child->sp = 0;*/
Denis Vlasenko262d7652007-05-20 21:52:49 +00003044 //pt: child->parse_type = ctx->parse_type;
Eric Andersen25f27032001-04-26 23:22:31 +00003045
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003046 ctx->child = child;
Eric Andersen25f27032001-04-26 23:22:31 +00003047 /* but ctx->pipe and ctx->list_head remain unchanged */
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003048
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003049 return pi->num_progs; /* used only for 0/nonzero check */
Eric Andersen25f27032001-04-26 23:22:31 +00003050}
3051
3052static int done_pipe(struct p_context *ctx, pipe_style type)
3053{
3054 struct pipe *new_p;
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003055 int not_null;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003056
3057 debug_printf_parse("done_pipe entered, followup %d\n", type);
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003058 not_null = done_command(ctx); /* implicit closure of previous command */
Eric Andersen25f27032001-04-26 23:22:31 +00003059 ctx->pipe->followup = type;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00003060 ctx->pipe->res_word = ctx->res_w;
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003061 /* Without this check, even just <enter> on command line generates
3062 * tree of three NOPs (!). Which is harmless but annoying.
3063 * IOW: it is safe to do it unconditionally. */
3064 if (not_null) {
3065 new_p = new_pipe();
3066 ctx->pipe->next = new_p;
3067 ctx->pipe = new_p;
3068 ctx->child = NULL;
3069 done_command(ctx); /* set up new pipe to accept commands */
3070 }
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003071 debug_printf_parse("done_pipe return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003072 return 0;
3073}
3074
3075/* peek ahead in the in_str to find out if we have a "&n" construct,
3076 * as in "2>&1", that represents duplicating a file descriptor.
3077 * returns either -2 (syntax error), -1 (no &), or the number found.
3078 */
3079static int redirect_dup_num(struct in_str *input)
3080{
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003081 int ch, d = 0, ok = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003082 ch = b_peek(input);
3083 if (ch != '&') return -1;
3084
3085 b_getch(input); /* get the & */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003086 ch = b_peek(input);
Eric Andersen83a2ae22001-05-07 17:59:25 +00003087 if (ch == '-') {
3088 b_getch(input);
3089 return -3; /* "-" represents "close me" */
3090 }
3091 while (isdigit(ch)) {
Denis Vlasenko7d4c44e2007-04-16 22:34:39 +00003092 d = d*10 + (ch-'0');
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003093 ok = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003094 b_getch(input);
Eric Andersen83a2ae22001-05-07 17:59:25 +00003095 ch = b_peek(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003096 }
3097 if (ok) return d;
3098
Manuel Novoa III cad53642003-03-19 09:13:01 +00003099 bb_error_msg("ambiguous redirect");
Eric Andersen25f27032001-04-26 23:22:31 +00003100 return -2;
3101}
3102
3103/* If a redirect is immediately preceded by a number, that number is
3104 * supposed to tell which file descriptor to redirect. This routine
3105 * looks for such preceding numbers. In an ideal world this routine
3106 * needs to handle all the following classes of redirects...
3107 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3108 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3109 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3110 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3111 * A -1 output from this program means no valid number was found, so the
3112 * caller should use the appropriate default for this redirection.
3113 */
3114static int redirect_opt_num(o_string *o)
3115{
3116 int num;
3117
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003118 if (o->length == 0)
3119 return -1;
3120 for (num = 0; num < o->length; num++) {
3121 if (!isdigit(*(o->data + num))) {
Eric Andersen25f27032001-04-26 23:22:31 +00003122 return -1;
3123 }
3124 }
3125 /* reuse num (and save an int) */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003126 num = atoi(o->data);
Eric Andersen25f27032001-04-26 23:22:31 +00003127 b_reset(o);
3128 return num;
3129}
3130
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003131#if ENABLE_HUSH_TICK
"Vladimir N. Oleynik"19c37012005-09-22 14:33:15 +00003132static FILE *generate_stream_from_list(struct pipe *head)
Eric Andersen25f27032001-04-26 23:22:31 +00003133{
3134 FILE *pf;
Eric Andersen25f27032001-04-26 23:22:31 +00003135 int pid, channel[2];
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003136
3137 if (pipe(channel) < 0)
3138 bb_perror_msg_and_die("pipe");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003139#if BB_MMU
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003140 pid = fork();
Eric Andersen72f9a422001-10-28 05:12:20 +00003141#else
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003142 pid = vfork();
Eric Andersen72f9a422001-10-28 05:12:20 +00003143#endif
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003144 if (pid < 0) {
Manuel Novoa III cad53642003-03-19 09:13:01 +00003145 bb_perror_msg_and_die("fork");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003146 } else if (pid == 0) {
Eric Andersen25f27032001-04-26 23:22:31 +00003147 close(channel[0]);
3148 if (channel[1] != 1) {
Denis Vlasenko7d4c44e2007-04-16 22:34:39 +00003149 dup2(channel[1], 1);
Eric Andersen25f27032001-04-26 23:22:31 +00003150 close(channel[1]);
3151 }
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003152 /* Prevent it from trying to handle ctrl-z etc */
3153 run_list_level = 1;
3154 /* Process substitution is not considered to be usual
3155 * 'command execution'.
3156 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not. */
3157 /* Not needed, we are relying on it being disabled
3158 * everywhere outside actual command execution. */
3159 /*set_jobctrl_sighandler(SIG_IGN);*/
3160 set_misc_sighandler(SIG_DFL);
Eric Andersen94ac2442001-05-22 19:05:18 +00003161 _exit(run_list_real(head)); /* leaks memory */
Eric Andersen25f27032001-04-26 23:22:31 +00003162 }
Eric Andersen25f27032001-04-26 23:22:31 +00003163 close(channel[1]);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003164 pf = fdopen(channel[0], "r");
Eric Andersen25f27032001-04-26 23:22:31 +00003165 return pf;
3166}
3167
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003168/* Return code is exit status of the process that is run. */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003169static int process_command_subs(o_string *dest, struct p_context *ctx,
3170 struct in_str *input, const char *subst_end)
Eric Andersen25f27032001-04-26 23:22:31 +00003171{
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003172 int retcode, ch, eol_cnt;
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003173 o_string result = NULL_O_STRING;
Eric Andersen25f27032001-04-26 23:22:31 +00003174 struct p_context inner;
3175 FILE *p;
3176 struct in_str pipe_str;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003177
Eric Andersen25f27032001-04-26 23:22:31 +00003178 initialize_context(&inner);
3179
3180 /* recursion to generate command */
3181 retcode = parse_stream(&result, &inner, input, subst_end);
Denis Vlasenko1a735862007-05-23 00:32:25 +00003182 if (retcode != 0)
3183 return retcode; /* syntax error or EOF */
Eric Andersen25f27032001-04-26 23:22:31 +00003184 done_word(&result, &inner);
3185 done_pipe(&inner, PIPE_SEQ);
3186 b_free(&result);
3187
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003188 p = generate_stream_from_list(inner.list_head);
3189 if (p == NULL) return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003190 mark_open(fileno(p));
3191 setup_file_in_str(&pipe_str, p);
3192
3193 /* now send results of command back into original context */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003194 eol_cnt = 0;
3195 while ((ch = b_getch(&pipe_str)) != EOF) {
3196 if (ch == '\n') {
3197 eol_cnt++;
3198 continue;
3199 }
3200 while (eol_cnt) {
3201 b_addqchr(dest, '\n', dest->quote);
3202 eol_cnt--;
3203 }
3204 b_addqchr(dest, ch, dest->quote);
Eric Andersen25f27032001-04-26 23:22:31 +00003205 }
3206
3207 debug_printf("done reading from pipe, pclose()ing\n");
3208 /* This is the step that wait()s for the child. Should be pretty
3209 * safe, since we just read an EOF from its stdout. We could try
Denis Vlasenko262d7652007-05-20 21:52:49 +00003210 * to do better, by using wait(), and keeping track of background jobs
Eric Andersen25f27032001-04-26 23:22:31 +00003211 * at the same time. That would be a lot of work, and contrary
3212 * to the KISS philosophy of this program. */
3213 mark_closed(fileno(p));
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003214 retcode = fclose(p);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003215 free_pipe_list(inner.list_head, 0);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003216 debug_printf("closed FILE from child, retcode=%d\n", retcode);
Eric Andersen25f27032001-04-26 23:22:31 +00003217 return retcode;
3218}
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003219#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003220
3221static int parse_group(o_string *dest, struct p_context *ctx,
3222 struct in_str *input, int ch)
3223{
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003224 int rcode;
3225 const char *endch = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003226 struct p_context sub;
3227 struct child_prog *child = ctx->child;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003228
3229 debug_printf_parse("parse_group entered\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003230 if (child->argv) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003231 syntax(NULL);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003232 debug_printf_parse("parse_group return 1: syntax error, groups and arglists don't mix\n");
3233 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003234 }
3235 initialize_context(&sub);
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003236 endch = "}";
3237 if (ch == '(') {
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003238 endch = ")";
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003239 child->subshell = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003240 }
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003241 rcode = parse_stream(dest, &sub, input, endch);
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00003242//vda: err chk?
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003243 done_word(dest, &sub); /* finish off the final word in the subcontext */
Eric Andersen25f27032001-04-26 23:22:31 +00003244 done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */
3245 child->group = sub.list_head;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003246
3247 debug_printf_parse("parse_group return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00003248 return rcode;
3249 /* child remains "open", available for possible redirects */
3250}
3251
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003252/* Basically useful version until someone wants to get fancier,
Eric Andersen25f27032001-04-26 23:22:31 +00003253 * see the bash man page under "Parameter Expansion" */
Denis Vlasenko15d78fb2007-01-30 22:28:21 +00003254static const char *lookup_param(const char *src)
Eric Andersen25f27032001-04-26 23:22:31 +00003255{
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003256 struct variable *var = get_local_var(src);
3257 if (var)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00003258 return strchr(var->varstr, '=') + 1;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003259 return NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003260}
3261
3262/* return code: 0 for OK, 1 for syntax error */
3263static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input)
3264{
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003265 int ch = b_peek(input); /* first character after the $ */
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003266 unsigned char quote_mask = dest->quote ? 0x80 : 0;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003267
3268 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003269 if (isalpha(ch)) {
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003270 b_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003271 //sp: ctx->child->sp++;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003272 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003273 debug_printf_parse(": '%c'\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003274 b_getch(input);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003275 b_addchr(dest, ch | quote_mask);
3276 quote_mask = 0;
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003277 ch = b_peek(input);
3278 if (!isalnum(ch) && ch != '_')
3279 break;
Eric Andersen25f27032001-04-26 23:22:31 +00003280 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003281 b_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003282 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003283 make_one_char_var:
3284 b_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003285 //sp: ctx->child->sp++;
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003286 debug_printf_parse(": '%c'\n", ch);
3287 b_getch(input);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003288 b_addchr(dest, ch | quote_mask);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003289 b_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003290 } else switch (ch) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003291 case '$': /* pid */
3292 case '!': /* last bg pid */
3293 case '?': /* last exit code */
3294 case '#': /* number of args */
3295 case '*': /* args */
3296 case '@': /* args */
3297 goto make_one_char_var;
Eric Andersen25f27032001-04-26 23:22:31 +00003298 case '{':
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003299 b_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003300 //sp: ctx->child->sp++;
Eric Andersen25f27032001-04-26 23:22:31 +00003301 b_getch(input);
3302 /* XXX maybe someone will try to escape the '}' */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003303 while (1) {
3304 ch = b_getch(input);
Denis Vlasenkob0550012007-05-24 12:18:16 +00003305 if (ch == '}')
3306 break;
3307 if (!isalnum(ch) && ch != '_') {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003308 syntax("unterminated ${name}");
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003309 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
3310 return 1;
3311 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003312 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003313 b_addchr(dest, ch | quote_mask);
3314 quote_mask = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003315 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003316 b_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003317 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003318#if ENABLE_HUSH_TICK
Eric Andersen25f27032001-04-26 23:22:31 +00003319 case '(':
Matt Kraai9f8caf12001-05-02 16:26:12 +00003320 b_getch(input);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003321 process_command_subs(dest, ctx, input, ")");
Eric Andersen25f27032001-04-26 23:22:31 +00003322 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003323#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003324 case '-':
3325 case '_':
3326 /* still unhandled, but should be eventually */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003327 bb_error_msg("unhandled syntax: $%c", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003328 return 1;
3329 break;
3330 default:
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003331 b_addqchr(dest, '$', dest->quote);
Eric Andersen25f27032001-04-26 23:22:31 +00003332 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003333 debug_printf_parse("handle_dollar return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003334 return 0;
3335}
3336
Eric Andersen25f27032001-04-26 23:22:31 +00003337/* return code is 0 for normal exit, 1 for syntax error */
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003338static int parse_stream(o_string *dest, struct p_context *ctx,
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003339 struct in_str *input, const char *end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00003340{
"Vladimir N. Oleynik"4ccd2b42006-01-31 09:27:48 +00003341 int ch, m;
Eric Andersen25f27032001-04-26 23:22:31 +00003342 int redir_fd;
3343 redir_type redir_style;
3344 int next;
3345
3346 /* Only double-quote state is handled in the state variable dest->quote.
3347 * A single-quote triggers a bypass of the main loop until its mate is
3348 * found. When recursing, quote state is passed in via dest->quote. */
3349
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003350 debug_printf_parse("parse_stream entered, end_trigger='%s'\n", end_trigger);
3351
Denis Vlasenko1a735862007-05-23 00:32:25 +00003352 while (1) {
Denis Vlasenko1a735862007-05-23 00:32:25 +00003353 m = CHAR_IFS;
3354 next = '\0';
Denis Vlasenko170435c2007-05-23 13:01:10 +00003355 ch = b_getch(input);
Denis Vlasenko1a735862007-05-23 00:32:25 +00003356 if (ch != EOF) {
3357 m = charmap[ch];
3358 if (ch != '\n')
3359 next = b_peek(input);
3360 }
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003361 debug_printf_parse(": ch=%c (%d) m=%d quote=%d\n",
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003362 ch, ch, m, dest->quote);
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003363 if (m == CHAR_ORDINARY
3364 || (m != CHAR_SPECIAL && dest->quote)
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003365 ) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00003366 if (ch == EOF) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003367 syntax("unterminated \"");
Denis Vlasenko170435c2007-05-23 13:01:10 +00003368 debug_printf_parse("parse_stream return 1: unterminated \"\n");
3369 return 1;
3370 }
Eric Andersen25f27032001-04-26 23:22:31 +00003371 b_addqchr(dest, ch, dest->quote);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003372 continue;
3373 }
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003374 if (m == CHAR_IFS) {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003375 if (done_word(dest, ctx)) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003376 debug_printf_parse("parse_stream return 1: done_word!=0\n");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003377 return 1;
Eric Andersenaac75e52001-04-30 18:18:45 +00003378 }
Denis Vlasenko1a735862007-05-23 00:32:25 +00003379 if (ch == EOF)
3380 break;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003381 /* If we aren't performing a substitution, treat
3382 * a newline as a command separator.
3383 * [why we don't handle it exactly like ';'? --vda] */
3384 if (end_trigger && ch == '\n') {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003385 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003386 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003387 }
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003388 if ((end_trigger && strchr(end_trigger, ch))
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003389 && !dest->quote && ctx->res_w == RES_NONE
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003390 ) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003391 debug_printf_parse("parse_stream return 0: end_trigger char found\n");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003392 return 0;
3393 }
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003394 if (m == CHAR_IFS)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003395 continue;
3396 switch (ch) {
Eric Andersen25f27032001-04-26 23:22:31 +00003397 case '#':
3398 if (dest->length == 0 && !dest->quote) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003399 while (1) {
3400 ch = b_peek(input);
3401 if (ch == EOF || ch == '\n')
3402 break;
3403 b_getch(input);
3404 }
Eric Andersen25f27032001-04-26 23:22:31 +00003405 } else {
3406 b_addqchr(dest, ch, dest->quote);
3407 }
3408 break;
3409 case '\\':
3410 if (next == EOF) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003411 syntax("\\<eof>");
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003412 debug_printf_parse("parse_stream return 1: \\<eof>\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003413 return 1;
3414 }
3415 b_addqchr(dest, '\\', dest->quote);
3416 b_addqchr(dest, b_getch(input), dest->quote);
3417 break;
3418 case '$':
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003419 if (handle_dollar(dest, ctx, input) != 0) {
3420 debug_printf_parse("parse_stream return 1: handle_dollar returned non-0\n");
3421 return 1;
3422 }
Eric Andersen25f27032001-04-26 23:22:31 +00003423 break;
3424 case '\'':
3425 dest->nonnull = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003426 while (1) {
3427 ch = b_getch(input);
3428 if (ch == EOF || ch == '\'')
3429 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003430 b_addchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003431 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003432 if (ch == EOF) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003433 syntax("unterminated '");
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003434 debug_printf_parse("parse_stream return 1: unterminated '\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003435 return 1;
3436 }
3437 break;
3438 case '"':
3439 dest->nonnull = 1;
3440 dest->quote = !dest->quote;
3441 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003442#if ENABLE_HUSH_TICK
Eric Andersen25f27032001-04-26 23:22:31 +00003443 case '`':
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003444 process_command_subs(dest, ctx, input, "`");
Eric Andersen25f27032001-04-26 23:22:31 +00003445 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003446#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003447 case '>':
3448 redir_fd = redirect_opt_num(dest);
3449 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003450 redir_style = REDIRECT_OVERWRITE;
Eric Andersen25f27032001-04-26 23:22:31 +00003451 if (next == '>') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003452 redir_style = REDIRECT_APPEND;
Eric Andersen25f27032001-04-26 23:22:31 +00003453 b_getch(input);
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003454 }
3455#if 0
3456 else if (next == '(') {
3457 syntax(">(process) not supported");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003458 debug_printf_parse("parse_stream return 1: >(process) not supported\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003459 return 1;
3460 }
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003461#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003462 setup_redirect(ctx, redir_fd, redir_style, input);
3463 break;
3464 case '<':
3465 redir_fd = redirect_opt_num(dest);
3466 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003467 redir_style = REDIRECT_INPUT;
Eric Andersen25f27032001-04-26 23:22:31 +00003468 if (next == '<') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003469 redir_style = REDIRECT_HEREIS;
Eric Andersen25f27032001-04-26 23:22:31 +00003470 b_getch(input);
3471 } else if (next == '>') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003472 redir_style = REDIRECT_IO;
Eric Andersen25f27032001-04-26 23:22:31 +00003473 b_getch(input);
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003474 }
3475#if 0
3476 else if (next == '(') {
3477 syntax("<(process) not supported");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003478 debug_printf_parse("parse_stream return 1: <(process) not supported\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003479 return 1;
3480 }
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003481#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003482 setup_redirect(ctx, redir_fd, redir_style, input);
3483 break;
3484 case ';':
3485 done_word(dest, ctx);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003486 done_pipe(ctx, PIPE_SEQ);
Eric Andersen25f27032001-04-26 23:22:31 +00003487 break;
3488 case '&':
3489 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003490 if (next == '&') {
Eric Andersen25f27032001-04-26 23:22:31 +00003491 b_getch(input);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003492 done_pipe(ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00003493 } else {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003494 done_pipe(ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00003495 }
3496 break;
3497 case '|':
3498 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003499 if (next == '|') {
Eric Andersen25f27032001-04-26 23:22:31 +00003500 b_getch(input);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003501 done_pipe(ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00003502 } else {
3503 /* we could pick up a file descriptor choice here
3504 * with redirect_opt_num(), but bash doesn't do it.
3505 * "echo foo 2| cat" yields "foo 2". */
3506 done_command(ctx);
3507 }
3508 break;
3509 case '(':
3510 case '{':
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003511 if (parse_group(dest, ctx, input, ch) != 0) {
3512 debug_printf_parse("parse_stream return 1: parse_group returned non-0\n");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003513 return 1;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003514 }
Eric Andersen25f27032001-04-26 23:22:31 +00003515 break;
3516 case ')':
3517 case '}':
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003518 syntax("unexpected }"); /* Proper use of this character is caught by end_trigger */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003519 debug_printf_parse("parse_stream return 1: unexpected '}'\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003520 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003521 default:
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003522 if (ENABLE_HUSH_DEBUG)
3523 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003524 }
3525 }
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003526 /* Complain if quote? No, maybe we just finished a command substitution
Eric Andersen25f27032001-04-26 23:22:31 +00003527 * that was quoted. Example:
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003528 * $ echo "`cat foo` plus more"
Eric Andersen25f27032001-04-26 23:22:31 +00003529 * and we just got the EOF generated by the subshell that ran "cat foo"
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003530 * The only real complaint is if we got an EOF when end_trigger != NULL,
Eric Andersen25f27032001-04-26 23:22:31 +00003531 * that is, we were really supposed to get end_trigger, and never got
3532 * one before the EOF. Can't use the standard "syntax error" return code,
3533 * so that parse_stream_outer can distinguish the EOF and exit smoothly. */
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003534 debug_printf_parse("parse_stream return %d\n", -(end_trigger != NULL));
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003535 if (end_trigger)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003536 return -1;
Eric Andersen25f27032001-04-26 23:22:31 +00003537 return 0;
3538}
3539
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003540static void set_in_charmap(const char *set, int code)
Eric Andersen25f27032001-04-26 23:22:31 +00003541{
Denis Vlasenkof5294e12007-04-14 10:09:57 +00003542 while (*set)
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003543 charmap[(unsigned char)*set++] = code;
Eric Andersen25f27032001-04-26 23:22:31 +00003544}
3545
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003546static void update_charmap(void)
Eric Andersen25f27032001-04-26 23:22:31 +00003547{
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003548 /* char *ifs and char charmap[256] are both globals. */
Eric Andersen25f27032001-04-26 23:22:31 +00003549 ifs = getenv("IFS");
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003550 if (ifs == NULL)
3551 ifs = " \t\n";
Eric Andersen25f27032001-04-26 23:22:31 +00003552 /* Precompute a list of 'flow through' behavior so it can be treated
3553 * quickly up front. Computation is necessary because of IFS.
3554 * Special case handling of IFS == " \t\n" is not implemented.
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003555 * The charmap[] array only really needs two bits each,
3556 * and on most machines that would be faster (reduced L1 cache use).
Eric Andersen25f27032001-04-26 23:22:31 +00003557 */
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003558 memset(charmap, CHAR_ORDINARY, sizeof(charmap));
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003559#if ENABLE_HUSH_TICK
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003560 set_in_charmap("\\$\"`", CHAR_SPECIAL);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003561#else
3562 set_in_charmap("\\$\"", CHAR_SPECIAL);
3563#endif
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003564 set_in_charmap("<>;&|(){}#'", CHAR_ORDINARY_IF_QUOTED);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003565 set_in_charmap(ifs, CHAR_IFS); /* are ordinary if quoted */
Eric Andersen25f27032001-04-26 23:22:31 +00003566}
3567
Eric Andersenaff114c2004-04-14 17:51:38 +00003568/* most recursion does not come through here, the exception is
Denis Vlasenko170435c2007-05-23 13:01:10 +00003569 * from builtin_source() and builtin_eval() */
3570static int parse_and_run_stream(struct in_str *inp, int parse_flag)
Eric Andersen25f27032001-04-26 23:22:31 +00003571{
Eric Andersen25f27032001-04-26 23:22:31 +00003572 struct p_context ctx;
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003573 o_string temp = NULL_O_STRING;
Eric Andersen25f27032001-04-26 23:22:31 +00003574 int rcode;
3575 do {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003576 ctx.parse_type = parse_flag;
Eric Andersen25f27032001-04-26 23:22:31 +00003577 initialize_context(&ctx);
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003578 update_charmap();
Denis Vlasenko219e88d2007-05-21 10:18:23 +00003579 if (!(parse_flag & PARSEFLAG_SEMICOLON) || (parse_flag & PARSEFLAG_REPARSING))
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003580 set_in_charmap(";$&|", CHAR_ORDINARY);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003581#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00003582 inp->promptmode = 0; /* PS1 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003583#endif
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003584 /* We will stop & execute after each ';' or '\n'.
3585 * Example: "sleep 9999; echo TEST" + ctrl-C:
3586 * TEST should be printed */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003587 rcode = parse_stream(&temp, &ctx, inp, ";\n");
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003588 if (rcode != 1 && ctx.old_flag != 0) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003589 syntax(NULL);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003590 }
3591 if (rcode != 1 && ctx.old_flag == 0) {
3592 done_word(&temp, &ctx);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003593 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003594 debug_print_tree(ctx.list_head, 0);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003595 debug_printf_exec("parse_stream_outer: run_list\n");
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003596 run_list(ctx.list_head);
3597 } else {
3598 if (ctx.old_flag != 0) {
3599 free(ctx.stack);
3600 b_reset(&temp);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003601 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003602 temp.nonnull = 0;
3603 temp.quote = 0;
3604 inp->p = NULL;
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00003605 free_pipe_list(ctx.list_head, 0);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003606 }
Eric Andersena813afc2001-05-24 16:19:36 +00003607 b_free(&temp);
Denis Vlasenko219e88d2007-05-21 10:18:23 +00003608 } while (rcode != -1 && !(parse_flag & PARSEFLAG_EXIT_FROM_LOOP)); /* loop on syntax errors, return on EOF */
Eric Andersen25f27032001-04-26 23:22:31 +00003609 return 0;
3610}
3611
Denis Vlasenko170435c2007-05-23 13:01:10 +00003612static int parse_and_run_string(const char *s, int parse_flag)
Eric Andersen25f27032001-04-26 23:22:31 +00003613{
3614 struct in_str input;
3615 setup_string_in_str(&input, s);
Denis Vlasenko170435c2007-05-23 13:01:10 +00003616 return parse_and_run_stream(&input, parse_flag);
Eric Andersen25f27032001-04-26 23:22:31 +00003617}
3618
Denis Vlasenko170435c2007-05-23 13:01:10 +00003619static int parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00003620{
3621 int rcode;
3622 struct in_str input;
3623 setup_file_in_str(&input, f);
Denis Vlasenko170435c2007-05-23 13:01:10 +00003624 rcode = parse_and_run_stream(&input, PARSEFLAG_SEMICOLON);
Eric Andersen25f27032001-04-26 23:22:31 +00003625 return rcode;
3626}
3627
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003628#if ENABLE_HUSH_JOB
Eric Andersen6c947d22001-06-25 22:24:38 +00003629/* Make sure we have a controlling tty. If we get started under a job
3630 * aware app (like bash for example), make sure we are now in charge so
3631 * we don't fight over who gets the foreground */
Eric Anderseneaecbf32001-10-31 10:41:31 +00003632static void setup_job_control(void)
Eric Andersen52a97ca2001-06-22 06:49:26 +00003633{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003634 pid_t shell_pgrp;
3635
Denis Vlasenkoa6a17852007-04-28 16:42:11 +00003636 saved_task_pgrp = shell_pgrp = getpgrp();
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003637 debug_printf_jobs("saved_task_pgrp=%d\n", saved_task_pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003638 fcntl(interactive_fd, F_SETFD, FD_CLOEXEC);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003639
Denis Vlasenkoa6a17852007-04-28 16:42:11 +00003640 /* If we were ran as 'hush &',
3641 * sleep until we are in the foreground. */
3642 while (tcgetpgrp(interactive_fd) != shell_pgrp) {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003643 /* Send TTIN to ourself (should stop us) */
Denis Vlasenkoff131b92007-04-10 15:42:06 +00003644 kill(- shell_pgrp, SIGTTIN);
Denis Vlasenkoa6a17852007-04-28 16:42:11 +00003645 shell_pgrp = getpgrp();
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003646 }
Eric Andersen52a97ca2001-06-22 06:49:26 +00003647
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003648 /* Ignore job-control and misc signals. */
3649 set_jobctrl_sighandler(SIG_IGN);
3650 set_misc_sighandler(SIG_IGN);
3651//huh? signal(SIGCHLD, SIG_IGN);
3652
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003653 /* We _must_ restore tty pgrp on fatal signals */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003654 set_fatal_sighandler(sigexit);
Eric Andersen6c947d22001-06-25 22:24:38 +00003655
3656 /* Put ourselves in our own process group. */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003657 setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
Eric Andersen6c947d22001-06-25 22:24:38 +00003658 /* Grab control of the terminal. */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003659 tcsetpgrp(interactive_fd, getpid());
Eric Andersen6c947d22001-06-25 22:24:38 +00003660}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003661#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00003662
Denis Vlasenko06af2162007-02-03 17:28:39 +00003663int hush_main(int argc, char **argv);
Matt Kraai2d91deb2001-08-01 17:21:35 +00003664int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00003665{
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00003666 static const char version_str[] = "HUSH_VERSION="HUSH_VER_STR;
3667 static const struct variable const_shell_ver = {
3668 .next = NULL,
3669 .varstr = (char*)version_str,
3670 .max_len = 1, /* 0 can provoke free(name) */
3671 .flg_export = 1,
3672 .flg_read_only = 1,
3673 };
3674
Eric Andersen25f27032001-04-26 23:22:31 +00003675 int opt;
3676 FILE *input;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003677 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003678 struct variable *cur_var;
Eric Andersenbc604a22001-05-16 05:24:03 +00003679
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00003680 PTR_TO_GLOBALS = xzalloc(sizeof(G));
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003681
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00003682 /* Deal with HUSH_VERSION */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00003683 shell_ver = const_shell_ver; /* copying struct here */
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003684 top_var = &shell_ver;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00003685 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
3686 /* Initialize our shell local variables with the values
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003687 * currently living in the environment */
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003688 cur_var = top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00003689 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003690 if (e) while (*e) {
3691 char *value = strchr(*e, '=');
3692 if (value) { /* paranoia */
3693 cur_var->next = xzalloc(sizeof(*cur_var));
3694 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00003695 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003696 cur_var->max_len = strlen(*e);
3697 cur_var->flg_export = 1;
3698 }
3699 e++;
3700 }
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00003701 putenv((char *)version_str); /* reinstate HUSH_VERSION */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00003702
Denis Vlasenko38f63192007-01-22 09:03:07 +00003703#if ENABLE_FEATURE_EDITING
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00003704 line_input_state = new_line_input_t(FOR_SHELL);
3705#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003706 /* XXX what should these be while sourcing /etc/profile? */
3707 global_argc = argc;
3708 global_argv = argv;
Eric Andersen94ac2442001-05-22 19:05:18 +00003709 /* Initialize some more globals to non-zero values */
3710 set_cwd();
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003711#if ENABLE_HUSH_INTERACTIVE
3712#if ENABLE_FEATURE_EDITING
3713 cmdedit_set_initial_prompt();
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003714#endif
Eric Andersen94ac2442001-05-22 19:05:18 +00003715 PS2 = "> ";
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003716#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00003717
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003718 if (EXIT_SUCCESS) /* otherwise is already done */
3719 last_return_code = EXIT_SUCCESS;
Eric Andersen25f27032001-04-26 23:22:31 +00003720
3721 if (argv[0] && argv[0][0] == '-') {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003722 debug_printf("sourcing /etc/profile\n");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003723 input = fopen("/etc/profile", "r");
3724 if (input != NULL) {
Eric Andersena90f20b2001-06-26 23:00:21 +00003725 mark_open(fileno(input));
Denis Vlasenko170435c2007-05-23 13:01:10 +00003726 parse_and_run_file(input);
Eric Andersena90f20b2001-06-26 23:00:21 +00003727 mark_closed(fileno(input));
3728 fclose(input);
3729 }
Eric Andersen25f27032001-04-26 23:22:31 +00003730 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003731 input = stdin;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003732
Eric Andersen25f27032001-04-26 23:22:31 +00003733 while ((opt = getopt(argc, argv, "c:xif")) > 0) {
3734 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003735 case 'c':
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003736 global_argv = argv + optind;
3737 global_argc = argc - optind;
Denis Vlasenko170435c2007-05-23 13:01:10 +00003738 opt = parse_and_run_string(optarg, PARSEFLAG_SEMICOLON);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003739 goto final_return;
3740 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003741 /* Well, we cannot just declare interactiveness,
3742 * we have to have some stuff (ctty, etc) */
3743 /* interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003744 break;
3745 case 'f':
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00003746 fake_mode = 1;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003747 break;
3748 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00003749#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003750 fprintf(stderr, "Usage: sh [FILE]...\n"
3751 " or: sh -c command [args]...\n\n");
3752 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00003753#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003754 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00003755#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003756 }
3757 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003758#if ENABLE_HUSH_JOB
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003759 /* A shell is interactive if the '-i' flag was given, or if all of
Eric Andersen25f27032001-04-26 23:22:31 +00003760 * the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00003761 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00003762 * no arguments remaining or the -s flag given
3763 * standard input is a terminal
3764 * standard output is a terminal
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003765 * Refer to Posix.2, the description of the 'sh' utility. */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003766 if (argv[optind] == NULL && input == stdin
3767 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3768 ) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003769 saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
3770 debug_printf("saved_tty_pgrp=%d\n", saved_tty_pgrp);
3771 if (saved_tty_pgrp >= 0) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003772 /* try to dup to high fd#, >= 255 */
3773 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3774 if (interactive_fd < 0) {
3775 /* try to dup to any fd */
3776 interactive_fd = dup(STDIN_FILENO);
3777 if (interactive_fd < 0)
3778 /* give up */
3779 interactive_fd = 0;
3780 }
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00003781 // TODO: track & disallow any attempts of user
3782 // to (inadvertently) close/redirect it
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003783 }
Eric Andersen25f27032001-04-26 23:22:31 +00003784 }
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003785 debug_printf("interactive_fd=%d\n", interactive_fd);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003786 if (interactive_fd) {
Eric Andersen25f27032001-04-26 23:22:31 +00003787 /* Looks like they want an interactive shell */
Eric Andersen52a97ca2001-06-22 06:49:26 +00003788 setup_job_control();
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003789 /* Make xfuncs do cleanup on exit */
3790 die_sleep = -1; /* flag */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003791// FIXME: should we reset die_sleep = 0 whereever we fork?
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003792 if (setjmp(die_jmp)) {
3793 /* xfunc has failed! die die die */
3794 hush_exit(xfunc_error_retval);
3795 }
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00003796#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denis Vlasenkoef36ead2007-05-02 15:34:47 +00003797 printf("\n\n%s hush - the humble shell v"HUSH_VER_STR"\n", BB_BANNER);
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00003798 printf("Enter 'help' for a list of built-in commands.\n\n");
3799#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00003800 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003801#elif ENABLE_HUSH_INTERACTIVE
3802/* no job control compiled, only prompt/line editing */
3803 if (argv[optind] == NULL && input == stdin
3804 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3805 ) {
3806 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3807 if (interactive_fd < 0) {
3808 /* try to dup to any fd */
3809 interactive_fd = dup(STDIN_FILENO);
3810 if (interactive_fd < 0)
3811 /* give up */
3812 interactive_fd = 0;
3813 }
3814 }
3815
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003816#endif
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003817
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003818 if (argv[optind] == NULL) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00003819 opt = parse_and_run_file(stdin);
Eric Andersene67c3ce2001-05-02 02:09:36 +00003820 goto final_return;
Eric Andersen25f27032001-04-26 23:22:31 +00003821 }
Eric Andersen25f27032001-04-26 23:22:31 +00003822
3823 debug_printf("\nrunning script '%s'\n", argv[optind]);
Denis Vlasenko4c978632007-02-03 03:31:13 +00003824 global_argv = argv + optind;
3825 global_argc = argc - optind;
Rob Landleyd921b2e2006-08-03 15:41:12 +00003826 input = xfopen(argv[optind], "r");
Denis Vlasenko170435c2007-05-23 13:01:10 +00003827 opt = parse_and_run_file(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003828
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003829 final_return:
3830
Denis Vlasenko38f63192007-01-22 09:03:07 +00003831#if ENABLE_FEATURE_CLEAN_UP
Eric Andersenaeb44c42001-05-22 20:29:00 +00003832 fclose(input);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003833 if (cwd != bb_msg_unknown)
Eric Andersenaeb44c42001-05-22 20:29:00 +00003834 free((char*)cwd);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003835 cur_var = top_var->next;
3836 while (cur_var) {
3837 struct variable *tmp = cur_var;
3838 if (!cur_var->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00003839 free(cur_var->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003840 cur_var = cur_var->next;
3841 free(tmp);
Eric Andersenaeb44c42001-05-22 20:29:00 +00003842 }
Eric Andersen25f27032001-04-26 23:22:31 +00003843#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003844 hush_exit(opt ? opt : last_return_code);
Eric Andersen25f27032001-04-26 23:22:31 +00003845}