blob: 579950ff92d25d87eef9f5590da07898f68c6394 [file] [log] [blame]
Eric Andersen25f27032001-04-26 23:22:31 +00001/* vi: set sw=4 ts=4: */
2/*
3 * sh.c -- a prototype Bourne shell grammar parser
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
7 *
8 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
9 *
10 * Credits:
11 * The parser routines proper are all original material, first
Eric Andersencb81e642003-07-14 21:21:08 +000012 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
13 * execution engine, the builtins, and much of the underlying
14 * support has been adapted from busybox-0.49pre's lash, which is
Eric Andersenc7bda1c2004-03-15 08:29:22 +000015 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
Eric Andersencb81e642003-07-14 21:21:08 +000016 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
17 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
18 * Troan, which they placed in the public domain. I don't know
19 * how much of the Johnson/Troan code has survived the repeated
20 * rewrites.
21 *
Eric Andersen25f27032001-04-26 23:22:31 +000022 * Other credits:
Eric Andersen25f27032001-04-26 23:22:31 +000023 * b_addchr() derived from similar w_addchar function in glibc-2.2
24 * setup_redirect(), redirect_opt_num(), and big chunks of main()
Denis Vlasenko55b2de72007-04-18 17:21:28 +000025 * and many builtins derived from contributions by Erik Andersen
Eric Andersen25f27032001-04-26 23:22:31 +000026 * miscellaneous bugfixes from Matt Kraai
27 *
28 * There are two big (and related) architecture differences between
29 * this parser and the lash parser. One is that this version is
30 * actually designed from the ground up to understand nearly all
31 * of the Bourne grammar. The second, consequential change is that
32 * the parser and input reader have been turned inside out. Now,
33 * the parser is in control, and asks for input as needed. The old
34 * way had the input reader in control, and it asked for parsing to
35 * take place as needed. The new way makes it much easier to properly
36 * handle the recursion implicit in the various substitutions, especially
37 * across continuation lines.
38 *
39 * Bash grammar not implemented: (how many of these were in original sh?)
40 * $@ (those sure look like weird quoting rules)
41 * $_
42 * ! negation operator for pipes
43 * &> and >& redirection of stdout+stderr
44 * Brace Expansion
45 * Tilde Expansion
46 * fancy forms of Parameter Expansion
Eric Andersen78a7c992001-05-15 16:30:25 +000047 * aliases
Eric Andersen25f27032001-04-26 23:22:31 +000048 * Arithmetic Expansion
49 * <(list) and >(list) Process Substitution
Eric Andersen83a2ae22001-05-07 17:59:25 +000050 * reserved words: case, esac, select, function
Eric Andersen25f27032001-04-26 23:22:31 +000051 * Here Documents ( << word )
52 * Functions
53 * Major bugs:
Denis Vlasenkob81b3df2007-04-28 16:48:04 +000054 * job handling woefully incomplete and buggy (improved --vda)
Eric Andersen25f27032001-04-26 23:22:31 +000055 * reserved word execution woefully incomplete and buggy
Eric Andersen25f27032001-04-26 23:22:31 +000056 * to-do:
Eric Andersen83a2ae22001-05-07 17:59:25 +000057 * port selected bugfixes from post-0.49 busybox lash - done?
58 * finish implementing reserved words: for, while, until, do, done
59 * change { and } from special chars to reserved words
60 * builtins: break, continue, eval, return, set, trap, ulimit
61 * test magic exec
Eric Andersen25f27032001-04-26 23:22:31 +000062 * handle children going into background
63 * clean up recognition of null pipes
Eric Andersen25f27032001-04-26 23:22:31 +000064 * check setting of global_argc and global_argv
65 * control-C handling, probably with longjmp
Eric Andersen25f27032001-04-26 23:22:31 +000066 * follow IFS rules more precisely, including update semantics
Eric Andersen25f27032001-04-26 23:22:31 +000067 * figure out what to do with backslash-newline
68 * explain why we use signal instead of sigaction
69 * propagate syntax errors, die on resource errors?
70 * continuation lines, both explicit and implicit - done?
71 * memory leak finding and plugging - done?
72 * more testing, especially quoting rules and redirection
Eric Andersen78a7c992001-05-15 16:30:25 +000073 * document how quoting rules not precisely followed for variable assignments
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +000074 * maybe change charmap[] to use 2-bit entries
Eric Andersen25f27032001-04-26 23:22:31 +000075 * (eventually) remove all the printf's
Eric Andersen25f27032001-04-26 23:22:31 +000076 *
Bernhard Reutner-Fischer86f5c992006-01-22 22:55:11 +000077 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
Eric Andersen25f27032001-04-26 23:22:31 +000078 */
Bernhard Reutner-Fischere15d7572006-06-02 20:56:16 +000079
80#include "busybox.h"
Eric Andersen25f27032001-04-26 23:22:31 +000081#include <glob.h> /* glob, of course */
Eric Andersen25f27032001-04-26 23:22:31 +000082#include <getopt.h> /* should be pretty obvious */
Eric Andersen25f27032001-04-26 23:22:31 +000083/* #include <dmalloc.h> */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +000084extern char **environ; /* This is in <unistd.h>, but protected with __USE_GNU */
Denis Vlasenkod01ff132007-05-02 21:40:23 +000085
86
87/* If you comment out one of these below, it will be #defined later
88 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +000089#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +000090/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +000091#define debug_printf_parse(...) do {} while (0)
92#define debug_print_tree(a, b) do {} while (0)
93#define debug_printf_exec(...) do {} while (0)
94#define debug_printf_jobs(...) do {} while (0)
95#define debug_printf_expand(...) do {} while (0)
96#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +000097
98#ifndef debug_printf
99#define debug_printf(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000100#endif
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000101
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000102#ifndef debug_printf_parse
103#define debug_printf_parse(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000104#endif
105
106#ifndef debug_printf_exec
107#define debug_printf_exec(...) fprintf(stderr, __VA_ARGS__)
108#endif
109
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000110#ifndef debug_printf_jobs
111#define debug_printf_jobs(...) fprintf(stderr, __VA_ARGS__)
112#define DEBUG_SHELL_JOBS 1
113#endif
114
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000115#ifndef debug_printf_expand
116#define debug_printf_expand(...) fprintf(stderr, __VA_ARGS__)
117#define DEBUG_EXPAND 1
118#endif
119
Denis Vlasenko170435c2007-05-23 13:01:10 +0000120/* Keep unconditionally on for now */
121#define ENABLE_HUSH_DEBUG 1
122
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000123#ifndef debug_printf_clean
124/* broken, of course, but OK for testing */
125static const char *indenter(int i)
126{
127 static const char blanks[] = " ";
128 return &blanks[sizeof(blanks) - i - 1];
129}
130#define debug_printf_clean(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkoc666f712007-05-16 22:18:54 +0000131#define DEBUG_CLEAN 1
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +0000132#endif
133
Eric Andersen25f27032001-04-26 23:22:31 +0000134
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000135#if !ENABLE_HUSH_INTERACTIVE
136#undef ENABLE_FEATURE_EDITING
137#define ENABLE_FEATURE_EDITING 0
138#undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
139#define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
140#endif
"Robert P. J. Day"f3501602006-07-01 12:19:39 +0000141
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +0000142#define SPECIAL_VAR_SYMBOL 3
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000143
144#define PARSEFLAG_EXIT_FROM_LOOP 1
145#define PARSEFLAG_SEMICOLON (1 << 1) /* symbol ';' is special for parser */
146#define PARSEFLAG_REPARSING (1 << 2) /* >= 2nd pass */
Eric Andersen25f27032001-04-26 23:22:31 +0000147
148typedef enum {
149 REDIRECT_INPUT = 1,
150 REDIRECT_OVERWRITE = 2,
151 REDIRECT_APPEND = 3,
152 REDIRECT_HEREIS = 4,
153 REDIRECT_IO = 5
154} redir_type;
155
156/* The descrip member of this structure is only used to make debugging
157 * output pretty */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +0000158static const struct {
159 int mode;
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000160 signed char default_fd;
161 char descrip[3];
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +0000162} redir_table[] = {
Eric Andersen25f27032001-04-26 23:22:31 +0000163 { 0, 0, "()" },
164 { O_RDONLY, 0, "<" },
165 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
166 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
167 { O_RDONLY, -1, "<<" },
168 { O_RDWR, 1, "<>" }
169};
170
171typedef enum {
172 PIPE_SEQ = 1,
173 PIPE_AND = 2,
174 PIPE_OR = 3,
175 PIPE_BG = 4,
176} pipe_style;
177
178/* might eventually control execution */
179typedef enum {
180 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000181#if ENABLE_HUSH_IF
Eric Andersen25f27032001-04-26 23:22:31 +0000182 RES_IF = 1,
183 RES_THEN = 2,
184 RES_ELIF = 3,
185 RES_ELSE = 4,
186 RES_FI = 5,
Denis Vlasenko06810332007-05-21 23:30:54 +0000187#endif
188#if ENABLE_HUSH_LOOPS
Eric Andersen25f27032001-04-26 23:22:31 +0000189 RES_FOR = 6,
190 RES_WHILE = 7,
191 RES_UNTIL = 8,
192 RES_DO = 9,
193 RES_DONE = 10,
Denis Vlasenko06810332007-05-21 23:30:54 +0000194 RES_IN = 11,
195#endif
196 RES_XXXX = 12,
Eric Andersen4c9b68f2002-04-13 12:33:41 +0000197 RES_SNTX = 13
Eric Andersen25f27032001-04-26 23:22:31 +0000198} reserved_style;
Denis Vlasenko5f786c22007-04-20 08:35:45 +0000199enum {
200 FLAG_END = (1 << RES_NONE ),
Denis Vlasenko06810332007-05-21 23:30:54 +0000201#if ENABLE_HUSH_IF
Denis Vlasenko5f786c22007-04-20 08:35:45 +0000202 FLAG_IF = (1 << RES_IF ),
203 FLAG_THEN = (1 << RES_THEN ),
204 FLAG_ELIF = (1 << RES_ELIF ),
205 FLAG_ELSE = (1 << RES_ELSE ),
206 FLAG_FI = (1 << RES_FI ),
Denis Vlasenko06810332007-05-21 23:30:54 +0000207#endif
208#if ENABLE_HUSH_LOOPS
Denis Vlasenko5f786c22007-04-20 08:35:45 +0000209 FLAG_FOR = (1 << RES_FOR ),
210 FLAG_WHILE = (1 << RES_WHILE),
211 FLAG_UNTIL = (1 << RES_UNTIL),
212 FLAG_DO = (1 << RES_DO ),
213 FLAG_DONE = (1 << RES_DONE ),
214 FLAG_IN = (1 << RES_IN ),
Denis Vlasenko06810332007-05-21 23:30:54 +0000215#endif
Denis Vlasenko5f786c22007-04-20 08:35:45 +0000216 FLAG_START = (1 << RES_XXXX ),
217};
Eric Andersen25f27032001-04-26 23:22:31 +0000218
219/* This holds pointers to the various results of parsing */
220struct p_context {
221 struct child_prog *child;
222 struct pipe *list_head;
223 struct pipe *pipe;
224 struct redir_struct *pending_redirect;
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000225 smallint res_w;
226 smallint parse_type; /* bitmask of PARSEFLAG_xxx, defines type of parser : ";$" common or special symbol */
227 int old_flag; /* bitmask of FLAG_xxx, for figuring out valid reserved words */
Eric Andersen25f27032001-04-26 23:22:31 +0000228 struct p_context *stack;
229 /* How about quoting status? */
230};
231
232struct redir_struct {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000233 struct redir_struct *next; /* pointer to the next redirect in the list */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000234 redir_type type; /* type of redirection */
235 int fd; /* file descriptor being redirected */
236 int dup; /* -1, or file descriptor being duplicated */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000237 glob_t word; /* *word.gl_pathv is the filename */
Eric Andersen25f27032001-04-26 23:22:31 +0000238};
239
240struct child_prog {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000241 pid_t pid; /* 0 if exited */
242 char **argv; /* program name and arguments */
243 struct pipe *group; /* if non-NULL, first in group or subshell */
Denis Vlasenko262d7652007-05-20 21:52:49 +0000244 smallint subshell; /* flag, non-zero if group must be forked */
245 smallint is_stopped; /* is the program currently running? */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000246 struct redir_struct *redirects; /* I/O redirections */
247 glob_t glob_result; /* result of parameter globbing */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000248 struct pipe *family; /* pointer back to the child's parent pipe */
Denis Vlasenkoc666f712007-05-16 22:18:54 +0000249 //sp counting seems to be broken... so commented out, grep for '//sp:'
250 //sp: int sp; /* number of SPECIAL_VAR_SYMBOL */
Denis Vlasenko262d7652007-05-20 21:52:49 +0000251 //seems to be unused, grep for '//pt:'
252 //pt: int parse_type;
Eric Andersen25f27032001-04-26 23:22:31 +0000253};
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000254/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
255 * and on execution these are substituted with their values.
256 * Substitution can make _several_ words out of one argv[n]!
257 * Example: argv[0]=='.^C*^C.' here: echo .$*.
258 */
Eric Andersen25f27032001-04-26 23:22:31 +0000259
260struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000261 struct pipe *next;
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000262 int num_progs; /* total number of programs in job */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000263 int running_progs; /* number of programs running (not exited) */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000264 int stopped_progs; /* number of programs alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000265#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000266 int jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000267 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000268 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000269#endif
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000270 char *cmdbuf; /* buffer various argv's point into */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000271 struct child_prog *progs; /* array of commands in pipe */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000272 int job_context; /* bitmask defining current context */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000273 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
274 smallint res_word; /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000275};
276
Eric Andersen25f27032001-04-26 23:22:31 +0000277struct close_me {
Eric Andersen25f27032001-04-26 23:22:31 +0000278 struct close_me *next;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000279 int fd;
Eric Andersen25f27032001-04-26 23:22:31 +0000280};
281
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000282struct variables {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000283 struct variables *next;
Denis Vlasenko15d78fb2007-01-30 22:28:21 +0000284 const char *name;
285 const char *value;
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000286 smallint flg_export;
287 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000288};
289
Eric Andersen25f27032001-04-26 23:22:31 +0000290typedef struct {
291 char *data;
292 int length;
293 int maxlen;
294 int quote;
295 int nonnull;
296} o_string;
297#define NULL_O_STRING {NULL,0,0,0,0}
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000298/* used for initialization: o_string foo = NULL_O_STRING; */
Eric Andersen25f27032001-04-26 23:22:31 +0000299
300/* I can almost use ordinary FILE *. Is open_memstream() universally
301 * available? Where is it documented? */
302struct in_str {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +0000303 const char *p;
304 /* eof_flag=1: last char in ->p is really an EOF */
305 char eof_flag; /* meaningless if ->p == NULL */
306 char peek_buf[2];
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000307#if ENABLE_HUSH_INTERACTIVE
Eric Andersen25f27032001-04-26 23:22:31 +0000308 int __promptme;
309 int promptmode;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000310#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000311 FILE *file;
312 int (*get) (struct in_str *);
313 int (*peek) (struct in_str *);
314};
315#define b_getch(input) ((input)->get(input))
316#define b_peek(input) ((input)->peek(input))
317
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000318enum {
319 CHAR_ORDINARY = 0,
320 CHAR_ORDINARY_IF_QUOTED = 1, /* example: *, # */
321 CHAR_IFS = 2, /* treated as ordinary if quoted */
322 CHAR_SPECIAL = 3, /* example: $ */
Eric Andersen25f27032001-04-26 23:22:31 +0000323};
324
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000325
326/* "Globals" within this file */
327
328#define HUSH_VER_STR "0.02"
329static const struct variables const_shell_ver = {
330 NULL, "HUSH_VERSION", HUSH_VER_STR, 1, 1
331};
332
333/* Sorted roughly by size (smaller offsets == smaller code) */
334struct globals {
335#if ENABLE_HUSH_INTERACTIVE
336 /* 'interactive_fd' is a fd# open to ctty, if we have one
337 * _AND_ if we decided to act interactively */
338 int interactive_fd;
339 const char *PS1;
340 const char *PS2;
341#endif
342#if ENABLE_FEATURE_EDITING
343 line_input_t *line_input_state;
344#endif
345#if ENABLE_HUSH_JOB
346 int run_list_level;
347 pid_t saved_task_pgrp;
348 pid_t saved_tty_pgrp;
349 int last_jobid;
350 struct pipe *job_list;
351 struct pipe *toplevel_list;
352 smallint ctrl_z_flag;
353#endif
354 smallint fake_mode;
355 /* these three support $?, $#, and $1 */
356 char **global_argv;
357 int global_argc;
358 int last_return_code;
359 const char *ifs;
360 struct close_me *close_me_head;
361 const char *cwd;
362 unsigned last_bg_pid;
363 struct variables *top_vars; /* = &shell_ver (both are set in main()) */
364 struct variables shell_ver; /* = const_shell_ver */
365#if ENABLE_FEATURE_SH_STANDALONE
366 struct nofork_save_area nofork_save;
367#endif
368#if ENABLE_HUSH_JOB
369 sigjmp_buf toplevel_jb;
370#endif
371 unsigned char charmap[256];
372 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
373};
374
375#define G (*ptr_to_globals)
376
377#if !ENABLE_HUSH_INTERACTIVE
378enum { interactive_fd = 0 };
379#endif
380#if !ENABLE_HUSH_JOB
381enum { run_list_level = 0 };
382#endif
383
384#if ENABLE_HUSH_INTERACTIVE
385#define interactive_fd (G.interactive_fd )
386#define PS1 (G.PS1 )
387#define PS2 (G.PS2 )
388#endif
389#if ENABLE_FEATURE_EDITING
390#define line_input_state (G.line_input_state)
391#endif
392#if ENABLE_HUSH_JOB
393#define run_list_level (G.run_list_level )
394#define saved_task_pgrp (G.saved_task_pgrp )
395#define saved_tty_pgrp (G.saved_tty_pgrp )
396#define last_jobid (G.last_jobid )
397#define job_list (G.job_list )
398#define toplevel_list (G.toplevel_list )
399#define toplevel_jb (G.toplevel_jb )
400#define ctrl_z_flag (G.ctrl_z_flag )
401#endif /* JOB */
402#define global_argv (G.global_argv )
403#define global_argc (G.global_argc )
404#define last_return_code (G.last_return_code)
405#define ifs (G.ifs )
406#define fake_mode (G.fake_mode )
407#define close_me_head (G.close_me_head )
408#define cwd (G.cwd )
409#define last_bg_pid (G.last_bg_pid )
410#define top_vars (G.top_vars )
411#define shell_ver (G.shell_ver )
412#if ENABLE_FEATURE_SH_STANDALONE
413#define nofork_save (G.nofork_save )
414#endif
415#if ENABLE_HUSH_JOB
416#define toplevel_jb (G.toplevel_jb )
417#endif
418#define charmap (G.charmap )
419#define user_input_buf (G.user_input_buf )
420
421
422#define B_CHUNK 100
423#define B_NOSPAC 1
424#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
425
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000426#if 1
427/* Normal */
428static void syntax(const char *msg)
429{
430 bb_error_msg(msg ? "%s: %s" : "syntax error", "syntax error", msg);
431}
432#else
433/* Debug */
434static void syntax_lineno(int line)
Denis Vlasenkob6aae0f2007-01-29 22:51:25 +0000435{
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000436 bb_error_msg("syntax error hush.c:%d", line);
Eric Andersen25f27032001-04-26 23:22:31 +0000437}
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000438#define syntax(str) syntax_lineno(__LINE__)
439#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000440
441/* Index of subroutines: */
442/* function prototypes for builtins */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000443static int builtin_cd(char **argv);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000444static int builtin_eval(char **argv);
445static int builtin_exec(char **argv);
446static int builtin_exit(char **argv);
447static int builtin_export(char **argv);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000448#if ENABLE_HUSH_JOB
Denis Vlasenko1359da62007-04-21 23:27:30 +0000449static int builtin_fg_bg(char **argv);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000450static int builtin_jobs(char **argv);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000451#endif
Denis Vlasenko06810332007-05-21 23:30:54 +0000452#if ENABLE_HUSH_HELP
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000453static int builtin_help(char **argv);
Denis Vlasenko06810332007-05-21 23:30:54 +0000454#endif
Denis Vlasenko1359da62007-04-21 23:27:30 +0000455static int builtin_pwd(char **argv);
456static int builtin_read(char **argv);
457static int builtin_set(char **argv);
458static int builtin_shift(char **argv);
459static int builtin_source(char **argv);
460static int builtin_umask(char **argv);
461static int builtin_unset(char **argv);
Denis Vlasenko06810332007-05-21 23:30:54 +0000462//static int builtin_not_written(char **argv);
Eric Andersen25f27032001-04-26 23:22:31 +0000463/* o_string manipulation: */
464static int b_check_space(o_string *o, int len);
465static int b_addchr(o_string *o, int ch);
466static void b_reset(o_string *o);
467static int b_addqchr(o_string *o, int ch, int quote);
Eric Andersen25f27032001-04-26 23:22:31 +0000468/* in_str manipulations: */
469static int static_get(struct in_str *i);
470static int static_peek(struct in_str *i);
471static int file_get(struct in_str *i);
472static int file_peek(struct in_str *i);
473static void setup_file_in_str(struct in_str *i, FILE *f);
474static void setup_string_in_str(struct in_str *i, const char *s);
475/* close_me manipulations: */
476static void mark_open(int fd);
477static void mark_closed(int fd);
Eric Anderseneaecbf32001-10-31 10:41:31 +0000478static void close_all(void);
Eric Andersen25f27032001-04-26 23:22:31 +0000479/* "run" the final data structures: */
Denis Vlasenkoc666f712007-05-16 22:18:54 +0000480#if !defined(DEBUG_CLEAN)
481#define free_pipe_list(head, indent) free_pipe_list(head)
482#define free_pipe(pi, indent) free_pipe(pi)
483#endif
Eric Andersenbf7df042001-05-23 22:18:35 +0000484static int free_pipe_list(struct pipe *head, int indent);
485static int free_pipe(struct pipe *pi, int indent);
Eric Andersen25f27032001-04-26 23:22:31 +0000486/* really run the final data structures: */
487static int setup_redirects(struct child_prog *prog, int squirrel[]);
Eric Andersen25f27032001-04-26 23:22:31 +0000488static int run_list_real(struct pipe *pi);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000489static void pseudo_exec_argv(char **argv) ATTRIBUTE_NORETURN;
Bernhard Reutner-Fischer86f5c992006-01-22 22:55:11 +0000490static void pseudo_exec(struct child_prog *child) ATTRIBUTE_NORETURN;
Eric Andersen25f27032001-04-26 23:22:31 +0000491static int run_pipe_real(struct pipe *pi);
492/* extended glob support: */
493static int globhack(const char *src, int flags, glob_t *pglob);
494static int glob_needed(const char *s);
495static int xglob(o_string *dest, int flags, glob_t *pglob);
Eric Andersen78a7c992001-05-15 16:30:25 +0000496/* variable assignment: */
Eric Andersen78a7c992001-05-15 16:30:25 +0000497static int is_assignment(const char *s);
Eric Andersen25f27032001-04-26 23:22:31 +0000498/* data structure manipulation: */
499static int setup_redirect(struct p_context *ctx, int fd, redir_type style, struct in_str *input);
500static void initialize_context(struct p_context *ctx);
501static int done_word(o_string *dest, struct p_context *ctx);
502static int done_command(struct p_context *ctx);
503static int done_pipe(struct p_context *ctx, pipe_style type);
504/* primary string parsing: */
505static int redirect_dup_num(struct in_str *input);
506static int redirect_opt_num(o_string *o);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +0000507#if ENABLE_HUSH_TICK
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +0000508static 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 +0000509#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000510static int parse_group(o_string *dest, struct p_context *ctx, struct in_str *input, int ch);
Denis Vlasenko15d78fb2007-01-30 22:28:21 +0000511static const char *lookup_param(const char *src);
Eric Andersen25f27032001-04-26 23:22:31 +0000512static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +0000513static 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 +0000514/* setup: */
Denis Vlasenko170435c2007-05-23 13:01:10 +0000515static int parse_and_run_stream(struct in_str *inp, int parse_flag);
516static int parse_and_run_string(const char *s, int parse_flag);
517static int parse_and_run_file(FILE *f);
Eric Andersenbafd94f2001-05-02 16:11:59 +0000518/* job management: */
Eric Andersenc798b072001-06-22 06:23:03 +0000519static int checkjobs(struct pipe* fg_pipe);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000520#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +0000521static int checkjobs_and_fg_shell(struct pipe* fg_pipe);
Eric Andersenbafd94f2001-05-02 16:11:59 +0000522static void insert_bg_job(struct pipe *pi);
523static void remove_bg_job(struct pipe *pi);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000524static void delete_finished_bg_job(struct pipe *pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000525#else
526int checkjobs_and_fg_shell(struct pipe* fg_pipe); /* never called */
527#endif
Eric Andersenf72f5622001-05-15 23:21:41 +0000528/* local variable support */
Denis Vlasenko170435c2007-05-23 13:01:10 +0000529static char **expand_strvec_to_strvec(char **argv);
530/* used for eval */
531static char *expand_strvec_to_string(char **argv);
Denis Vlasenkob6a741f2007-05-17 14:38:17 +0000532/* used for expansion of right hand of assignments */
Denis Vlasenko170435c2007-05-23 13:01:10 +0000533static char *expand_string_to_string(const char *str);
Denis Vlasenko15d78fb2007-01-30 22:28:21 +0000534static const char *get_local_var(const char *var);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000535static int set_local_var(const char *s, int flg_export);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +0000536static void unset_local_var(const char *name);
Eric Andersen25f27032001-04-26 23:22:31 +0000537
538/* Table of built-in functions. They can be forked or not, depending on
539 * context: within pipes, they fork. As simple commands, they do not.
540 * When used in non-forking context, they can change global variables
Denis Vlasenkoe1a0d482006-10-20 13:28:22 +0000541 * in the parent shell process. If forked, of course they cannot.
Eric Andersen25f27032001-04-26 23:22:31 +0000542 * For example, 'unset foo | whatever' will parse and run, but foo will
543 * still be set at the end. */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000544struct built_in_command {
545 const char *cmd; /* name */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000546 int (*function) (char **argv); /* function ptr */
Denis Vlasenko06810332007-05-21 23:30:54 +0000547#if ENABLE_HUSH_HELP
548 const char *descr; /* description */
549#define BLTIN(cmd, func, help) { cmd, func, help }
550#else
551#define BLTIN(cmd, func, help) { cmd, func }
552#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000553};
554
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +0000555static const struct built_in_command bltins[] = {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000556#if ENABLE_HUSH_JOB
Denis Vlasenko06810332007-05-21 23:30:54 +0000557 BLTIN("bg" , builtin_fg_bg, "Resume a job in the background"),
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000558#endif
Denis Vlasenko06810332007-05-21 23:30:54 +0000559// BLTIN("break" , builtin_not_written, "Exit for, while or until loop"),
560 BLTIN("cd" , builtin_cd, "Change working directory"),
561// BLTIN("continue", builtin_not_written, "Continue for, while or until loop"),
562 BLTIN("eval" , builtin_eval, "Construct and run shell command"),
563 BLTIN("exec" , builtin_exec, "Exec command, replacing this shell with the exec'd process"),
564 BLTIN("exit" , builtin_exit, "Exit from shell"),
565 BLTIN("export", builtin_export, "Set environment variable"),
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000566#if ENABLE_HUSH_JOB
Denis Vlasenko06810332007-05-21 23:30:54 +0000567 BLTIN("fg" , builtin_fg_bg, "Bring job into the foreground"),
568 BLTIN("jobs" , builtin_jobs, "Lists the active jobs"),
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000569#endif
Denis Vlasenko06810332007-05-21 23:30:54 +0000570// TODO: remove pwd? we have it as an applet...
571 BLTIN("pwd" , builtin_pwd, "Print current directory"),
572 BLTIN("read" , builtin_read, "Input environment variable"),
573// BLTIN("return", builtin_not_written, "Return from a function"),
574 BLTIN("set" , builtin_set, "Set/unset shell local variables"),
575 BLTIN("shift" , builtin_shift, "Shift positional parameters"),
576// BLTIN("trap" , builtin_not_written, "Trap signals"),
577// BLTIN("ulimit", builtin_not_written, "Controls resource limits"),
578 BLTIN("umask" , builtin_umask, "Sets file creation mask"),
579 BLTIN("unset" , builtin_unset, "Unset environment variable"),
580 BLTIN("." , builtin_source, "Source-in and run commands in a file"),
581#if ENABLE_HUSH_HELP
582 BLTIN("help" , builtin_help, "List shell built-in commands"),
583#endif
584 BLTIN(NULL, NULL, NULL)
Eric Andersen25f27032001-04-26 23:22:31 +0000585};
586
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000587#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000588
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000589/* move to libbb? */
590static void signal_SA_RESTART(int sig, void (*handler)(int))
591{
592 struct sigaction sa;
593 sa.sa_handler = handler;
594 sa.sa_flags = SA_RESTART;
595 sigemptyset(&sa.sa_mask);
596 sigaction(sig, &sa, NULL);
597}
598
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000599/* Signals are grouped, we handle them in batches */
600static void set_fatal_sighandler(void (*handler)(int))
601{
602 signal(SIGILL , handler);
603 signal(SIGTRAP, handler);
604 signal(SIGABRT, handler);
605 signal(SIGFPE , handler);
606 signal(SIGBUS , handler);
607 signal(SIGSEGV, handler);
608 /* bash 3.2 seems to handle these just like 'fatal' ones */
609 signal(SIGHUP , handler);
610 signal(SIGPIPE, handler);
611 signal(SIGALRM, handler);
612}
613static void set_jobctrl_sighandler(void (*handler)(int))
614{
615 signal(SIGTSTP, handler);
616 signal(SIGTTIN, handler);
617 signal(SIGTTOU, handler);
618}
619static void set_misc_sighandler(void (*handler)(int))
620{
621 signal(SIGINT , handler);
622 signal(SIGQUIT, handler);
623 signal(SIGTERM, handler);
624}
625/* SIGCHLD is special and handled separately */
626
627static void set_every_sighandler(void (*handler)(int))
628{
629 set_fatal_sighandler(handler);
630 set_jobctrl_sighandler(handler);
631 set_misc_sighandler(handler);
632 signal(SIGCHLD, handler);
633}
634
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000635static void handler_ctrl_c(int sig)
636{
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000637 debug_printf_jobs("got sig %d\n", sig);
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000638// as usual we can have all kinds of nasty problems with leaked malloc data here
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000639 siglongjmp(toplevel_jb, 1);
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000640}
641
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000642static void handler_ctrl_z(int sig)
643{
644 pid_t pid;
645
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000646 debug_printf_jobs("got tty sig %d in pid %d\n", sig, getpid());
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000647 pid = fork();
Denis Vlasenkoc2990322007-05-16 12:57:12 +0000648 if (pid < 0) /* can't fork. Pretend there was no ctrl-Z */
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000649 return;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000650 ctrl_z_flag = 1;
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000651 if (!pid) { /* child */
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000652 setpgrp();
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000653 debug_printf_jobs("set pgrp for child %d ok\n", getpid());
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000654 set_every_sighandler(SIG_DFL);
Denis Vlasenko18e19f22007-04-28 16:43:18 +0000655 raise(SIGTSTP); /* resend TSTP so that child will be stopped */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000656 debug_printf_jobs("returning in child\n");
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000657 /* return to nofork, it will eventually exit now,
658 * not return back to shell */
659 return;
660 }
661 /* parent */
662 /* finish filling up pipe info */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000663 toplevel_list->pgrp = pid; /* child is in its own pgrp */
664 toplevel_list->progs[0].pid = pid;
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000665 /* parent needs to longjmp out of running nofork.
666 * we will "return" exitcode 0, with child put in background */
667// as usual we can have all kinds of nasty problems with leaked malloc data here
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000668 debug_printf_jobs("siglongjmp in parent\n");
669 siglongjmp(toplevel_jb, 1);
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000670}
671
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000672/* Restores tty foreground process group, and exits.
673 * May be called as signal handler for fatal signal
674 * (will faithfully resend signal to itself, producing correct exit state)
675 * or called directly with -EXITCODE.
676 * We also call it if xfunc is exiting. */
677static void sigexit(int sig) ATTRIBUTE_NORETURN;
678static void sigexit(int sig)
679{
680 sigset_t block_all;
681
682 /* Disable all signals: job control, SIGPIPE, etc. */
683 sigfillset(&block_all);
684 sigprocmask(SIG_SETMASK, &block_all, NULL);
685
Denis Vlasenko87cb2db2007-04-21 10:00:01 +0000686 if (interactive_fd)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000687 tcsetpgrp(interactive_fd, saved_tty_pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000688
689 /* Not a signal, just exit */
690 if (sig <= 0)
691 _exit(- sig);
692
693 /* Enable only this sig and kill ourself with it */
694 signal(sig, SIG_DFL);
695 sigdelset(&block_all, sig);
696 sigprocmask(SIG_SETMASK, &block_all, NULL);
697 raise(sig);
698 _exit(1); /* Should not reach it */
699}
700
701/* Restores tty foreground process group, and exits. */
702static void hush_exit(int exitcode) ATTRIBUTE_NORETURN;
703static void hush_exit(int exitcode)
704{
705 fflush(NULL); /* flush all streams */
706 sigexit(- (exitcode & 0xff));
707}
708
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000709#else /* !JOB */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000710
711#define set_fatal_sighandler(handler) ((void)0)
712#define set_jobctrl_sighandler(handler) ((void)0)
713#define set_misc_sighandler(handler) ((void)0)
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000714#define hush_exit(e) exit(e)
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000715
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000716#endif /* JOB */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000717
718
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000719static const char *set_cwd(void)
720{
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000721 if (cwd == bb_msg_unknown)
Denis Vlasenko7cced6e2007-04-12 17:08:53 +0000722 cwd = NULL; /* xrealloc_getcwd_or_warn(arg) calls free(arg)! */
Denis Vlasenko6ca04442007-02-11 16:19:28 +0000723 cwd = xrealloc_getcwd_or_warn((char *)cwd);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000724 if (!cwd)
Manuel Novoa III cad53642003-03-19 09:13:01 +0000725 cwd = bb_msg_unknown;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000726 return cwd;
727}
728
Eric Andersen4c9b68f2002-04-13 12:33:41 +0000729/* built-in 'eval' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000730static int builtin_eval(char **argv)
Eric Andersen4c9b68f2002-04-13 12:33:41 +0000731{
Eric Andersen4c9b68f2002-04-13 12:33:41 +0000732 int rcode = EXIT_SUCCESS;
Eric Andersenc7bda1c2004-03-15 08:29:22 +0000733
Denis Vlasenko1359da62007-04-21 23:27:30 +0000734 if (argv[1]) {
Denis Vlasenko170435c2007-05-23 13:01:10 +0000735 char *str = expand_strvec_to_string(argv + 1);
736 parse_and_run_string(str, PARSEFLAG_EXIT_FROM_LOOP |
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000737 PARSEFLAG_SEMICOLON);
Eric Andersen4c9b68f2002-04-13 12:33:41 +0000738 free(str);
739 rcode = last_return_code;
740 }
741 return rcode;
742}
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000743
Eric Andersen25f27032001-04-26 23:22:31 +0000744/* built-in 'cd <path>' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000745static int builtin_cd(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000746{
Denis Vlasenko170435c2007-05-23 13:01:10 +0000747 const char *newdir;
Denis Vlasenko1359da62007-04-21 23:27:30 +0000748 if (argv[1] == NULL)
Denis Vlasenko170435c2007-05-23 13:01:10 +0000749 newdir = getenv("HOME") ? : "/";
Eric Andersen25f27032001-04-26 23:22:31 +0000750 else
Denis Vlasenko1359da62007-04-21 23:27:30 +0000751 newdir = argv[1];
Eric Andersen25f27032001-04-26 23:22:31 +0000752 if (chdir(newdir)) {
753 printf("cd: %s: %s\n", newdir, strerror(errno));
754 return EXIT_FAILURE;
755 }
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000756 set_cwd();
Eric Andersen25f27032001-04-26 23:22:31 +0000757 return EXIT_SUCCESS;
758}
759
Eric Andersen25f27032001-04-26 23:22:31 +0000760/* built-in 'exec' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000761static int builtin_exec(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000762{
Denis Vlasenko1359da62007-04-21 23:27:30 +0000763 if (argv[1] == NULL)
Eric Andersen25f27032001-04-26 23:22:31 +0000764 return EXIT_SUCCESS; /* Really? */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000765 pseudo_exec_argv(argv + 1);
Eric Andersen25f27032001-04-26 23:22:31 +0000766 /* never returns */
767}
768
769/* built-in 'exit' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000770static int builtin_exit(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000771{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000772// TODO: bash does it ONLY on top-level sh exit (+interacive only?)
773 //puts("exit"); /* bash does it */
Denis Vlasenkof2fffd02007-05-02 23:39:04 +0000774// TODO: warn if we have background jobs: "There are stopped jobs"
775// On second consecutive 'exit', exit anyway.
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000776
Denis Vlasenko1359da62007-04-21 23:27:30 +0000777 if (argv[1] == NULL)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000778 hush_exit(last_return_code);
Denis Vlasenko5f786c22007-04-20 08:35:45 +0000779 /* mimic bash: exit 123abc == exit 255 + error msg */
780 xfunc_error_retval = 255;
781 /* bash: exit -2 == exit 254, no error msg */
Denis Vlasenkof2fffd02007-05-02 23:39:04 +0000782 hush_exit(xatoi(argv[1]) & 0xff);
Eric Andersen25f27032001-04-26 23:22:31 +0000783}
784
785/* built-in 'export VAR=value' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000786static int builtin_export(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000787{
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000788 int res = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +0000789 char *name = argv[1];
Eric Andersen25f27032001-04-26 23:22:31 +0000790
Eric Andersenf72f5622001-05-15 23:21:41 +0000791 if (name == NULL) {
Denis Vlasenkof2fffd02007-05-02 23:39:04 +0000792 // TODO:
793 // ash emits: export VAR='VAL'
794 // bash: declare -x VAR="VAL"
795 // (both also escape as needed (quotes, $, etc))
796 char **e = environ;
797 if (e)
798 while (*e)
799 puts(*e++);
800 return EXIT_SUCCESS;
Eric Andersen25f27032001-04-26 23:22:31 +0000801 }
Eric Andersenf72f5622001-05-15 23:21:41 +0000802
Denis Vlasenkoc666f712007-05-16 22:18:54 +0000803 name = xstrdup(name);
804 {
Denis Vlasenko15d78fb2007-01-30 22:28:21 +0000805 const char *value = strchr(name, '=');
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000806
Eric Andersen94ac2442001-05-22 19:05:18 +0000807 if (!value) {
808 char *tmp;
809 /* They are exporting something without an =VALUE */
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000810
Eric Andersen94ac2442001-05-22 19:05:18 +0000811 value = get_local_var(name);
812 if (value) {
813 size_t ln = strlen(name);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000814
Denis Vlasenkoc666f712007-05-16 22:18:54 +0000815 tmp = xrealloc(name, ln+strlen(value)+2);
816 sprintf(tmp+ln, "=%s", value);
817 name = tmp;
Eric Andersen94ac2442001-05-22 19:05:18 +0000818 } else {
819 /* bash does not return an error when trying to export
820 * an undefined variable. Do likewise. */
821 res = 1;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000822 }
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000823 }
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000824 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000825 if (res < 0)
Manuel Novoa III cad53642003-03-19 09:13:01 +0000826 bb_perror_msg("export");
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000827 else if (res == 0)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000828 res = set_local_var(name, 1);
829 else
830 res = 0;
831 free(name);
832 return res;
Eric Andersen25f27032001-04-26 23:22:31 +0000833}
834
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000835#if ENABLE_HUSH_JOB
Eric Andersen25f27032001-04-26 23:22:31 +0000836/* built-in 'fg' and 'bg' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000837static int builtin_fg_bg(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000838{
Eric Andersen0fcd4472001-05-02 20:12:03 +0000839 int i, jobnum;
Denis Vlasenko8a28e622007-04-14 11:16:29 +0000840 struct pipe *pi;
Eric Andersen25f27032001-04-26 23:22:31 +0000841
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000842 if (!interactive_fd)
Eric Andersenc798b072001-06-22 06:23:03 +0000843 return EXIT_FAILURE;
Eric Andersen0fcd4472001-05-02 20:12:03 +0000844 /* If they gave us no args, assume they want the last backgrounded task */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000845 if (!argv[1]) {
Eric Andersenc798b072001-06-22 06:23:03 +0000846 for (pi = job_list; pi; pi = pi->next) {
847 if (pi->jobid == last_jobid) {
Denis Vlasenko8a28e622007-04-14 11:16:29 +0000848 goto found;
Eric Andersen0fcd4472001-05-02 20:12:03 +0000849 }
850 }
Denis Vlasenko1359da62007-04-21 23:27:30 +0000851 bb_error_msg("%s: no current job", argv[0]);
Denis Vlasenko8a28e622007-04-14 11:16:29 +0000852 return EXIT_FAILURE;
853 }
Denis Vlasenko1359da62007-04-21 23:27:30 +0000854 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
855 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
Denis Vlasenko8a28e622007-04-14 11:16:29 +0000856 return EXIT_FAILURE;
857 }
858 for (pi = job_list; pi; pi = pi->next) {
859 if (pi->jobid == jobnum) {
860 goto found;
Eric Andersen25f27032001-04-26 23:22:31 +0000861 }
862 }
Denis Vlasenko1359da62007-04-21 23:27:30 +0000863 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
Denis Vlasenko8a28e622007-04-14 11:16:29 +0000864 return EXIT_FAILURE;
865 found:
Denis Vlasenko52881e92007-04-21 13:42:52 +0000866 // TODO: bash prints a string representation
867 // of job being foregrounded (like "sleep 1 | cat")
Denis Vlasenko1359da62007-04-21 23:27:30 +0000868 if (*argv[0] == 'f') {
Eric Andersen028b65b2001-06-28 01:10:11 +0000869 /* Put the job into the foreground. */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000870 tcsetpgrp(interactive_fd, pi->pgrp);
Eric Andersen25f27032001-04-26 23:22:31 +0000871 }
872
873 /* Restart the processes in the job */
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000874 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_progs, pi->pgrp);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000875 for (i = 0; i < pi->num_progs; i++) {
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000876 debug_printf_jobs("reviving pid %d\n", pi->progs[i].pid);
Eric Andersen0fcd4472001-05-02 20:12:03 +0000877 pi->progs[i].is_stopped = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +0000878 }
879 pi->stopped_progs = 0;
Eric Andersen25f27032001-04-26 23:22:31 +0000880
Denis Vlasenkobb81c582007-01-30 22:32:09 +0000881 i = kill(- pi->pgrp, SIGCONT);
882 if (i < 0) {
Denis Vlasenko8a28e622007-04-14 11:16:29 +0000883 if (errno == ESRCH) {
Denis Vlasenko1359da62007-04-21 23:27:30 +0000884 delete_finished_bg_job(pi);
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000885 return EXIT_SUCCESS;
Eric Andersen028b65b2001-06-28 01:10:11 +0000886 } else {
Manuel Novoa III cad53642003-03-19 09:13:01 +0000887 bb_perror_msg("kill (SIGCONT)");
Eric Andersen028b65b2001-06-28 01:10:11 +0000888 }
889 }
Eric Andersen25f27032001-04-26 23:22:31 +0000890
Denis Vlasenko1359da62007-04-21 23:27:30 +0000891 if (*argv[0] == 'f') {
892 remove_bg_job(pi);
Denis Vlasenko52881e92007-04-21 13:42:52 +0000893 return checkjobs_and_fg_shell(pi);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000894 }
Eric Andersen25f27032001-04-26 23:22:31 +0000895 return EXIT_SUCCESS;
896}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000897#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000898
899/* built-in 'help' handler */
Denis Vlasenko06810332007-05-21 23:30:54 +0000900#if ENABLE_HUSH_HELP
Denis Vlasenko1359da62007-04-21 23:27:30 +0000901static int builtin_help(char **argv ATTRIBUTE_UNUSED)
Eric Andersen25f27032001-04-26 23:22:31 +0000902{
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +0000903 const struct built_in_command *x;
Eric Andersen25f27032001-04-26 23:22:31 +0000904
905 printf("\nBuilt-in commands:\n");
906 printf("-------------------\n");
907 for (x = bltins; x->cmd; x++) {
Eric Andersen25f27032001-04-26 23:22:31 +0000908 printf("%s\t%s\n", x->cmd, x->descr);
909 }
910 printf("\n\n");
911 return EXIT_SUCCESS;
912}
Denis Vlasenko06810332007-05-21 23:30:54 +0000913#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000914
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000915#if ENABLE_HUSH_JOB
Eric Andersen25f27032001-04-26 23:22:31 +0000916/* built-in 'jobs' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000917static int builtin_jobs(char **argv ATTRIBUTE_UNUSED)
Eric Andersen25f27032001-04-26 23:22:31 +0000918{
919 struct pipe *job;
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000920 const char *status_string;
Eric Andersen25f27032001-04-26 23:22:31 +0000921
Eric Andersenc798b072001-06-22 06:23:03 +0000922 for (job = job_list; job; job = job->next) {
Eric Andersen25f27032001-04-26 23:22:31 +0000923 if (job->running_progs == job->stopped_progs)
924 status_string = "Stopped";
925 else
926 status_string = "Running";
Eric Andersen52a97ca2001-06-22 06:49:26 +0000927
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000928 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
Eric Andersen25f27032001-04-26 23:22:31 +0000929 }
930 return EXIT_SUCCESS;
931}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000932#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000933
Eric Andersen25f27032001-04-26 23:22:31 +0000934/* built-in 'pwd' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000935static int builtin_pwd(char **argv ATTRIBUTE_UNUSED)
Eric Andersen25f27032001-04-26 23:22:31 +0000936{
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000937 puts(set_cwd());
Eric Andersen25f27032001-04-26 23:22:31 +0000938 return EXIT_SUCCESS;
939}
940
941/* built-in 'read VAR' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000942static int builtin_read(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000943{
Denis Vlasenko3e7b0e62007-05-16 12:52:15 +0000944 char string[BUFSIZ];
945 char *p;
946 const char *name = argv[1] ? argv[1] : "REPLY";
947 int name_len = strlen(name);
Eric Andersen25f27032001-04-26 23:22:31 +0000948
Denis Vlasenko3e7b0e62007-05-16 12:52:15 +0000949 if (name_len >= sizeof(string) - 2)
950 return EXIT_FAILURE;
951 strcpy(string, name);
952 p = string + name_len;
953 *p++ = '=';
954 *p = '\0'; /* In case stdin has only EOF */
955 /* read string. name_len+1 chars are already used by 'name=' */
956 fgets(p, sizeof(string) - 1 - name_len, stdin);
957 chomp(p);
958 return set_local_var(string, 0);
Eric Andersen25f27032001-04-26 23:22:31 +0000959}
960
Denis Vlasenko3e7b0e62007-05-16 12:52:15 +0000961/* built-in 'set [VAR=value]' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000962static int builtin_set(char **argv)
Eric Andersenf72f5622001-05-15 23:21:41 +0000963{
Denis Vlasenko1359da62007-04-21 23:27:30 +0000964 char *temp = argv[1];
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000965 struct variables *e;
Eric Andersenf72f5622001-05-15 23:21:41 +0000966
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000967 if (temp == NULL)
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000968 for (e = top_vars; e; e = e->next)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000969 printf("%s=%s\n", e->name, e->value);
970 else
971 set_local_var(temp, 0);
972
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000973 return EXIT_SUCCESS;
Eric Andersenf72f5622001-05-15 23:21:41 +0000974}
975
976
Eric Andersen25f27032001-04-26 23:22:31 +0000977/* Built-in 'shift' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000978static int builtin_shift(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000979{
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000980 int n = 1;
Denis Vlasenko1359da62007-04-21 23:27:30 +0000981 if (argv[1]) {
982 n = atoi(argv[1]);
Eric Andersen25f27032001-04-26 23:22:31 +0000983 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000984 if (n >= 0 && n < global_argc) {
Denis Vlasenko004baba2007-05-20 22:22:18 +0000985 global_argv[n] = global_argv[0];
Eric Andersen25f27032001-04-26 23:22:31 +0000986 global_argc -= n;
987 global_argv += n;
988 return EXIT_SUCCESS;
Eric Andersen25f27032001-04-26 23:22:31 +0000989 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +0000990 return EXIT_FAILURE;
Eric Andersen25f27032001-04-26 23:22:31 +0000991}
992
993/* Built-in '.' handler (read-in and execute commands from file) */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000994static int builtin_source(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000995{
996 FILE *input;
997 int status;
998
Denis Vlasenko1359da62007-04-21 23:27:30 +0000999 if (argv[1] == NULL)
Eric Andersen25f27032001-04-26 23:22:31 +00001000 return EXIT_FAILURE;
1001
1002 /* XXX search through $PATH is missing */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001003 input = fopen(argv[1], "r");
Eric Andersen25f27032001-04-26 23:22:31 +00001004 if (!input) {
Denis Vlasenko1359da62007-04-21 23:27:30 +00001005 bb_error_msg("cannot open '%s'", argv[1]);
Eric Andersen25f27032001-04-26 23:22:31 +00001006 return EXIT_FAILURE;
1007 }
1008
1009 /* Now run the file */
1010 /* XXX argv and argc are broken; need to save old global_argv
1011 * (pointer only is OK!) on this stack frame,
Denis Vlasenko1359da62007-04-21 23:27:30 +00001012 * set global_argv=argv+1, recurse, and restore. */
Eric Andersen25f27032001-04-26 23:22:31 +00001013 mark_open(fileno(input));
Denis Vlasenko170435c2007-05-23 13:01:10 +00001014 status = parse_and_run_file(input);
Eric Andersen25f27032001-04-26 23:22:31 +00001015 mark_closed(fileno(input));
1016 fclose(input);
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00001017 return status;
Eric Andersen25f27032001-04-26 23:22:31 +00001018}
1019
Denis Vlasenko1359da62007-04-21 23:27:30 +00001020static int builtin_umask(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00001021{
Eric Andersen83a2ae22001-05-07 17:59:25 +00001022 mode_t new_umask;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001023 const char *arg = argv[1];
Eric Andersen83a2ae22001-05-07 17:59:25 +00001024 char *end;
1025 if (arg) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001026 new_umask = strtoul(arg, &end, 8);
1027 if (*end != '\0' || end == arg) {
Eric Andersen83a2ae22001-05-07 17:59:25 +00001028 return EXIT_FAILURE;
1029 }
1030 } else {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001031 new_umask = umask(0);
1032 printf("%.3o\n", (unsigned) new_umask);
Eric Andersen83a2ae22001-05-07 17:59:25 +00001033 }
1034 umask(new_umask);
1035 return EXIT_SUCCESS;
Eric Andersen25f27032001-04-26 23:22:31 +00001036}
1037
1038/* built-in 'unset VAR' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001039static int builtin_unset(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00001040{
Denis Vlasenko3e7b0e62007-05-16 12:52:15 +00001041 /* bash always returns true */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001042 unset_local_var(argv[1]);
Eric Andersen25f27032001-04-26 23:22:31 +00001043 return EXIT_SUCCESS;
1044}
1045
Denis Vlasenko06810332007-05-21 23:30:54 +00001046//static int builtin_not_written(char **argv)
1047//{
1048// printf("builtin_%s not written\n", argv[0]);
1049// return EXIT_FAILURE;
1050//}
Eric Andersen83a2ae22001-05-07 17:59:25 +00001051
Eric Andersen25f27032001-04-26 23:22:31 +00001052static int b_check_space(o_string *o, int len)
1053{
1054 /* It would be easy to drop a more restrictive policy
1055 * in here, such as setting a maximum string length */
1056 if (o->length + len > o->maxlen) {
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001057 /* assert(data == NULL || o->maxlen != 0); */
Denis Vlasenkoef36ead2007-05-02 15:34:47 +00001058 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001059 o->data = xrealloc(o->data, 1 + o->maxlen);
Eric Andersen25f27032001-04-26 23:22:31 +00001060 }
1061 return o->data == NULL;
1062}
1063
1064static int b_addchr(o_string *o, int ch)
1065{
Denis Vlasenko831dcc42007-05-16 15:05:36 +00001066 debug_printf("b_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001067 if (b_check_space(o, 1))
1068 return B_NOSPAC;
Eric Andersen25f27032001-04-26 23:22:31 +00001069 o->data[o->length] = ch;
1070 o->length++;
1071 o->data[o->length] = '\0';
1072 return 0;
1073}
1074
1075static void b_reset(o_string *o)
1076{
1077 o->length = 0;
1078 o->nonnull = 0;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001079 if (o->data != NULL)
1080 *o->data = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001081}
1082
1083static void b_free(o_string *o)
1084{
1085 b_reset(o);
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00001086 free(o->data);
Eric Andersen25f27032001-04-26 23:22:31 +00001087 o->data = NULL;
1088 o->maxlen = 0;
1089}
1090
1091/* My analysis of quoting semantics tells me that state information
1092 * is associated with a destination, not a source.
1093 */
1094static int b_addqchr(o_string *o, int ch, int quote)
1095{
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00001096 if (quote && strchr("*?[\\", ch)) {
Eric Andersen25f27032001-04-26 23:22:31 +00001097 int rc;
1098 rc = b_addchr(o, '\\');
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001099 if (rc)
1100 return rc;
Eric Andersen25f27032001-04-26 23:22:31 +00001101 }
1102 return b_addchr(o, ch);
1103}
1104
Eric Andersen25f27032001-04-26 23:22:31 +00001105static int static_get(struct in_str *i)
1106{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001107 int ch = *i->p++;
1108 if (ch == '\0') return EOF;
Eric Andersen25f27032001-04-26 23:22:31 +00001109 return ch;
1110}
1111
1112static int static_peek(struct in_str *i)
1113{
1114 return *i->p;
1115}
1116
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001117#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001118#if ENABLE_FEATURE_EDITING
Rob Landley88621d72006-08-29 19:41:06 +00001119static void cmdedit_set_initial_prompt(void)
Eric Andersen25f27032001-04-26 23:22:31 +00001120{
Denis Vlasenko38f63192007-01-22 09:03:07 +00001121#if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
Eric Andersen25f27032001-04-26 23:22:31 +00001122 PS1 = NULL;
1123#else
1124 PS1 = getenv("PS1");
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001125 if (PS1 == NULL)
Eric Andersen25f27032001-04-26 23:22:31 +00001126 PS1 = "\\w \\$ ";
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001127#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001128}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001129#endif /* EDITING */
Eric Andersen25f27032001-04-26 23:22:31 +00001130
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001131static const char* setup_prompt_string(int promptmode)
Eric Andersen25f27032001-04-26 23:22:31 +00001132{
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001133 const char *prompt_str;
1134 debug_printf("setup_prompt_string %d ", promptmode);
Denis Vlasenko38f63192007-01-22 09:03:07 +00001135#if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
Eric Andersen25f27032001-04-26 23:22:31 +00001136 /* Set up the prompt */
1137 if (promptmode == 1) {
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001138 char *ns;
1139 free((char*)PS1);
1140 ns = xmalloc(strlen(cwd)+4);
1141 sprintf(ns, "%s %s", cwd, (geteuid() != 0) ? "$ " : "# ");
1142 prompt_str = ns;
1143 PS1 = ns;
Eric Andersen25f27032001-04-26 23:22:31 +00001144 } else {
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001145 prompt_str = PS2;
Eric Andersen25f27032001-04-26 23:22:31 +00001146 }
1147#else
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001148 prompt_str = (promptmode == 1) ? PS1 : PS2;
Eric Andersenaf44a0e2001-04-27 07:26:12 +00001149#endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001150 debug_printf("result %s\n", prompt_str);
1151 return prompt_str;
Eric Andersen25f27032001-04-26 23:22:31 +00001152}
1153
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001154static void get_user_input(struct in_str *i)
Eric Andersen25f27032001-04-26 23:22:31 +00001155{
Denis Vlasenko0937be52007-04-28 16:47:08 +00001156 int r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001157 const char *prompt_str;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001158
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001159 prompt_str = setup_prompt_string(i->promptmode);
Denis Vlasenko38f63192007-01-22 09:03:07 +00001160#if ENABLE_FEATURE_EDITING
Denis Vlasenko170435c2007-05-23 13:01:10 +00001161 /* Enable command line editing only while a command line
1162 * is actually being read; otherwise, we'll end up bequeathing
1163 * atexit() handlers and other unwanted stuff to our
1164 * child processes (rob@sysgo.de) */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001165 r = read_line_input(prompt_str, user_input_buf, BUFSIZ-1, line_input_state);
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001166 i->eof_flag = (r < 0);
1167 if (i->eof_flag) { /* EOF/error detected */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001168 user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1169 user_input_buf[1] = '\0';
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001170 }
Eric Andersen25f27032001-04-26 23:22:31 +00001171#else
1172 fputs(prompt_str, stdout);
1173 fflush(stdout);
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001174 user_input_buf[0] = r = fgetc(i->file);
1175 /*user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001176 i->eof_flag = (r == EOF);
Eric Andersen25f27032001-04-26 23:22:31 +00001177#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001178 i->p = user_input_buf;
Eric Andersen25f27032001-04-26 23:22:31 +00001179}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001180#endif /* INTERACTIVE */
Eric Andersen25f27032001-04-26 23:22:31 +00001181
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001182/* This is the magic location that prints prompts
Eric Andersen25f27032001-04-26 23:22:31 +00001183 * and gets data back from the user */
1184static int file_get(struct in_str *i)
1185{
1186 int ch;
1187
Eric Andersen25f27032001-04-26 23:22:31 +00001188 /* If there is data waiting, eat it up */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001189 if (i->p && *i->p) {
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001190#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001191 take_cached:
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001192#endif
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001193 ch = *i->p++;
1194 if (i->eof_flag && !*i->p)
1195 ch = EOF;
Eric Andersen25f27032001-04-26 23:22:31 +00001196 } else {
1197 /* need to double check i->file because we might be doing something
1198 * more complicated by now, like sourcing or substituting. */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001199#if ENABLE_HUSH_INTERACTIVE
1200 if (interactive_fd && i->__promptme && i->file == stdin) {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001201 do {
1202 get_user_input(i);
1203 } while (!*i->p); /* need non-empty line */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001204 i->promptmode = 2;
Eric Andersene67c3ce2001-05-02 02:09:36 +00001205 i->__promptme = 0;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001206 goto take_cached;
Eric Andersen25f27032001-04-26 23:22:31 +00001207 }
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001208#endif
1209 ch = fgetc(i->file);
Eric Andersen25f27032001-04-26 23:22:31 +00001210 }
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001211 debug_printf("file_get: got a '%c' %d\n", ch, ch);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001212#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001213 if (ch == '\n')
1214 i->__promptme = 1;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001215#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001216 return ch;
1217}
1218
1219/* All the callers guarantee this routine will never be
1220 * used right after a newline, so prompting is not needed.
1221 */
1222static int file_peek(struct in_str *i)
1223{
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00001224 int ch;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001225 if (i->p && *i->p) {
1226 if (i->eof_flag && !i->p[1])
1227 return EOF;
1228 return *i->p;
Eric Andersen25f27032001-04-26 23:22:31 +00001229 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00001230 ch = fgetc(i->file);
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001231 i->eof_flag = (ch == EOF);
1232 i->peek_buf[0] = ch;
1233 i->peek_buf[1] = '\0';
1234 i->p = i->peek_buf;
1235 debug_printf("file_peek: got a '%c' %d\n", *i->p, *i->p);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00001236 return ch;
Eric Andersen25f27032001-04-26 23:22:31 +00001237}
1238
1239static void setup_file_in_str(struct in_str *i, FILE *f)
1240{
1241 i->peek = file_peek;
1242 i->get = file_get;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001243#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001244 i->__promptme = 1;
1245 i->promptmode = 1;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001246#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001247 i->file = f;
1248 i->p = NULL;
1249}
1250
1251static void setup_string_in_str(struct in_str *i, const char *s)
1252{
1253 i->peek = static_peek;
1254 i->get = static_get;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001255#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenkobb81c582007-01-30 22:32:09 +00001256 i->__promptme = 1;
1257 i->promptmode = 1;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001258#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001259 i->p = s;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001260 i->eof_flag = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00001261}
1262
1263static void mark_open(int fd)
1264{
1265 struct close_me *new = xmalloc(sizeof(struct close_me));
1266 new->fd = fd;
1267 new->next = close_me_head;
1268 close_me_head = new;
1269}
1270
1271static void mark_closed(int fd)
1272{
1273 struct close_me *tmp;
1274 if (close_me_head == NULL || close_me_head->fd != fd)
Manuel Novoa III cad53642003-03-19 09:13:01 +00001275 bb_error_msg_and_die("corrupt close_me");
Eric Andersen25f27032001-04-26 23:22:31 +00001276 tmp = close_me_head;
1277 close_me_head = close_me_head->next;
1278 free(tmp);
1279}
1280
Eric Anderseneaecbf32001-10-31 10:41:31 +00001281static void close_all(void)
Eric Andersen25f27032001-04-26 23:22:31 +00001282{
1283 struct close_me *c;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001284 for (c = close_me_head; c; c = c->next) {
Eric Andersen25f27032001-04-26 23:22:31 +00001285 close(c->fd);
1286 }
1287 close_me_head = NULL;
1288}
1289
1290/* squirrel != NULL means we squirrel away copies of stdin, stdout,
1291 * and stderr if they are redirected. */
1292static int setup_redirects(struct child_prog *prog, int squirrel[])
1293{
1294 int openfd, mode;
1295 struct redir_struct *redir;
1296
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001297 for (redir = prog->redirects; redir; redir = redir->next) {
Eric Andersen817e73c2001-06-06 17:56:09 +00001298 if (redir->dup == -1 && redir->word.gl_pathv == NULL) {
1299 /* something went wrong in the parse. Pretend it didn't happen */
1300 continue;
1301 }
Eric Andersen25f27032001-04-26 23:22:31 +00001302 if (redir->dup == -1) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001303 mode = redir_table[redir->type].mode;
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001304 openfd = open_or_warn(redir->word.gl_pathv[0], mode);
Eric Andersen25f27032001-04-26 23:22:31 +00001305 if (openfd < 0) {
1306 /* this could get lost if stderr has been redirected, but
1307 bash and ash both lose it as well (though zsh doesn't!) */
Eric Andersen25f27032001-04-26 23:22:31 +00001308 return 1;
1309 }
1310 } else {
1311 openfd = redir->dup;
1312 }
1313
1314 if (openfd != redir->fd) {
1315 if (squirrel && redir->fd < 3) {
1316 squirrel[redir->fd] = dup(redir->fd);
1317 }
Eric Andersen83a2ae22001-05-07 17:59:25 +00001318 if (openfd == -3) {
1319 close(openfd);
1320 } else {
1321 dup2(openfd, redir->fd);
Matt Kraaic616e532001-06-05 16:50:08 +00001322 if (redir->dup == -1)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001323 close(openfd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00001324 }
Eric Andersen25f27032001-04-26 23:22:31 +00001325 }
1326 }
1327 return 0;
1328}
1329
1330static void restore_redirects(int squirrel[])
1331{
1332 int i, fd;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001333 for (i = 0; i < 3; i++) {
Eric Andersen25f27032001-04-26 23:22:31 +00001334 fd = squirrel[i];
1335 if (fd != -1) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00001336 /* We simply die on error */
1337 xmove_fd(fd, i);
Eric Andersen25f27032001-04-26 23:22:31 +00001338 }
1339 }
1340}
1341
Eric Andersenada18ff2001-05-21 16:18:22 +00001342/* never returns */
Eric Andersen94ac2442001-05-22 19:05:18 +00001343/* XXX no exit() here. If you don't exec, use _exit instead.
1344 * The at_exit handlers apparently confuse the calling process,
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001345 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001346static void pseudo_exec_argv(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00001347{
Eric Andersen78a7c992001-05-15 16:30:25 +00001348 int i, rcode;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001349 char *p;
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +00001350 const struct built_in_command *x;
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001351
Denis Vlasenko1359da62007-04-21 23:27:30 +00001352 for (i = 0; is_assignment(argv[i]); i++) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001353 debug_printf_exec("pid %d environment modification: %s\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001354 getpid(), argv[i]);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001355// FIXME: vfork case??
Denis Vlasenko170435c2007-05-23 13:01:10 +00001356 p = expand_string_to_string(argv[i]);
1357 putenv(p);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001358 }
1359 argv += i;
1360 /* If a variable is assigned in a forest, and nobody listens,
1361 * was it ever really set?
1362 */
1363 if (argv[0] == NULL) {
1364 _exit(EXIT_SUCCESS);
1365 }
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001366
Denis Vlasenko170435c2007-05-23 13:01:10 +00001367 argv = expand_strvec_to_strvec(argv);
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001368
Denis Vlasenko1359da62007-04-21 23:27:30 +00001369 /*
1370 * Check if the command matches any of the builtins.
1371 * Depending on context, this might be redundant. But it's
1372 * easier to waste a few CPU cycles than it is to figure out
1373 * if this is one of those cases.
1374 */
1375 for (x = bltins; x->cmd; x++) {
1376 if (strcmp(argv[0], x->cmd) == 0) {
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001377 debug_printf_exec("running builtin '%s'\n", argv[0]);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001378 rcode = x->function(argv);
1379 fflush(stdout);
1380 _exit(rcode);
Eric Andersen94ac2442001-05-22 19:05:18 +00001381 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00001382 }
Eric Andersen78a7c992001-05-15 16:30:25 +00001383
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001384 /* Check if the command matches any busybox applets */
Denis Vlasenko80d14be2007-04-10 23:03:30 +00001385#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001386 if (strchr(argv[0], '/') == NULL) {
1387 const struct bb_applet *a = find_applet_by_name(argv[0]);
1388 if (a) {
1389 if (a->noexec) {
1390 current_applet = a;
1391 debug_printf_exec("running applet '%s'\n", argv[0]);
1392// is it ok that run_current_applet_and_exit() does exit(), not _exit()?
1393 run_current_applet_and_exit(argv);
1394 }
1395 /* re-exec ourselves with the new arguments */
1396 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
1397 execvp(CONFIG_BUSYBOX_EXEC_PATH, argv);
1398 /* If they called chroot or otherwise made the binary no longer
1399 * executable, fall through */
1400 }
1401 }
Eric Andersenaac75e52001-04-30 18:18:45 +00001402#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001403
1404 debug_printf_exec("execing '%s'\n", argv[0]);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001405 execvp(argv[0], argv);
1406 bb_perror_msg("cannot exec '%s'", argv[0]);
1407 _exit(1);
1408}
1409
1410static void pseudo_exec(struct child_prog *child)
1411{
Denis Vlasenkof2fffd02007-05-02 23:39:04 +00001412// FIXME: buggy wrt NOMMU! Must not modify any global data
1413// until it does exec/_exit, but currently it does.
Denis Vlasenko1359da62007-04-21 23:27:30 +00001414 int rcode;
1415
1416 if (child->argv) {
1417 pseudo_exec_argv(child->argv);
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001418 }
1419
1420 if (child->group) {
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001421 // FIXME: do not modify globals! Think vfork!
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001422#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001423 debug_printf_exec("pseudo_exec: setting interactive_fd=0\n");
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001424 interactive_fd = 0; /* crucial!!!! */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001425#endif
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001426 debug_printf_exec("pseudo_exec: run_list_real\n");
Eric Andersen25f27032001-04-26 23:22:31 +00001427 rcode = run_list_real(child->group);
Eric Andersenbf7df042001-05-23 22:18:35 +00001428 /* OK to leak memory by not calling free_pipe_list,
Eric Andersen25f27032001-04-26 23:22:31 +00001429 * since this process is about to exit */
Eric Andersen94ac2442001-05-22 19:05:18 +00001430 _exit(rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00001431 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001432
1433 /* Can happen. See what bash does with ">foo" by itself. */
1434 debug_printf("trying to pseudo_exec null command\n");
1435 _exit(EXIT_SUCCESS);
Eric Andersen25f27032001-04-26 23:22:31 +00001436}
1437
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001438#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001439static const char *get_cmdtext(struct pipe *pi)
1440{
1441 char **argv;
1442 char *p;
1443 int len;
1444
1445 /* This is subtle. ->cmdtext is created only on first backgrounding.
1446 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001447 * On subsequent bg argv is trashed, but we won't use it */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001448 if (pi->cmdtext)
1449 return pi->cmdtext;
1450 argv = pi->progs[0].argv;
1451 if (!argv || !argv[0])
1452 return (pi->cmdtext = xzalloc(1));
1453
1454 len = 0;
1455 do len += strlen(*argv) + 1; while (*++argv);
1456 pi->cmdtext = p = xmalloc(len);
1457 argv = pi->progs[0].argv;
1458 do {
1459 len = strlen(*argv);
1460 memcpy(p, *argv, len);
1461 p += len;
1462 *p++ = ' ';
1463 } while (*++argv);
1464 p[-1] = '\0';
1465 return pi->cmdtext;
1466}
1467
Eric Andersenbafd94f2001-05-02 16:11:59 +00001468static void insert_bg_job(struct pipe *pi)
1469{
1470 struct pipe *thejob;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001471 int i;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001472
1473 /* Linear search for the ID of the job to use */
1474 pi->jobid = 1;
Eric Andersenc798b072001-06-22 06:23:03 +00001475 for (thejob = job_list; thejob; thejob = thejob->next)
Eric Andersenbafd94f2001-05-02 16:11:59 +00001476 if (thejob->jobid >= pi->jobid)
1477 pi->jobid = thejob->jobid + 1;
1478
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001479 /* Add thejob to the list of running jobs */
Eric Andersenc798b072001-06-22 06:23:03 +00001480 if (!job_list) {
Eric Andersen52a97ca2001-06-22 06:49:26 +00001481 thejob = job_list = xmalloc(sizeof(*thejob));
Eric Andersenbafd94f2001-05-02 16:11:59 +00001482 } else {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001483 for (thejob = job_list; thejob->next; thejob = thejob->next)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001484 continue;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001485 thejob->next = xmalloc(sizeof(*thejob));
1486 thejob = thejob->next;
1487 }
1488
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001489 /* Physically copy the struct job */
Eric Andersen0fcd4472001-05-02 20:12:03 +00001490 memcpy(thejob, pi, sizeof(struct pipe));
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001491 thejob->progs = xzalloc(sizeof(pi->progs[0]) * pi->num_progs);
1492 /* We cannot copy entire pi->progs[] vector! Double free()s will happen */
1493 for (i = 0; i < pi->num_progs; i++) {
1494// TODO: do we really need to have so many fields which are just dead weight
1495// at execution stage?
1496 thejob->progs[i].pid = pi->progs[i].pid;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001497 /* all other fields are not used and stay zero */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001498 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00001499 thejob->next = NULL;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001500 thejob->cmdtext = xstrdup(get_cmdtext(pi));
Eric Andersenbafd94f2001-05-02 16:11:59 +00001501
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001502 /* We don't wait for background thejobs to return -- append it
Eric Andersenbafd94f2001-05-02 16:11:59 +00001503 to the list of backgrounded thejobs and leave it alone */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001504 printf("[%d] %d %s\n", thejob->jobid, thejob->progs[0].pid, thejob->cmdtext);
Eric Andersen1a6d39b2001-05-08 05:11:54 +00001505 last_bg_pid = thejob->progs[0].pid;
Eric Andersenc798b072001-06-22 06:23:03 +00001506 last_jobid = thejob->jobid;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001507}
1508
Eric Andersenbafd94f2001-05-02 16:11:59 +00001509static void remove_bg_job(struct pipe *pi)
1510{
1511 struct pipe *prev_pipe;
1512
Eric Andersenc798b072001-06-22 06:23:03 +00001513 if (pi == job_list) {
Eric Andersen52a97ca2001-06-22 06:49:26 +00001514 job_list = pi->next;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001515 } else {
Eric Andersenc798b072001-06-22 06:23:03 +00001516 prev_pipe = job_list;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001517 while (prev_pipe->next != pi)
1518 prev_pipe = prev_pipe->next;
1519 prev_pipe->next = pi->next;
1520 }
Eric Andersen028b65b2001-06-28 01:10:11 +00001521 if (job_list)
1522 last_jobid = job_list->jobid;
1523 else
1524 last_jobid = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001525}
Eric Andersen028b65b2001-06-28 01:10:11 +00001526
Denis Vlasenko1359da62007-04-21 23:27:30 +00001527/* remove a backgrounded job */
1528static void delete_finished_bg_job(struct pipe *pi)
1529{
1530 remove_bg_job(pi);
Eric Andersen52a97ca2001-06-22 06:49:26 +00001531 pi->stopped_progs = 0;
Eric Andersenbf7df042001-05-23 22:18:35 +00001532 free_pipe(pi, 0);
Eric Andersenbafd94f2001-05-02 16:11:59 +00001533 free(pi);
1534}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001535#endif /* JOB */
Eric Andersenbafd94f2001-05-02 16:11:59 +00001536
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001537/* Checks to see if any processes have exited -- if they
Eric Andersenbafd94f2001-05-02 16:11:59 +00001538 have, figure out why and see if a job has completed */
Eric Andersenc798b072001-06-22 06:23:03 +00001539static int checkjobs(struct pipe* fg_pipe)
Eric Andersenbafd94f2001-05-02 16:11:59 +00001540{
Eric Andersenc798b072001-06-22 06:23:03 +00001541 int attributes;
1542 int status;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001543#if ENABLE_HUSH_JOB
Eric Andersenbafd94f2001-05-02 16:11:59 +00001544 int prognum = 0;
1545 struct pipe *pi;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001546#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00001547 pid_t childpid;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001548 int rcode = 0;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001549
Eric Andersenc798b072001-06-22 06:23:03 +00001550 attributes = WUNTRACED;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001551 if (fg_pipe == NULL) {
Eric Andersenc798b072001-06-22 06:23:03 +00001552 attributes |= WNOHANG;
1553 }
1554
Denis Vlasenko1359da62007-04-21 23:27:30 +00001555/* Do we do this right?
1556 * bash-3.00# sleep 20 | false
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001557 * <ctrl-Z pressed>
Denis Vlasenko1359da62007-04-21 23:27:30 +00001558 * [3]+ Stopped sleep 20 | false
1559 * bash-3.00# echo $?
1560 * 1 <========== bg pipe is not fully done, but exitcode is already known!
1561 */
1562
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001563//FIXME: non-interactive bash does not continue even if all processes in fg pipe
1564//are stopped. Testcase: "cat | cat" in a script (not on command line)
1565// + killall -STOP cat
1566
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001567 wait_more:
Eric Andersenc798b072001-06-22 06:23:03 +00001568 while ((childpid = waitpid(-1, &status, attributes)) > 0) {
Denis Vlasenko1359da62007-04-21 23:27:30 +00001569 const int dead = WIFEXITED(status) || WIFSIGNALED(status);
1570
1571#ifdef DEBUG_SHELL_JOBS
1572 if (WIFSTOPPED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001573 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001574 childpid, WSTOPSIG(status), WEXITSTATUS(status));
1575 if (WIFSIGNALED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001576 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001577 childpid, WTERMSIG(status), WEXITSTATUS(status));
1578 if (WIFEXITED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001579 debug_printf_jobs("pid %d exited, exitcode %d\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001580 childpid, WEXITSTATUS(status));
1581#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001582 /* Were we asked to wait for fg pipe? */
Eric Andersenc798b072001-06-22 06:23:03 +00001583 if (fg_pipe) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001584 int i;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001585 for (i = 0; i < fg_pipe->num_progs; i++) {
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001586 debug_printf_jobs("check pid %d\n", fg_pipe->progs[i].pid);
Eric Andersenc798b072001-06-22 06:23:03 +00001587 if (fg_pipe->progs[i].pid == childpid) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001588 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001589 if (dead) {
1590 fg_pipe->progs[i].pid = 0;
1591 fg_pipe->running_progs--;
1592 if (i == fg_pipe->num_progs-1)
1593 /* last process gives overall exitstatus */
1594 rcode = WEXITSTATUS(status);
1595 } else {
1596 fg_pipe->progs[i].is_stopped = 1;
1597 fg_pipe->stopped_progs++;
1598 }
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001599 debug_printf_jobs("fg_pipe: running_progs %d stopped_progs %d\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001600 fg_pipe->running_progs, fg_pipe->stopped_progs);
1601 if (fg_pipe->running_progs - fg_pipe->stopped_progs <= 0) {
1602 /* All processes in fg pipe have exited/stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001603#if ENABLE_HUSH_JOB
Denis Vlasenko1359da62007-04-21 23:27:30 +00001604 if (fg_pipe->running_progs)
1605 insert_bg_job(fg_pipe);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001606#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001607 return rcode;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001608 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001609 /* There are still running processes in the fg pipe */
1610 goto wait_more;
Eric Andersenc798b072001-06-22 06:23:03 +00001611 }
1612 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00001613 /* fall through to searching process in bg pipes */
Eric Andersenc798b072001-06-22 06:23:03 +00001614 }
1615
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001616#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001617 /* We asked to wait for bg or orphaned children */
1618 /* No need to remember exitcode in this case */
Eric Andersenc798b072001-06-22 06:23:03 +00001619 for (pi = job_list; pi; pi = pi->next) {
Eric Andersenbafd94f2001-05-02 16:11:59 +00001620 prognum = 0;
Denis Vlasenko5f786c22007-04-20 08:35:45 +00001621 while (prognum < pi->num_progs) {
1622 if (pi->progs[prognum].pid == childpid)
1623 goto found_pi_and_prognum;
Eric Andersen52a97ca2001-06-22 06:49:26 +00001624 prognum++;
1625 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00001626 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001627#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00001628
Denis Vlasenko5f786c22007-04-20 08:35:45 +00001629 /* Happens when shell is used as init process (init=/bin/sh) */
1630 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001631 goto wait_more;
Eric Andersenaeb44c42001-05-22 20:29:00 +00001632
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001633#if ENABLE_HUSH_JOB
Denis Vlasenko5f786c22007-04-20 08:35:45 +00001634 found_pi_and_prognum:
Denis Vlasenko1359da62007-04-21 23:27:30 +00001635 if (dead) {
Eric Andersenbafd94f2001-05-02 16:11:59 +00001636 /* child exited */
Eric Andersenbafd94f2001-05-02 16:11:59 +00001637 pi->progs[prognum].pid = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001638 pi->running_progs--;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001639 if (!pi->running_progs) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001640 printf(JOB_STATUS_FORMAT, pi->jobid,
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001641 "Done", pi->cmdtext);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001642 delete_finished_bg_job(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00001643 }
1644 } else {
1645 /* child stopped */
1646 pi->stopped_progs++;
1647 pi->progs[prognum].is_stopped = 1;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001648 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001649#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00001650 }
1651
Denis Vlasenko1359da62007-04-21 23:27:30 +00001652 /* wait found no children or failed */
1653
1654 if (childpid && errno != ECHILD)
Manuel Novoa III cad53642003-03-19 09:13:01 +00001655 bb_perror_msg("waitpid");
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001656 return rcode;
Eric Andersenada18ff2001-05-21 16:18:22 +00001657}
1658
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001659#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +00001660static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
1661{
1662 pid_t p;
1663 int rcode = checkjobs(fg_pipe);
1664 /* Job finished, move the shell to the foreground */
Denis Vlasenko170435c2007-05-23 13:01:10 +00001665 p = getpgid(0); /* pgid of our process */
1666 debug_printf_jobs("fg'ing ourself: getpgid(0)=%d\n", (int)p);
Denis Vlasenko52881e92007-04-21 13:42:52 +00001667 if (tcsetpgrp(interactive_fd, p) && errno != ENOTTY)
1668 bb_perror_msg("tcsetpgrp-4a");
1669 return rcode;
1670}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001671#endif
Denis Vlasenko52881e92007-04-21 13:42:52 +00001672
Eric Andersen25f27032001-04-26 23:22:31 +00001673/* run_pipe_real() starts all the jobs, but doesn't wait for anything
Eric Andersenc798b072001-06-22 06:23:03 +00001674 * to finish. See checkjobs().
Eric Andersen25f27032001-04-26 23:22:31 +00001675 *
1676 * return code is normally -1, when the caller has to wait for children
1677 * to finish to determine the exit status of the pipe. If the pipe
1678 * is a simple builtin command, however, the action is done by the
1679 * time run_pipe_real returns, and the exit code is provided as the
1680 * return value.
1681 *
1682 * The input of the pipe is always stdin, the output is always
1683 * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
1684 * because it tries to avoid running the command substitution in
1685 * subshell, when that is in fact necessary. The subshell process
1686 * now has its stdout directed to the input of the appropriate pipe,
1687 * so this routine is noticeably simpler.
Denis Vlasenko170435c2007-05-23 13:01:10 +00001688 *
1689 * Returns -1 only if started some children. IOW: we have to
1690 * mask out retvals of builtins etc with 0xff!
Eric Andersen25f27032001-04-26 23:22:31 +00001691 */
1692static int run_pipe_real(struct pipe *pi)
1693{
1694 int i;
1695 int nextin, nextout;
1696 int pipefds[2]; /* pipefds[0] is for reading */
Rob Landley53702e52006-07-19 21:43:53 +00001697 struct child_prog *child;
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +00001698 const struct built_in_command *x;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001699 char *p;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001700 /* it is not always needed, but we aim to smaller code */
1701 int squirrel[] = { -1, -1, -1 };
1702 int rcode;
Denis Vlasenko52881e92007-04-21 13:42:52 +00001703 const int single_fg = (pi->num_progs == 1 && pi->followup != PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00001704
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001705 debug_printf_exec("run_pipe_real start: single_fg=%d\n", single_fg);
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00001706
Eric Andersen25f27032001-04-26 23:22:31 +00001707 nextin = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001708#if ENABLE_HUSH_JOB
Eric Andersenada18ff2001-05-21 16:18:22 +00001709 pi->pgrp = -1;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001710#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001711 pi->running_progs = 1;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001712 pi->stopped_progs = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00001713
1714 /* Check if this is a simple builtin (not part of a pipe).
1715 * Builtins within pipes have to fork anyway, and are handled in
1716 * pseudo_exec. "echo foo | read bar" doesn't work on bash, either.
1717 */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001718 child = &(pi->progs[0]);
Denis Vlasenko52881e92007-04-21 13:42:52 +00001719 if (single_fg && child->group && child->subshell == 0) {
Eric Andersen04407e52001-06-07 16:42:05 +00001720 debug_printf("non-subshell grouping\n");
1721 setup_redirects(child, squirrel);
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001722 debug_printf_exec(": run_list_real\n");
Eric Andersen04407e52001-06-07 16:42:05 +00001723 rcode = run_list_real(child->group);
1724 restore_redirects(squirrel);
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001725 debug_printf_exec("run_pipe_real return %d\n", rcode);
Denis Vlasenko170435c2007-05-23 13:01:10 +00001726 return rcode; // do we need to add '... & 0xff' ?
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001727 }
1728
Denis Vlasenko1359da62007-04-21 23:27:30 +00001729 if (single_fg && child->argv != NULL) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001730 char **argv_expanded;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001731 char **argv = child->argv;
1732
1733 for (i = 0; is_assignment(argv[i]); i++)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001734 continue;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001735 if (i != 0 && argv[i] == NULL) {
Eric Andersen78a7c992001-05-15 16:30:25 +00001736 /* assignments, but no command: set the local environment */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001737 for (i = 0; argv[i] != NULL; i++) {
Eric Andersen99785762001-05-22 21:37:48 +00001738 /* Ok, this case is tricky. We have to decide if this is a
1739 * local variable, or an already exported variable. If it is
1740 * already exported, we have to export the new value. If it is
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001741 * not exported, we need only set this as a local variable.
Eric Andersen99785762001-05-22 21:37:48 +00001742 * This junk is all to decide whether or not to export this
1743 * variable. */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001744 int export_me = 0;
Eric Andersen99785762001-05-22 21:37:48 +00001745 char *name, *value;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001746 name = xstrdup(argv[i]);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00001747 debug_printf("local environment set: %s\n", name);
Eric Andersen99785762001-05-22 21:37:48 +00001748 value = strchr(name, '=');
1749 if (value)
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00001750 *value = '\0';
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001751 if (get_local_var(name)) {
1752 export_me = 1;
Eric Andersen99785762001-05-22 21:37:48 +00001753 }
1754 free(name);
Denis Vlasenko170435c2007-05-23 13:01:10 +00001755 p = expand_string_to_string(argv[i]);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001756 set_local_var(p, export_me);
Denis Vlasenko170435c2007-05-23 13:01:10 +00001757 free(p);
Eric Andersen78a7c992001-05-15 16:30:25 +00001758 }
1759 return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
1760 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00001761 for (i = 0; is_assignment(argv[i]); i++) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00001762 p = expand_string_to_string(argv[i]);
1763 //sp: child->sp--;
1764 putenv(p);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001765 }
Eric Andersen25f27032001-04-26 23:22:31 +00001766 for (x = bltins; x->cmd; x++) {
Denis Vlasenko1359da62007-04-21 23:27:30 +00001767 if (strcmp(argv[i], x->cmd) == 0) {
1768 if (x->function == builtin_exec && argv[i+1] == NULL) {
Eric Andersen83a2ae22001-05-07 17:59:25 +00001769 debug_printf("magic exec\n");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001770 setup_redirects(child, NULL);
Eric Andersen83a2ae22001-05-07 17:59:25 +00001771 return EXIT_SUCCESS;
1772 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00001773 debug_printf("builtin inline %s\n", argv[0]);
Eric Andersen25f27032001-04-26 23:22:31 +00001774 /* XXX setup_redirects acts on file descriptors, not FILEs.
1775 * This is perfect for work that comes after exec().
1776 * Is it really safe for inline use? Experimentally,
1777 * things seem to work with glibc. */
1778 setup_redirects(child, squirrel);
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001779 debug_printf_exec(": builtin '%s' '%s'...\n", x->cmd, argv[i+1]);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001780 //sp: if (child->sp) /* btw we can do it unconditionally... */
Denis Vlasenko170435c2007-05-23 13:01:10 +00001781 argv_expanded = expand_strvec_to_strvec(argv + i);
1782 rcode = x->function(argv_expanded) & 0xff;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001783 free(argv_expanded);
Eric Andersen25f27032001-04-26 23:22:31 +00001784 restore_redirects(squirrel);
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001785 debug_printf_exec("run_pipe_real return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00001786 return rcode;
1787 }
1788 }
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001789#if ENABLE_FEATURE_SH_STANDALONE
1790 {
Denis Vlasenko1359da62007-04-21 23:27:30 +00001791 const struct bb_applet *a = find_applet_by_name(argv[i]);
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001792 if (a && a->nofork) {
1793 setup_redirects(child, squirrel);
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001794 save_nofork_data(&nofork_save);
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001795 argv_expanded = argv + i;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001796 //sp: if (child->sp)
Denis Vlasenko170435c2007-05-23 13:01:10 +00001797 argv_expanded = expand_strvec_to_strvec(argv + i);
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001798 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n", argv_expanded[0], argv_expanded[1]);
Denis Vlasenko170435c2007-05-23 13:01:10 +00001799 rcode = run_nofork_applet_prime(&nofork_save, a, argv_expanded) & 0xff;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001800 free(argv_expanded);
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001801 restore_redirects(squirrel);
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001802 debug_printf_exec("run_pipe_real return %d\n", rcode);
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001803 return rcode;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001804 }
1805 }
1806#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001807 }
1808
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001809 /* Going to fork a child per each pipe member */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001810 pi->running_progs = 0;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001811
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001812 /* Disable job control signals for shell (parent) and
1813 * for initial child code after fork */
1814 set_jobctrl_sighandler(SIG_IGN);
1815
Eric Andersen25f27032001-04-26 23:22:31 +00001816 for (i = 0; i < pi->num_progs; i++) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001817 child = &(pi->progs[i]);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001818 if (child->argv)
1819 debug_printf_exec(": pipe member '%s' '%s'...\n", child->argv[0], child->argv[1]);
1820 else
1821 debug_printf_exec(": pipe member with no argv\n");
Eric Andersen25f27032001-04-26 23:22:31 +00001822
1823 /* pipes are inserted between pairs of commands */
1824 if ((i + 1) < pi->num_progs) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001825 if (pipe(pipefds) < 0)
1826 bb_perror_msg_and_die("pipe");
Eric Andersen25f27032001-04-26 23:22:31 +00001827 nextout = pipefds[1];
1828 } else {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001829 nextout = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00001830 pipefds[0] = -1;
1831 }
1832
1833 /* XXX test for failed fork()? */
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001834#if BB_MMU
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001835 child->pid = fork();
Eric Andersen72f9a422001-10-28 05:12:20 +00001836#else
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001837 child->pid = vfork();
Eric Andersen72f9a422001-10-28 05:12:20 +00001838#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001839 if (!child->pid) { /* child */
1840 /* Every child adds itself to new process group
1841 * with pgid == pid of first child in pipe */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001842#if ENABLE_HUSH_JOB
Denis Vlasenko170435c2007-05-23 13:01:10 +00001843 if (run_list_level == 1 && interactive_fd) {
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001844 /* Don't do pgrp restore anymore on fatal signals */
1845 set_fatal_sighandler(SIG_DFL);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001846 if (pi->pgrp < 0) /* true for 1st process only */
1847 pi->pgrp = getpid();
1848 if (setpgid(0, pi->pgrp) == 0 && pi->followup != PIPE_BG) {
1849 /* We do it in *every* child, not just first,
1850 * to avoid races */
1851 tcsetpgrp(interactive_fd, pi->pgrp);
1852 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001853 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001854#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001855 /* in non-interactive case fatal sigs are already SIG_DFL */
Eric Andersen25f27032001-04-26 23:22:31 +00001856 close_all();
Eric Andersen25f27032001-04-26 23:22:31 +00001857 if (nextin != 0) {
1858 dup2(nextin, 0);
1859 close(nextin);
1860 }
1861 if (nextout != 1) {
1862 dup2(nextout, 1);
1863 close(nextout);
1864 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00001865 if (pipefds[0] != -1) {
Eric Andersen25f27032001-04-26 23:22:31 +00001866 close(pipefds[0]); /* opposite end of our output pipe */
1867 }
Eric Andersen25f27032001-04-26 23:22:31 +00001868 /* Like bash, explicit redirects override pipes,
1869 * and the pipe fd is available for dup'ing. */
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001870 setup_redirects(child, NULL);
Eric Andersen52a97ca2001-06-22 06:49:26 +00001871
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001872 /* Restore default handlers just prior to exec */
1873 set_jobctrl_sighandler(SIG_DFL);
1874 set_misc_sighandler(SIG_DFL);
1875 signal(SIGCHLD, SIG_DFL);
Eric Andersen25f27032001-04-26 23:22:31 +00001876 pseudo_exec(child);
1877 }
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001878
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001879 pi->running_progs++;
1880
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001881#if ENABLE_HUSH_JOB
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00001882 /* Second and next children need to know pid of first one */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001883 if (pi->pgrp < 0)
Eric Andersen0fcd4472001-05-02 20:12:03 +00001884 pi->pgrp = child->pid;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001885#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001886 if (nextin != 0)
1887 close(nextin);
1888 if (nextout != 1)
1889 close(nextout);
1890
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001891 /* If there isn't another process, nextin is garbage
Eric Andersen25f27032001-04-26 23:22:31 +00001892 but it doesn't matter */
1893 nextin = pipefds[0];
1894 }
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001895 debug_printf_exec("run_pipe_real return -1\n");
Eric Andersen25f27032001-04-26 23:22:31 +00001896 return -1;
1897}
1898
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001899#ifndef debug_print_tree
1900static void debug_print_tree(struct pipe *pi, int lvl)
1901{
1902 static const char *PIPE[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001903 [PIPE_SEQ] = "SEQ",
1904 [PIPE_AND] = "AND",
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001905 [PIPE_OR ] = "OR" ,
1906 [PIPE_BG ] = "BG" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001907 };
1908 static const char *RES[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001909 [RES_NONE ] = "NONE" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00001910#if ENABLE_HUSH_IF
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001911 [RES_IF ] = "IF" ,
1912 [RES_THEN ] = "THEN" ,
1913 [RES_ELIF ] = "ELIF" ,
1914 [RES_ELSE ] = "ELSE" ,
1915 [RES_FI ] = "FI" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00001916#endif
1917#if ENABLE_HUSH_LOOPS
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001918 [RES_FOR ] = "FOR" ,
1919 [RES_WHILE] = "WHILE",
1920 [RES_UNTIL] = "UNTIL",
1921 [RES_DO ] = "DO" ,
1922 [RES_DONE ] = "DONE" ,
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001923 [RES_IN ] = "IN" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00001924#endif
1925 [RES_XXXX ] = "XXXX" ,
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001926 [RES_SNTX ] = "SNTX" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001927 };
1928
1929 int pin, prn;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00001930
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001931 pin = 0;
1932 while (pi) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00001933 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
1934 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001935 prn = 0;
1936 while (prn < pi->num_progs) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00001937 struct child_prog *child = &pi->progs[prn];
1938 char **argv = child->argv;
1939
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001940 fprintf(stderr, "%*s prog %d", lvl*2, "", prn);
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00001941 if (child->group) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001942 fprintf(stderr, " group %s: (argv=%p)\n",
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00001943 (child->subshell ? "()" : "{}"),
1944 argv);
1945 debug_print_tree(child->group, lvl+1);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001946 prn++;
1947 continue;
1948 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001949 if (argv) while (*argv) {
1950 fprintf(stderr, " '%s'", *argv);
1951 argv++;
1952 }
1953 fprintf(stderr, "\n");
1954 prn++;
1955 }
1956 pi = pi->next;
1957 pin++;
1958 }
1959}
1960#endif
1961
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001962/* NB: called by pseudo_exec, and therefore must not modify any
1963 * global data until exec/_exit (we can be a child after vfork!) */
Eric Andersen25f27032001-04-26 23:22:31 +00001964static int run_list_real(struct pipe *pi)
1965{
Denis Vlasenko06810332007-05-21 23:30:54 +00001966 struct pipe *rpipe;
1967#if ENABLE_HUSH_LOOPS
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00001968 char *for_varname = NULL;
1969 char **for_lcur = NULL;
1970 char **for_list = NULL;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001971 int flag_rep = 0;
Denis Vlasenko06810332007-05-21 23:30:54 +00001972#endif
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001973 int save_num_progs;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001974 int flag_skip = 1;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00001975 int rcode = 0; /* probably for gcc only */
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001976 int flag_restore = 0;
Denis Vlasenko06810332007-05-21 23:30:54 +00001977#if ENABLE_HUSH_IF
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001978 int if_code = 0, next_if_code = 0; /* need double-buffer to handle elif */
Denis Vlasenko06810332007-05-21 23:30:54 +00001979#else
1980 enum { if_code = 0, next_if_code = 0 };
1981#endif
Denis Vlasenko219e88d2007-05-21 10:18:23 +00001982 reserved_style rword;
1983 reserved_style skip_more_for_this_rword = RES_XXXX;
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00001984
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001985 debug_printf_exec("run_list_real start lvl %d\n", run_list_level + 1);
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00001986
Denis Vlasenko06810332007-05-21 23:30:54 +00001987#if ENABLE_HUSH_LOOPS
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001988 /* check syntax for "for" */
1989 for (rpipe = pi; rpipe; rpipe = rpipe->next) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00001990 if ((rpipe->res_word == RES_IN || rpipe->res_word == RES_FOR)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001991 && (rpipe->next == NULL)
1992 ) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001993 syntax("malformed for"); /* no IN or no commands after IN */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001994 debug_printf_exec("run_list_real lvl %d return 1\n", run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001995 return 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001996 }
Denis Vlasenko219e88d2007-05-21 10:18:23 +00001997 if ((rpipe->res_word == RES_IN && rpipe->next->res_word == RES_IN && rpipe->next->progs[0].argv != NULL)
1998 || (rpipe->res_word == RES_FOR && rpipe->next->res_word != RES_IN)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001999 ) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002000 /* TODO: what is tested in the first condition? */
Denis Vlasenko90e485c2007-05-23 15:22:50 +00002001 syntax("malformed for"); /* 2nd condition: not followed by IN */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00002002 debug_printf_exec("run_list_real lvl %d return 1\n", run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002003 return 1;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002004 }
2005 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002006#else
2007 rpipe = NULL;
2008#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002009
2010#if ENABLE_HUSH_JOB
2011 /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
2012 * We are saving state before entering outermost list ("while...done")
2013 * so that ctrl-Z will correctly background _entire_ outermost list,
2014 * not just a part of it (like "sleep 1 | exit 2") */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00002015 if (++run_list_level == 1 && interactive_fd) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002016 if (sigsetjmp(toplevel_jb, 1)) {
2017 /* ctrl-Z forked and we are parent; or ctrl-C.
2018 * Sighandler has longjmped us here */
2019 signal(SIGINT, SIG_IGN);
2020 signal(SIGTSTP, SIG_IGN);
2021 /* Restore level (we can be coming from deep inside
2022 * nested levels) */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00002023 run_list_level = 1;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002024#if ENABLE_FEATURE_SH_STANDALONE
2025 if (nofork_save.saved) { /* if save area is valid */
2026 debug_printf_jobs("exiting nofork early\n");
2027 restore_nofork_data(&nofork_save);
2028 }
2029#endif
2030 if (ctrl_z_flag) {
2031 /* ctrl-Z has forked and stored pid of the child in pi->pid.
2032 * Remember this child as background job */
2033 insert_bg_job(pi);
2034 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002035 /* ctrl-C. We just stop doing whatever we were doing */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002036 putchar('\n');
2037 }
2038 rcode = 0;
2039 goto ret;
2040 }
2041 /* ctrl-Z handler will store pid etc in pi */
2042 toplevel_list = pi;
2043 ctrl_z_flag = 0;
2044#if ENABLE_FEATURE_SH_STANDALONE
2045 nofork_save.saved = 0; /* in case we will run a nofork later */
2046#endif
2047 signal_SA_RESTART(SIGTSTP, handler_ctrl_z);
2048 signal(SIGINT, handler_ctrl_c);
2049 }
2050#endif
2051
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002052 for (; pi; pi = flag_restore ? rpipe : pi->next) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002053 rword = pi->res_word;
Denis Vlasenko06810332007-05-21 23:30:54 +00002054#if ENABLE_HUSH_LOOPS
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002055 if (rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002056 flag_restore = 0;
2057 if (!rpipe) {
2058 flag_rep = 0;
2059 rpipe = pi;
2060 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002061 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002062#endif
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002063 debug_printf_exec(": rword=%d if_code=%d next_if_code=%d skip_more=%d\n",
2064 rword, if_code, next_if_code, skip_more_for_this_rword);
2065 if (rword == skip_more_for_this_rword && flag_skip) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002066 if (pi->followup == PIPE_SEQ)
2067 flag_skip = 0;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002068 continue;
2069 }
2070 flag_skip = 1;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002071 skip_more_for_this_rword = RES_XXXX;
Denis Vlasenko06810332007-05-21 23:30:54 +00002072#if ENABLE_HUSH_IF
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002073 if (rword == RES_THEN || rword == RES_ELSE)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002074 if_code = next_if_code;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002075 if (rword == RES_THEN && if_code)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002076 continue;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002077 if (rword == RES_ELSE && !if_code)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002078 continue;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002079 if (rword == RES_ELIF && !if_code)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002080 break;
Denis Vlasenko06810332007-05-21 23:30:54 +00002081#endif
2082#if ENABLE_HUSH_LOOPS
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002083 if (rword == RES_FOR && pi->num_progs) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002084 if (!for_lcur) {
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002085 /* if no variable values after "in" we skip "for" */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002086 if (!pi->next->progs->argv)
2087 continue;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002088 /* create list of variable values */
Denis Vlasenko170435c2007-05-23 13:01:10 +00002089 for_list = expand_strvec_to_strvec(pi->next->progs->argv);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002090 for_lcur = for_list;
2091 for_varname = pi->progs->argv[0];
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002092 pi->progs->argv[0] = NULL;
2093 flag_rep = 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002094 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002095 free(pi->progs->argv[0]);
2096 if (!*for_lcur) {
2097 free(for_list);
2098 for_lcur = NULL;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002099 flag_rep = 0;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002100 pi->progs->argv[0] = for_varname;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002101 pi->progs->glob_result.gl_pathv[0] = pi->progs->argv[0];
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002102 continue;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002103 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002104 /* insert next value from for_lcur */
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002105 /* vda: does it need escaping? */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002106 pi->progs->argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002107 pi->progs->glob_result.gl_pathv[0] = pi->progs->argv[0];
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002108 }
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002109 if (rword == RES_IN)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002110 continue;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002111 if (rword == RES_DO) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002112 if (!flag_rep)
2113 continue;
Tim Rikerc1ef7bd2006-01-25 00:08:53 +00002114 }
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002115 if (rword == RES_DONE) {
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002116 if (flag_rep) {
2117 flag_restore = 1;
2118 } else {
2119 rpipe = NULL;
2120 }
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002121 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002122#endif
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002123 if (pi->num_progs == 0)
2124 continue;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002125 save_num_progs = pi->num_progs; /* save number of programs */
Denis Vlasenkod01ff132007-05-02 21:40:23 +00002126 debug_printf_exec(": run_pipe_real with %d members\n", pi->num_progs);
Eric Andersen25f27032001-04-26 23:22:31 +00002127 rcode = run_pipe_real(pi);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002128 if (rcode != -1) {
Eric Andersen25f27032001-04-26 23:22:31 +00002129 /* We only ran a builtin: rcode was set by the return value
2130 * of run_pipe_real(), and we don't need to wait for anything. */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002131 } else if (pi->followup == PIPE_BG) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002132 /* What does bash do with attempts to background builtins? */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002133 /* Even bash 3.2 doesn't do that well with nested bg:
2134 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
Denis Vlasenko170435c2007-05-23 13:01:10 +00002135 * I'm NOT treating inner &'s as jobs */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002136#if ENABLE_HUSH_JOB
Denis Vlasenko170435c2007-05-23 13:01:10 +00002137 if (run_list_level == 1)
2138 insert_bg_job(pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002139#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002140 rcode = EXIT_SUCCESS;
2141 } else {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002142#if ENABLE_HUSH_JOB
Denis Vlasenko170435c2007-05-23 13:01:10 +00002143 /* Paranoia, just "interactive_fd" should be enough? */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00002144 if (run_list_level == 1 && interactive_fd) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00002145 /* waits for completion, then fg's main shell */
Denis Vlasenko52881e92007-04-21 13:42:52 +00002146 rcode = checkjobs_and_fg_shell(pi);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002147 } else
2148#endif
2149 {
Denis Vlasenko170435c2007-05-23 13:01:10 +00002150 /* this one just waits for completion */
Eric Andersenc798b072001-06-22 06:23:03 +00002151 rcode = checkjobs(pi);
Eric Andersen25f27032001-04-26 23:22:31 +00002152 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002153 debug_printf_exec(": checkjobs returned %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00002154 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002155 debug_printf_exec(": setting last_return_code=%d\n", rcode);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002156 last_return_code = rcode;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002157 pi->num_progs = save_num_progs; /* restore number of programs */
Denis Vlasenko06810332007-05-21 23:30:54 +00002158#if ENABLE_HUSH_IF
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002159 if (rword == RES_IF || rword == RES_ELIF)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002160 next_if_code = rcode; /* can be overwritten a number of times */
Denis Vlasenko06810332007-05-21 23:30:54 +00002161#endif
2162#if ENABLE_HUSH_LOOPS
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002163 if (rword == RES_WHILE)
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002164 flag_rep = !last_return_code;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002165 if (rword == RES_UNTIL)
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002166 flag_rep = last_return_code;
Denis Vlasenko06810332007-05-21 23:30:54 +00002167#endif
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002168 if ((rcode == EXIT_SUCCESS && pi->followup == PIPE_OR)
2169 || (rcode != EXIT_SUCCESS && pi->followup == PIPE_AND)
2170 ) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002171 skip_more_for_this_rword = rword;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002172 }
Eric Andersen028b65b2001-06-28 01:10:11 +00002173 checkjobs(NULL);
Eric Andersen25f27032001-04-26 23:22:31 +00002174 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002175
2176#if ENABLE_HUSH_JOB
2177 if (ctrl_z_flag) {
2178 /* ctrl-Z forked somewhere in the past, we are the child,
2179 * and now we completed running the list. Exit. */
2180 exit(rcode);
2181 }
2182 ret:
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00002183 run_list_level--;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002184#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00002185 debug_printf_exec("run_list_real lvl %d return %d\n", run_list_level + 1, rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00002186 return rcode;
2187}
2188
Eric Andersen25f27032001-04-26 23:22:31 +00002189/* return code is the exit status of the pipe */
Eric Andersenbf7df042001-05-23 22:18:35 +00002190static int free_pipe(struct pipe *pi, int indent)
Eric Andersen25f27032001-04-26 23:22:31 +00002191{
2192 char **p;
2193 struct child_prog *child;
2194 struct redir_struct *r, *rnext;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002195 int a, i, ret_code = 0;
Eric Andersen52a97ca2001-06-22 06:49:26 +00002196
2197 if (pi->stopped_progs > 0)
2198 return ret_code;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002199 debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002200 for (i = 0; i < pi->num_progs; i++) {
Eric Andersen25f27032001-04-26 23:22:31 +00002201 child = &pi->progs[i];
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002202 debug_printf_clean("%s command %d:\n", indenter(indent), i);
Eric Andersen25f27032001-04-26 23:22:31 +00002203 if (child->argv) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002204 for (a = 0, p = child->argv; *p; a++, p++) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002205 debug_printf_clean("%s argv[%d] = %s\n", indenter(indent), a, *p);
Eric Andersen25f27032001-04-26 23:22:31 +00002206 }
2207 globfree(&child->glob_result);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002208 child->argv = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002209 } else if (child->group) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002210 debug_printf_clean("%s begin group (subshell:%d)\n", indenter(indent), child->subshell);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002211 ret_code = free_pipe_list(child->group, indent+3);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002212 debug_printf_clean("%s end group\n", indenter(indent));
Eric Andersen25f27032001-04-26 23:22:31 +00002213 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002214 debug_printf_clean("%s (nil)\n", indenter(indent));
Eric Andersen25f27032001-04-26 23:22:31 +00002215 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002216 for (r = child->redirects; r; r = rnext) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002217 debug_printf_clean("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->type].descrip);
Eric Andersen25f27032001-04-26 23:22:31 +00002218 if (r->dup == -1) {
Eric Andersen817e73c2001-06-06 17:56:09 +00002219 /* guard against the case >$FOO, where foo is unset or blank */
2220 if (r->word.gl_pathv) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002221 debug_printf_clean(" %s\n", *r->word.gl_pathv);
Eric Andersen817e73c2001-06-06 17:56:09 +00002222 globfree(&r->word);
2223 }
Eric Andersen25f27032001-04-26 23:22:31 +00002224 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002225 debug_printf_clean("&%d\n", r->dup);
Eric Andersen25f27032001-04-26 23:22:31 +00002226 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002227 rnext = r->next;
Eric Andersen25f27032001-04-26 23:22:31 +00002228 free(r);
2229 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002230 child->redirects = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002231 }
2232 free(pi->progs); /* children are an array, they get freed all at once */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002233 pi->progs = NULL;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002234#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002235 free(pi->cmdtext);
2236 pi->cmdtext = NULL;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002237#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002238 return ret_code;
2239}
2240
Eric Andersenbf7df042001-05-23 22:18:35 +00002241static int free_pipe_list(struct pipe *head, int indent)
Eric Andersen25f27032001-04-26 23:22:31 +00002242{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002243 int rcode = 0; /* if list has no members */
Eric Andersen25f27032001-04-26 23:22:31 +00002244 struct pipe *pi, *next;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002245
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002246 for (pi = head; pi; pi = next) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002247 debug_printf_clean("%s pipe reserved mode %d\n", indenter(indent), pi->res_word);
Eric Andersenbf7df042001-05-23 22:18:35 +00002248 rcode = free_pipe(pi, indent);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002249 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002250 next = pi->next;
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002251 /*pi->next = NULL;*/
Eric Andersen25f27032001-04-26 23:22:31 +00002252 free(pi);
2253 }
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002254 return rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00002255}
2256
2257/* Select which version we will use */
2258static int run_list(struct pipe *pi)
2259{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002260 int rcode = 0;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002261 debug_printf_exec("run_list entered\n");
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002262 if (fake_mode == 0) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002263 debug_printf_exec(": run_list_real with %d members\n", pi->num_progs);
Eric Andersen25f27032001-04-26 23:22:31 +00002264 rcode = run_list_real(pi);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002265 }
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002266 /* free_pipe_list has the side effect of clearing memory.
Eric Andersen25f27032001-04-26 23:22:31 +00002267 * In the long run that function can be merged with run_list_real,
2268 * but doing that now would hobble the debugging effort. */
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002269 free_pipe_list(pi, 0);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002270 debug_printf_exec("run_list return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00002271 return rcode;
2272}
2273
2274/* The API for glob is arguably broken. This routine pushes a non-matching
2275 * string into the output structure, removing non-backslashed backslashes.
2276 * If someone can prove me wrong, by performing this function within the
2277 * original glob(3) api, feel free to rewrite this routine into oblivion.
2278 * Return code (0 vs. GLOB_NOSPACE) matches glob(3).
2279 * XXX broken if the last character is '\\', check that before calling.
2280 */
2281static int globhack(const char *src, int flags, glob_t *pglob)
2282{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002283 int cnt = 0, pathc;
Eric Andersen25f27032001-04-26 23:22:31 +00002284 const char *s;
2285 char *dest;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002286 for (cnt = 1, s = src; s && *s; s++) {
Eric Andersen25f27032001-04-26 23:22:31 +00002287 if (*s == '\\') s++;
2288 cnt++;
2289 }
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002290 dest = xmalloc(cnt);
Eric Andersen25f27032001-04-26 23:22:31 +00002291 if (!(flags & GLOB_APPEND)) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002292 pglob->gl_pathv = NULL;
2293 pglob->gl_pathc = 0;
2294 pglob->gl_offs = 0;
2295 pglob->gl_offs = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00002296 }
2297 pathc = ++pglob->gl_pathc;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002298 pglob->gl_pathv = xrealloc(pglob->gl_pathv, (pathc+1) * sizeof(*pglob->gl_pathv));
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002299 pglob->gl_pathv[pathc-1] = dest;
2300 pglob->gl_pathv[pathc] = NULL;
2301 for (s = src; s && *s; s++, dest++) {
Eric Andersen25f27032001-04-26 23:22:31 +00002302 if (*s == '\\') s++;
2303 *dest = *s;
2304 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002305 *dest = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002306 return 0;
2307}
2308
2309/* XXX broken if the last character is '\\', check that before calling */
2310static int glob_needed(const char *s)
2311{
2312 for (; *s; s++) {
2313 if (*s == '\\') s++;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002314 if (strchr("*[?", *s)) return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002315 }
2316 return 0;
2317}
2318
Eric Andersen25f27032001-04-26 23:22:31 +00002319static int xglob(o_string *dest, int flags, glob_t *pglob)
2320{
2321 int gr;
2322
Tim Rikerc1ef7bd2006-01-25 00:08:53 +00002323 /* short-circuit for null word */
Eric Andersen25f27032001-04-26 23:22:31 +00002324 /* we can code this better when the debug_printf's are gone */
Tim Rikerc1ef7bd2006-01-25 00:08:53 +00002325 if (dest->length == 0) {
2326 if (dest->nonnull) {
2327 /* bash man page calls this an "explicit" null */
2328 gr = globhack(dest->data, flags, pglob);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002329 debug_printf("globhack returned %d\n", gr);
Tim Rikerc1ef7bd2006-01-25 00:08:53 +00002330 } else {
Eric Andersen25f27032001-04-26 23:22:31 +00002331 return 0;
2332 }
Tim Rikerc1ef7bd2006-01-25 00:08:53 +00002333 } else if (glob_needed(dest->data)) {
Eric Andersen25f27032001-04-26 23:22:31 +00002334 gr = glob(dest->data, flags, NULL, pglob);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002335 debug_printf("glob returned %d\n", gr);
Eric Andersen25f27032001-04-26 23:22:31 +00002336 if (gr == GLOB_NOMATCH) {
2337 /* quote removal, or more accurately, backslash removal */
2338 gr = globhack(dest->data, flags, pglob);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002339 debug_printf("globhack returned %d\n", gr);
Eric Andersen25f27032001-04-26 23:22:31 +00002340 }
2341 } else {
2342 gr = globhack(dest->data, flags, pglob);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002343 debug_printf("globhack returned %d\n", gr);
Eric Andersen25f27032001-04-26 23:22:31 +00002344 }
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002345 if (gr == GLOB_NOSPACE)
Manuel Novoa III cad53642003-03-19 09:13:01 +00002346 bb_error_msg_and_die("out of memory during glob");
Eric Andersen25f27032001-04-26 23:22:31 +00002347 if (gr != 0) { /* GLOB_ABORTED ? */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002348 bb_error_msg("glob(3) error %d", gr);
Eric Andersen25f27032001-04-26 23:22:31 +00002349 }
2350 /* globprint(glob_target); */
2351 return gr;
2352}
2353
Denis Vlasenko170435c2007-05-23 13:01:10 +00002354/* expand_strvec_to_strvec() takes a list of strings, expands
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002355 * all variable references within and returns a pointer to
2356 * a list of expanded strings, possibly with larger number
2357 * of strings. (Think VAR="a b"; echo $VAR).
2358 * This new list is allocated as a single malloc block.
2359 * NULL-terminated list of char* pointers is at the beginning of it,
2360 * followed by strings themself.
2361 * Caller can deallocate entire list by single free(list). */
2362
2363/* Helpers first:
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00002364 * count_XXX estimates size of the block we need. It's okay
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002365 * to over-estimate sizes a bit, if it makes code simpler */
2366static int count_ifs(const char *str)
2367{
2368 int cnt = 0;
2369 debug_printf_expand("count_ifs('%s') ifs='%s'", str, ifs);
2370 while (1) {
2371 str += strcspn(str, ifs);
2372 if (!*str) break;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002373 str++; /* str += strspn(str, ifs); */
2374 cnt++; /* cnt += strspn(str, ifs); - but this code is larger */
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002375 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002376 debug_printf_expand(" return %d\n", cnt);
2377 return cnt;
2378}
2379
2380static void count_var_expansion_space(int *countp, int *lenp, char *arg)
2381{
2382 char first_ch;
2383 int i;
2384 int len = *lenp;
2385 int count = *countp;
2386 const char *val;
2387 char *p;
2388
2389 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL))) {
2390 len += p - arg;
2391 arg = ++p;
2392 p = strchr(p, SPECIAL_VAR_SYMBOL);
2393 first_ch = arg[0];
2394
2395 switch (first_ch & 0x7f) {
2396 /* high bit in 1st_ch indicates that var is double-quoted */
2397 case '$': /* pid */
2398 case '!': /* bg pid */
2399 case '?': /* exitcode */
2400 case '#': /* argc */
2401 len += sizeof(int)*3 + 1; /* enough for int */
2402 break;
2403 case '*':
2404 case '@':
2405 for (i = 1; i < global_argc; i++) {
2406 len += strlen(global_argv[i]) + 1;
2407 count++;
2408 if (!(first_ch & 0x80))
2409 count += count_ifs(global_argv[i]);
2410 }
2411 break;
2412 default:
2413 *p = '\0';
2414 arg[0] = first_ch & 0x7f;
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002415 if (isdigit(arg[0])) {
2416 i = xatoi_u(arg);
2417 val = NULL;
2418 if (i < global_argc)
2419 val = global_argv[i];
2420 } else
2421 val = lookup_param(arg);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002422 arg[0] = first_ch;
2423 *p = SPECIAL_VAR_SYMBOL;
2424
2425 if (val) {
2426 len += strlen(val) + 1;
2427 if (!(first_ch & 0x80))
2428 count += count_ifs(val);
2429 }
2430 }
2431 arg = ++p;
2432 }
2433
2434 len += strlen(arg) + 1;
2435 count++;
2436 *lenp = len;
2437 *countp = count;
2438}
2439
2440/* Store given string, finalizing the word and starting new one whenever
2441 * we encounter ifs char(s). This is used for expanding variable values.
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002442 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002443static int expand_on_ifs(char **list, int n, char **posp, const char *str)
2444{
2445 char *pos = *posp;
2446 while (1) {
2447 int word_len = strcspn(str, ifs);
2448 if (word_len) {
2449 memcpy(pos, str, word_len); /* store non-ifs chars */
2450 pos += word_len;
2451 str += word_len;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002452 }
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002453 if (!*str) /* EOL - do not finalize word */
2454 break;
2455 *pos++ = '\0';
2456 if (n) debug_printf_expand("expand_on_ifs finalized list[%d]=%p '%s' "
2457 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2458 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2459 list[n++] = pos;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002460 str += strspn(str, ifs); /* skip ifs chars */
2461 }
2462 *posp = pos;
2463 return n;
2464}
2465
2466/* Expand all variable references in given string, adding words to list[]
2467 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2468 * to be filled). This routine is extremely tricky: has to deal with
2469 * variables/parameters with whitespace, $* and $@, and constructs like
2470 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002471/* NB: another bug is that we cannot detect empty strings yet:
2472 * "" or $empty"" expands to zero words, has to expand to empty word */
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002473static int expand_vars_to_list(char **list, int n, char **posp, char *arg, char or_mask)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002474{
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002475 /* or_mask is either 0 (normal case) or 0x80
2476 * (expansion of right-hand side of assignment == 1-element expand) */
2477
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002478 char first_ch, ored_ch;
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002479 int i;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002480 const char *val;
2481 char *p;
2482 char *pos = *posp;
2483
2484 ored_ch = 0;
2485
2486 if (n) debug_printf_expand("expand_vars_to_list finalized list[%d]=%p '%s' "
2487 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2488 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2489 list[n++] = pos;
2490
2491 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL))) {
2492 memcpy(pos, arg, p - arg);
2493 pos += (p - arg);
2494 arg = ++p;
2495 p = strchr(p, SPECIAL_VAR_SYMBOL);
2496
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002497 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002498 ored_ch |= first_ch;
2499 val = NULL;
2500 switch (first_ch & 0x7f) {
2501 /* Highest bit in first_ch indicates that var is double-quoted */
2502 case '$': /* pid */
2503 /* FIXME: (echo $$) should still print pid of main shell */
2504 val = utoa(getpid());
2505 break;
2506 case '!': /* bg pid */
2507 val = last_bg_pid ? utoa(last_bg_pid) : (char*)"";
2508 break;
2509 case '?': /* exitcode */
2510 val = utoa(last_return_code);
2511 break;
2512 case '#': /* argc */
2513 val = utoa(global_argc ? global_argc-1 : 0);
2514 break;
2515 case '*':
2516 case '@':
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002517 i = 1;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002518 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002519 while (i < global_argc) {
2520 n = expand_on_ifs(list, n, &pos, global_argv[i]);
2521 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, global_argc-1);
2522 if (global_argv[i++][0] && i < global_argc) {
2523 /* this argv[] is not empty and not last:
2524 * put terminating NUL, start new word */
2525 *pos++ = '\0';
2526 if (n) debug_printf_expand("expand_vars_to_list 2 finalized list[%d]=%p '%s' "
2527 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2528 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2529 list[n++] = pos;
2530 }
2531 }
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002532 } else
2533 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2534 * and in this case should theat it like '$*' */
2535 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002536 while (1) {
2537 strcpy(pos, global_argv[i]);
2538 pos += strlen(global_argv[i]);
2539 if (++i >= global_argc)
2540 break;
2541 *pos++ = '\0';
2542 if (n) debug_printf_expand("expand_vars_to_list 3 finalized list[%d]=%p '%s' "
2543 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2544 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2545 list[n++] = pos;
2546 }
2547 } else { /* quoted $*: add as one word */
2548 while (1) {
2549 strcpy(pos, global_argv[i]);
2550 pos += strlen(global_argv[i]);
2551 if (++i >= global_argc)
2552 break;
2553 if (ifs[0])
2554 *pos++ = ifs[0];
2555 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002556 }
2557 break;
2558 default:
2559 *p = '\0';
2560 arg[0] = first_ch & 0x7f;
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002561 if (isdigit(arg[0])) {
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002562 i = xatoi_u(arg);
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002563 val = NULL;
2564 if (i < global_argc)
2565 val = global_argv[i];
2566 } else
2567 val = lookup_param(arg);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002568 arg[0] = first_ch;
2569 *p = SPECIAL_VAR_SYMBOL;
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002570 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002571 if (val) {
2572 n = expand_on_ifs(list, n, &pos, val);
2573 val = NULL;
2574 }
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002575 } /* else: quoted $VAR, val will be appended at pos */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002576 }
2577 if (val) {
2578 strcpy(pos, val);
2579 pos += strlen(val);
2580 }
2581 arg = ++p;
2582 }
2583 debug_printf_expand("expand_vars_to_list adding tail '%s' at %p\n", arg, pos);
2584 strcpy(pos, arg);
2585 pos += strlen(arg) + 1;
2586 if (pos == list[n-1] + 1) { /* expansion is empty */
2587 if (!(ored_ch & 0x80)) { /* all vars were not quoted... */
2588 debug_printf_expand("expand_vars_to_list list[%d] empty, going back\n", n);
2589 pos--;
2590 n--;
2591 }
2592 }
2593
2594 *posp = pos;
2595 return n;
2596}
2597
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002598static char **expand_variables(char **argv, char or_mask)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002599{
2600 int n;
2601 int count = 1;
2602 int len = 0;
2603 char *pos, **v, **list;
2604
2605 v = argv;
2606 if (!*v) debug_printf_expand("count_var_expansion_space: "
2607 "argv[0]=NULL count=%d len=%d alloc_space=%d\n",
2608 count, len, sizeof(char*) * count + len);
2609 while (*v) {
2610 count_var_expansion_space(&count, &len, *v);
2611 debug_printf_expand("count_var_expansion_space: "
2612 "'%s' count=%d len=%d alloc_space=%d\n",
2613 *v, count, len, sizeof(char*) * count + len);
2614 v++;
2615 }
2616 len += sizeof(char*) * count; /* total to alloc */
2617 list = xmalloc(len);
2618 pos = (char*)(list + count);
2619 debug_printf_expand("list=%p, list[0] should be %p\n", list, pos);
2620 n = 0;
2621 v = argv;
2622 while (*v)
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002623 n = expand_vars_to_list(list, n, &pos, *v++, or_mask);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002624
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002625 if (n) debug_printf_expand("finalized list[%d]=%p '%s' "
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002626 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2627 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002628 list[n] = NULL;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002629
2630#ifdef DEBUG_EXPAND
2631 {
2632 int m = 0;
2633 while (m <= n) {
2634 debug_printf_expand("list[%d]=%p '%s'\n", m, list[m], list[m]);
2635 m++;
2636 }
2637 debug_printf_expand("used_space=%d\n", pos - (char*)list);
2638 }
2639#endif
Denis Vlasenko170435c2007-05-23 13:01:10 +00002640 if (ENABLE_HUSH_DEBUG)
2641 if (pos - (char*)list > len)
2642 bb_error_msg_and_die("BUG in varexp");
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002643 return list;
2644}
2645
Denis Vlasenko170435c2007-05-23 13:01:10 +00002646static char **expand_strvec_to_strvec(char **argv)
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002647{
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002648 return expand_variables(argv, 0);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002649}
2650
Denis Vlasenko170435c2007-05-23 13:01:10 +00002651static char *expand_string_to_string(const char *str)
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002652{
2653 char *argv[2], **list;
2654
2655 argv[0] = (char*)str;
2656 argv[1] = NULL;
2657 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
Denis Vlasenko170435c2007-05-23 13:01:10 +00002658 if (ENABLE_HUSH_DEBUG)
2659 if (!list[0] || list[1])
2660 bb_error_msg_and_die("BUG in varexp2");
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002661 /* actually, just move string 2*sizeof(char*) bytes back */
2662 strcpy((char*)list, list[0]);
Denis Vlasenko170435c2007-05-23 13:01:10 +00002663 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2664 return (char*)list;
2665}
2666
2667static char* expand_strvec_to_string(char **argv)
2668{
2669 char **list;
2670
2671 list = expand_variables(argv, 0x80);
2672 /* Convert all NULs to spaces */
2673 if (list[0]) {
2674 int n = 1;
2675 while (list[n]) {
2676 if (ENABLE_HUSH_DEBUG)
2677 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2678 bb_error_msg_and_die("BUG in varexp3");
2679 list[n][-1] = ' '; /* TODO: or to ifs[0]? */
2680 n++;
2681 }
2682 }
2683 strcpy((char*)list, list[0]);
2684 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002685 return (char*)list;
2686}
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002687
Eric Andersenf72f5622001-05-15 23:21:41 +00002688/* This is used to get/check local shell variables */
Denis Vlasenko15d78fb2007-01-30 22:28:21 +00002689static const char *get_local_var(const char *s)
Eric Andersenf72f5622001-05-15 23:21:41 +00002690{
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002691 struct variables *cur;
Eric Andersenf72f5622001-05-15 23:21:41 +00002692
2693 if (!s)
2694 return NULL;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00002695 for (cur = top_vars; cur; cur = cur->next) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002696 if (strcmp(cur->name, s) == 0)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002697 return cur->value;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00002698 }
Eric Andersenf72f5622001-05-15 23:21:41 +00002699 return NULL;
2700}
2701
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002702/* This is used to set local shell variables
Denis Vlasenkobb81c582007-01-30 22:32:09 +00002703 flg_export == 0 if only local (not exporting) variable
2704 flg_export == 1 if "new" exporting environ
2705 flg_export > 1 if current startup environ (not call putenv()) */
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002706static int set_local_var(const char *s, int flg_export)
Eric Andersen78a7c992001-05-15 16:30:25 +00002707{
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002708 char *name, *value;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002709 int result = 0;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002710 struct variables *cur;
Eric Andersen20a69a72001-05-15 17:24:44 +00002711
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00002712 name = xstrdup(s);
Eric Andersen20a69a72001-05-15 17:24:44 +00002713
2714 /* Assume when we enter this function that we are already in
2715 * NAME=VALUE format. So the first order of business is to
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002716 * split 's' on the '=' into 'name' and 'value' */
Eric Andersen20a69a72001-05-15 17:24:44 +00002717 value = strchr(name, '=');
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00002718 /*if (value == 0 && ++value == 0) ??? -vda */
2719 if (value == NULL || value[1] == '\0') {
Eric Andersen99785762001-05-22 21:37:48 +00002720 free(name);
2721 return -1;
2722 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00002723 *value++ = '\0';
Eric Andersen20a69a72001-05-15 17:24:44 +00002724
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002725 for (cur = top_vars; cur; cur = cur->next) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00002726 if (strcmp(cur->name, name) == 0) {
2727 if (strcmp(cur->value, value) == 0) {
Denis Vlasenko3e7b0e62007-05-16 12:52:15 +00002728 if (flg_export && !cur->flg_export)
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00002729 cur->flg_export = flg_export;
2730 else
2731 result++;
2732 } else if (cur->flg_read_only) {
2733 bb_error_msg("%s: readonly variable", name);
Eric Andersen99785762001-05-22 21:37:48 +00002734 result = -1;
2735 } else {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00002736 if (flg_export > 0 || cur->flg_export > 1)
2737 cur->flg_export = 1;
2738 free((char*)cur->value);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002739 cur->value = xstrdup(value);
Eric Andersen20a69a72001-05-15 17:24:44 +00002740 }
Denis Vlasenko3e7b0e62007-05-16 12:52:15 +00002741 goto skip;
Eric Andersen20a69a72001-05-15 17:24:44 +00002742 }
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002743 }
Eric Andersen20a69a72001-05-15 17:24:44 +00002744
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002745 cur = xzalloc(sizeof(*cur));
Denis Vlasenko170435c2007-05-23 13:01:10 +00002746 /*cur->next = 0;*/
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002747 cur->name = xstrdup(name);
2748 cur->value = xstrdup(value);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002749 cur->flg_export = flg_export;
2750 /*cur->flg_read_only = 0;*/
2751 {
2752 struct variables *bottom = top_vars;
2753 while (bottom->next)
2754 bottom = bottom->next;
2755 bottom->next = cur;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00002756 }
2757 skip:
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002758 if (result == 0 && cur->flg_export == 1) {
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002759 *(value-1) = '=';
2760 result = putenv(name);
2761 } else {
Eric Andersen94ac2442001-05-22 19:05:18 +00002762 free(name);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002763 if (result > 0) /* equivalent to previous set */
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002764 result = 0;
2765 }
Eric Andersen20a69a72001-05-15 17:24:44 +00002766 return result;
2767}
2768
Eric Andersenf72f5622001-05-15 23:21:41 +00002769static void unset_local_var(const char *name)
Eric Andersen20a69a72001-05-15 17:24:44 +00002770{
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002771 struct variables *cur, *next;
Eric Andersen20a69a72001-05-15 17:24:44 +00002772
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002773 if (!name)
2774 return;
2775 for (cur = top_vars; cur; cur = cur->next) {
2776 if (strcmp(cur->name, name) == 0) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002777 if (cur->flg_read_only) {
Manuel Novoa III cad53642003-03-19 09:13:01 +00002778 bb_error_msg("%s: readonly variable", name);
Eric Andersen94ac2442001-05-22 19:05:18 +00002779 return;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002780 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002781 if (cur->flg_export)
2782 unsetenv(cur->name);
2783 free((char*)cur->name);
2784 free((char*)cur->value);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002785 next = top_vars;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002786 while (next->next != cur)
2787 next = next->next;
2788 next->next = cur->next;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002789 free(cur);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002790 return;
Eric Andersenf72f5622001-05-15 23:21:41 +00002791 }
Eric Andersen20a69a72001-05-15 17:24:44 +00002792 }
Eric Andersen78a7c992001-05-15 16:30:25 +00002793}
2794
2795static int is_assignment(const char *s)
2796{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002797 if (!s || !isalpha(*s))
2798 return 0;
2799 s++;
2800 while (isalnum(*s) || *s == '_')
2801 s++;
2802 return *s == '=';
Eric Andersen78a7c992001-05-15 16:30:25 +00002803}
2804
Eric Andersen25f27032001-04-26 23:22:31 +00002805/* the src parameter allows us to peek forward to a possible &n syntax
2806 * for file descriptor duplication, e.g., "2>&1".
2807 * Return code is 0 normally, 1 if a syntax error is detected in src.
2808 * Resource errors (in xmalloc) cause the process to exit */
2809static int setup_redirect(struct p_context *ctx, int fd, redir_type style,
2810 struct in_str *input)
2811{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002812 struct child_prog *child = ctx->child;
Eric Andersen25f27032001-04-26 23:22:31 +00002813 struct redir_struct *redir = child->redirects;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002814 struct redir_struct *last_redir = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002815
2816 /* Create a new redir_struct and drop it onto the end of the linked list */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002817 while (redir) {
2818 last_redir = redir;
2819 redir = redir->next;
Eric Andersen25f27032001-04-26 23:22:31 +00002820 }
2821 redir = xmalloc(sizeof(struct redir_struct));
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002822 redir->next = NULL;
2823 redir->word.gl_pathv = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002824 if (last_redir) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002825 last_redir->next = redir;
Eric Andersen25f27032001-04-26 23:22:31 +00002826 } else {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002827 child->redirects = redir;
Eric Andersen25f27032001-04-26 23:22:31 +00002828 }
2829
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002830 redir->type = style;
2831 redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
Eric Andersen25f27032001-04-26 23:22:31 +00002832
2833 debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
2834
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002835 /* Check for a '2>&1' type redirect */
Eric Andersen25f27032001-04-26 23:22:31 +00002836 redir->dup = redirect_dup_num(input);
2837 if (redir->dup == -2) return 1; /* syntax error */
2838 if (redir->dup != -1) {
2839 /* Erik had a check here that the file descriptor in question
Eric Andersen83a2ae22001-05-07 17:59:25 +00002840 * is legit; I postpone that to "run time"
2841 * A "-" representation of "close me" shows up as a -3 here */
Eric Andersen25f27032001-04-26 23:22:31 +00002842 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
2843 } else {
2844 /* We do _not_ try to open the file that src points to,
2845 * since we need to return and let src be expanded first.
2846 * Set ctx->pending_redirect, so we know what to do at the
2847 * end of the next parsed word.
2848 */
2849 ctx->pending_redirect = redir;
2850 }
2851 return 0;
2852}
2853
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00002854static struct pipe *new_pipe(void)
2855{
Eric Andersen25f27032001-04-26 23:22:31 +00002856 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002857 pi = xzalloc(sizeof(struct pipe));
2858 /*pi->num_progs = 0;*/
2859 /*pi->progs = NULL;*/
2860 /*pi->next = NULL;*/
2861 /*pi->followup = 0; invalid */
2862 if (RES_NONE)
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002863 pi->res_word = RES_NONE;
Eric Andersen25f27032001-04-26 23:22:31 +00002864 return pi;
2865}
2866
2867static void initialize_context(struct p_context *ctx)
2868{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002869 ctx->child = NULL;
Denis Vlasenko1a735862007-05-23 00:32:25 +00002870 ctx->pipe = ctx->list_head = new_pipe();
2871 ctx->pending_redirect = NULL;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002872 ctx->res_w = RES_NONE;
Denis Vlasenko1a735862007-05-23 00:32:25 +00002873 //only ctx->parse_type is not touched... is this intentional?
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002874 ctx->old_flag = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00002875 ctx->stack = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002876 done_command(ctx); /* creates the memory for working child */
2877}
2878
2879/* normal return is 0
2880 * if a reserved word is found, and processed, return 1
2881 * should handle if, then, elif, else, fi, for, while, until, do, done.
2882 * case, function, and select are obnoxious, save those for later.
2883 */
Denis Vlasenko06810332007-05-21 23:30:54 +00002884#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS
"Vladimir N. Oleynik"19c37012005-09-22 14:33:15 +00002885static int reserved_word(o_string *dest, struct p_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00002886{
2887 struct reserved_combo {
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002888 char literal[7];
2889 unsigned char code;
2890 int flag;
Eric Andersen25f27032001-04-26 23:22:31 +00002891 };
2892 /* Mostly a list of accepted follow-up reserved words.
2893 * FLAG_END means we are done with the sequence, and are ready
2894 * to turn the compound list into a command.
2895 * FLAG_START means the word must start a new compound list.
2896 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002897 static const struct reserved_combo reserved_list[] = {
Denis Vlasenko06810332007-05-21 23:30:54 +00002898#if ENABLE_HUSH_IF
Eric Andersen25f27032001-04-26 23:22:31 +00002899 { "if", RES_IF, FLAG_THEN | FLAG_START },
2900 { "then", RES_THEN, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2901 { "elif", RES_ELIF, FLAG_THEN },
2902 { "else", RES_ELSE, FLAG_FI },
2903 { "fi", RES_FI, FLAG_END },
Denis Vlasenko06810332007-05-21 23:30:54 +00002904#endif
2905#if ENABLE_HUSH_LOOPS
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002906 { "for", RES_FOR, FLAG_IN | FLAG_START },
Eric Andersen25f27032001-04-26 23:22:31 +00002907 { "while", RES_WHILE, FLAG_DO | FLAG_START },
2908 { "until", RES_UNTIL, FLAG_DO | FLAG_START },
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002909 { "in", RES_IN, FLAG_DO },
Eric Andersen25f27032001-04-26 23:22:31 +00002910 { "do", RES_DO, FLAG_DONE },
2911 { "done", RES_DONE, FLAG_END }
Denis Vlasenko06810332007-05-21 23:30:54 +00002912#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002913 };
Denis Vlasenko7d4c44e2007-04-16 22:34:39 +00002914 enum { NRES = sizeof(reserved_list)/sizeof(reserved_list[0]) };
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002915 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002916
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002917 for (r = reserved_list; r < reserved_list + NRES; r++) {
Denis Vlasenko1a735862007-05-23 00:32:25 +00002918 if (strcmp(dest->data, r->literal) != 0)
2919 continue;
2920 debug_printf("found reserved word %s, code %d\n", r->literal, r->code);
2921 if (r->flag & FLAG_START) {
2922 struct p_context *new;
2923 debug_printf("push stack\n");
Denis Vlasenko06810332007-05-21 23:30:54 +00002924#if ENABLE_HUSH_LOOPS
Denis Vlasenko1a735862007-05-23 00:32:25 +00002925 if (ctx->res_w == RES_IN || ctx->res_w == RES_FOR) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00002926 syntax("malformed for"); /* example: 'for if' */
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002927 ctx->res_w = RES_SNTX;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002928 b_reset(dest);
Eric Andersenaf44a0e2001-04-27 07:26:12 +00002929 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002930 }
Denis Vlasenko1a735862007-05-23 00:32:25 +00002931#endif
2932 new = xmalloc(sizeof(*new));
2933 *new = *ctx; /* physical copy */
2934 initialize_context(ctx);
2935 ctx->stack = new;
2936 } else if (ctx->res_w == RES_NONE || !(ctx->old_flag & (1 << r->code))) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00002937 syntax(NULL);
Denis Vlasenko1a735862007-05-23 00:32:25 +00002938 ctx->res_w = RES_SNTX;
Denis Vlasenkoff131b92007-04-10 15:42:06 +00002939 b_reset(dest);
Eric Andersen25f27032001-04-26 23:22:31 +00002940 return 1;
2941 }
Denis Vlasenko1a735862007-05-23 00:32:25 +00002942 ctx->res_w = r->code;
2943 ctx->old_flag = r->flag;
2944 if (ctx->old_flag & FLAG_END) {
2945 struct p_context *old;
2946 debug_printf("pop stack\n");
2947 done_pipe(ctx, PIPE_SEQ);
2948 old = ctx->stack;
2949 old->child->group = ctx->list_head;
2950 old->child->subshell = 0;
2951 *ctx = *old; /* physical copy */
2952 free(old);
2953 }
2954 b_reset(dest);
2955 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002956 }
2957 return 0;
2958}
Denis Vlasenko06810332007-05-21 23:30:54 +00002959#else
2960#define reserved_word(dest, ctx) ((int)0)
2961#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002962
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002963/* Normal return is 0.
Eric Andersen25f27032001-04-26 23:22:31 +00002964 * Syntax or xglob errors return 1. */
2965static int done_word(o_string *dest, struct p_context *ctx)
2966{
Denis Vlasenkobb81c582007-01-30 22:32:09 +00002967 struct child_prog *child = ctx->child;
Eric Andersen25f27032001-04-26 23:22:31 +00002968 glob_t *glob_target;
2969 int gr, flags = 0;
2970
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002971 debug_printf_parse("done_word entered: '%s' %p\n", dest->data, child);
Eric Andersen25f27032001-04-26 23:22:31 +00002972 if (dest->length == 0 && !dest->nonnull) {
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002973 debug_printf_parse("done_word return 0: true null, ignored\n");
Eric Andersen25f27032001-04-26 23:22:31 +00002974 return 0;
2975 }
2976 if (ctx->pending_redirect) {
2977 glob_target = &ctx->pending_redirect->word;
2978 } else {
2979 if (child->group) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00002980 syntax(NULL);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002981 debug_printf_parse("done_word return 1: syntax error, groups and arglists don't mix\n");
2982 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002983 }
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002984 if (!child->argv && (ctx->parse_type & PARSEFLAG_SEMICOLON)) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002985 debug_printf_parse(": checking '%s' for reserved-ness\n", dest->data);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002986 if (reserved_word(dest, ctx)) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002987 debug_printf_parse("done_word return %d\n", (ctx->res_w == RES_SNTX));
2988 return (ctx->res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002989 }
Eric Andersen25f27032001-04-26 23:22:31 +00002990 }
2991 glob_target = &child->glob_result;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002992 if (child->argv)
2993 flags |= GLOB_APPEND;
Eric Andersen25f27032001-04-26 23:22:31 +00002994 }
2995 gr = xglob(dest, flags, glob_target);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002996 if (gr != 0) {
2997 debug_printf_parse("done_word return 1: xglob returned %d\n", gr);
2998 return 1;
2999 }
Eric Andersen25f27032001-04-26 23:22:31 +00003000
3001 b_reset(dest);
3002 if (ctx->pending_redirect) {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003003 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003004 if (glob_target->gl_pathc != 1) {
Manuel Novoa III cad53642003-03-19 09:13:01 +00003005 bb_error_msg("ambiguous redirect");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003006 debug_printf_parse("done_word return 1: ambiguous redirect\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003007 return 1;
3008 }
3009 } else {
3010 child->argv = glob_target->gl_pathv;
3011 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003012#if ENABLE_HUSH_LOOPS
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003013 if (ctx->res_w == RES_FOR) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003014 done_word(dest, ctx);
3015 done_pipe(ctx, PIPE_SEQ);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003016 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003017#endif
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003018 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003019 return 0;
3020}
3021
3022/* The only possible error here is out of memory, in which case
3023 * xmalloc exits. */
3024static int done_command(struct p_context *ctx)
3025{
3026 /* The child is really already in the pipe structure, so
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003027 * advance the pipe counter and make a new, null child. */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003028 struct pipe *pi = ctx->pipe;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003029 struct child_prog *child = ctx->child;
Eric Andersen25f27032001-04-26 23:22:31 +00003030
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003031 if (child) {
3032 if (child->group == NULL
3033 && child->argv == NULL
3034 && child->redirects == NULL
3035 ) {
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003036 debug_printf_parse("done_command: skipping null cmd, num_progs=%d\n", pi->num_progs);
3037 return pi->num_progs;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003038 }
Eric Andersen25f27032001-04-26 23:22:31 +00003039 pi->num_progs++;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003040 debug_printf_parse("done_command: ++num_progs=%d\n", pi->num_progs);
Eric Andersen25f27032001-04-26 23:22:31 +00003041 } else {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003042 debug_printf_parse("done_command: initializing, num_progs=%d\n", pi->num_progs);
Eric Andersen25f27032001-04-26 23:22:31 +00003043 }
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003044
3045 /* Only real trickiness here is that the uncommitted
3046 * child structure is not counted in pi->num_progs. */
Eric Andersen25f27032001-04-26 23:22:31 +00003047 pi->progs = xrealloc(pi->progs, sizeof(*pi->progs) * (pi->num_progs+1));
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003048 child = &pi->progs[pi->num_progs];
Eric Andersen25f27032001-04-26 23:22:31 +00003049
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003050 memset(child, 0, sizeof(*child));
3051 /*child->redirects = NULL;*/
3052 /*child->argv = NULL;*/
3053 /*child->is_stopped = 0;*/
3054 /*child->group = NULL;*/
3055 /*child->glob_result.gl_pathv = NULL;*/
3056 child->family = pi;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003057 //sp: /*child->sp = 0;*/
Denis Vlasenko262d7652007-05-20 21:52:49 +00003058 //pt: child->parse_type = ctx->parse_type;
Eric Andersen25f27032001-04-26 23:22:31 +00003059
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003060 ctx->child = child;
Eric Andersen25f27032001-04-26 23:22:31 +00003061 /* but ctx->pipe and ctx->list_head remain unchanged */
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003062
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003063 return pi->num_progs; /* used only for 0/nonzero check */
Eric Andersen25f27032001-04-26 23:22:31 +00003064}
3065
3066static int done_pipe(struct p_context *ctx, pipe_style type)
3067{
3068 struct pipe *new_p;
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003069 int not_null;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003070
3071 debug_printf_parse("done_pipe entered, followup %d\n", type);
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003072 not_null = done_command(ctx); /* implicit closure of previous command */
Eric Andersen25f27032001-04-26 23:22:31 +00003073 ctx->pipe->followup = type;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00003074 ctx->pipe->res_word = ctx->res_w;
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003075 /* Without this check, even just <enter> on command line generates
3076 * tree of three NOPs (!). Which is harmless but annoying.
3077 * IOW: it is safe to do it unconditionally. */
3078 if (not_null) {
3079 new_p = new_pipe();
3080 ctx->pipe->next = new_p;
3081 ctx->pipe = new_p;
3082 ctx->child = NULL;
3083 done_command(ctx); /* set up new pipe to accept commands */
3084 }
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003085 debug_printf_parse("done_pipe return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003086 return 0;
3087}
3088
3089/* peek ahead in the in_str to find out if we have a "&n" construct,
3090 * as in "2>&1", that represents duplicating a file descriptor.
3091 * returns either -2 (syntax error), -1 (no &), or the number found.
3092 */
3093static int redirect_dup_num(struct in_str *input)
3094{
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003095 int ch, d = 0, ok = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003096 ch = b_peek(input);
3097 if (ch != '&') return -1;
3098
3099 b_getch(input); /* get the & */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003100 ch = b_peek(input);
Eric Andersen83a2ae22001-05-07 17:59:25 +00003101 if (ch == '-') {
3102 b_getch(input);
3103 return -3; /* "-" represents "close me" */
3104 }
3105 while (isdigit(ch)) {
Denis Vlasenko7d4c44e2007-04-16 22:34:39 +00003106 d = d*10 + (ch-'0');
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003107 ok = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003108 b_getch(input);
Eric Andersen83a2ae22001-05-07 17:59:25 +00003109 ch = b_peek(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003110 }
3111 if (ok) return d;
3112
Manuel Novoa III cad53642003-03-19 09:13:01 +00003113 bb_error_msg("ambiguous redirect");
Eric Andersen25f27032001-04-26 23:22:31 +00003114 return -2;
3115}
3116
3117/* If a redirect is immediately preceded by a number, that number is
3118 * supposed to tell which file descriptor to redirect. This routine
3119 * looks for such preceding numbers. In an ideal world this routine
3120 * needs to handle all the following classes of redirects...
3121 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3122 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3123 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3124 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3125 * A -1 output from this program means no valid number was found, so the
3126 * caller should use the appropriate default for this redirection.
3127 */
3128static int redirect_opt_num(o_string *o)
3129{
3130 int num;
3131
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003132 if (o->length == 0)
3133 return -1;
3134 for (num = 0; num < o->length; num++) {
3135 if (!isdigit(*(o->data + num))) {
Eric Andersen25f27032001-04-26 23:22:31 +00003136 return -1;
3137 }
3138 }
3139 /* reuse num (and save an int) */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003140 num = atoi(o->data);
Eric Andersen25f27032001-04-26 23:22:31 +00003141 b_reset(o);
3142 return num;
3143}
3144
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003145#if ENABLE_HUSH_TICK
"Vladimir N. Oleynik"19c37012005-09-22 14:33:15 +00003146static FILE *generate_stream_from_list(struct pipe *head)
Eric Andersen25f27032001-04-26 23:22:31 +00003147{
3148 FILE *pf;
Eric Andersen25f27032001-04-26 23:22:31 +00003149 int pid, channel[2];
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003150 if (pipe(channel) < 0) bb_perror_msg_and_die("pipe");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003151#if BB_MMU
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003152 pid = fork();
Eric Andersen72f9a422001-10-28 05:12:20 +00003153#else
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003154 pid = vfork();
Eric Andersen72f9a422001-10-28 05:12:20 +00003155#endif
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003156 if (pid < 0) {
Manuel Novoa III cad53642003-03-19 09:13:01 +00003157 bb_perror_msg_and_die("fork");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003158 } else if (pid == 0) {
Eric Andersen25f27032001-04-26 23:22:31 +00003159 close(channel[0]);
3160 if (channel[1] != 1) {
Denis Vlasenko7d4c44e2007-04-16 22:34:39 +00003161 dup2(channel[1], 1);
Eric Andersen25f27032001-04-26 23:22:31 +00003162 close(channel[1]);
3163 }
Eric Andersen94ac2442001-05-22 19:05:18 +00003164 _exit(run_list_real(head)); /* leaks memory */
Eric Andersen25f27032001-04-26 23:22:31 +00003165 }
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003166 debug_printf("forked child %d\n", pid);
Eric Andersen25f27032001-04-26 23:22:31 +00003167 close(channel[1]);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003168 pf = fdopen(channel[0], "r");
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003169 debug_printf("pipe on FILE *%p\n", pf);
Eric Andersen25f27032001-04-26 23:22:31 +00003170 return pf;
3171}
3172
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003173/* Return code is exit status of the process that is run. */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003174static int process_command_subs(o_string *dest, struct p_context *ctx,
3175 struct in_str *input, const char *subst_end)
Eric Andersen25f27032001-04-26 23:22:31 +00003176{
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003177 int retcode, ch, eol_cnt;
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003178 o_string result = NULL_O_STRING;
Eric Andersen25f27032001-04-26 23:22:31 +00003179 struct p_context inner;
3180 FILE *p;
3181 struct in_str pipe_str;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003182
Eric Andersen25f27032001-04-26 23:22:31 +00003183 initialize_context(&inner);
3184
3185 /* recursion to generate command */
3186 retcode = parse_stream(&result, &inner, input, subst_end);
Denis Vlasenko1a735862007-05-23 00:32:25 +00003187 if (retcode != 0)
3188 return retcode; /* syntax error or EOF */
Eric Andersen25f27032001-04-26 23:22:31 +00003189 done_word(&result, &inner);
3190 done_pipe(&inner, PIPE_SEQ);
3191 b_free(&result);
3192
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003193 p = generate_stream_from_list(inner.list_head);
3194 if (p == NULL) return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003195 mark_open(fileno(p));
3196 setup_file_in_str(&pipe_str, p);
3197
3198 /* now send results of command back into original context */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003199 eol_cnt = 0;
3200 while ((ch = b_getch(&pipe_str)) != EOF) {
3201 if (ch == '\n') {
3202 eol_cnt++;
3203 continue;
3204 }
3205 while (eol_cnt) {
3206 b_addqchr(dest, '\n', dest->quote);
3207 eol_cnt--;
3208 }
3209 b_addqchr(dest, ch, dest->quote);
Eric Andersen25f27032001-04-26 23:22:31 +00003210 }
3211
3212 debug_printf("done reading from pipe, pclose()ing\n");
3213 /* This is the step that wait()s for the child. Should be pretty
3214 * safe, since we just read an EOF from its stdout. We could try
Denis Vlasenko262d7652007-05-20 21:52:49 +00003215 * to do better, by using wait(), and keeping track of background jobs
Eric Andersen25f27032001-04-26 23:22:31 +00003216 * at the same time. That would be a lot of work, and contrary
3217 * to the KISS philosophy of this program. */
3218 mark_closed(fileno(p));
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003219 retcode = pclose(p);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003220 free_pipe_list(inner.list_head, 0);
3221 debug_printf("pclosed, retcode=%d\n", retcode);
Eric Andersen25f27032001-04-26 23:22:31 +00003222 return retcode;
3223}
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003224#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003225
3226static int parse_group(o_string *dest, struct p_context *ctx,
3227 struct in_str *input, int ch)
3228{
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003229 int rcode;
3230 const char *endch = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003231 struct p_context sub;
3232 struct child_prog *child = ctx->child;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003233
3234 debug_printf_parse("parse_group entered\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003235 if (child->argv) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003236 syntax(NULL);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003237 debug_printf_parse("parse_group return 1: syntax error, groups and arglists don't mix\n");
3238 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003239 }
3240 initialize_context(&sub);
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003241 endch = "}";
3242 if (ch == '(') {
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003243 endch = ")";
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003244 child->subshell = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003245 }
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003246 rcode = parse_stream(dest, &sub, input, endch);
3247 done_word(dest, &sub); /* finish off the final word in the subcontext */
Eric Andersen25f27032001-04-26 23:22:31 +00003248 done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */
3249 child->group = sub.list_head;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003250
3251 debug_printf_parse("parse_group return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00003252 return rcode;
3253 /* child remains "open", available for possible redirects */
3254}
3255
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003256/* Basically useful version until someone wants to get fancier,
Eric Andersen25f27032001-04-26 23:22:31 +00003257 * see the bash man page under "Parameter Expansion" */
Denis Vlasenko15d78fb2007-01-30 22:28:21 +00003258static const char *lookup_param(const char *src)
Eric Andersen25f27032001-04-26 23:22:31 +00003259{
Denis Vlasenko15d78fb2007-01-30 22:28:21 +00003260 const char *p = NULL;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003261 if (src) {
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003262 p = getenv(src);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003263 if (!p)
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003264 p = get_local_var(src);
Eric Andersen20a69a72001-05-15 17:24:44 +00003265 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003266 return p;
Eric Andersen25f27032001-04-26 23:22:31 +00003267}
3268
3269/* return code: 0 for OK, 1 for syntax error */
3270static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input)
3271{
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003272 int ch = b_peek(input); /* first character after the $ */
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003273 unsigned char quote_mask = dest->quote ? 0x80 : 0;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003274
3275 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003276 if (isalpha(ch)) {
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003277 b_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003278 //sp: ctx->child->sp++;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003279 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003280 debug_printf_parse(": '%c'\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003281 b_getch(input);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003282 b_addchr(dest, ch | quote_mask);
3283 quote_mask = 0;
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003284 ch = b_peek(input);
3285 if (!isalnum(ch) && ch != '_')
3286 break;
Eric Andersen25f27032001-04-26 23:22:31 +00003287 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003288 b_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003289 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003290 make_one_char_var:
3291 b_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003292 //sp: ctx->child->sp++;
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003293 debug_printf_parse(": '%c'\n", ch);
3294 b_getch(input);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003295 b_addchr(dest, ch | quote_mask);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003296 b_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003297 } else switch (ch) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003298 case '$': /* pid */
3299 case '!': /* last bg pid */
3300 case '?': /* last exit code */
3301 case '#': /* number of args */
3302 case '*': /* args */
3303 case '@': /* args */
3304 goto make_one_char_var;
Eric Andersen25f27032001-04-26 23:22:31 +00003305 case '{':
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003306 b_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003307 //sp: ctx->child->sp++;
Eric Andersen25f27032001-04-26 23:22:31 +00003308 b_getch(input);
3309 /* XXX maybe someone will try to escape the '}' */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003310 while (1) {
3311 ch = b_getch(input);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003312 if (ch == EOF) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003313 syntax("unterminated ${name}");
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003314 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
3315 return 1;
3316 }
3317 if (ch == '}')
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003318 break;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003319 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003320 b_addchr(dest, ch | quote_mask);
3321 quote_mask = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003322 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003323 b_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003324 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003325#if ENABLE_HUSH_TICK
Eric Andersen25f27032001-04-26 23:22:31 +00003326 case '(':
Matt Kraai9f8caf12001-05-02 16:26:12 +00003327 b_getch(input);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003328 process_command_subs(dest, ctx, input, ")");
Eric Andersen25f27032001-04-26 23:22:31 +00003329 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003330#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003331 case '-':
3332 case '_':
3333 /* still unhandled, but should be eventually */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003334 bb_error_msg("unhandled syntax: $%c", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003335 return 1;
3336 break;
3337 default:
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003338 b_addqchr(dest, '$', dest->quote);
Eric Andersen25f27032001-04-26 23:22:31 +00003339 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003340 debug_printf_parse("handle_dollar return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003341 return 0;
3342}
3343
Eric Andersen25f27032001-04-26 23:22:31 +00003344/* return code is 0 for normal exit, 1 for syntax error */
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003345static int parse_stream(o_string *dest, struct p_context *ctx,
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003346 struct in_str *input, const char *end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00003347{
"Vladimir N. Oleynik"4ccd2b42006-01-31 09:27:48 +00003348 int ch, m;
Eric Andersen25f27032001-04-26 23:22:31 +00003349 int redir_fd;
3350 redir_type redir_style;
3351 int next;
3352
3353 /* Only double-quote state is handled in the state variable dest->quote.
3354 * A single-quote triggers a bypass of the main loop until its mate is
3355 * found. When recursing, quote state is passed in via dest->quote. */
3356
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003357 debug_printf_parse("parse_stream entered, end_trigger='%s'\n", end_trigger);
3358
Denis Vlasenko1a735862007-05-23 00:32:25 +00003359 while (1) {
Denis Vlasenko1a735862007-05-23 00:32:25 +00003360 m = CHAR_IFS;
3361 next = '\0';
Denis Vlasenko170435c2007-05-23 13:01:10 +00003362 ch = b_getch(input);
Denis Vlasenko1a735862007-05-23 00:32:25 +00003363 if (ch != EOF) {
3364 m = charmap[ch];
3365 if (ch != '\n')
3366 next = b_peek(input);
3367 }
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003368 debug_printf_parse(": ch=%c (%d) m=%d quote=%d\n",
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003369 ch, ch, m, dest->quote);
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003370 if (m == CHAR_ORDINARY
3371 || (m != CHAR_SPECIAL && dest->quote)
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003372 ) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00003373 if (ch == EOF) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003374 syntax("unterminated \"");
Denis Vlasenko170435c2007-05-23 13:01:10 +00003375 debug_printf_parse("parse_stream return 1: unterminated \"\n");
3376 return 1;
3377 }
Eric Andersen25f27032001-04-26 23:22:31 +00003378 b_addqchr(dest, ch, dest->quote);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003379 continue;
3380 }
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003381 if (m == CHAR_IFS) {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003382 if (done_word(dest, ctx)) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003383 debug_printf_parse("parse_stream return 1: done_word!=0\n");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003384 return 1;
Eric Andersenaac75e52001-04-30 18:18:45 +00003385 }
Denis Vlasenko1a735862007-05-23 00:32:25 +00003386 if (ch == EOF)
3387 break;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003388 /* If we aren't performing a substitution, treat
3389 * a newline as a command separator.
3390 * [why we don't handle it exactly like ';'? --vda] */
3391 if (end_trigger && ch == '\n') {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003392 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003393 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003394 }
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003395 if ((end_trigger && strchr(end_trigger, ch))
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003396 && !dest->quote && ctx->res_w == RES_NONE
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003397 ) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003398 debug_printf_parse("parse_stream return 0: end_trigger char found\n");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003399 return 0;
3400 }
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003401 if (m == CHAR_IFS)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003402 continue;
3403 switch (ch) {
Eric Andersen25f27032001-04-26 23:22:31 +00003404 case '#':
3405 if (dest->length == 0 && !dest->quote) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003406 while (1) {
3407 ch = b_peek(input);
3408 if (ch == EOF || ch == '\n')
3409 break;
3410 b_getch(input);
3411 }
Eric Andersen25f27032001-04-26 23:22:31 +00003412 } else {
3413 b_addqchr(dest, ch, dest->quote);
3414 }
3415 break;
3416 case '\\':
3417 if (next == EOF) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003418 syntax("\\<eof>");
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003419 debug_printf_parse("parse_stream return 1: \\<eof>\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003420 return 1;
3421 }
3422 b_addqchr(dest, '\\', dest->quote);
3423 b_addqchr(dest, b_getch(input), dest->quote);
3424 break;
3425 case '$':
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003426 if (handle_dollar(dest, ctx, input) != 0) {
3427 debug_printf_parse("parse_stream return 1: handle_dollar returned non-0\n");
3428 return 1;
3429 }
Eric Andersen25f27032001-04-26 23:22:31 +00003430 break;
3431 case '\'':
3432 dest->nonnull = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003433 while (1) {
3434 ch = b_getch(input);
3435 if (ch == EOF || ch == '\'')
3436 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003437 b_addchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003438 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003439 if (ch == EOF) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003440 syntax("unterminated '");
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003441 debug_printf_parse("parse_stream return 1: unterminated '\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003442 return 1;
3443 }
3444 break;
3445 case '"':
3446 dest->nonnull = 1;
3447 dest->quote = !dest->quote;
3448 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003449#if ENABLE_HUSH_TICK
Eric Andersen25f27032001-04-26 23:22:31 +00003450 case '`':
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003451 process_command_subs(dest, ctx, input, "`");
Eric Andersen25f27032001-04-26 23:22:31 +00003452 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003453#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003454 case '>':
3455 redir_fd = redirect_opt_num(dest);
3456 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003457 redir_style = REDIRECT_OVERWRITE;
Eric Andersen25f27032001-04-26 23:22:31 +00003458 if (next == '>') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003459 redir_style = REDIRECT_APPEND;
Eric Andersen25f27032001-04-26 23:22:31 +00003460 b_getch(input);
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003461 }
3462#if 0
3463 else if (next == '(') {
3464 syntax(">(process) not supported");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003465 debug_printf_parse("parse_stream return 1: >(process) not supported\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003466 return 1;
3467 }
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003468#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003469 setup_redirect(ctx, redir_fd, redir_style, input);
3470 break;
3471 case '<':
3472 redir_fd = redirect_opt_num(dest);
3473 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003474 redir_style = REDIRECT_INPUT;
Eric Andersen25f27032001-04-26 23:22:31 +00003475 if (next == '<') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003476 redir_style = REDIRECT_HEREIS;
Eric Andersen25f27032001-04-26 23:22:31 +00003477 b_getch(input);
3478 } else if (next == '>') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003479 redir_style = REDIRECT_IO;
Eric Andersen25f27032001-04-26 23:22:31 +00003480 b_getch(input);
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003481 }
3482#if 0
3483 else if (next == '(') {
3484 syntax("<(process) not supported");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003485 debug_printf_parse("parse_stream return 1: <(process) not supported\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003486 return 1;
3487 }
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003488#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003489 setup_redirect(ctx, redir_fd, redir_style, input);
3490 break;
3491 case ';':
3492 done_word(dest, ctx);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003493 done_pipe(ctx, PIPE_SEQ);
Eric Andersen25f27032001-04-26 23:22:31 +00003494 break;
3495 case '&':
3496 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003497 if (next == '&') {
Eric Andersen25f27032001-04-26 23:22:31 +00003498 b_getch(input);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003499 done_pipe(ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00003500 } else {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003501 done_pipe(ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00003502 }
3503 break;
3504 case '|':
3505 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003506 if (next == '|') {
Eric Andersen25f27032001-04-26 23:22:31 +00003507 b_getch(input);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003508 done_pipe(ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00003509 } else {
3510 /* we could pick up a file descriptor choice here
3511 * with redirect_opt_num(), but bash doesn't do it.
3512 * "echo foo 2| cat" yields "foo 2". */
3513 done_command(ctx);
3514 }
3515 break;
3516 case '(':
3517 case '{':
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003518 if (parse_group(dest, ctx, input, ch) != 0) {
3519 debug_printf_parse("parse_stream return 1: parse_group returned non-0\n");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003520 return 1;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003521 }
Eric Andersen25f27032001-04-26 23:22:31 +00003522 break;
3523 case ')':
3524 case '}':
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003525 syntax("unexpected }"); /* Proper use of this character is caught by end_trigger */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003526 debug_printf_parse("parse_stream return 1: unexpected '}'\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003527 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003528 default:
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003529 if (ENABLE_HUSH_DEBUG)
3530 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003531 }
3532 }
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003533 /* Complain if quote? No, maybe we just finished a command substitution
Eric Andersen25f27032001-04-26 23:22:31 +00003534 * that was quoted. Example:
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003535 * $ echo "`cat foo` plus more"
Eric Andersen25f27032001-04-26 23:22:31 +00003536 * and we just got the EOF generated by the subshell that ran "cat foo"
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003537 * The only real complaint is if we got an EOF when end_trigger != NULL,
Eric Andersen25f27032001-04-26 23:22:31 +00003538 * that is, we were really supposed to get end_trigger, and never got
3539 * one before the EOF. Can't use the standard "syntax error" return code,
3540 * so that parse_stream_outer can distinguish the EOF and exit smoothly. */
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003541 debug_printf_parse("parse_stream return %d\n", -(end_trigger != NULL));
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003542 if (end_trigger)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003543 return -1;
Eric Andersen25f27032001-04-26 23:22:31 +00003544 return 0;
3545}
3546
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003547static void set_in_charmap(const char *set, int code)
Eric Andersen25f27032001-04-26 23:22:31 +00003548{
Denis Vlasenkof5294e12007-04-14 10:09:57 +00003549 while (*set)
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003550 charmap[(unsigned char)*set++] = code;
Eric Andersen25f27032001-04-26 23:22:31 +00003551}
3552
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003553static void update_charmap(void)
Eric Andersen25f27032001-04-26 23:22:31 +00003554{
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003555 /* char *ifs and char charmap[256] are both globals. */
Eric Andersen25f27032001-04-26 23:22:31 +00003556 ifs = getenv("IFS");
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003557 if (ifs == NULL)
3558 ifs = " \t\n";
Eric Andersen25f27032001-04-26 23:22:31 +00003559 /* Precompute a list of 'flow through' behavior so it can be treated
3560 * quickly up front. Computation is necessary because of IFS.
3561 * Special case handling of IFS == " \t\n" is not implemented.
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003562 * The charmap[] array only really needs two bits each,
3563 * and on most machines that would be faster (reduced L1 cache use).
Eric Andersen25f27032001-04-26 23:22:31 +00003564 */
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003565 memset(charmap, CHAR_ORDINARY, sizeof(charmap));
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003566#if ENABLE_HUSH_TICK
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003567 set_in_charmap("\\$\"`", CHAR_SPECIAL);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003568#else
3569 set_in_charmap("\\$\"", CHAR_SPECIAL);
3570#endif
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003571 set_in_charmap("<>;&|(){}#'", CHAR_ORDINARY_IF_QUOTED);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003572 set_in_charmap(ifs, CHAR_IFS); /* are ordinary if quoted */
Eric Andersen25f27032001-04-26 23:22:31 +00003573}
3574
Eric Andersenaff114c2004-04-14 17:51:38 +00003575/* most recursion does not come through here, the exception is
Denis Vlasenko170435c2007-05-23 13:01:10 +00003576 * from builtin_source() and builtin_eval() */
3577static int parse_and_run_stream(struct in_str *inp, int parse_flag)
Eric Andersen25f27032001-04-26 23:22:31 +00003578{
Eric Andersen25f27032001-04-26 23:22:31 +00003579 struct p_context ctx;
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003580 o_string temp = NULL_O_STRING;
Eric Andersen25f27032001-04-26 23:22:31 +00003581 int rcode;
3582 do {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003583 ctx.parse_type = parse_flag;
Eric Andersen25f27032001-04-26 23:22:31 +00003584 initialize_context(&ctx);
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003585 update_charmap();
Denis Vlasenko219e88d2007-05-21 10:18:23 +00003586 if (!(parse_flag & PARSEFLAG_SEMICOLON) || (parse_flag & PARSEFLAG_REPARSING))
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003587 set_in_charmap(";$&|", CHAR_ORDINARY);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003588#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003589 inp->promptmode = 1;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003590#endif
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003591 /* We will stop & execute after each ';' or '\n'.
3592 * Example: "sleep 9999; echo TEST" + ctrl-C:
3593 * TEST should be printed */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003594 rcode = parse_stream(&temp, &ctx, inp, ";\n");
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003595 if (rcode != 1 && ctx.old_flag != 0) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003596 syntax(NULL);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003597 }
3598 if (rcode != 1 && ctx.old_flag == 0) {
3599 done_word(&temp, &ctx);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003600 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003601 debug_print_tree(ctx.list_head, 0);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003602 debug_printf_exec("parse_stream_outer: run_list\n");
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003603 run_list(ctx.list_head);
3604 } else {
3605 if (ctx.old_flag != 0) {
3606 free(ctx.stack);
3607 b_reset(&temp);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003608 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003609 temp.nonnull = 0;
3610 temp.quote = 0;
3611 inp->p = NULL;
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00003612 free_pipe_list(ctx.list_head, 0);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003613 }
Eric Andersena813afc2001-05-24 16:19:36 +00003614 b_free(&temp);
Denis Vlasenko219e88d2007-05-21 10:18:23 +00003615 } while (rcode != -1 && !(parse_flag & PARSEFLAG_EXIT_FROM_LOOP)); /* loop on syntax errors, return on EOF */
Eric Andersen25f27032001-04-26 23:22:31 +00003616 return 0;
3617}
3618
Denis Vlasenko170435c2007-05-23 13:01:10 +00003619static int parse_and_run_string(const char *s, int parse_flag)
Eric Andersen25f27032001-04-26 23:22:31 +00003620{
3621 struct in_str input;
3622 setup_string_in_str(&input, s);
Denis Vlasenko170435c2007-05-23 13:01:10 +00003623 return parse_and_run_stream(&input, parse_flag);
Eric Andersen25f27032001-04-26 23:22:31 +00003624}
3625
Denis Vlasenko170435c2007-05-23 13:01:10 +00003626static int parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00003627{
3628 int rcode;
3629 struct in_str input;
3630 setup_file_in_str(&input, f);
Denis Vlasenko170435c2007-05-23 13:01:10 +00003631 rcode = parse_and_run_stream(&input, PARSEFLAG_SEMICOLON);
Eric Andersen25f27032001-04-26 23:22:31 +00003632 return rcode;
3633}
3634
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003635#if ENABLE_HUSH_JOB
Eric Andersen6c947d22001-06-25 22:24:38 +00003636/* Make sure we have a controlling tty. If we get started under a job
3637 * aware app (like bash for example), make sure we are now in charge so
3638 * we don't fight over who gets the foreground */
Eric Anderseneaecbf32001-10-31 10:41:31 +00003639static void setup_job_control(void)
Eric Andersen52a97ca2001-06-22 06:49:26 +00003640{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003641 pid_t shell_pgrp;
3642
Denis Vlasenkoa6a17852007-04-28 16:42:11 +00003643 saved_task_pgrp = shell_pgrp = getpgrp();
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003644 debug_printf_jobs("saved_task_pgrp=%d\n", saved_task_pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003645 fcntl(interactive_fd, F_SETFD, FD_CLOEXEC);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003646
Denis Vlasenkoa6a17852007-04-28 16:42:11 +00003647 /* If we were ran as 'hush &',
3648 * sleep until we are in the foreground. */
3649 while (tcgetpgrp(interactive_fd) != shell_pgrp) {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003650 /* Send TTIN to ourself (should stop us) */
Denis Vlasenkoff131b92007-04-10 15:42:06 +00003651 kill(- shell_pgrp, SIGTTIN);
Denis Vlasenkoa6a17852007-04-28 16:42:11 +00003652 shell_pgrp = getpgrp();
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003653 }
Eric Andersen52a97ca2001-06-22 06:49:26 +00003654
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003655 /* Ignore job-control and misc signals. */
3656 set_jobctrl_sighandler(SIG_IGN);
3657 set_misc_sighandler(SIG_IGN);
3658//huh? signal(SIGCHLD, SIG_IGN);
3659
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003660 /* We _must_ restore tty pgrp on fatal signals */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003661 set_fatal_sighandler(sigexit);
Eric Andersen6c947d22001-06-25 22:24:38 +00003662
3663 /* Put ourselves in our own process group. */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003664 setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
Eric Andersen6c947d22001-06-25 22:24:38 +00003665 /* Grab control of the terminal. */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003666 tcsetpgrp(interactive_fd, getpid());
Eric Andersen6c947d22001-06-25 22:24:38 +00003667}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003668#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00003669
Denis Vlasenko06af2162007-02-03 17:28:39 +00003670int hush_main(int argc, char **argv);
Matt Kraai2d91deb2001-08-01 17:21:35 +00003671int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00003672{
3673 int opt;
3674 FILE *input;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003675 char **e;
Eric Andersenbc604a22001-05-16 05:24:03 +00003676
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00003677 PTR_TO_GLOBALS = xzalloc(sizeof(G));
3678 top_vars = &shell_ver;
3679 shell_ver = const_shell_ver; /* copying struct here */
3680
Denis Vlasenko38f63192007-01-22 09:03:07 +00003681#if ENABLE_FEATURE_EDITING
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00003682 line_input_state = new_line_input_t(FOR_SHELL);
3683#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003684 /* XXX what should these be while sourcing /etc/profile? */
3685 global_argc = argc;
3686 global_argv = argv;
Eric Andersen94ac2442001-05-22 19:05:18 +00003687 /* Initialize some more globals to non-zero values */
3688 set_cwd();
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003689#if ENABLE_HUSH_INTERACTIVE
3690#if ENABLE_FEATURE_EDITING
3691 cmdedit_set_initial_prompt();
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003692#endif
Eric Andersen94ac2442001-05-22 19:05:18 +00003693 PS2 = "> ";
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003694#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00003695
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003696 /* initialize our shell local variables with the values
Eric Andersen94ac2442001-05-22 19:05:18 +00003697 * currently living in the environment */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003698 e = environ;
3699 if (e)
3700 while (*e)
3701 set_local_var(*e++, 2); /* without call putenv() */
Eric Andersen94ac2442001-05-22 19:05:18 +00003702
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003703 last_return_code = EXIT_SUCCESS;
Eric Andersen25f27032001-04-26 23:22:31 +00003704
3705 if (argv[0] && argv[0][0] == '-') {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003706 debug_printf("sourcing /etc/profile\n");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003707 input = fopen("/etc/profile", "r");
3708 if (input != NULL) {
Eric Andersena90f20b2001-06-26 23:00:21 +00003709 mark_open(fileno(input));
Denis Vlasenko170435c2007-05-23 13:01:10 +00003710 parse_and_run_file(input);
Eric Andersena90f20b2001-06-26 23:00:21 +00003711 mark_closed(fileno(input));
3712 fclose(input);
3713 }
Eric Andersen25f27032001-04-26 23:22:31 +00003714 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003715 input = stdin;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003716
Eric Andersen25f27032001-04-26 23:22:31 +00003717 while ((opt = getopt(argc, argv, "c:xif")) > 0) {
3718 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003719 case 'c':
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003720 global_argv = argv + optind;
3721 global_argc = argc - optind;
Denis Vlasenko170435c2007-05-23 13:01:10 +00003722 opt = parse_and_run_string(optarg, PARSEFLAG_SEMICOLON);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003723 goto final_return;
3724 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003725 /* Well, we cannot just declare interactiveness,
3726 * we have to have some stuff (ctty, etc) */
3727 /* interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003728 break;
3729 case 'f':
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00003730 fake_mode = 1;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003731 break;
3732 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00003733#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003734 fprintf(stderr, "Usage: sh [FILE]...\n"
3735 " or: sh -c command [args]...\n\n");
3736 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00003737#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003738 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00003739#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003740 }
3741 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003742#if ENABLE_HUSH_JOB
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003743 /* A shell is interactive if the '-i' flag was given, or if all of
Eric Andersen25f27032001-04-26 23:22:31 +00003744 * the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00003745 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00003746 * no arguments remaining or the -s flag given
3747 * standard input is a terminal
3748 * standard output is a terminal
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003749 * Refer to Posix.2, the description of the 'sh' utility. */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003750 if (argv[optind] == NULL && input == stdin
3751 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3752 ) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003753 saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
3754 debug_printf("saved_tty_pgrp=%d\n", saved_tty_pgrp);
3755 if (saved_tty_pgrp >= 0) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003756 /* try to dup to high fd#, >= 255 */
3757 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3758 if (interactive_fd < 0) {
3759 /* try to dup to any fd */
3760 interactive_fd = dup(STDIN_FILENO);
3761 if (interactive_fd < 0)
3762 /* give up */
3763 interactive_fd = 0;
3764 }
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00003765 // TODO: track & disallow any attempts of user
3766 // to (inadvertently) close/redirect it
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003767 }
Eric Andersen25f27032001-04-26 23:22:31 +00003768 }
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003769 debug_printf("interactive_fd=%d\n", interactive_fd);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003770 if (interactive_fd) {
Eric Andersen25f27032001-04-26 23:22:31 +00003771 /* Looks like they want an interactive shell */
Eric Andersen52a97ca2001-06-22 06:49:26 +00003772 setup_job_control();
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003773 /* Make xfuncs do cleanup on exit */
3774 die_sleep = -1; /* flag */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003775// FIXME: should we reset die_sleep = 0 whereever we fork?
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003776 if (setjmp(die_jmp)) {
3777 /* xfunc has failed! die die die */
3778 hush_exit(xfunc_error_retval);
3779 }
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00003780#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denis Vlasenkoef36ead2007-05-02 15:34:47 +00003781 printf("\n\n%s hush - the humble shell v"HUSH_VER_STR"\n", BB_BANNER);
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00003782 printf("Enter 'help' for a list of built-in commands.\n\n");
3783#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00003784 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003785#elif ENABLE_HUSH_INTERACTIVE
3786/* no job control compiled, only prompt/line editing */
3787 if (argv[optind] == NULL && input == stdin
3788 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3789 ) {
3790 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3791 if (interactive_fd < 0) {
3792 /* try to dup to any fd */
3793 interactive_fd = dup(STDIN_FILENO);
3794 if (interactive_fd < 0)
3795 /* give up */
3796 interactive_fd = 0;
3797 }
3798 }
3799
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003800#endif
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003801
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003802 if (argv[optind] == NULL) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00003803 opt = parse_and_run_file(stdin);
Eric Andersene67c3ce2001-05-02 02:09:36 +00003804 goto final_return;
Eric Andersen25f27032001-04-26 23:22:31 +00003805 }
Eric Andersen25f27032001-04-26 23:22:31 +00003806
3807 debug_printf("\nrunning script '%s'\n", argv[optind]);
Denis Vlasenko4c978632007-02-03 03:31:13 +00003808 global_argv = argv + optind;
3809 global_argc = argc - optind;
Rob Landleyd921b2e2006-08-03 15:41:12 +00003810 input = xfopen(argv[optind], "r");
Denis Vlasenko170435c2007-05-23 13:01:10 +00003811 opt = parse_and_run_file(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003812
Denis Vlasenko38f63192007-01-22 09:03:07 +00003813#if ENABLE_FEATURE_CLEAN_UP
Eric Andersenaeb44c42001-05-22 20:29:00 +00003814 fclose(input);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003815 if (cwd != bb_msg_unknown)
Eric Andersenaeb44c42001-05-22 20:29:00 +00003816 free((char*)cwd);
3817 {
3818 struct variables *cur, *tmp;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003819 for (cur = top_vars; cur; cur = tmp) {
Eric Andersenaeb44c42001-05-22 20:29:00 +00003820 tmp = cur->next;
3821 if (!cur->flg_read_only) {
Denis Vlasenko4c978632007-02-03 03:31:13 +00003822 free((char*)cur->name);
3823 free((char*)cur->value);
Eric Andersenaeb44c42001-05-22 20:29:00 +00003824 free(cur);
3825 }
3826 }
3827 }
Eric Andersen25f27032001-04-26 23:22:31 +00003828#endif
3829
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003830 final_return:
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003831 hush_exit(opt ? opt : last_return_code);
Eric Andersen25f27032001-04-26 23:22:31 +00003832}