blob: 0b8e7d68d334fa83540c1a4417e94367f799d3a4 [file] [log] [blame]
Eric Andersen25f27032001-04-26 23:22:31 +00001/* vi: set sw=4 ts=4: */
2/*
3 * sh.c -- a prototype Bourne shell grammar parser
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
7 *
8 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
9 *
10 * Credits:
11 * The parser routines proper are all original material, first
Eric Andersencb81e642003-07-14 21:21:08 +000012 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
13 * execution engine, the builtins, and much of the underlying
14 * support has been adapted from busybox-0.49pre's lash, which is
Eric Andersenc7bda1c2004-03-15 08:29:22 +000015 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
Eric Andersencb81e642003-07-14 21:21:08 +000016 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
17 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
18 * Troan, which they placed in the public domain. I don't know
19 * how much of the Johnson/Troan code has survived the repeated
20 * rewrites.
21 *
Eric Andersen25f27032001-04-26 23:22:31 +000022 * Other credits:
Eric Andersen25f27032001-04-26 23:22:31 +000023 * b_addchr() derived from similar w_addchar function in glibc-2.2
24 * setup_redirect(), redirect_opt_num(), and big chunks of main()
Denis Vlasenko55b2de72007-04-18 17:21:28 +000025 * and many builtins derived from contributions by Erik Andersen
Eric Andersen25f27032001-04-26 23:22:31 +000026 * miscellaneous bugfixes from Matt Kraai
27 *
28 * There are two big (and related) architecture differences between
29 * this parser and the lash parser. One is that this version is
30 * actually designed from the ground up to understand nearly all
31 * of the Bourne grammar. The second, consequential change is that
32 * the parser and input reader have been turned inside out. Now,
33 * the parser is in control, and asks for input as needed. The old
34 * way had the input reader in control, and it asked for parsing to
35 * take place as needed. The new way makes it much easier to properly
36 * handle the recursion implicit in the various substitutions, especially
37 * across continuation lines.
38 *
39 * Bash grammar not implemented: (how many of these were in original sh?)
Eric Andersen25f27032001-04-26 23:22:31 +000040 * $_
41 * ! negation operator for pipes
42 * &> and >& redirection of stdout+stderr
43 * Brace Expansion
44 * Tilde Expansion
45 * fancy forms of Parameter Expansion
Eric Andersen78a7c992001-05-15 16:30:25 +000046 * aliases
Eric Andersen25f27032001-04-26 23:22:31 +000047 * Arithmetic Expansion
48 * <(list) and >(list) Process Substitution
Eric Andersen83a2ae22001-05-07 17:59:25 +000049 * reserved words: case, esac, select, function
Eric Andersen25f27032001-04-26 23:22:31 +000050 * Here Documents ( << word )
51 * Functions
52 * Major bugs:
Denis Vlasenkob81b3df2007-04-28 16:48:04 +000053 * job handling woefully incomplete and buggy (improved --vda)
Eric Andersen25f27032001-04-26 23:22:31 +000054 * reserved word execution woefully incomplete and buggy
Eric Andersen25f27032001-04-26 23:22:31 +000055 * to-do:
Eric Andersen83a2ae22001-05-07 17:59:25 +000056 * port selected bugfixes from post-0.49 busybox lash - done?
57 * finish implementing reserved words: for, while, until, do, done
58 * change { and } from special chars to reserved words
59 * builtins: break, continue, eval, return, set, trap, ulimit
60 * test magic exec
Eric Andersen25f27032001-04-26 23:22:31 +000061 * handle children going into background
62 * clean up recognition of null pipes
Eric Andersen25f27032001-04-26 23:22:31 +000063 * check setting of global_argc and global_argv
64 * control-C handling, probably with longjmp
Eric Andersen25f27032001-04-26 23:22:31 +000065 * follow IFS rules more precisely, including update semantics
Eric Andersen25f27032001-04-26 23:22:31 +000066 * figure out what to do with backslash-newline
67 * explain why we use signal instead of sigaction
68 * propagate syntax errors, die on resource errors?
69 * continuation lines, both explicit and implicit - done?
70 * memory leak finding and plugging - done?
71 * more testing, especially quoting rules and redirection
Eric Andersen78a7c992001-05-15 16:30:25 +000072 * document how quoting rules not precisely followed for variable assignments
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +000073 * maybe change charmap[] to use 2-bit entries
Eric Andersen25f27032001-04-26 23:22:31 +000074 * (eventually) remove all the printf's
Eric Andersen25f27032001-04-26 23:22:31 +000075 *
Bernhard Reutner-Fischer86f5c992006-01-22 22:55:11 +000076 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
Eric Andersen25f27032001-04-26 23:22:31 +000077 */
Bernhard Reutner-Fischere15d7572006-06-02 20:56:16 +000078
79#include "busybox.h"
Eric Andersen25f27032001-04-26 23:22:31 +000080#include <glob.h> /* glob, of course */
Eric Andersen25f27032001-04-26 23:22:31 +000081#include <getopt.h> /* should be pretty obvious */
Eric Andersen25f27032001-04-26 23:22:31 +000082/* #include <dmalloc.h> */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +000083extern char **environ; /* This is in <unistd.h>, but protected with __USE_GNU */
Denis Vlasenkod01ff132007-05-02 21:40:23 +000084
85
86/* If you comment out one of these below, it will be #defined later
87 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +000088#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +000089/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +000090#define debug_printf_parse(...) do {} while (0)
91#define debug_print_tree(a, b) do {} while (0)
92#define debug_printf_exec(...) do {} while (0)
93#define debug_printf_jobs(...) do {} while (0)
94#define debug_printf_expand(...) do {} while (0)
95#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +000096
97#ifndef debug_printf
98#define debug_printf(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkod01ff132007-05-02 21:40:23 +000099#endif
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000100
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000101#ifndef debug_printf_parse
102#define debug_printf_parse(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000103#endif
104
105#ifndef debug_printf_exec
106#define debug_printf_exec(...) fprintf(stderr, __VA_ARGS__)
107#endif
108
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000109#ifndef debug_printf_jobs
110#define debug_printf_jobs(...) fprintf(stderr, __VA_ARGS__)
111#define DEBUG_SHELL_JOBS 1
112#endif
113
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000114#ifndef debug_printf_expand
115#define debug_printf_expand(...) fprintf(stderr, __VA_ARGS__)
116#define DEBUG_EXPAND 1
117#endif
118
Denis Vlasenko170435c2007-05-23 13:01:10 +0000119/* Keep unconditionally on for now */
120#define ENABLE_HUSH_DEBUG 1
121
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000122#ifndef debug_printf_clean
123/* broken, of course, but OK for testing */
124static const char *indenter(int i)
125{
126 static const char blanks[] = " ";
127 return &blanks[sizeof(blanks) - i - 1];
128}
129#define debug_printf_clean(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkoc666f712007-05-16 22:18:54 +0000130#define DEBUG_CLEAN 1
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +0000131#endif
132
Eric Andersen25f27032001-04-26 23:22:31 +0000133
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000134#if !ENABLE_HUSH_INTERACTIVE
135#undef ENABLE_FEATURE_EDITING
136#define ENABLE_FEATURE_EDITING 0
137#undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
138#define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
139#endif
"Robert P. J. Day"f3501602006-07-01 12:19:39 +0000140
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +0000141#define SPECIAL_VAR_SYMBOL 3
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000142
143#define PARSEFLAG_EXIT_FROM_LOOP 1
144#define PARSEFLAG_SEMICOLON (1 << 1) /* symbol ';' is special for parser */
145#define PARSEFLAG_REPARSING (1 << 2) /* >= 2nd pass */
Eric Andersen25f27032001-04-26 23:22:31 +0000146
147typedef enum {
148 REDIRECT_INPUT = 1,
149 REDIRECT_OVERWRITE = 2,
150 REDIRECT_APPEND = 3,
151 REDIRECT_HEREIS = 4,
152 REDIRECT_IO = 5
153} redir_type;
154
155/* The descrip member of this structure is only used to make debugging
156 * output pretty */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +0000157static const struct {
158 int mode;
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000159 signed char default_fd;
160 char descrip[3];
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +0000161} redir_table[] = {
Eric Andersen25f27032001-04-26 23:22:31 +0000162 { 0, 0, "()" },
163 { O_RDONLY, 0, "<" },
164 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
165 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
166 { O_RDONLY, -1, "<<" },
167 { O_RDWR, 1, "<>" }
168};
169
170typedef enum {
171 PIPE_SEQ = 1,
172 PIPE_AND = 2,
173 PIPE_OR = 3,
174 PIPE_BG = 4,
175} pipe_style;
176
177/* might eventually control execution */
178typedef enum {
179 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000180#if ENABLE_HUSH_IF
Eric Andersen25f27032001-04-26 23:22:31 +0000181 RES_IF = 1,
182 RES_THEN = 2,
183 RES_ELIF = 3,
184 RES_ELSE = 4,
185 RES_FI = 5,
Denis Vlasenko06810332007-05-21 23:30:54 +0000186#endif
187#if ENABLE_HUSH_LOOPS
Eric Andersen25f27032001-04-26 23:22:31 +0000188 RES_FOR = 6,
189 RES_WHILE = 7,
190 RES_UNTIL = 8,
191 RES_DO = 9,
192 RES_DONE = 10,
Denis Vlasenko06810332007-05-21 23:30:54 +0000193 RES_IN = 11,
194#endif
195 RES_XXXX = 12,
Eric Andersen4c9b68f2002-04-13 12:33:41 +0000196 RES_SNTX = 13
Eric Andersen25f27032001-04-26 23:22:31 +0000197} reserved_style;
Denis Vlasenko5f786c22007-04-20 08:35:45 +0000198enum {
199 FLAG_END = (1 << RES_NONE ),
Denis Vlasenko06810332007-05-21 23:30:54 +0000200#if ENABLE_HUSH_IF
Denis Vlasenko5f786c22007-04-20 08:35:45 +0000201 FLAG_IF = (1 << RES_IF ),
202 FLAG_THEN = (1 << RES_THEN ),
203 FLAG_ELIF = (1 << RES_ELIF ),
204 FLAG_ELSE = (1 << RES_ELSE ),
205 FLAG_FI = (1 << RES_FI ),
Denis Vlasenko06810332007-05-21 23:30:54 +0000206#endif
207#if ENABLE_HUSH_LOOPS
Denis Vlasenko5f786c22007-04-20 08:35:45 +0000208 FLAG_FOR = (1 << RES_FOR ),
209 FLAG_WHILE = (1 << RES_WHILE),
210 FLAG_UNTIL = (1 << RES_UNTIL),
211 FLAG_DO = (1 << RES_DO ),
212 FLAG_DONE = (1 << RES_DONE ),
213 FLAG_IN = (1 << RES_IN ),
Denis Vlasenko06810332007-05-21 23:30:54 +0000214#endif
Denis Vlasenko5f786c22007-04-20 08:35:45 +0000215 FLAG_START = (1 << RES_XXXX ),
216};
Eric Andersen25f27032001-04-26 23:22:31 +0000217
218/* This holds pointers to the various results of parsing */
219struct p_context {
220 struct child_prog *child;
221 struct pipe *list_head;
222 struct pipe *pipe;
223 struct redir_struct *pending_redirect;
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000224 smallint res_w;
225 smallint parse_type; /* bitmask of PARSEFLAG_xxx, defines type of parser : ";$" common or special symbol */
226 int old_flag; /* bitmask of FLAG_xxx, for figuring out valid reserved words */
Eric Andersen25f27032001-04-26 23:22:31 +0000227 struct p_context *stack;
228 /* How about quoting status? */
229};
230
231struct redir_struct {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000232 struct redir_struct *next; /* pointer to the next redirect in the list */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000233 redir_type type; /* type of redirection */
234 int fd; /* file descriptor being redirected */
235 int dup; /* -1, or file descriptor being duplicated */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000236 glob_t word; /* *word.gl_pathv is the filename */
Eric Andersen25f27032001-04-26 23:22:31 +0000237};
238
239struct child_prog {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000240 pid_t pid; /* 0 if exited */
241 char **argv; /* program name and arguments */
242 struct pipe *group; /* if non-NULL, first in group or subshell */
Denis Vlasenko262d7652007-05-20 21:52:49 +0000243 smallint subshell; /* flag, non-zero if group must be forked */
244 smallint is_stopped; /* is the program currently running? */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000245 struct redir_struct *redirects; /* I/O redirections */
246 glob_t glob_result; /* result of parameter globbing */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000247 struct pipe *family; /* pointer back to the child's parent pipe */
Denis Vlasenkoc666f712007-05-16 22:18:54 +0000248 //sp counting seems to be broken... so commented out, grep for '//sp:'
249 //sp: int sp; /* number of SPECIAL_VAR_SYMBOL */
Denis Vlasenko262d7652007-05-20 21:52:49 +0000250 //seems to be unused, grep for '//pt:'
251 //pt: int parse_type;
Eric Andersen25f27032001-04-26 23:22:31 +0000252};
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000253/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
254 * and on execution these are substituted with their values.
255 * Substitution can make _several_ words out of one argv[n]!
256 * Example: argv[0]=='.^C*^C.' here: echo .$*.
257 */
Eric Andersen25f27032001-04-26 23:22:31 +0000258
259struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000260 struct pipe *next;
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000261 int num_progs; /* total number of programs in job */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000262 int running_progs; /* number of programs running (not exited) */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000263 int stopped_progs; /* number of programs alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000264#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000265 int jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000266 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000267 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000268#endif
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000269 char *cmdbuf; /* buffer various argv's point into */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000270 struct child_prog *progs; /* array of commands in pipe */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000271 int job_context; /* bitmask defining current context */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000272 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
273 smallint res_word; /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000274};
275
Eric Andersen25f27032001-04-26 23:22:31 +0000276struct close_me {
Eric Andersen25f27032001-04-26 23:22:31 +0000277 struct close_me *next;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000278 int fd;
Eric Andersen25f27032001-04-26 23:22:31 +0000279};
280
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000281/* On program start, environ points to initial environment.
282 * putenv adds new pointers into it, unsetenv removes them.
283 * Neither of these (de)allocates the strings.
284 * setenv allocates new strings in malloc space and does putenv,
285 * and thus setenv is unusable (leaky) for shell's purposes */
286#define setenv(...) setenv_is_leaky_dont_use()
287struct variable {
288 struct variable *next;
289 char *name; /* points to "name=" portion */
290 char *value; /* points directly after "=" */
291 int max_len; /* if > 0, name is part of initial env; else name is malloced */
292 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000293 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000294};
295
Eric Andersen25f27032001-04-26 23:22:31 +0000296typedef struct {
297 char *data;
298 int length;
299 int maxlen;
300 int quote;
301 int nonnull;
302} o_string;
303#define NULL_O_STRING {NULL,0,0,0,0}
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000304/* used for initialization: o_string foo = NULL_O_STRING; */
Eric Andersen25f27032001-04-26 23:22:31 +0000305
306/* I can almost use ordinary FILE *. Is open_memstream() universally
307 * available? Where is it documented? */
308struct in_str {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +0000309 const char *p;
310 /* eof_flag=1: last char in ->p is really an EOF */
311 char eof_flag; /* meaningless if ->p == NULL */
312 char peek_buf[2];
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000313#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000314 smallint promptme;
315 smallint promptmode; /* 0: PS1, 1: PS2 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000316#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000317 FILE *file;
318 int (*get) (struct in_str *);
319 int (*peek) (struct in_str *);
320};
321#define b_getch(input) ((input)->get(input))
322#define b_peek(input) ((input)->peek(input))
323
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000324enum {
325 CHAR_ORDINARY = 0,
326 CHAR_ORDINARY_IF_QUOTED = 1, /* example: *, # */
327 CHAR_IFS = 2, /* treated as ordinary if quoted */
328 CHAR_SPECIAL = 3, /* example: $ */
Eric Andersen25f27032001-04-26 23:22:31 +0000329};
330
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000331#define HUSH_VER_STR "0.02"
332
333static const char version_str[] = "HUSH_VERSION="HUSH_VER_STR;
334
335static const struct variable const_shell_ver = {
336 .next = NULL,
337 .name = (char*)version_str,
338 .value = (char*)version_str + sizeof("HUSH_VERSION=")-1,
339 .max_len = 1, /* 0 can provoke free(name) */
340 .flg_export = 1,
341 .flg_read_only = 1,
342};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000343
344/* "Globals" within this file */
345
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000346/* Sorted roughly by size (smaller offsets == smaller code) */
347struct globals {
348#if ENABLE_HUSH_INTERACTIVE
349 /* 'interactive_fd' is a fd# open to ctty, if we have one
350 * _AND_ if we decided to act interactively */
351 int interactive_fd;
352 const char *PS1;
353 const char *PS2;
354#endif
355#if ENABLE_FEATURE_EDITING
356 line_input_t *line_input_state;
357#endif
358#if ENABLE_HUSH_JOB
359 int run_list_level;
360 pid_t saved_task_pgrp;
361 pid_t saved_tty_pgrp;
362 int last_jobid;
363 struct pipe *job_list;
364 struct pipe *toplevel_list;
365 smallint ctrl_z_flag;
366#endif
367 smallint fake_mode;
368 /* these three support $?, $#, and $1 */
369 char **global_argv;
370 int global_argc;
371 int last_return_code;
372 const char *ifs;
373 struct close_me *close_me_head;
374 const char *cwd;
375 unsigned last_bg_pid;
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000376 struct variable *top_var; /* = &shell_ver (both are set in main()) */
377 struct variable shell_ver; /* = const_shell_ver */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000378#if ENABLE_FEATURE_SH_STANDALONE
379 struct nofork_save_area nofork_save;
380#endif
381#if ENABLE_HUSH_JOB
382 sigjmp_buf toplevel_jb;
383#endif
384 unsigned char charmap[256];
385 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
386};
387
388#define G (*ptr_to_globals)
389
390#if !ENABLE_HUSH_INTERACTIVE
391enum { interactive_fd = 0 };
392#endif
393#if !ENABLE_HUSH_JOB
394enum { run_list_level = 0 };
395#endif
396
397#if ENABLE_HUSH_INTERACTIVE
398#define interactive_fd (G.interactive_fd )
399#define PS1 (G.PS1 )
400#define PS2 (G.PS2 )
401#endif
402#if ENABLE_FEATURE_EDITING
403#define line_input_state (G.line_input_state)
404#endif
405#if ENABLE_HUSH_JOB
406#define run_list_level (G.run_list_level )
407#define saved_task_pgrp (G.saved_task_pgrp )
408#define saved_tty_pgrp (G.saved_tty_pgrp )
409#define last_jobid (G.last_jobid )
410#define job_list (G.job_list )
411#define toplevel_list (G.toplevel_list )
412#define toplevel_jb (G.toplevel_jb )
413#define ctrl_z_flag (G.ctrl_z_flag )
414#endif /* JOB */
415#define global_argv (G.global_argv )
416#define global_argc (G.global_argc )
417#define last_return_code (G.last_return_code)
418#define ifs (G.ifs )
419#define fake_mode (G.fake_mode )
420#define close_me_head (G.close_me_head )
421#define cwd (G.cwd )
422#define last_bg_pid (G.last_bg_pid )
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000423#define top_var (G.top_var )
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000424#define shell_ver (G.shell_ver )
425#if ENABLE_FEATURE_SH_STANDALONE
426#define nofork_save (G.nofork_save )
427#endif
428#if ENABLE_HUSH_JOB
429#define toplevel_jb (G.toplevel_jb )
430#endif
431#define charmap (G.charmap )
432#define user_input_buf (G.user_input_buf )
433
434
435#define B_CHUNK 100
436#define B_NOSPAC 1
437#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
438
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000439#if 1
440/* Normal */
441static void syntax(const char *msg)
442{
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000443 /* Was using fancy stuff:
444 * (interactive_fd ? bb_error_msg : bb_error_msg_and_die)(...params...)
445 * but it SEGVs. ?! Oh well... explicit temp ptr works around that */
446 void (*fp)(const char *s, ...);
447
448 fp = (interactive_fd ? bb_error_msg : bb_error_msg_and_die);
449 fp(msg ? "%s: %s" : "syntax error", "syntax error", msg);
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000450}
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000451
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000452#else
453/* Debug */
454static void syntax_lineno(int line)
Denis Vlasenkob6aae0f2007-01-29 22:51:25 +0000455{
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000456 void (*fp)(const char *s, ...);
457
458 fp = (interactive_fd ? bb_error_msg : bb_error_msg_and_die);
459 fp("syntax error hush.c:%d", line);
Eric Andersen25f27032001-04-26 23:22:31 +0000460}
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000461#define syntax(str) syntax_lineno(__LINE__)
462#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000463
464/* Index of subroutines: */
465/* function prototypes for builtins */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000466static int builtin_cd(char **argv);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000467static int builtin_eval(char **argv);
468static int builtin_exec(char **argv);
469static int builtin_exit(char **argv);
470static int builtin_export(char **argv);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000471#if ENABLE_HUSH_JOB
Denis Vlasenko1359da62007-04-21 23:27:30 +0000472static int builtin_fg_bg(char **argv);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000473static int builtin_jobs(char **argv);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000474#endif
Denis Vlasenko06810332007-05-21 23:30:54 +0000475#if ENABLE_HUSH_HELP
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000476static int builtin_help(char **argv);
Denis Vlasenko06810332007-05-21 23:30:54 +0000477#endif
Denis Vlasenko1359da62007-04-21 23:27:30 +0000478static int builtin_pwd(char **argv);
479static int builtin_read(char **argv);
480static int builtin_set(char **argv);
481static int builtin_shift(char **argv);
482static int builtin_source(char **argv);
483static int builtin_umask(char **argv);
484static int builtin_unset(char **argv);
Denis Vlasenko06810332007-05-21 23:30:54 +0000485//static int builtin_not_written(char **argv);
Eric Andersen25f27032001-04-26 23:22:31 +0000486/* o_string manipulation: */
487static int b_check_space(o_string *o, int len);
488static int b_addchr(o_string *o, int ch);
489static void b_reset(o_string *o);
490static int b_addqchr(o_string *o, int ch, int quote);
Eric Andersen25f27032001-04-26 23:22:31 +0000491/* in_str manipulations: */
492static int static_get(struct in_str *i);
493static int static_peek(struct in_str *i);
494static int file_get(struct in_str *i);
495static int file_peek(struct in_str *i);
496static void setup_file_in_str(struct in_str *i, FILE *f);
497static void setup_string_in_str(struct in_str *i, const char *s);
498/* close_me manipulations: */
499static void mark_open(int fd);
500static void mark_closed(int fd);
Eric Anderseneaecbf32001-10-31 10:41:31 +0000501static void close_all(void);
Eric Andersen25f27032001-04-26 23:22:31 +0000502/* "run" the final data structures: */
Denis Vlasenkoc666f712007-05-16 22:18:54 +0000503#if !defined(DEBUG_CLEAN)
504#define free_pipe_list(head, indent) free_pipe_list(head)
505#define free_pipe(pi, indent) free_pipe(pi)
506#endif
Eric Andersenbf7df042001-05-23 22:18:35 +0000507static int free_pipe_list(struct pipe *head, int indent);
508static int free_pipe(struct pipe *pi, int indent);
Eric Andersen25f27032001-04-26 23:22:31 +0000509/* really run the final data structures: */
510static int setup_redirects(struct child_prog *prog, int squirrel[]);
Eric Andersen25f27032001-04-26 23:22:31 +0000511static int run_list_real(struct pipe *pi);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000512static void pseudo_exec_argv(char **argv) ATTRIBUTE_NORETURN;
Bernhard Reutner-Fischer86f5c992006-01-22 22:55:11 +0000513static void pseudo_exec(struct child_prog *child) ATTRIBUTE_NORETURN;
Eric Andersen25f27032001-04-26 23:22:31 +0000514static int run_pipe_real(struct pipe *pi);
515/* extended glob support: */
516static int globhack(const char *src, int flags, glob_t *pglob);
517static int glob_needed(const char *s);
518static int xglob(o_string *dest, int flags, glob_t *pglob);
Eric Andersen78a7c992001-05-15 16:30:25 +0000519/* variable assignment: */
Eric Andersen78a7c992001-05-15 16:30:25 +0000520static int is_assignment(const char *s);
Eric Andersen25f27032001-04-26 23:22:31 +0000521/* data structure manipulation: */
522static int setup_redirect(struct p_context *ctx, int fd, redir_type style, struct in_str *input);
523static void initialize_context(struct p_context *ctx);
524static int done_word(o_string *dest, struct p_context *ctx);
525static int done_command(struct p_context *ctx);
526static int done_pipe(struct p_context *ctx, pipe_style type);
527/* primary string parsing: */
528static int redirect_dup_num(struct in_str *input);
529static int redirect_opt_num(o_string *o);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +0000530#if ENABLE_HUSH_TICK
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +0000531static 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 +0000532#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000533static int parse_group(o_string *dest, struct p_context *ctx, struct in_str *input, int ch);
Denis Vlasenko15d78fb2007-01-30 22:28:21 +0000534static const char *lookup_param(const char *src);
Eric Andersen25f27032001-04-26 23:22:31 +0000535static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +0000536static 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 +0000537/* setup: */
Denis Vlasenko170435c2007-05-23 13:01:10 +0000538static int parse_and_run_stream(struct in_str *inp, int parse_flag);
539static int parse_and_run_string(const char *s, int parse_flag);
540static int parse_and_run_file(FILE *f);
Eric Andersenbafd94f2001-05-02 16:11:59 +0000541/* job management: */
Eric Andersenc798b072001-06-22 06:23:03 +0000542static int checkjobs(struct pipe* fg_pipe);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000543#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +0000544static int checkjobs_and_fg_shell(struct pipe* fg_pipe);
Eric Andersenbafd94f2001-05-02 16:11:59 +0000545static void insert_bg_job(struct pipe *pi);
546static void remove_bg_job(struct pipe *pi);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000547static void delete_finished_bg_job(struct pipe *pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000548#else
549int checkjobs_and_fg_shell(struct pipe* fg_pipe); /* never called */
550#endif
Eric Andersenf72f5622001-05-15 23:21:41 +0000551/* local variable support */
Denis Vlasenko170435c2007-05-23 13:01:10 +0000552static char **expand_strvec_to_strvec(char **argv);
553/* used for eval */
554static char *expand_strvec_to_string(char **argv);
Denis Vlasenkob6a741f2007-05-17 14:38:17 +0000555/* used for expansion of right hand of assignments */
Denis Vlasenko170435c2007-05-23 13:01:10 +0000556static char *expand_string_to_string(const char *str);
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000557static struct variable *get_local_var(const char *var);
558static int set_local_var(char *s, int flg_export);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +0000559static void unset_local_var(const char *name);
Eric Andersen25f27032001-04-26 23:22:31 +0000560
561/* Table of built-in functions. They can be forked or not, depending on
562 * context: within pipes, they fork. As simple commands, they do not.
563 * When used in non-forking context, they can change global variables
Denis Vlasenkoe1a0d482006-10-20 13:28:22 +0000564 * in the parent shell process. If forked, of course they cannot.
Eric Andersen25f27032001-04-26 23:22:31 +0000565 * For example, 'unset foo | whatever' will parse and run, but foo will
566 * still be set at the end. */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000567struct built_in_command {
568 const char *cmd; /* name */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000569 int (*function) (char **argv); /* function ptr */
Denis Vlasenko06810332007-05-21 23:30:54 +0000570#if ENABLE_HUSH_HELP
571 const char *descr; /* description */
572#define BLTIN(cmd, func, help) { cmd, func, help }
573#else
574#define BLTIN(cmd, func, help) { cmd, func }
575#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000576};
577
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +0000578static const struct built_in_command bltins[] = {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000579#if ENABLE_HUSH_JOB
Denis Vlasenko06810332007-05-21 23:30:54 +0000580 BLTIN("bg" , builtin_fg_bg, "Resume a job in the background"),
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000581#endif
Denis Vlasenko06810332007-05-21 23:30:54 +0000582// BLTIN("break" , builtin_not_written, "Exit for, while or until loop"),
583 BLTIN("cd" , builtin_cd, "Change working directory"),
584// BLTIN("continue", builtin_not_written, "Continue for, while or until loop"),
585 BLTIN("eval" , builtin_eval, "Construct and run shell command"),
586 BLTIN("exec" , builtin_exec, "Exec command, replacing this shell with the exec'd process"),
587 BLTIN("exit" , builtin_exit, "Exit from shell"),
588 BLTIN("export", builtin_export, "Set environment variable"),
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000589#if ENABLE_HUSH_JOB
Denis Vlasenko06810332007-05-21 23:30:54 +0000590 BLTIN("fg" , builtin_fg_bg, "Bring job into the foreground"),
591 BLTIN("jobs" , builtin_jobs, "Lists the active jobs"),
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000592#endif
Denis Vlasenko06810332007-05-21 23:30:54 +0000593// TODO: remove pwd? we have it as an applet...
594 BLTIN("pwd" , builtin_pwd, "Print current directory"),
595 BLTIN("read" , builtin_read, "Input environment variable"),
596// BLTIN("return", builtin_not_written, "Return from a function"),
597 BLTIN("set" , builtin_set, "Set/unset shell local variables"),
598 BLTIN("shift" , builtin_shift, "Shift positional parameters"),
599// BLTIN("trap" , builtin_not_written, "Trap signals"),
600// BLTIN("ulimit", builtin_not_written, "Controls resource limits"),
601 BLTIN("umask" , builtin_umask, "Sets file creation mask"),
602 BLTIN("unset" , builtin_unset, "Unset environment variable"),
603 BLTIN("." , builtin_source, "Source-in and run commands in a file"),
604#if ENABLE_HUSH_HELP
605 BLTIN("help" , builtin_help, "List shell built-in commands"),
606#endif
607 BLTIN(NULL, NULL, NULL)
Eric Andersen25f27032001-04-26 23:22:31 +0000608};
609
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000610#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000611
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000612/* move to libbb? */
613static void signal_SA_RESTART(int sig, void (*handler)(int))
614{
615 struct sigaction sa;
616 sa.sa_handler = handler;
617 sa.sa_flags = SA_RESTART;
618 sigemptyset(&sa.sa_mask);
619 sigaction(sig, &sa, NULL);
620}
621
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000622/* Signals are grouped, we handle them in batches */
623static void set_fatal_sighandler(void (*handler)(int))
624{
625 signal(SIGILL , handler);
626 signal(SIGTRAP, handler);
627 signal(SIGABRT, handler);
628 signal(SIGFPE , handler);
629 signal(SIGBUS , handler);
630 signal(SIGSEGV, handler);
631 /* bash 3.2 seems to handle these just like 'fatal' ones */
632 signal(SIGHUP , handler);
633 signal(SIGPIPE, handler);
634 signal(SIGALRM, handler);
635}
636static void set_jobctrl_sighandler(void (*handler)(int))
637{
638 signal(SIGTSTP, handler);
639 signal(SIGTTIN, handler);
640 signal(SIGTTOU, handler);
641}
642static void set_misc_sighandler(void (*handler)(int))
643{
644 signal(SIGINT , handler);
645 signal(SIGQUIT, handler);
646 signal(SIGTERM, handler);
647}
648/* SIGCHLD is special and handled separately */
649
650static void set_every_sighandler(void (*handler)(int))
651{
652 set_fatal_sighandler(handler);
653 set_jobctrl_sighandler(handler);
654 set_misc_sighandler(handler);
655 signal(SIGCHLD, handler);
656}
657
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000658static void handler_ctrl_c(int sig)
659{
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000660 debug_printf_jobs("got sig %d\n", sig);
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000661// as usual we can have all kinds of nasty problems with leaked malloc data here
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000662 siglongjmp(toplevel_jb, 1);
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000663}
664
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000665static void handler_ctrl_z(int sig)
666{
667 pid_t pid;
668
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000669 debug_printf_jobs("got tty sig %d in pid %d\n", sig, getpid());
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000670 pid = fork();
Denis Vlasenkoc2990322007-05-16 12:57:12 +0000671 if (pid < 0) /* can't fork. Pretend there was no ctrl-Z */
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000672 return;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000673 ctrl_z_flag = 1;
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000674 if (!pid) { /* child */
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000675 setpgrp();
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000676 debug_printf_jobs("set pgrp for child %d ok\n", getpid());
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000677 set_every_sighandler(SIG_DFL);
Denis Vlasenko18e19f22007-04-28 16:43:18 +0000678 raise(SIGTSTP); /* resend TSTP so that child will be stopped */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000679 debug_printf_jobs("returning in child\n");
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000680 /* return to nofork, it will eventually exit now,
681 * not return back to shell */
682 return;
683 }
684 /* parent */
685 /* finish filling up pipe info */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000686 toplevel_list->pgrp = pid; /* child is in its own pgrp */
687 toplevel_list->progs[0].pid = pid;
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000688 /* parent needs to longjmp out of running nofork.
689 * we will "return" exitcode 0, with child put in background */
690// as usual we can have all kinds of nasty problems with leaked malloc data here
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000691 debug_printf_jobs("siglongjmp in parent\n");
692 siglongjmp(toplevel_jb, 1);
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000693}
694
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000695/* Restores tty foreground process group, and exits.
696 * May be called as signal handler for fatal signal
697 * (will faithfully resend signal to itself, producing correct exit state)
698 * or called directly with -EXITCODE.
699 * We also call it if xfunc is exiting. */
700static void sigexit(int sig) ATTRIBUTE_NORETURN;
701static void sigexit(int sig)
702{
703 sigset_t block_all;
704
705 /* Disable all signals: job control, SIGPIPE, etc. */
706 sigfillset(&block_all);
707 sigprocmask(SIG_SETMASK, &block_all, NULL);
708
Denis Vlasenko87cb2db2007-04-21 10:00:01 +0000709 if (interactive_fd)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000710 tcsetpgrp(interactive_fd, saved_tty_pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000711
712 /* Not a signal, just exit */
713 if (sig <= 0)
714 _exit(- sig);
715
716 /* Enable only this sig and kill ourself with it */
717 signal(sig, SIG_DFL);
718 sigdelset(&block_all, sig);
719 sigprocmask(SIG_SETMASK, &block_all, NULL);
720 raise(sig);
721 _exit(1); /* Should not reach it */
722}
723
724/* Restores tty foreground process group, and exits. */
725static void hush_exit(int exitcode) ATTRIBUTE_NORETURN;
726static void hush_exit(int exitcode)
727{
728 fflush(NULL); /* flush all streams */
729 sigexit(- (exitcode & 0xff));
730}
731
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000732#else /* !JOB */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000733
734#define set_fatal_sighandler(handler) ((void)0)
735#define set_jobctrl_sighandler(handler) ((void)0)
736#define set_misc_sighandler(handler) ((void)0)
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000737#define hush_exit(e) exit(e)
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000738
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000739#endif /* JOB */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000740
741
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000742static const char *set_cwd(void)
743{
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000744 if (cwd == bb_msg_unknown)
Denis Vlasenko7cced6e2007-04-12 17:08:53 +0000745 cwd = NULL; /* xrealloc_getcwd_or_warn(arg) calls free(arg)! */
Denis Vlasenko6ca04442007-02-11 16:19:28 +0000746 cwd = xrealloc_getcwd_or_warn((char *)cwd);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000747 if (!cwd)
Manuel Novoa III cad53642003-03-19 09:13:01 +0000748 cwd = bb_msg_unknown;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000749 return cwd;
750}
751
Eric Andersen4c9b68f2002-04-13 12:33:41 +0000752/* built-in 'eval' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000753static int builtin_eval(char **argv)
Eric Andersen4c9b68f2002-04-13 12:33:41 +0000754{
Eric Andersen4c9b68f2002-04-13 12:33:41 +0000755 int rcode = EXIT_SUCCESS;
Eric Andersenc7bda1c2004-03-15 08:29:22 +0000756
Denis Vlasenko1359da62007-04-21 23:27:30 +0000757 if (argv[1]) {
Denis Vlasenko170435c2007-05-23 13:01:10 +0000758 char *str = expand_strvec_to_string(argv + 1);
759 parse_and_run_string(str, PARSEFLAG_EXIT_FROM_LOOP |
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000760 PARSEFLAG_SEMICOLON);
Eric Andersen4c9b68f2002-04-13 12:33:41 +0000761 free(str);
762 rcode = last_return_code;
763 }
764 return rcode;
765}
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000766
Eric Andersen25f27032001-04-26 23:22:31 +0000767/* built-in 'cd <path>' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000768static int builtin_cd(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000769{
Denis Vlasenko170435c2007-05-23 13:01:10 +0000770 const char *newdir;
Denis Vlasenko1359da62007-04-21 23:27:30 +0000771 if (argv[1] == NULL)
Denis Vlasenko170435c2007-05-23 13:01:10 +0000772 newdir = getenv("HOME") ? : "/";
Eric Andersen25f27032001-04-26 23:22:31 +0000773 else
Denis Vlasenko1359da62007-04-21 23:27:30 +0000774 newdir = argv[1];
Eric Andersen25f27032001-04-26 23:22:31 +0000775 if (chdir(newdir)) {
776 printf("cd: %s: %s\n", newdir, strerror(errno));
777 return EXIT_FAILURE;
778 }
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000779 set_cwd();
Eric Andersen25f27032001-04-26 23:22:31 +0000780 return EXIT_SUCCESS;
781}
782
Eric Andersen25f27032001-04-26 23:22:31 +0000783/* built-in 'exec' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000784static int builtin_exec(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000785{
Denis Vlasenko1359da62007-04-21 23:27:30 +0000786 if (argv[1] == NULL)
Eric Andersen25f27032001-04-26 23:22:31 +0000787 return EXIT_SUCCESS; /* Really? */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000788 pseudo_exec_argv(argv + 1);
Eric Andersen25f27032001-04-26 23:22:31 +0000789 /* never returns */
790}
791
792/* built-in 'exit' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000793static int builtin_exit(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000794{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000795// TODO: bash does it ONLY on top-level sh exit (+interacive only?)
796 //puts("exit"); /* bash does it */
Denis Vlasenkof2fffd02007-05-02 23:39:04 +0000797// TODO: warn if we have background jobs: "There are stopped jobs"
798// On second consecutive 'exit', exit anyway.
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000799
Denis Vlasenko1359da62007-04-21 23:27:30 +0000800 if (argv[1] == NULL)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000801 hush_exit(last_return_code);
Denis Vlasenko5f786c22007-04-20 08:35:45 +0000802 /* mimic bash: exit 123abc == exit 255 + error msg */
803 xfunc_error_retval = 255;
804 /* bash: exit -2 == exit 254, no error msg */
Denis Vlasenkof2fffd02007-05-02 23:39:04 +0000805 hush_exit(xatoi(argv[1]) & 0xff);
Eric Andersen25f27032001-04-26 23:22:31 +0000806}
807
808/* built-in 'export VAR=value' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000809static int builtin_export(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000810{
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000811 const char *value;
Denis Vlasenko1359da62007-04-21 23:27:30 +0000812 char *name = argv[1];
Eric Andersen25f27032001-04-26 23:22:31 +0000813
Eric Andersenf72f5622001-05-15 23:21:41 +0000814 if (name == NULL) {
Denis Vlasenkof2fffd02007-05-02 23:39:04 +0000815 // TODO:
816 // ash emits: export VAR='VAL'
817 // bash: declare -x VAR="VAL"
818 // (both also escape as needed (quotes, $, etc))
819 char **e = environ;
820 if (e)
821 while (*e)
822 puts(*e++);
823 return EXIT_SUCCESS;
Eric Andersen25f27032001-04-26 23:22:31 +0000824 }
Eric Andersenf72f5622001-05-15 23:21:41 +0000825
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000826 value = strchr(name, '=');
827 if (!value) {
828 /* They are exporting something without a =VALUE */
829 struct variable *var;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000830
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000831 var = get_local_var(name);
832 if (var) {
833 var->flg_export = 1;
834 putenv(var->name);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000835 }
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000836 /* bash does not return an error when trying to export
837 * an undefined variable. Do likewise. */
838 return EXIT_SUCCESS;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000839 }
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000840
841 set_local_var(xstrdup(name), 1);
842 return EXIT_SUCCESS;
Eric Andersen25f27032001-04-26 23:22:31 +0000843}
844
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000845#if ENABLE_HUSH_JOB
Eric Andersen25f27032001-04-26 23:22:31 +0000846/* built-in 'fg' and 'bg' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000847static int builtin_fg_bg(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000848{
Eric Andersen0fcd4472001-05-02 20:12:03 +0000849 int i, jobnum;
Denis Vlasenko8a28e622007-04-14 11:16:29 +0000850 struct pipe *pi;
Eric Andersen25f27032001-04-26 23:22:31 +0000851
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000852 if (!interactive_fd)
Eric Andersenc798b072001-06-22 06:23:03 +0000853 return EXIT_FAILURE;
Eric Andersen0fcd4472001-05-02 20:12:03 +0000854 /* If they gave us no args, assume they want the last backgrounded task */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000855 if (!argv[1]) {
Eric Andersenc798b072001-06-22 06:23:03 +0000856 for (pi = job_list; pi; pi = pi->next) {
857 if (pi->jobid == last_jobid) {
Denis Vlasenko8a28e622007-04-14 11:16:29 +0000858 goto found;
Eric Andersen0fcd4472001-05-02 20:12:03 +0000859 }
860 }
Denis Vlasenko1359da62007-04-21 23:27:30 +0000861 bb_error_msg("%s: no current job", argv[0]);
Denis Vlasenko8a28e622007-04-14 11:16:29 +0000862 return EXIT_FAILURE;
863 }
Denis Vlasenko1359da62007-04-21 23:27:30 +0000864 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
865 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
Denis Vlasenko8a28e622007-04-14 11:16:29 +0000866 return EXIT_FAILURE;
867 }
868 for (pi = job_list; pi; pi = pi->next) {
869 if (pi->jobid == jobnum) {
870 goto found;
Eric Andersen25f27032001-04-26 23:22:31 +0000871 }
872 }
Denis Vlasenko1359da62007-04-21 23:27:30 +0000873 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
Denis Vlasenko8a28e622007-04-14 11:16:29 +0000874 return EXIT_FAILURE;
875 found:
Denis Vlasenko52881e92007-04-21 13:42:52 +0000876 // TODO: bash prints a string representation
877 // of job being foregrounded (like "sleep 1 | cat")
Denis Vlasenko1359da62007-04-21 23:27:30 +0000878 if (*argv[0] == 'f') {
Eric Andersen028b65b2001-06-28 01:10:11 +0000879 /* Put the job into the foreground. */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000880 tcsetpgrp(interactive_fd, pi->pgrp);
Eric Andersen25f27032001-04-26 23:22:31 +0000881 }
882
883 /* Restart the processes in the job */
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000884 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_progs, pi->pgrp);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000885 for (i = 0; i < pi->num_progs; i++) {
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000886 debug_printf_jobs("reviving pid %d\n", pi->progs[i].pid);
Eric Andersen0fcd4472001-05-02 20:12:03 +0000887 pi->progs[i].is_stopped = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +0000888 }
889 pi->stopped_progs = 0;
Eric Andersen25f27032001-04-26 23:22:31 +0000890
Denis Vlasenkobb81c582007-01-30 22:32:09 +0000891 i = kill(- pi->pgrp, SIGCONT);
892 if (i < 0) {
Denis Vlasenko8a28e622007-04-14 11:16:29 +0000893 if (errno == ESRCH) {
Denis Vlasenko1359da62007-04-21 23:27:30 +0000894 delete_finished_bg_job(pi);
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000895 return EXIT_SUCCESS;
Eric Andersen028b65b2001-06-28 01:10:11 +0000896 } else {
Manuel Novoa III cad53642003-03-19 09:13:01 +0000897 bb_perror_msg("kill (SIGCONT)");
Eric Andersen028b65b2001-06-28 01:10:11 +0000898 }
899 }
Eric Andersen25f27032001-04-26 23:22:31 +0000900
Denis Vlasenko1359da62007-04-21 23:27:30 +0000901 if (*argv[0] == 'f') {
902 remove_bg_job(pi);
Denis Vlasenko52881e92007-04-21 13:42:52 +0000903 return checkjobs_and_fg_shell(pi);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000904 }
Eric Andersen25f27032001-04-26 23:22:31 +0000905 return EXIT_SUCCESS;
906}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000907#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000908
909/* built-in 'help' handler */
Denis Vlasenko06810332007-05-21 23:30:54 +0000910#if ENABLE_HUSH_HELP
Denis Vlasenko1359da62007-04-21 23:27:30 +0000911static int builtin_help(char **argv ATTRIBUTE_UNUSED)
Eric Andersen25f27032001-04-26 23:22:31 +0000912{
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +0000913 const struct built_in_command *x;
Eric Andersen25f27032001-04-26 23:22:31 +0000914
915 printf("\nBuilt-in commands:\n");
916 printf("-------------------\n");
917 for (x = bltins; x->cmd; x++) {
Eric Andersen25f27032001-04-26 23:22:31 +0000918 printf("%s\t%s\n", x->cmd, x->descr);
919 }
920 printf("\n\n");
921 return EXIT_SUCCESS;
922}
Denis Vlasenko06810332007-05-21 23:30:54 +0000923#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000924
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000925#if ENABLE_HUSH_JOB
Eric Andersen25f27032001-04-26 23:22:31 +0000926/* built-in 'jobs' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000927static int builtin_jobs(char **argv ATTRIBUTE_UNUSED)
Eric Andersen25f27032001-04-26 23:22:31 +0000928{
929 struct pipe *job;
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000930 const char *status_string;
Eric Andersen25f27032001-04-26 23:22:31 +0000931
Eric Andersenc798b072001-06-22 06:23:03 +0000932 for (job = job_list; job; job = job->next) {
Eric Andersen25f27032001-04-26 23:22:31 +0000933 if (job->running_progs == job->stopped_progs)
934 status_string = "Stopped";
935 else
936 status_string = "Running";
Eric Andersen52a97ca2001-06-22 06:49:26 +0000937
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000938 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
Eric Andersen25f27032001-04-26 23:22:31 +0000939 }
940 return EXIT_SUCCESS;
941}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000942#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000943
Eric Andersen25f27032001-04-26 23:22:31 +0000944/* built-in 'pwd' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000945static int builtin_pwd(char **argv ATTRIBUTE_UNUSED)
Eric Andersen25f27032001-04-26 23:22:31 +0000946{
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000947 puts(set_cwd());
Eric Andersen25f27032001-04-26 23:22:31 +0000948 return EXIT_SUCCESS;
949}
950
951/* built-in 'read VAR' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000952static int builtin_read(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000953{
Denis Vlasenko3e7b0e62007-05-16 12:52:15 +0000954 char string[BUFSIZ];
955 char *p;
956 const char *name = argv[1] ? argv[1] : "REPLY";
957 int name_len = strlen(name);
Eric Andersen25f27032001-04-26 23:22:31 +0000958
Denis Vlasenko3e7b0e62007-05-16 12:52:15 +0000959 if (name_len >= sizeof(string) - 2)
960 return EXIT_FAILURE;
961 strcpy(string, name);
962 p = string + name_len;
963 *p++ = '=';
964 *p = '\0'; /* In case stdin has only EOF */
965 /* read string. name_len+1 chars are already used by 'name=' */
966 fgets(p, sizeof(string) - 1 - name_len, stdin);
967 chomp(p);
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000968 return set_local_var(xstrdup(string), 0);
Eric Andersen25f27032001-04-26 23:22:31 +0000969}
970
Denis Vlasenko3e7b0e62007-05-16 12:52:15 +0000971/* built-in 'set [VAR=value]' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000972static int builtin_set(char **argv)
Eric Andersenf72f5622001-05-15 23:21:41 +0000973{
Denis Vlasenko1359da62007-04-21 23:27:30 +0000974 char *temp = argv[1];
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000975 struct variable *e;
Eric Andersenf72f5622001-05-15 23:21:41 +0000976
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000977 if (temp == NULL)
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000978 for (e = top_var; e; e = e->next)
979 puts(e->name);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000980 else
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000981 set_local_var(xstrdup(temp), 0);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000982
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000983 return EXIT_SUCCESS;
Eric Andersenf72f5622001-05-15 23:21:41 +0000984}
985
986
Eric Andersen25f27032001-04-26 23:22:31 +0000987/* Built-in 'shift' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000988static int builtin_shift(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000989{
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000990 int n = 1;
Denis Vlasenko1359da62007-04-21 23:27:30 +0000991 if (argv[1]) {
992 n = atoi(argv[1]);
Eric Andersen25f27032001-04-26 23:22:31 +0000993 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000994 if (n >= 0 && n < global_argc) {
Denis Vlasenko004baba2007-05-20 22:22:18 +0000995 global_argv[n] = global_argv[0];
Eric Andersen25f27032001-04-26 23:22:31 +0000996 global_argc -= n;
997 global_argv += n;
998 return EXIT_SUCCESS;
Eric Andersen25f27032001-04-26 23:22:31 +0000999 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001000 return EXIT_FAILURE;
Eric Andersen25f27032001-04-26 23:22:31 +00001001}
1002
1003/* Built-in '.' handler (read-in and execute commands from file) */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001004static int builtin_source(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00001005{
1006 FILE *input;
1007 int status;
1008
Denis Vlasenko1359da62007-04-21 23:27:30 +00001009 if (argv[1] == NULL)
Eric Andersen25f27032001-04-26 23:22:31 +00001010 return EXIT_FAILURE;
1011
1012 /* XXX search through $PATH is missing */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001013 input = fopen(argv[1], "r");
Eric Andersen25f27032001-04-26 23:22:31 +00001014 if (!input) {
Denis Vlasenko1359da62007-04-21 23:27:30 +00001015 bb_error_msg("cannot open '%s'", argv[1]);
Eric Andersen25f27032001-04-26 23:22:31 +00001016 return EXIT_FAILURE;
1017 }
1018
1019 /* Now run the file */
1020 /* XXX argv and argc are broken; need to save old global_argv
1021 * (pointer only is OK!) on this stack frame,
Denis Vlasenko1359da62007-04-21 23:27:30 +00001022 * set global_argv=argv+1, recurse, and restore. */
Eric Andersen25f27032001-04-26 23:22:31 +00001023 mark_open(fileno(input));
Denis Vlasenko170435c2007-05-23 13:01:10 +00001024 status = parse_and_run_file(input);
Eric Andersen25f27032001-04-26 23:22:31 +00001025 mark_closed(fileno(input));
1026 fclose(input);
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00001027 return status;
Eric Andersen25f27032001-04-26 23:22:31 +00001028}
1029
Denis Vlasenko1359da62007-04-21 23:27:30 +00001030static int builtin_umask(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00001031{
Eric Andersen83a2ae22001-05-07 17:59:25 +00001032 mode_t new_umask;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001033 const char *arg = argv[1];
Eric Andersen83a2ae22001-05-07 17:59:25 +00001034 char *end;
1035 if (arg) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001036 new_umask = strtoul(arg, &end, 8);
1037 if (*end != '\0' || end == arg) {
Eric Andersen83a2ae22001-05-07 17:59:25 +00001038 return EXIT_FAILURE;
1039 }
1040 } else {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001041 new_umask = umask(0);
1042 printf("%.3o\n", (unsigned) new_umask);
Eric Andersen83a2ae22001-05-07 17:59:25 +00001043 }
1044 umask(new_umask);
1045 return EXIT_SUCCESS;
Eric Andersen25f27032001-04-26 23:22:31 +00001046}
1047
1048/* built-in 'unset VAR' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001049static int builtin_unset(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00001050{
Denis Vlasenko3e7b0e62007-05-16 12:52:15 +00001051 /* bash always returns true */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001052 unset_local_var(argv[1]);
Eric Andersen25f27032001-04-26 23:22:31 +00001053 return EXIT_SUCCESS;
1054}
1055
Denis Vlasenko06810332007-05-21 23:30:54 +00001056//static int builtin_not_written(char **argv)
1057//{
1058// printf("builtin_%s not written\n", argv[0]);
1059// return EXIT_FAILURE;
1060//}
Eric Andersen83a2ae22001-05-07 17:59:25 +00001061
Eric Andersen25f27032001-04-26 23:22:31 +00001062static int b_check_space(o_string *o, int len)
1063{
1064 /* It would be easy to drop a more restrictive policy
1065 * in here, such as setting a maximum string length */
1066 if (o->length + len > o->maxlen) {
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001067 /* assert(data == NULL || o->maxlen != 0); */
Denis Vlasenkoef36ead2007-05-02 15:34:47 +00001068 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001069 o->data = xrealloc(o->data, 1 + o->maxlen);
Eric Andersen25f27032001-04-26 23:22:31 +00001070 }
1071 return o->data == NULL;
1072}
1073
1074static int b_addchr(o_string *o, int ch)
1075{
Denis Vlasenko831dcc42007-05-16 15:05:36 +00001076 debug_printf("b_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001077 if (b_check_space(o, 1))
1078 return B_NOSPAC;
Eric Andersen25f27032001-04-26 23:22:31 +00001079 o->data[o->length] = ch;
1080 o->length++;
1081 o->data[o->length] = '\0';
1082 return 0;
1083}
1084
1085static void b_reset(o_string *o)
1086{
1087 o->length = 0;
1088 o->nonnull = 0;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001089 if (o->data != NULL)
1090 *o->data = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001091}
1092
1093static void b_free(o_string *o)
1094{
1095 b_reset(o);
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00001096 free(o->data);
Eric Andersen25f27032001-04-26 23:22:31 +00001097 o->data = NULL;
1098 o->maxlen = 0;
1099}
1100
1101/* My analysis of quoting semantics tells me that state information
1102 * is associated with a destination, not a source.
1103 */
1104static int b_addqchr(o_string *o, int ch, int quote)
1105{
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00001106 if (quote && strchr("*?[\\", ch)) {
Eric Andersen25f27032001-04-26 23:22:31 +00001107 int rc;
1108 rc = b_addchr(o, '\\');
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001109 if (rc)
1110 return rc;
Eric Andersen25f27032001-04-26 23:22:31 +00001111 }
1112 return b_addchr(o, ch);
1113}
1114
Eric Andersen25f27032001-04-26 23:22:31 +00001115static int static_get(struct in_str *i)
1116{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001117 int ch = *i->p++;
1118 if (ch == '\0') return EOF;
Eric Andersen25f27032001-04-26 23:22:31 +00001119 return ch;
1120}
1121
1122static int static_peek(struct in_str *i)
1123{
1124 return *i->p;
1125}
1126
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001127#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001128#if ENABLE_FEATURE_EDITING
Rob Landley88621d72006-08-29 19:41:06 +00001129static void cmdedit_set_initial_prompt(void)
Eric Andersen25f27032001-04-26 23:22:31 +00001130{
Denis Vlasenko38f63192007-01-22 09:03:07 +00001131#if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
Eric Andersen25f27032001-04-26 23:22:31 +00001132 PS1 = NULL;
1133#else
1134 PS1 = getenv("PS1");
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001135 if (PS1 == NULL)
Eric Andersen25f27032001-04-26 23:22:31 +00001136 PS1 = "\\w \\$ ";
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001137#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001138}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001139#endif /* EDITING */
Eric Andersen25f27032001-04-26 23:22:31 +00001140
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001141static const char* setup_prompt_string(int promptmode)
Eric Andersen25f27032001-04-26 23:22:31 +00001142{
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001143 const char *prompt_str;
1144 debug_printf("setup_prompt_string %d ", promptmode);
Denis Vlasenko38f63192007-01-22 09:03:07 +00001145#if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
Eric Andersen25f27032001-04-26 23:22:31 +00001146 /* Set up the prompt */
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001147 if (promptmode == 0) { /* PS1 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001148 free((char*)PS1);
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001149 PS1 = xasprintf("%s %c ", cwd, (geteuid() != 0) ? '$' : '#');
1150 prompt_str = PS1;
Eric Andersen25f27032001-04-26 23:22:31 +00001151 } else {
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001152 prompt_str = PS2;
Eric Andersen25f27032001-04-26 23:22:31 +00001153 }
1154#else
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001155 prompt_str = (promptmode == 0) ? PS1 : PS2;
Eric Andersenaf44a0e2001-04-27 07:26:12 +00001156#endif
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001157 debug_printf("result '%s'\n", prompt_str);
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001158 return prompt_str;
Eric Andersen25f27032001-04-26 23:22:31 +00001159}
1160
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001161static void get_user_input(struct in_str *i)
Eric Andersen25f27032001-04-26 23:22:31 +00001162{
Denis Vlasenko0937be52007-04-28 16:47:08 +00001163 int r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001164 const char *prompt_str;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001165
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001166 prompt_str = setup_prompt_string(i->promptmode);
Denis Vlasenko38f63192007-01-22 09:03:07 +00001167#if ENABLE_FEATURE_EDITING
Denis Vlasenko170435c2007-05-23 13:01:10 +00001168 /* Enable command line editing only while a command line
1169 * is actually being read; otherwise, we'll end up bequeathing
1170 * atexit() handlers and other unwanted stuff to our
1171 * child processes (rob@sysgo.de) */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001172 r = read_line_input(prompt_str, user_input_buf, BUFSIZ-1, line_input_state);
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001173 i->eof_flag = (r < 0);
1174 if (i->eof_flag) { /* EOF/error detected */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001175 user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1176 user_input_buf[1] = '\0';
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001177 }
Eric Andersen25f27032001-04-26 23:22:31 +00001178#else
1179 fputs(prompt_str, stdout);
1180 fflush(stdout);
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001181 user_input_buf[0] = r = fgetc(i->file);
1182 /*user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001183 i->eof_flag = (r == EOF);
Eric Andersen25f27032001-04-26 23:22:31 +00001184#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001185 i->p = user_input_buf;
Eric Andersen25f27032001-04-26 23:22:31 +00001186}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001187#endif /* INTERACTIVE */
Eric Andersen25f27032001-04-26 23:22:31 +00001188
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001189/* This is the magic location that prints prompts
Eric Andersen25f27032001-04-26 23:22:31 +00001190 * and gets data back from the user */
1191static int file_get(struct in_str *i)
1192{
1193 int ch;
1194
Eric Andersen25f27032001-04-26 23:22:31 +00001195 /* If there is data waiting, eat it up */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001196 if (i->p && *i->p) {
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001197#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001198 take_cached:
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001199#endif
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001200 ch = *i->p++;
1201 if (i->eof_flag && !*i->p)
1202 ch = EOF;
Eric Andersen25f27032001-04-26 23:22:31 +00001203 } else {
1204 /* need to double check i->file because we might be doing something
1205 * more complicated by now, like sourcing or substituting. */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001206#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001207 if (interactive_fd && i->promptme && i->file == stdin) {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001208 do {
1209 get_user_input(i);
1210 } while (!*i->p); /* need non-empty line */
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001211 i->promptmode = 1; /* PS2 */
1212 i->promptme = 0;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001213 goto take_cached;
Eric Andersen25f27032001-04-26 23:22:31 +00001214 }
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001215#endif
1216 ch = fgetc(i->file);
Eric Andersen25f27032001-04-26 23:22:31 +00001217 }
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001218 debug_printf("file_get: got a '%c' %d\n", ch, ch);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001219#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001220 if (ch == '\n')
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001221 i->promptme = 1;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001222#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001223 return ch;
1224}
1225
1226/* All the callers guarantee this routine will never be
1227 * used right after a newline, so prompting is not needed.
1228 */
1229static int file_peek(struct in_str *i)
1230{
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00001231 int ch;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001232 if (i->p && *i->p) {
1233 if (i->eof_flag && !i->p[1])
1234 return EOF;
1235 return *i->p;
Eric Andersen25f27032001-04-26 23:22:31 +00001236 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00001237 ch = fgetc(i->file);
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001238 i->eof_flag = (ch == EOF);
1239 i->peek_buf[0] = ch;
1240 i->peek_buf[1] = '\0';
1241 i->p = i->peek_buf;
1242 debug_printf("file_peek: got a '%c' %d\n", *i->p, *i->p);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00001243 return ch;
Eric Andersen25f27032001-04-26 23:22:31 +00001244}
1245
1246static void setup_file_in_str(struct in_str *i, FILE *f)
1247{
1248 i->peek = file_peek;
1249 i->get = file_get;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001250#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001251 i->promptme = 1;
1252 i->promptmode = 0; /* PS1 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001253#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001254 i->file = f;
1255 i->p = NULL;
1256}
1257
1258static void setup_string_in_str(struct in_str *i, const char *s)
1259{
1260 i->peek = static_peek;
1261 i->get = static_get;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001262#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001263 i->promptme = 1;
1264 i->promptmode = 0; /* PS1 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001265#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001266 i->p = s;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001267 i->eof_flag = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00001268}
1269
1270static void mark_open(int fd)
1271{
1272 struct close_me *new = xmalloc(sizeof(struct close_me));
1273 new->fd = fd;
1274 new->next = close_me_head;
1275 close_me_head = new;
1276}
1277
1278static void mark_closed(int fd)
1279{
1280 struct close_me *tmp;
1281 if (close_me_head == NULL || close_me_head->fd != fd)
Manuel Novoa III cad53642003-03-19 09:13:01 +00001282 bb_error_msg_and_die("corrupt close_me");
Eric Andersen25f27032001-04-26 23:22:31 +00001283 tmp = close_me_head;
1284 close_me_head = close_me_head->next;
1285 free(tmp);
1286}
1287
Eric Anderseneaecbf32001-10-31 10:41:31 +00001288static void close_all(void)
Eric Andersen25f27032001-04-26 23:22:31 +00001289{
1290 struct close_me *c;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001291 for (c = close_me_head; c; c = c->next) {
Eric Andersen25f27032001-04-26 23:22:31 +00001292 close(c->fd);
1293 }
1294 close_me_head = NULL;
1295}
1296
1297/* squirrel != NULL means we squirrel away copies of stdin, stdout,
1298 * and stderr if they are redirected. */
1299static int setup_redirects(struct child_prog *prog, int squirrel[])
1300{
1301 int openfd, mode;
1302 struct redir_struct *redir;
1303
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001304 for (redir = prog->redirects; redir; redir = redir->next) {
Eric Andersen817e73c2001-06-06 17:56:09 +00001305 if (redir->dup == -1 && redir->word.gl_pathv == NULL) {
1306 /* something went wrong in the parse. Pretend it didn't happen */
1307 continue;
1308 }
Eric Andersen25f27032001-04-26 23:22:31 +00001309 if (redir->dup == -1) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001310 mode = redir_table[redir->type].mode;
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001311 openfd = open_or_warn(redir->word.gl_pathv[0], mode);
Eric Andersen25f27032001-04-26 23:22:31 +00001312 if (openfd < 0) {
1313 /* this could get lost if stderr has been redirected, but
1314 bash and ash both lose it as well (though zsh doesn't!) */
Eric Andersen25f27032001-04-26 23:22:31 +00001315 return 1;
1316 }
1317 } else {
1318 openfd = redir->dup;
1319 }
1320
1321 if (openfd != redir->fd) {
1322 if (squirrel && redir->fd < 3) {
1323 squirrel[redir->fd] = dup(redir->fd);
1324 }
Eric Andersen83a2ae22001-05-07 17:59:25 +00001325 if (openfd == -3) {
1326 close(openfd);
1327 } else {
1328 dup2(openfd, redir->fd);
Matt Kraaic616e532001-06-05 16:50:08 +00001329 if (redir->dup == -1)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001330 close(openfd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00001331 }
Eric Andersen25f27032001-04-26 23:22:31 +00001332 }
1333 }
1334 return 0;
1335}
1336
1337static void restore_redirects(int squirrel[])
1338{
1339 int i, fd;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001340 for (i = 0; i < 3; i++) {
Eric Andersen25f27032001-04-26 23:22:31 +00001341 fd = squirrel[i];
1342 if (fd != -1) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00001343 /* We simply die on error */
1344 xmove_fd(fd, i);
Eric Andersen25f27032001-04-26 23:22:31 +00001345 }
1346 }
1347}
1348
Eric Andersenada18ff2001-05-21 16:18:22 +00001349/* never returns */
Eric Andersen94ac2442001-05-22 19:05:18 +00001350/* XXX no exit() here. If you don't exec, use _exit instead.
1351 * The at_exit handlers apparently confuse the calling process,
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001352 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001353static void pseudo_exec_argv(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00001354{
Eric Andersen78a7c992001-05-15 16:30:25 +00001355 int i, rcode;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001356 char *p;
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +00001357 const struct built_in_command *x;
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001358
Denis Vlasenko1359da62007-04-21 23:27:30 +00001359 for (i = 0; is_assignment(argv[i]); i++) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001360 debug_printf_exec("pid %d environment modification: %s\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001361 getpid(), argv[i]);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001362// FIXME: vfork case??
Denis Vlasenko170435c2007-05-23 13:01:10 +00001363 p = expand_string_to_string(argv[i]);
1364 putenv(p);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001365 }
1366 argv += i;
1367 /* If a variable is assigned in a forest, and nobody listens,
1368 * was it ever really set?
1369 */
1370 if (argv[0] == NULL) {
1371 _exit(EXIT_SUCCESS);
1372 }
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001373
Denis Vlasenko170435c2007-05-23 13:01:10 +00001374 argv = expand_strvec_to_strvec(argv);
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001375
Denis Vlasenko1359da62007-04-21 23:27:30 +00001376 /*
1377 * Check if the command matches any of the builtins.
1378 * Depending on context, this might be redundant. But it's
1379 * easier to waste a few CPU cycles than it is to figure out
1380 * if this is one of those cases.
1381 */
1382 for (x = bltins; x->cmd; x++) {
1383 if (strcmp(argv[0], x->cmd) == 0) {
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001384 debug_printf_exec("running builtin '%s'\n", argv[0]);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001385 rcode = x->function(argv);
1386 fflush(stdout);
1387 _exit(rcode);
Eric Andersen94ac2442001-05-22 19:05:18 +00001388 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00001389 }
Eric Andersen78a7c992001-05-15 16:30:25 +00001390
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001391 /* Check if the command matches any busybox applets */
Denis Vlasenko80d14be2007-04-10 23:03:30 +00001392#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001393 if (strchr(argv[0], '/') == NULL) {
1394 const struct bb_applet *a = find_applet_by_name(argv[0]);
1395 if (a) {
1396 if (a->noexec) {
1397 current_applet = a;
1398 debug_printf_exec("running applet '%s'\n", argv[0]);
1399// is it ok that run_current_applet_and_exit() does exit(), not _exit()?
1400 run_current_applet_and_exit(argv);
1401 }
1402 /* re-exec ourselves with the new arguments */
1403 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
1404 execvp(CONFIG_BUSYBOX_EXEC_PATH, argv);
1405 /* If they called chroot or otherwise made the binary no longer
1406 * executable, fall through */
1407 }
1408 }
Eric Andersenaac75e52001-04-30 18:18:45 +00001409#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001410
1411 debug_printf_exec("execing '%s'\n", argv[0]);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001412 execvp(argv[0], argv);
1413 bb_perror_msg("cannot exec '%s'", argv[0]);
1414 _exit(1);
1415}
1416
1417static void pseudo_exec(struct child_prog *child)
1418{
Denis Vlasenkof2fffd02007-05-02 23:39:04 +00001419// FIXME: buggy wrt NOMMU! Must not modify any global data
1420// until it does exec/_exit, but currently it does.
Denis Vlasenko1359da62007-04-21 23:27:30 +00001421 int rcode;
1422
1423 if (child->argv) {
1424 pseudo_exec_argv(child->argv);
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001425 }
1426
1427 if (child->group) {
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001428 // FIXME: do not modify globals! Think vfork!
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001429#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001430 debug_printf_exec("pseudo_exec: setting interactive_fd=0\n");
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001431 interactive_fd = 0; /* crucial!!!! */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001432#endif
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001433 debug_printf_exec("pseudo_exec: run_list_real\n");
Eric Andersen25f27032001-04-26 23:22:31 +00001434 rcode = run_list_real(child->group);
Eric Andersenbf7df042001-05-23 22:18:35 +00001435 /* OK to leak memory by not calling free_pipe_list,
Eric Andersen25f27032001-04-26 23:22:31 +00001436 * since this process is about to exit */
Eric Andersen94ac2442001-05-22 19:05:18 +00001437 _exit(rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00001438 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001439
1440 /* Can happen. See what bash does with ">foo" by itself. */
1441 debug_printf("trying to pseudo_exec null command\n");
1442 _exit(EXIT_SUCCESS);
Eric Andersen25f27032001-04-26 23:22:31 +00001443}
1444
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001445#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001446static const char *get_cmdtext(struct pipe *pi)
1447{
1448 char **argv;
1449 char *p;
1450 int len;
1451
1452 /* This is subtle. ->cmdtext is created only on first backgrounding.
1453 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001454 * On subsequent bg argv is trashed, but we won't use it */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001455 if (pi->cmdtext)
1456 return pi->cmdtext;
1457 argv = pi->progs[0].argv;
1458 if (!argv || !argv[0])
1459 return (pi->cmdtext = xzalloc(1));
1460
1461 len = 0;
1462 do len += strlen(*argv) + 1; while (*++argv);
1463 pi->cmdtext = p = xmalloc(len);
1464 argv = pi->progs[0].argv;
1465 do {
1466 len = strlen(*argv);
1467 memcpy(p, *argv, len);
1468 p += len;
1469 *p++ = ' ';
1470 } while (*++argv);
1471 p[-1] = '\0';
1472 return pi->cmdtext;
1473}
1474
Eric Andersenbafd94f2001-05-02 16:11:59 +00001475static void insert_bg_job(struct pipe *pi)
1476{
1477 struct pipe *thejob;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001478 int i;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001479
1480 /* Linear search for the ID of the job to use */
1481 pi->jobid = 1;
Eric Andersenc798b072001-06-22 06:23:03 +00001482 for (thejob = job_list; thejob; thejob = thejob->next)
Eric Andersenbafd94f2001-05-02 16:11:59 +00001483 if (thejob->jobid >= pi->jobid)
1484 pi->jobid = thejob->jobid + 1;
1485
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001486 /* Add thejob to the list of running jobs */
Eric Andersenc798b072001-06-22 06:23:03 +00001487 if (!job_list) {
Eric Andersen52a97ca2001-06-22 06:49:26 +00001488 thejob = job_list = xmalloc(sizeof(*thejob));
Eric Andersenbafd94f2001-05-02 16:11:59 +00001489 } else {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001490 for (thejob = job_list; thejob->next; thejob = thejob->next)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001491 continue;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001492 thejob->next = xmalloc(sizeof(*thejob));
1493 thejob = thejob->next;
1494 }
1495
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001496 /* Physically copy the struct job */
Eric Andersen0fcd4472001-05-02 20:12:03 +00001497 memcpy(thejob, pi, sizeof(struct pipe));
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001498 thejob->progs = xzalloc(sizeof(pi->progs[0]) * pi->num_progs);
1499 /* We cannot copy entire pi->progs[] vector! Double free()s will happen */
1500 for (i = 0; i < pi->num_progs; i++) {
1501// TODO: do we really need to have so many fields which are just dead weight
1502// at execution stage?
1503 thejob->progs[i].pid = pi->progs[i].pid;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001504 /* all other fields are not used and stay zero */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001505 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00001506 thejob->next = NULL;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001507 thejob->cmdtext = xstrdup(get_cmdtext(pi));
Eric Andersenbafd94f2001-05-02 16:11:59 +00001508
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001509 /* We don't wait for background thejobs to return -- append it
Eric Andersenbafd94f2001-05-02 16:11:59 +00001510 to the list of backgrounded thejobs and leave it alone */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001511 printf("[%d] %d %s\n", thejob->jobid, thejob->progs[0].pid, thejob->cmdtext);
Eric Andersen1a6d39b2001-05-08 05:11:54 +00001512 last_bg_pid = thejob->progs[0].pid;
Eric Andersenc798b072001-06-22 06:23:03 +00001513 last_jobid = thejob->jobid;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001514}
1515
Eric Andersenbafd94f2001-05-02 16:11:59 +00001516static void remove_bg_job(struct pipe *pi)
1517{
1518 struct pipe *prev_pipe;
1519
Eric Andersenc798b072001-06-22 06:23:03 +00001520 if (pi == job_list) {
Eric Andersen52a97ca2001-06-22 06:49:26 +00001521 job_list = pi->next;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001522 } else {
Eric Andersenc798b072001-06-22 06:23:03 +00001523 prev_pipe = job_list;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001524 while (prev_pipe->next != pi)
1525 prev_pipe = prev_pipe->next;
1526 prev_pipe->next = pi->next;
1527 }
Eric Andersen028b65b2001-06-28 01:10:11 +00001528 if (job_list)
1529 last_jobid = job_list->jobid;
1530 else
1531 last_jobid = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001532}
Eric Andersen028b65b2001-06-28 01:10:11 +00001533
Denis Vlasenko1359da62007-04-21 23:27:30 +00001534/* remove a backgrounded job */
1535static void delete_finished_bg_job(struct pipe *pi)
1536{
1537 remove_bg_job(pi);
Eric Andersen52a97ca2001-06-22 06:49:26 +00001538 pi->stopped_progs = 0;
Eric Andersenbf7df042001-05-23 22:18:35 +00001539 free_pipe(pi, 0);
Eric Andersenbafd94f2001-05-02 16:11:59 +00001540 free(pi);
1541}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001542#endif /* JOB */
Eric Andersenbafd94f2001-05-02 16:11:59 +00001543
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001544/* Checks to see if any processes have exited -- if they
Eric Andersenbafd94f2001-05-02 16:11:59 +00001545 have, figure out why and see if a job has completed */
Eric Andersenc798b072001-06-22 06:23:03 +00001546static int checkjobs(struct pipe* fg_pipe)
Eric Andersenbafd94f2001-05-02 16:11:59 +00001547{
Eric Andersenc798b072001-06-22 06:23:03 +00001548 int attributes;
1549 int status;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001550#if ENABLE_HUSH_JOB
Eric Andersenbafd94f2001-05-02 16:11:59 +00001551 int prognum = 0;
1552 struct pipe *pi;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001553#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00001554 pid_t childpid;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001555 int rcode = 0;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001556
Eric Andersenc798b072001-06-22 06:23:03 +00001557 attributes = WUNTRACED;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001558 if (fg_pipe == NULL) {
Eric Andersenc798b072001-06-22 06:23:03 +00001559 attributes |= WNOHANG;
1560 }
1561
Denis Vlasenko1359da62007-04-21 23:27:30 +00001562/* Do we do this right?
1563 * bash-3.00# sleep 20 | false
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001564 * <ctrl-Z pressed>
Denis Vlasenko1359da62007-04-21 23:27:30 +00001565 * [3]+ Stopped sleep 20 | false
1566 * bash-3.00# echo $?
1567 * 1 <========== bg pipe is not fully done, but exitcode is already known!
1568 */
1569
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001570//FIXME: non-interactive bash does not continue even if all processes in fg pipe
1571//are stopped. Testcase: "cat | cat" in a script (not on command line)
1572// + killall -STOP cat
1573
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001574 wait_more:
Eric Andersenc798b072001-06-22 06:23:03 +00001575 while ((childpid = waitpid(-1, &status, attributes)) > 0) {
Denis Vlasenko1359da62007-04-21 23:27:30 +00001576 const int dead = WIFEXITED(status) || WIFSIGNALED(status);
1577
1578#ifdef DEBUG_SHELL_JOBS
1579 if (WIFSTOPPED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001580 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001581 childpid, WSTOPSIG(status), WEXITSTATUS(status));
1582 if (WIFSIGNALED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001583 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001584 childpid, WTERMSIG(status), WEXITSTATUS(status));
1585 if (WIFEXITED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001586 debug_printf_jobs("pid %d exited, exitcode %d\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001587 childpid, WEXITSTATUS(status));
1588#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001589 /* Were we asked to wait for fg pipe? */
Eric Andersenc798b072001-06-22 06:23:03 +00001590 if (fg_pipe) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001591 int i;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001592 for (i = 0; i < fg_pipe->num_progs; i++) {
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001593 debug_printf_jobs("check pid %d\n", fg_pipe->progs[i].pid);
Eric Andersenc798b072001-06-22 06:23:03 +00001594 if (fg_pipe->progs[i].pid == childpid) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001595 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001596 if (dead) {
1597 fg_pipe->progs[i].pid = 0;
1598 fg_pipe->running_progs--;
1599 if (i == fg_pipe->num_progs-1)
1600 /* last process gives overall exitstatus */
1601 rcode = WEXITSTATUS(status);
1602 } else {
1603 fg_pipe->progs[i].is_stopped = 1;
1604 fg_pipe->stopped_progs++;
1605 }
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001606 debug_printf_jobs("fg_pipe: running_progs %d stopped_progs %d\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001607 fg_pipe->running_progs, fg_pipe->stopped_progs);
1608 if (fg_pipe->running_progs - fg_pipe->stopped_progs <= 0) {
1609 /* All processes in fg pipe have exited/stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001610#if ENABLE_HUSH_JOB
Denis Vlasenko1359da62007-04-21 23:27:30 +00001611 if (fg_pipe->running_progs)
1612 insert_bg_job(fg_pipe);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001613#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001614 return rcode;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001615 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001616 /* There are still running processes in the fg pipe */
1617 goto wait_more;
Eric Andersenc798b072001-06-22 06:23:03 +00001618 }
1619 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00001620 /* fall through to searching process in bg pipes */
Eric Andersenc798b072001-06-22 06:23:03 +00001621 }
1622
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001623#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001624 /* We asked to wait for bg or orphaned children */
1625 /* No need to remember exitcode in this case */
Eric Andersenc798b072001-06-22 06:23:03 +00001626 for (pi = job_list; pi; pi = pi->next) {
Eric Andersenbafd94f2001-05-02 16:11:59 +00001627 prognum = 0;
Denis Vlasenko5f786c22007-04-20 08:35:45 +00001628 while (prognum < pi->num_progs) {
1629 if (pi->progs[prognum].pid == childpid)
1630 goto found_pi_and_prognum;
Eric Andersen52a97ca2001-06-22 06:49:26 +00001631 prognum++;
1632 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00001633 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001634#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00001635
Denis Vlasenko5f786c22007-04-20 08:35:45 +00001636 /* Happens when shell is used as init process (init=/bin/sh) */
1637 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001638 goto wait_more;
Eric Andersenaeb44c42001-05-22 20:29:00 +00001639
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001640#if ENABLE_HUSH_JOB
Denis Vlasenko5f786c22007-04-20 08:35:45 +00001641 found_pi_and_prognum:
Denis Vlasenko1359da62007-04-21 23:27:30 +00001642 if (dead) {
Eric Andersenbafd94f2001-05-02 16:11:59 +00001643 /* child exited */
Eric Andersenbafd94f2001-05-02 16:11:59 +00001644 pi->progs[prognum].pid = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001645 pi->running_progs--;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001646 if (!pi->running_progs) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001647 printf(JOB_STATUS_FORMAT, pi->jobid,
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001648 "Done", pi->cmdtext);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001649 delete_finished_bg_job(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00001650 }
1651 } else {
1652 /* child stopped */
1653 pi->stopped_progs++;
1654 pi->progs[prognum].is_stopped = 1;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001655 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001656#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00001657 }
1658
Denis Vlasenko1359da62007-04-21 23:27:30 +00001659 /* wait found no children or failed */
1660
1661 if (childpid && errno != ECHILD)
Manuel Novoa III cad53642003-03-19 09:13:01 +00001662 bb_perror_msg("waitpid");
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001663 return rcode;
Eric Andersenada18ff2001-05-21 16:18:22 +00001664}
1665
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001666#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +00001667static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
1668{
1669 pid_t p;
1670 int rcode = checkjobs(fg_pipe);
1671 /* Job finished, move the shell to the foreground */
Denis Vlasenko170435c2007-05-23 13:01:10 +00001672 p = getpgid(0); /* pgid of our process */
1673 debug_printf_jobs("fg'ing ourself: getpgid(0)=%d\n", (int)p);
Denis Vlasenko52881e92007-04-21 13:42:52 +00001674 if (tcsetpgrp(interactive_fd, p) && errno != ENOTTY)
1675 bb_perror_msg("tcsetpgrp-4a");
1676 return rcode;
1677}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001678#endif
Denis Vlasenko52881e92007-04-21 13:42:52 +00001679
Eric Andersen25f27032001-04-26 23:22:31 +00001680/* run_pipe_real() starts all the jobs, but doesn't wait for anything
Eric Andersenc798b072001-06-22 06:23:03 +00001681 * to finish. See checkjobs().
Eric Andersen25f27032001-04-26 23:22:31 +00001682 *
1683 * return code is normally -1, when the caller has to wait for children
1684 * to finish to determine the exit status of the pipe. If the pipe
1685 * is a simple builtin command, however, the action is done by the
1686 * time run_pipe_real returns, and the exit code is provided as the
1687 * return value.
1688 *
1689 * The input of the pipe is always stdin, the output is always
1690 * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
1691 * because it tries to avoid running the command substitution in
1692 * subshell, when that is in fact necessary. The subshell process
1693 * now has its stdout directed to the input of the appropriate pipe,
1694 * so this routine is noticeably simpler.
Denis Vlasenko170435c2007-05-23 13:01:10 +00001695 *
1696 * Returns -1 only if started some children. IOW: we have to
1697 * mask out retvals of builtins etc with 0xff!
Eric Andersen25f27032001-04-26 23:22:31 +00001698 */
1699static int run_pipe_real(struct pipe *pi)
1700{
1701 int i;
1702 int nextin, nextout;
1703 int pipefds[2]; /* pipefds[0] is for reading */
Rob Landley53702e52006-07-19 21:43:53 +00001704 struct child_prog *child;
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +00001705 const struct built_in_command *x;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001706 char *p;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001707 /* it is not always needed, but we aim to smaller code */
1708 int squirrel[] = { -1, -1, -1 };
1709 int rcode;
Denis Vlasenko52881e92007-04-21 13:42:52 +00001710 const int single_fg = (pi->num_progs == 1 && pi->followup != PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00001711
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001712 debug_printf_exec("run_pipe_real start: single_fg=%d\n", single_fg);
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00001713
Eric Andersen25f27032001-04-26 23:22:31 +00001714 nextin = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001715#if ENABLE_HUSH_JOB
Eric Andersenada18ff2001-05-21 16:18:22 +00001716 pi->pgrp = -1;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001717#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001718 pi->running_progs = 1;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001719 pi->stopped_progs = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00001720
1721 /* Check if this is a simple builtin (not part of a pipe).
1722 * Builtins within pipes have to fork anyway, and are handled in
1723 * pseudo_exec. "echo foo | read bar" doesn't work on bash, either.
1724 */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001725 child = &(pi->progs[0]);
Denis Vlasenko52881e92007-04-21 13:42:52 +00001726 if (single_fg && child->group && child->subshell == 0) {
Eric Andersen04407e52001-06-07 16:42:05 +00001727 debug_printf("non-subshell grouping\n");
1728 setup_redirects(child, squirrel);
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001729 debug_printf_exec(": run_list_real\n");
Eric Andersen04407e52001-06-07 16:42:05 +00001730 rcode = run_list_real(child->group);
1731 restore_redirects(squirrel);
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001732 debug_printf_exec("run_pipe_real return %d\n", rcode);
Denis Vlasenko170435c2007-05-23 13:01:10 +00001733 return rcode; // do we need to add '... & 0xff' ?
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001734 }
1735
Denis Vlasenko1359da62007-04-21 23:27:30 +00001736 if (single_fg && child->argv != NULL) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001737 char **argv_expanded;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001738 char **argv = child->argv;
1739
1740 for (i = 0; is_assignment(argv[i]); i++)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001741 continue;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001742 if (i != 0 && argv[i] == NULL) {
Eric Andersen78a7c992001-05-15 16:30:25 +00001743 /* assignments, but no command: set the local environment */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001744 for (i = 0; argv[i] != NULL; i++) {
Denis Vlasenkod76c0492007-05-25 02:16:25 +00001745 debug_printf("local environment set: %s\n", argv[i]);
Denis Vlasenko170435c2007-05-23 13:01:10 +00001746 p = expand_string_to_string(argv[i]);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00001747 set_local_var(p, 0);
Eric Andersen78a7c992001-05-15 16:30:25 +00001748 }
1749 return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
1750 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00001751 for (i = 0; is_assignment(argv[i]); i++) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00001752 p = expand_string_to_string(argv[i]);
1753 //sp: child->sp--;
1754 putenv(p);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001755 }
Eric Andersen25f27032001-04-26 23:22:31 +00001756 for (x = bltins; x->cmd; x++) {
Denis Vlasenko1359da62007-04-21 23:27:30 +00001757 if (strcmp(argv[i], x->cmd) == 0) {
1758 if (x->function == builtin_exec && argv[i+1] == NULL) {
Eric Andersen83a2ae22001-05-07 17:59:25 +00001759 debug_printf("magic exec\n");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001760 setup_redirects(child, NULL);
Eric Andersen83a2ae22001-05-07 17:59:25 +00001761 return EXIT_SUCCESS;
1762 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00001763 debug_printf("builtin inline %s\n", argv[0]);
Eric Andersen25f27032001-04-26 23:22:31 +00001764 /* XXX setup_redirects acts on file descriptors, not FILEs.
1765 * This is perfect for work that comes after exec().
1766 * Is it really safe for inline use? Experimentally,
1767 * things seem to work with glibc. */
1768 setup_redirects(child, squirrel);
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001769 debug_printf_exec(": builtin '%s' '%s'...\n", x->cmd, argv[i+1]);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001770 //sp: if (child->sp) /* btw we can do it unconditionally... */
Denis Vlasenko170435c2007-05-23 13:01:10 +00001771 argv_expanded = expand_strvec_to_strvec(argv + i);
1772 rcode = x->function(argv_expanded) & 0xff;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001773 free(argv_expanded);
Eric Andersen25f27032001-04-26 23:22:31 +00001774 restore_redirects(squirrel);
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001775 debug_printf_exec("run_pipe_real return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00001776 return rcode;
1777 }
1778 }
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001779#if ENABLE_FEATURE_SH_STANDALONE
1780 {
Denis Vlasenko1359da62007-04-21 23:27:30 +00001781 const struct bb_applet *a = find_applet_by_name(argv[i]);
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001782 if (a && a->nofork) {
1783 setup_redirects(child, squirrel);
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001784 save_nofork_data(&nofork_save);
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001785 argv_expanded = argv + i;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001786 //sp: if (child->sp)
Denis Vlasenko170435c2007-05-23 13:01:10 +00001787 argv_expanded = expand_strvec_to_strvec(argv + i);
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001788 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n", argv_expanded[0], argv_expanded[1]);
Denis Vlasenko170435c2007-05-23 13:01:10 +00001789 rcode = run_nofork_applet_prime(&nofork_save, a, argv_expanded) & 0xff;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001790 free(argv_expanded);
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001791 restore_redirects(squirrel);
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001792 debug_printf_exec("run_pipe_real return %d\n", rcode);
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001793 return rcode;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001794 }
1795 }
1796#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001797 }
1798
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001799 /* Going to fork a child per each pipe member */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001800 pi->running_progs = 0;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001801
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001802 /* Disable job control signals for shell (parent) and
1803 * for initial child code after fork */
1804 set_jobctrl_sighandler(SIG_IGN);
1805
Eric Andersen25f27032001-04-26 23:22:31 +00001806 for (i = 0; i < pi->num_progs; i++) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001807 child = &(pi->progs[i]);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001808 if (child->argv)
1809 debug_printf_exec(": pipe member '%s' '%s'...\n", child->argv[0], child->argv[1]);
1810 else
1811 debug_printf_exec(": pipe member with no argv\n");
Eric Andersen25f27032001-04-26 23:22:31 +00001812
1813 /* pipes are inserted between pairs of commands */
1814 if ((i + 1) < pi->num_progs) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001815 if (pipe(pipefds) < 0)
1816 bb_perror_msg_and_die("pipe");
Eric Andersen25f27032001-04-26 23:22:31 +00001817 nextout = pipefds[1];
1818 } else {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001819 nextout = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00001820 pipefds[0] = -1;
1821 }
1822
1823 /* XXX test for failed fork()? */
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001824#if BB_MMU
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001825 child->pid = fork();
Eric Andersen72f9a422001-10-28 05:12:20 +00001826#else
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001827 child->pid = vfork();
Eric Andersen72f9a422001-10-28 05:12:20 +00001828#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001829 if (!child->pid) { /* child */
1830 /* Every child adds itself to new process group
1831 * with pgid == pid of first child in pipe */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001832#if ENABLE_HUSH_JOB
Denis Vlasenko170435c2007-05-23 13:01:10 +00001833 if (run_list_level == 1 && interactive_fd) {
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001834 /* Don't do pgrp restore anymore on fatal signals */
1835 set_fatal_sighandler(SIG_DFL);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001836 if (pi->pgrp < 0) /* true for 1st process only */
1837 pi->pgrp = getpid();
1838 if (setpgid(0, pi->pgrp) == 0 && pi->followup != PIPE_BG) {
1839 /* We do it in *every* child, not just first,
1840 * to avoid races */
1841 tcsetpgrp(interactive_fd, pi->pgrp);
1842 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001843 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001844#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001845 /* in non-interactive case fatal sigs are already SIG_DFL */
Eric Andersen25f27032001-04-26 23:22:31 +00001846 close_all();
Eric Andersen25f27032001-04-26 23:22:31 +00001847 if (nextin != 0) {
1848 dup2(nextin, 0);
1849 close(nextin);
1850 }
1851 if (nextout != 1) {
1852 dup2(nextout, 1);
1853 close(nextout);
1854 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00001855 if (pipefds[0] != -1) {
Eric Andersen25f27032001-04-26 23:22:31 +00001856 close(pipefds[0]); /* opposite end of our output pipe */
1857 }
Eric Andersen25f27032001-04-26 23:22:31 +00001858 /* Like bash, explicit redirects override pipes,
1859 * and the pipe fd is available for dup'ing. */
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001860 setup_redirects(child, NULL);
Eric Andersen52a97ca2001-06-22 06:49:26 +00001861
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001862 /* Restore default handlers just prior to exec */
1863 set_jobctrl_sighandler(SIG_DFL);
1864 set_misc_sighandler(SIG_DFL);
1865 signal(SIGCHLD, SIG_DFL);
Eric Andersen25f27032001-04-26 23:22:31 +00001866 pseudo_exec(child);
1867 }
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001868
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001869 pi->running_progs++;
1870
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001871#if ENABLE_HUSH_JOB
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00001872 /* Second and next children need to know pid of first one */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001873 if (pi->pgrp < 0)
Eric Andersen0fcd4472001-05-02 20:12:03 +00001874 pi->pgrp = child->pid;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001875#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001876 if (nextin != 0)
1877 close(nextin);
1878 if (nextout != 1)
1879 close(nextout);
1880
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001881 /* If there isn't another process, nextin is garbage
Eric Andersen25f27032001-04-26 23:22:31 +00001882 but it doesn't matter */
1883 nextin = pipefds[0];
1884 }
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001885 debug_printf_exec("run_pipe_real return -1\n");
Eric Andersen25f27032001-04-26 23:22:31 +00001886 return -1;
1887}
1888
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001889#ifndef debug_print_tree
1890static void debug_print_tree(struct pipe *pi, int lvl)
1891{
1892 static const char *PIPE[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001893 [PIPE_SEQ] = "SEQ",
1894 [PIPE_AND] = "AND",
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001895 [PIPE_OR ] = "OR" ,
1896 [PIPE_BG ] = "BG" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001897 };
1898 static const char *RES[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001899 [RES_NONE ] = "NONE" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00001900#if ENABLE_HUSH_IF
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001901 [RES_IF ] = "IF" ,
1902 [RES_THEN ] = "THEN" ,
1903 [RES_ELIF ] = "ELIF" ,
1904 [RES_ELSE ] = "ELSE" ,
1905 [RES_FI ] = "FI" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00001906#endif
1907#if ENABLE_HUSH_LOOPS
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001908 [RES_FOR ] = "FOR" ,
1909 [RES_WHILE] = "WHILE",
1910 [RES_UNTIL] = "UNTIL",
1911 [RES_DO ] = "DO" ,
1912 [RES_DONE ] = "DONE" ,
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001913 [RES_IN ] = "IN" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00001914#endif
1915 [RES_XXXX ] = "XXXX" ,
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001916 [RES_SNTX ] = "SNTX" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001917 };
1918
1919 int pin, prn;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00001920
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001921 pin = 0;
1922 while (pi) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00001923 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
1924 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001925 prn = 0;
1926 while (prn < pi->num_progs) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00001927 struct child_prog *child = &pi->progs[prn];
1928 char **argv = child->argv;
1929
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001930 fprintf(stderr, "%*s prog %d", lvl*2, "", prn);
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00001931 if (child->group) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001932 fprintf(stderr, " group %s: (argv=%p)\n",
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00001933 (child->subshell ? "()" : "{}"),
1934 argv);
1935 debug_print_tree(child->group, lvl+1);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001936 prn++;
1937 continue;
1938 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001939 if (argv) while (*argv) {
1940 fprintf(stderr, " '%s'", *argv);
1941 argv++;
1942 }
1943 fprintf(stderr, "\n");
1944 prn++;
1945 }
1946 pi = pi->next;
1947 pin++;
1948 }
1949}
1950#endif
1951
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001952/* NB: called by pseudo_exec, and therefore must not modify any
1953 * global data until exec/_exit (we can be a child after vfork!) */
Eric Andersen25f27032001-04-26 23:22:31 +00001954static int run_list_real(struct pipe *pi)
1955{
Denis Vlasenko06810332007-05-21 23:30:54 +00001956 struct pipe *rpipe;
1957#if ENABLE_HUSH_LOOPS
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00001958 char *for_varname = NULL;
1959 char **for_lcur = NULL;
1960 char **for_list = NULL;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001961 int flag_rep = 0;
Denis Vlasenko06810332007-05-21 23:30:54 +00001962#endif
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001963 int save_num_progs;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001964 int flag_skip = 1;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00001965 int rcode = 0; /* probably for gcc only */
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001966 int flag_restore = 0;
Denis Vlasenko06810332007-05-21 23:30:54 +00001967#if ENABLE_HUSH_IF
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001968 int if_code = 0, next_if_code = 0; /* need double-buffer to handle elif */
Denis Vlasenko06810332007-05-21 23:30:54 +00001969#else
1970 enum { if_code = 0, next_if_code = 0 };
1971#endif
Denis Vlasenko219e88d2007-05-21 10:18:23 +00001972 reserved_style rword;
1973 reserved_style skip_more_for_this_rword = RES_XXXX;
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00001974
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001975 debug_printf_exec("run_list_real start lvl %d\n", run_list_level + 1);
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00001976
Denis Vlasenko06810332007-05-21 23:30:54 +00001977#if ENABLE_HUSH_LOOPS
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001978 /* check syntax for "for" */
1979 for (rpipe = pi; rpipe; rpipe = rpipe->next) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00001980 if ((rpipe->res_word == RES_IN || rpipe->res_word == RES_FOR)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001981 && (rpipe->next == NULL)
1982 ) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001983 syntax("malformed for"); /* no IN or no commands after IN */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001984 debug_printf_exec("run_list_real lvl %d return 1\n", run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001985 return 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001986 }
Denis Vlasenko219e88d2007-05-21 10:18:23 +00001987 if ((rpipe->res_word == RES_IN && rpipe->next->res_word == RES_IN && rpipe->next->progs[0].argv != NULL)
1988 || (rpipe->res_word == RES_FOR && rpipe->next->res_word != RES_IN)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001989 ) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001990 /* TODO: what is tested in the first condition? */
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001991 syntax("malformed for"); /* 2nd condition: not followed by IN */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001992 debug_printf_exec("run_list_real lvl %d return 1\n", run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001993 return 1;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001994 }
1995 }
Denis Vlasenko06810332007-05-21 23:30:54 +00001996#else
1997 rpipe = NULL;
1998#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001999
2000#if ENABLE_HUSH_JOB
2001 /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
2002 * We are saving state before entering outermost list ("while...done")
2003 * so that ctrl-Z will correctly background _entire_ outermost list,
2004 * not just a part of it (like "sleep 1 | exit 2") */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00002005 if (++run_list_level == 1 && interactive_fd) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002006 if (sigsetjmp(toplevel_jb, 1)) {
2007 /* ctrl-Z forked and we are parent; or ctrl-C.
2008 * Sighandler has longjmped us here */
2009 signal(SIGINT, SIG_IGN);
2010 signal(SIGTSTP, SIG_IGN);
2011 /* Restore level (we can be coming from deep inside
2012 * nested levels) */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00002013 run_list_level = 1;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002014#if ENABLE_FEATURE_SH_STANDALONE
2015 if (nofork_save.saved) { /* if save area is valid */
2016 debug_printf_jobs("exiting nofork early\n");
2017 restore_nofork_data(&nofork_save);
2018 }
2019#endif
2020 if (ctrl_z_flag) {
2021 /* ctrl-Z has forked and stored pid of the child in pi->pid.
2022 * Remember this child as background job */
2023 insert_bg_job(pi);
2024 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002025 /* ctrl-C. We just stop doing whatever we were doing */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002026 putchar('\n');
2027 }
2028 rcode = 0;
2029 goto ret;
2030 }
2031 /* ctrl-Z handler will store pid etc in pi */
2032 toplevel_list = pi;
2033 ctrl_z_flag = 0;
2034#if ENABLE_FEATURE_SH_STANDALONE
2035 nofork_save.saved = 0; /* in case we will run a nofork later */
2036#endif
2037 signal_SA_RESTART(SIGTSTP, handler_ctrl_z);
2038 signal(SIGINT, handler_ctrl_c);
2039 }
2040#endif
2041
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002042 for (; pi; pi = flag_restore ? rpipe : pi->next) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002043 rword = pi->res_word;
Denis Vlasenko06810332007-05-21 23:30:54 +00002044#if ENABLE_HUSH_LOOPS
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002045 if (rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002046 flag_restore = 0;
2047 if (!rpipe) {
2048 flag_rep = 0;
2049 rpipe = pi;
2050 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002051 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002052#endif
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002053 debug_printf_exec(": rword=%d if_code=%d next_if_code=%d skip_more=%d\n",
2054 rword, if_code, next_if_code, skip_more_for_this_rword);
2055 if (rword == skip_more_for_this_rword && flag_skip) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002056 if (pi->followup == PIPE_SEQ)
2057 flag_skip = 0;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002058 continue;
2059 }
2060 flag_skip = 1;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002061 skip_more_for_this_rword = RES_XXXX;
Denis Vlasenko06810332007-05-21 23:30:54 +00002062#if ENABLE_HUSH_IF
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002063 if (rword == RES_THEN || rword == RES_ELSE)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002064 if_code = next_if_code;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002065 if (rword == RES_THEN && if_code)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002066 continue;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002067 if (rword == RES_ELSE && !if_code)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002068 continue;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002069 if (rword == RES_ELIF && !if_code)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002070 break;
Denis Vlasenko06810332007-05-21 23:30:54 +00002071#endif
2072#if ENABLE_HUSH_LOOPS
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002073 if (rword == RES_FOR && pi->num_progs) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002074 if (!for_lcur) {
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002075 /* if no variable values after "in" we skip "for" */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002076 if (!pi->next->progs->argv)
2077 continue;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002078 /* create list of variable values */
Denis Vlasenko170435c2007-05-23 13:01:10 +00002079 for_list = expand_strvec_to_strvec(pi->next->progs->argv);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002080 for_lcur = for_list;
2081 for_varname = pi->progs->argv[0];
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002082 pi->progs->argv[0] = NULL;
2083 flag_rep = 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002084 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002085 free(pi->progs->argv[0]);
2086 if (!*for_lcur) {
2087 free(for_list);
2088 for_lcur = NULL;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002089 flag_rep = 0;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002090 pi->progs->argv[0] = for_varname;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002091 pi->progs->glob_result.gl_pathv[0] = pi->progs->argv[0];
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002092 continue;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002093 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002094 /* insert next value from for_lcur */
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002095 /* vda: does it need escaping? */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002096 pi->progs->argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002097 pi->progs->glob_result.gl_pathv[0] = pi->progs->argv[0];
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002098 }
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002099 if (rword == RES_IN)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002100 continue;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002101 if (rword == RES_DO) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002102 if (!flag_rep)
2103 continue;
Tim Rikerc1ef7bd2006-01-25 00:08:53 +00002104 }
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002105 if (rword == RES_DONE) {
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002106 if (flag_rep) {
2107 flag_restore = 1;
2108 } else {
2109 rpipe = NULL;
2110 }
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002111 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002112#endif
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002113 if (pi->num_progs == 0)
2114 continue;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002115 save_num_progs = pi->num_progs; /* save number of programs */
Denis Vlasenkod01ff132007-05-02 21:40:23 +00002116 debug_printf_exec(": run_pipe_real with %d members\n", pi->num_progs);
Eric Andersen25f27032001-04-26 23:22:31 +00002117 rcode = run_pipe_real(pi);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002118 if (rcode != -1) {
Eric Andersen25f27032001-04-26 23:22:31 +00002119 /* We only ran a builtin: rcode was set by the return value
2120 * of run_pipe_real(), and we don't need to wait for anything. */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002121 } else if (pi->followup == PIPE_BG) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002122 /* What does bash do with attempts to background builtins? */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002123 /* Even bash 3.2 doesn't do that well with nested bg:
2124 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
Denis Vlasenko170435c2007-05-23 13:01:10 +00002125 * I'm NOT treating inner &'s as jobs */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002126#if ENABLE_HUSH_JOB
Denis Vlasenko170435c2007-05-23 13:01:10 +00002127 if (run_list_level == 1)
2128 insert_bg_job(pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002129#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002130 rcode = EXIT_SUCCESS;
2131 } else {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002132#if ENABLE_HUSH_JOB
Denis Vlasenko170435c2007-05-23 13:01:10 +00002133 /* Paranoia, just "interactive_fd" should be enough? */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00002134 if (run_list_level == 1 && interactive_fd) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00002135 /* waits for completion, then fg's main shell */
Denis Vlasenko52881e92007-04-21 13:42:52 +00002136 rcode = checkjobs_and_fg_shell(pi);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002137 } else
2138#endif
2139 {
Denis Vlasenko170435c2007-05-23 13:01:10 +00002140 /* this one just waits for completion */
Eric Andersenc798b072001-06-22 06:23:03 +00002141 rcode = checkjobs(pi);
Eric Andersen25f27032001-04-26 23:22:31 +00002142 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002143 debug_printf_exec(": checkjobs returned %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00002144 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002145 debug_printf_exec(": setting last_return_code=%d\n", rcode);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002146 last_return_code = rcode;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002147 pi->num_progs = save_num_progs; /* restore number of programs */
Denis Vlasenko06810332007-05-21 23:30:54 +00002148#if ENABLE_HUSH_IF
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002149 if (rword == RES_IF || rword == RES_ELIF)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002150 next_if_code = rcode; /* can be overwritten a number of times */
Denis Vlasenko06810332007-05-21 23:30:54 +00002151#endif
2152#if ENABLE_HUSH_LOOPS
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002153 if (rword == RES_WHILE)
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002154 flag_rep = !last_return_code;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002155 if (rword == RES_UNTIL)
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002156 flag_rep = last_return_code;
Denis Vlasenko06810332007-05-21 23:30:54 +00002157#endif
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002158 if ((rcode == EXIT_SUCCESS && pi->followup == PIPE_OR)
2159 || (rcode != EXIT_SUCCESS && pi->followup == PIPE_AND)
2160 ) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002161 skip_more_for_this_rword = rword;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002162 }
Eric Andersen028b65b2001-06-28 01:10:11 +00002163 checkjobs(NULL);
Eric Andersen25f27032001-04-26 23:22:31 +00002164 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002165
2166#if ENABLE_HUSH_JOB
2167 if (ctrl_z_flag) {
2168 /* ctrl-Z forked somewhere in the past, we are the child,
2169 * and now we completed running the list. Exit. */
2170 exit(rcode);
2171 }
2172 ret:
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00002173 run_list_level--;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002174#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00002175 debug_printf_exec("run_list_real lvl %d return %d\n", run_list_level + 1, rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00002176 return rcode;
2177}
2178
Eric Andersen25f27032001-04-26 23:22:31 +00002179/* return code is the exit status of the pipe */
Eric Andersenbf7df042001-05-23 22:18:35 +00002180static int free_pipe(struct pipe *pi, int indent)
Eric Andersen25f27032001-04-26 23:22:31 +00002181{
2182 char **p;
2183 struct child_prog *child;
2184 struct redir_struct *r, *rnext;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002185 int a, i, ret_code = 0;
Eric Andersen52a97ca2001-06-22 06:49:26 +00002186
2187 if (pi->stopped_progs > 0)
2188 return ret_code;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002189 debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002190 for (i = 0; i < pi->num_progs; i++) {
Eric Andersen25f27032001-04-26 23:22:31 +00002191 child = &pi->progs[i];
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002192 debug_printf_clean("%s command %d:\n", indenter(indent), i);
Eric Andersen25f27032001-04-26 23:22:31 +00002193 if (child->argv) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002194 for (a = 0, p = child->argv; *p; a++, p++) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002195 debug_printf_clean("%s argv[%d] = %s\n", indenter(indent), a, *p);
Eric Andersen25f27032001-04-26 23:22:31 +00002196 }
2197 globfree(&child->glob_result);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002198 child->argv = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002199 } else if (child->group) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002200 debug_printf_clean("%s begin group (subshell:%d)\n", indenter(indent), child->subshell);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002201 ret_code = free_pipe_list(child->group, indent+3);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002202 debug_printf_clean("%s end group\n", indenter(indent));
Eric Andersen25f27032001-04-26 23:22:31 +00002203 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002204 debug_printf_clean("%s (nil)\n", indenter(indent));
Eric Andersen25f27032001-04-26 23:22:31 +00002205 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002206 for (r = child->redirects; r; r = rnext) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002207 debug_printf_clean("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->type].descrip);
Eric Andersen25f27032001-04-26 23:22:31 +00002208 if (r->dup == -1) {
Eric Andersen817e73c2001-06-06 17:56:09 +00002209 /* guard against the case >$FOO, where foo is unset or blank */
2210 if (r->word.gl_pathv) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002211 debug_printf_clean(" %s\n", *r->word.gl_pathv);
Eric Andersen817e73c2001-06-06 17:56:09 +00002212 globfree(&r->word);
2213 }
Eric Andersen25f27032001-04-26 23:22:31 +00002214 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002215 debug_printf_clean("&%d\n", r->dup);
Eric Andersen25f27032001-04-26 23:22:31 +00002216 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002217 rnext = r->next;
Eric Andersen25f27032001-04-26 23:22:31 +00002218 free(r);
2219 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002220 child->redirects = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002221 }
2222 free(pi->progs); /* children are an array, they get freed all at once */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002223 pi->progs = NULL;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002224#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002225 free(pi->cmdtext);
2226 pi->cmdtext = NULL;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002227#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002228 return ret_code;
2229}
2230
Eric Andersenbf7df042001-05-23 22:18:35 +00002231static int free_pipe_list(struct pipe *head, int indent)
Eric Andersen25f27032001-04-26 23:22:31 +00002232{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002233 int rcode = 0; /* if list has no members */
Eric Andersen25f27032001-04-26 23:22:31 +00002234 struct pipe *pi, *next;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002235
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002236 for (pi = head; pi; pi = next) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002237 debug_printf_clean("%s pipe reserved mode %d\n", indenter(indent), pi->res_word);
Eric Andersenbf7df042001-05-23 22:18:35 +00002238 rcode = free_pipe(pi, indent);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002239 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002240 next = pi->next;
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002241 /*pi->next = NULL;*/
Eric Andersen25f27032001-04-26 23:22:31 +00002242 free(pi);
2243 }
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002244 return rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00002245}
2246
2247/* Select which version we will use */
2248static int run_list(struct pipe *pi)
2249{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002250 int rcode = 0;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002251 debug_printf_exec("run_list entered\n");
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002252 if (fake_mode == 0) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002253 debug_printf_exec(": run_list_real with %d members\n", pi->num_progs);
Eric Andersen25f27032001-04-26 23:22:31 +00002254 rcode = run_list_real(pi);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002255 }
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002256 /* free_pipe_list has the side effect of clearing memory.
Eric Andersen25f27032001-04-26 23:22:31 +00002257 * In the long run that function can be merged with run_list_real,
2258 * but doing that now would hobble the debugging effort. */
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002259 free_pipe_list(pi, 0);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002260 debug_printf_exec("run_list return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00002261 return rcode;
2262}
2263
2264/* The API for glob is arguably broken. This routine pushes a non-matching
2265 * string into the output structure, removing non-backslashed backslashes.
2266 * If someone can prove me wrong, by performing this function within the
2267 * original glob(3) api, feel free to rewrite this routine into oblivion.
2268 * Return code (0 vs. GLOB_NOSPACE) matches glob(3).
2269 * XXX broken if the last character is '\\', check that before calling.
2270 */
2271static int globhack(const char *src, int flags, glob_t *pglob)
2272{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002273 int cnt = 0, pathc;
Eric Andersen25f27032001-04-26 23:22:31 +00002274 const char *s;
2275 char *dest;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002276 for (cnt = 1, s = src; s && *s; s++) {
Eric Andersen25f27032001-04-26 23:22:31 +00002277 if (*s == '\\') s++;
2278 cnt++;
2279 }
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002280 dest = xmalloc(cnt);
Eric Andersen25f27032001-04-26 23:22:31 +00002281 if (!(flags & GLOB_APPEND)) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002282 pglob->gl_pathv = NULL;
2283 pglob->gl_pathc = 0;
2284 pglob->gl_offs = 0;
2285 pglob->gl_offs = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00002286 }
2287 pathc = ++pglob->gl_pathc;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002288 pglob->gl_pathv = xrealloc(pglob->gl_pathv, (pathc+1) * sizeof(*pglob->gl_pathv));
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002289 pglob->gl_pathv[pathc-1] = dest;
2290 pglob->gl_pathv[pathc] = NULL;
2291 for (s = src; s && *s; s++, dest++) {
Eric Andersen25f27032001-04-26 23:22:31 +00002292 if (*s == '\\') s++;
2293 *dest = *s;
2294 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002295 *dest = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002296 return 0;
2297}
2298
2299/* XXX broken if the last character is '\\', check that before calling */
2300static int glob_needed(const char *s)
2301{
2302 for (; *s; s++) {
2303 if (*s == '\\') s++;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002304 if (strchr("*[?", *s)) return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002305 }
2306 return 0;
2307}
2308
Eric Andersen25f27032001-04-26 23:22:31 +00002309static int xglob(o_string *dest, int flags, glob_t *pglob)
2310{
2311 int gr;
2312
Tim Rikerc1ef7bd2006-01-25 00:08:53 +00002313 /* short-circuit for null word */
Eric Andersen25f27032001-04-26 23:22:31 +00002314 /* we can code this better when the debug_printf's are gone */
Tim Rikerc1ef7bd2006-01-25 00:08:53 +00002315 if (dest->length == 0) {
2316 if (dest->nonnull) {
2317 /* bash man page calls this an "explicit" null */
2318 gr = globhack(dest->data, flags, pglob);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002319 debug_printf("globhack returned %d\n", gr);
Tim Rikerc1ef7bd2006-01-25 00:08:53 +00002320 } else {
Eric Andersen25f27032001-04-26 23:22:31 +00002321 return 0;
2322 }
Tim Rikerc1ef7bd2006-01-25 00:08:53 +00002323 } else if (glob_needed(dest->data)) {
Eric Andersen25f27032001-04-26 23:22:31 +00002324 gr = glob(dest->data, flags, NULL, pglob);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002325 debug_printf("glob returned %d\n", gr);
Eric Andersen25f27032001-04-26 23:22:31 +00002326 if (gr == GLOB_NOMATCH) {
2327 /* quote removal, or more accurately, backslash removal */
2328 gr = globhack(dest->data, flags, pglob);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002329 debug_printf("globhack returned %d\n", gr);
Eric Andersen25f27032001-04-26 23:22:31 +00002330 }
2331 } else {
2332 gr = globhack(dest->data, flags, pglob);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002333 debug_printf("globhack returned %d\n", gr);
Eric Andersen25f27032001-04-26 23:22:31 +00002334 }
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002335 if (gr == GLOB_NOSPACE)
Manuel Novoa III cad53642003-03-19 09:13:01 +00002336 bb_error_msg_and_die("out of memory during glob");
Eric Andersen25f27032001-04-26 23:22:31 +00002337 if (gr != 0) { /* GLOB_ABORTED ? */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002338 bb_error_msg("glob(3) error %d", gr);
Eric Andersen25f27032001-04-26 23:22:31 +00002339 }
2340 /* globprint(glob_target); */
2341 return gr;
2342}
2343
Denis Vlasenko170435c2007-05-23 13:01:10 +00002344/* expand_strvec_to_strvec() takes a list of strings, expands
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002345 * all variable references within and returns a pointer to
2346 * a list of expanded strings, possibly with larger number
2347 * of strings. (Think VAR="a b"; echo $VAR).
2348 * This new list is allocated as a single malloc block.
2349 * NULL-terminated list of char* pointers is at the beginning of it,
2350 * followed by strings themself.
2351 * Caller can deallocate entire list by single free(list). */
2352
2353/* Helpers first:
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00002354 * count_XXX estimates size of the block we need. It's okay
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002355 * to over-estimate sizes a bit, if it makes code simpler */
2356static int count_ifs(const char *str)
2357{
2358 int cnt = 0;
2359 debug_printf_expand("count_ifs('%s') ifs='%s'", str, ifs);
2360 while (1) {
2361 str += strcspn(str, ifs);
2362 if (!*str) break;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002363 str++; /* str += strspn(str, ifs); */
2364 cnt++; /* cnt += strspn(str, ifs); - but this code is larger */
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002365 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002366 debug_printf_expand(" return %d\n", cnt);
2367 return cnt;
2368}
2369
2370static void count_var_expansion_space(int *countp, int *lenp, char *arg)
2371{
2372 char first_ch;
2373 int i;
2374 int len = *lenp;
2375 int count = *countp;
2376 const char *val;
2377 char *p;
2378
2379 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL))) {
2380 len += p - arg;
2381 arg = ++p;
2382 p = strchr(p, SPECIAL_VAR_SYMBOL);
2383 first_ch = arg[0];
2384
2385 switch (first_ch & 0x7f) {
2386 /* high bit in 1st_ch indicates that var is double-quoted */
2387 case '$': /* pid */
2388 case '!': /* bg pid */
2389 case '?': /* exitcode */
2390 case '#': /* argc */
2391 len += sizeof(int)*3 + 1; /* enough for int */
2392 break;
2393 case '*':
2394 case '@':
2395 for (i = 1; i < global_argc; i++) {
2396 len += strlen(global_argv[i]) + 1;
2397 count++;
2398 if (!(first_ch & 0x80))
2399 count += count_ifs(global_argv[i]);
2400 }
2401 break;
2402 default:
2403 *p = '\0';
2404 arg[0] = first_ch & 0x7f;
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002405 if (isdigit(arg[0])) {
2406 i = xatoi_u(arg);
2407 val = NULL;
2408 if (i < global_argc)
2409 val = global_argv[i];
2410 } else
2411 val = lookup_param(arg);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002412 arg[0] = first_ch;
2413 *p = SPECIAL_VAR_SYMBOL;
2414
2415 if (val) {
2416 len += strlen(val) + 1;
2417 if (!(first_ch & 0x80))
2418 count += count_ifs(val);
2419 }
2420 }
2421 arg = ++p;
2422 }
2423
2424 len += strlen(arg) + 1;
2425 count++;
2426 *lenp = len;
2427 *countp = count;
2428}
2429
2430/* Store given string, finalizing the word and starting new one whenever
2431 * we encounter ifs char(s). This is used for expanding variable values.
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002432 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002433static int expand_on_ifs(char **list, int n, char **posp, const char *str)
2434{
2435 char *pos = *posp;
2436 while (1) {
2437 int word_len = strcspn(str, ifs);
2438 if (word_len) {
2439 memcpy(pos, str, word_len); /* store non-ifs chars */
2440 pos += word_len;
2441 str += word_len;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002442 }
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002443 if (!*str) /* EOL - do not finalize word */
2444 break;
2445 *pos++ = '\0';
2446 if (n) debug_printf_expand("expand_on_ifs finalized list[%d]=%p '%s' "
2447 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2448 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2449 list[n++] = pos;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002450 str += strspn(str, ifs); /* skip ifs chars */
2451 }
2452 *posp = pos;
2453 return n;
2454}
2455
2456/* Expand all variable references in given string, adding words to list[]
2457 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2458 * to be filled). This routine is extremely tricky: has to deal with
2459 * variables/parameters with whitespace, $* and $@, and constructs like
2460 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002461/* NB: another bug is that we cannot detect empty strings yet:
2462 * "" or $empty"" expands to zero words, has to expand to empty word */
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002463static int expand_vars_to_list(char **list, int n, char **posp, char *arg, char or_mask)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002464{
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002465 /* or_mask is either 0 (normal case) or 0x80
2466 * (expansion of right-hand side of assignment == 1-element expand) */
2467
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002468 char first_ch, ored_ch;
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002469 int i;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002470 const char *val;
2471 char *p;
2472 char *pos = *posp;
2473
2474 ored_ch = 0;
2475
2476 if (n) debug_printf_expand("expand_vars_to_list finalized list[%d]=%p '%s' "
2477 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2478 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2479 list[n++] = pos;
2480
2481 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL))) {
2482 memcpy(pos, arg, p - arg);
2483 pos += (p - arg);
2484 arg = ++p;
2485 p = strchr(p, SPECIAL_VAR_SYMBOL);
2486
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002487 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002488 ored_ch |= first_ch;
2489 val = NULL;
2490 switch (first_ch & 0x7f) {
2491 /* Highest bit in first_ch indicates that var is double-quoted */
2492 case '$': /* pid */
2493 /* FIXME: (echo $$) should still print pid of main shell */
2494 val = utoa(getpid());
2495 break;
2496 case '!': /* bg pid */
2497 val = last_bg_pid ? utoa(last_bg_pid) : (char*)"";
2498 break;
2499 case '?': /* exitcode */
2500 val = utoa(last_return_code);
2501 break;
2502 case '#': /* argc */
2503 val = utoa(global_argc ? global_argc-1 : 0);
2504 break;
2505 case '*':
2506 case '@':
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002507 i = 1;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002508 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002509 while (i < global_argc) {
2510 n = expand_on_ifs(list, n, &pos, global_argv[i]);
2511 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, global_argc-1);
2512 if (global_argv[i++][0] && i < global_argc) {
2513 /* this argv[] is not empty and not last:
2514 * put terminating NUL, start new word */
2515 *pos++ = '\0';
2516 if (n) debug_printf_expand("expand_vars_to_list 2 finalized list[%d]=%p '%s' "
2517 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2518 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2519 list[n++] = pos;
2520 }
2521 }
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002522 } else
2523 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2524 * and in this case should theat it like '$*' */
2525 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002526 while (1) {
2527 strcpy(pos, global_argv[i]);
2528 pos += strlen(global_argv[i]);
2529 if (++i >= global_argc)
2530 break;
2531 *pos++ = '\0';
2532 if (n) debug_printf_expand("expand_vars_to_list 3 finalized list[%d]=%p '%s' "
2533 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2534 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2535 list[n++] = pos;
2536 }
2537 } else { /* quoted $*: add as one word */
2538 while (1) {
2539 strcpy(pos, global_argv[i]);
2540 pos += strlen(global_argv[i]);
2541 if (++i >= global_argc)
2542 break;
2543 if (ifs[0])
2544 *pos++ = ifs[0];
2545 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002546 }
2547 break;
2548 default:
2549 *p = '\0';
2550 arg[0] = first_ch & 0x7f;
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002551 if (isdigit(arg[0])) {
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002552 i = xatoi_u(arg);
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002553 val = NULL;
2554 if (i < global_argc)
2555 val = global_argv[i];
2556 } else
2557 val = lookup_param(arg);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002558 arg[0] = first_ch;
2559 *p = SPECIAL_VAR_SYMBOL;
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002560 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002561 if (val) {
2562 n = expand_on_ifs(list, n, &pos, val);
2563 val = NULL;
2564 }
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002565 } /* else: quoted $VAR, val will be appended at pos */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002566 }
2567 if (val) {
2568 strcpy(pos, val);
2569 pos += strlen(val);
2570 }
2571 arg = ++p;
2572 }
2573 debug_printf_expand("expand_vars_to_list adding tail '%s' at %p\n", arg, pos);
2574 strcpy(pos, arg);
2575 pos += strlen(arg) + 1;
2576 if (pos == list[n-1] + 1) { /* expansion is empty */
2577 if (!(ored_ch & 0x80)) { /* all vars were not quoted... */
2578 debug_printf_expand("expand_vars_to_list list[%d] empty, going back\n", n);
2579 pos--;
2580 n--;
2581 }
2582 }
2583
2584 *posp = pos;
2585 return n;
2586}
2587
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002588static char **expand_variables(char **argv, char or_mask)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002589{
2590 int n;
2591 int count = 1;
2592 int len = 0;
2593 char *pos, **v, **list;
2594
2595 v = argv;
2596 if (!*v) debug_printf_expand("count_var_expansion_space: "
2597 "argv[0]=NULL count=%d len=%d alloc_space=%d\n",
2598 count, len, sizeof(char*) * count + len);
2599 while (*v) {
2600 count_var_expansion_space(&count, &len, *v);
2601 debug_printf_expand("count_var_expansion_space: "
2602 "'%s' count=%d len=%d alloc_space=%d\n",
2603 *v, count, len, sizeof(char*) * count + len);
2604 v++;
2605 }
2606 len += sizeof(char*) * count; /* total to alloc */
2607 list = xmalloc(len);
2608 pos = (char*)(list + count);
2609 debug_printf_expand("list=%p, list[0] should be %p\n", list, pos);
2610 n = 0;
2611 v = argv;
2612 while (*v)
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002613 n = expand_vars_to_list(list, n, &pos, *v++, or_mask);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002614
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002615 if (n) debug_printf_expand("finalized list[%d]=%p '%s' "
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002616 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2617 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002618 list[n] = NULL;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002619
2620#ifdef DEBUG_EXPAND
2621 {
2622 int m = 0;
2623 while (m <= n) {
2624 debug_printf_expand("list[%d]=%p '%s'\n", m, list[m], list[m]);
2625 m++;
2626 }
2627 debug_printf_expand("used_space=%d\n", pos - (char*)list);
2628 }
2629#endif
Denis Vlasenko170435c2007-05-23 13:01:10 +00002630 if (ENABLE_HUSH_DEBUG)
2631 if (pos - (char*)list > len)
2632 bb_error_msg_and_die("BUG in varexp");
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002633 return list;
2634}
2635
Denis Vlasenko170435c2007-05-23 13:01:10 +00002636static char **expand_strvec_to_strvec(char **argv)
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002637{
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002638 return expand_variables(argv, 0);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002639}
2640
Denis Vlasenko170435c2007-05-23 13:01:10 +00002641static char *expand_string_to_string(const char *str)
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002642{
2643 char *argv[2], **list;
2644
2645 argv[0] = (char*)str;
2646 argv[1] = NULL;
2647 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
Denis Vlasenko170435c2007-05-23 13:01:10 +00002648 if (ENABLE_HUSH_DEBUG)
2649 if (!list[0] || list[1])
2650 bb_error_msg_and_die("BUG in varexp2");
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002651 /* actually, just move string 2*sizeof(char*) bytes back */
2652 strcpy((char*)list, list[0]);
Denis Vlasenko170435c2007-05-23 13:01:10 +00002653 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2654 return (char*)list;
2655}
2656
2657static char* expand_strvec_to_string(char **argv)
2658{
2659 char **list;
2660
2661 list = expand_variables(argv, 0x80);
2662 /* Convert all NULs to spaces */
2663 if (list[0]) {
2664 int n = 1;
2665 while (list[n]) {
2666 if (ENABLE_HUSH_DEBUG)
2667 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2668 bb_error_msg_and_die("BUG in varexp3");
2669 list[n][-1] = ' '; /* TODO: or to ifs[0]? */
2670 n++;
2671 }
2672 }
2673 strcpy((char*)list, list[0]);
2674 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002675 return (char*)list;
2676}
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002677
Eric Andersenf72f5622001-05-15 23:21:41 +00002678/* This is used to get/check local shell variables */
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002679static struct variable *get_local_var(const char *s)
Eric Andersenf72f5622001-05-15 23:21:41 +00002680{
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002681 struct variable *cur;
2682 int len;
Eric Andersenf72f5622001-05-15 23:21:41 +00002683
2684 if (!s)
2685 return NULL;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002686 len = strlen(s);
2687 for (cur = top_var; cur; cur = cur->next) {
2688 if (strncmp(cur->name, s, len) == 0 && cur->name[len] == '=')
2689 return cur;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00002690 }
Eric Andersenf72f5622001-05-15 23:21:41 +00002691 return NULL;
2692}
2693
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002694/* name holds "NAME=VAL" and is expected to be malloced.
2695 * We take ownership of it. */
2696static int set_local_var(char *name, int flg_export)
Eric Andersen78a7c992001-05-15 16:30:25 +00002697{
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002698 struct variable *cur;
2699 char *value;
2700 int name_len;
Eric Andersen20a69a72001-05-15 17:24:44 +00002701
Eric Andersen20a69a72001-05-15 17:24:44 +00002702 value = strchr(name, '=');
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002703 if (!value) { /* not expected to ever happen? */
Eric Andersen99785762001-05-22 21:37:48 +00002704 free(name);
2705 return -1;
2706 }
Eric Andersen20a69a72001-05-15 17:24:44 +00002707
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002708 name_len = value - name;
2709 cur = top_var; /* cannot be NULL (we have HUSH_VERSION and it's RO) */
2710 while (1) {
2711 if (strncmp(cur->name, name, name_len) != 0 || cur->name[name_len] != '=') {
2712 if (!cur->next) {
2713 /* cur points to last var in linked list */
2714 break;
Eric Andersen20a69a72001-05-15 17:24:44 +00002715 }
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002716 cur = cur->next;
2717 continue;
Eric Andersen20a69a72001-05-15 17:24:44 +00002718 }
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002719 /* We already have a var with this name */
2720 if (cur->flg_read_only) {
2721 bb_error_msg("%s: readonly variable", name);
2722 free(name);
2723 return -1;
2724 }
2725 *value = '\0';
2726 unsetenv(name); /* just in case */
2727 *value++ = '=';
2728 if (strcmp(cur->value, value) == 0) {
2729 free_and_exp:
2730 free(name);
2731 goto exp;
2732 }
2733 if (cur->max_len >= strlen(name)) {
2734 /* This one is from startup env, reuse space */
2735 strcpy(cur->name, name);
2736 goto free_and_exp;
2737 }
2738 /* max_len == 0 signifies "malloced" var, which we can
2739 * (and has to) free */
2740 if (!cur->max_len)
2741 free(cur->name);
2742 cur->max_len = 0;
2743 goto set_name_and_exp;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002744 }
Eric Andersen20a69a72001-05-15 17:24:44 +00002745
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002746 /* Not found - create next variable struct */
2747 cur->next = xzalloc(sizeof(*cur));
2748 cur = cur->next;
2749
2750 set_name_and_exp:
2751 cur->name = name;
2752 exp:
2753 cur->value = cur->name + name_len + 1;
2754 if (flg_export)
2755 cur->flg_export = 1;
2756 if (cur->flg_export)
2757 return putenv(cur->name);
2758 return 0;
Eric Andersen20a69a72001-05-15 17:24:44 +00002759}
2760
Eric Andersenf72f5622001-05-15 23:21:41 +00002761static void unset_local_var(const char *name)
Eric Andersen20a69a72001-05-15 17:24:44 +00002762{
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002763 struct variable *cur;
2764 struct variable *prev = prev; /* for gcc */
2765 int name_len;
Eric Andersen20a69a72001-05-15 17:24:44 +00002766
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002767 if (!name)
2768 return;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002769 name_len = strlen(name);
2770 cur = top_var;
2771 while (cur) {
2772 if (strncmp(cur->name, name, name_len) == 0 && cur->name[name_len] == '=') {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002773 if (cur->flg_read_only) {
Manuel Novoa III cad53642003-03-19 09:13:01 +00002774 bb_error_msg("%s: readonly variable", name);
Eric Andersen94ac2442001-05-22 19:05:18 +00002775 return;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002776 }
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002777 /* prev is ok to use here because 1st variable, HUSH_VERSION,
2778 * is ro, and we cannot reach this code on the 1st pass */
2779 prev->next = cur->next;
2780 unsetenv(cur->name);
2781 if (!cur->max_len)
2782 free(cur->name);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002783 free(cur);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002784 return;
Eric Andersenf72f5622001-05-15 23:21:41 +00002785 }
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002786 prev = cur;
2787 cur = cur->next;
Eric Andersen20a69a72001-05-15 17:24:44 +00002788 }
Eric Andersen78a7c992001-05-15 16:30:25 +00002789}
2790
2791static int is_assignment(const char *s)
2792{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002793 if (!s || !isalpha(*s))
2794 return 0;
2795 s++;
2796 while (isalnum(*s) || *s == '_')
2797 s++;
2798 return *s == '=';
Eric Andersen78a7c992001-05-15 16:30:25 +00002799}
2800
Eric Andersen25f27032001-04-26 23:22:31 +00002801/* the src parameter allows us to peek forward to a possible &n syntax
2802 * for file descriptor duplication, e.g., "2>&1".
2803 * Return code is 0 normally, 1 if a syntax error is detected in src.
2804 * Resource errors (in xmalloc) cause the process to exit */
2805static int setup_redirect(struct p_context *ctx, int fd, redir_type style,
2806 struct in_str *input)
2807{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002808 struct child_prog *child = ctx->child;
Eric Andersen25f27032001-04-26 23:22:31 +00002809 struct redir_struct *redir = child->redirects;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002810 struct redir_struct *last_redir = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002811
2812 /* Create a new redir_struct and drop it onto the end of the linked list */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002813 while (redir) {
2814 last_redir = redir;
2815 redir = redir->next;
Eric Andersen25f27032001-04-26 23:22:31 +00002816 }
2817 redir = xmalloc(sizeof(struct redir_struct));
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002818 redir->next = NULL;
2819 redir->word.gl_pathv = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002820 if (last_redir) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002821 last_redir->next = redir;
Eric Andersen25f27032001-04-26 23:22:31 +00002822 } else {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002823 child->redirects = redir;
Eric Andersen25f27032001-04-26 23:22:31 +00002824 }
2825
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002826 redir->type = style;
2827 redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
Eric Andersen25f27032001-04-26 23:22:31 +00002828
2829 debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
2830
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002831 /* Check for a '2>&1' type redirect */
Eric Andersen25f27032001-04-26 23:22:31 +00002832 redir->dup = redirect_dup_num(input);
2833 if (redir->dup == -2) return 1; /* syntax error */
2834 if (redir->dup != -1) {
2835 /* Erik had a check here that the file descriptor in question
Eric Andersen83a2ae22001-05-07 17:59:25 +00002836 * is legit; I postpone that to "run time"
2837 * A "-" representation of "close me" shows up as a -3 here */
Eric Andersen25f27032001-04-26 23:22:31 +00002838 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
2839 } else {
2840 /* We do _not_ try to open the file that src points to,
2841 * since we need to return and let src be expanded first.
2842 * Set ctx->pending_redirect, so we know what to do at the
2843 * end of the next parsed word.
2844 */
2845 ctx->pending_redirect = redir;
2846 }
2847 return 0;
2848}
2849
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00002850static struct pipe *new_pipe(void)
2851{
Eric Andersen25f27032001-04-26 23:22:31 +00002852 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002853 pi = xzalloc(sizeof(struct pipe));
2854 /*pi->num_progs = 0;*/
2855 /*pi->progs = NULL;*/
2856 /*pi->next = NULL;*/
2857 /*pi->followup = 0; invalid */
2858 if (RES_NONE)
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002859 pi->res_word = RES_NONE;
Eric Andersen25f27032001-04-26 23:22:31 +00002860 return pi;
2861}
2862
2863static void initialize_context(struct p_context *ctx)
2864{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002865 ctx->child = NULL;
Denis Vlasenko1a735862007-05-23 00:32:25 +00002866 ctx->pipe = ctx->list_head = new_pipe();
2867 ctx->pending_redirect = NULL;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002868 ctx->res_w = RES_NONE;
Denis Vlasenko1a735862007-05-23 00:32:25 +00002869 //only ctx->parse_type is not touched... is this intentional?
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002870 ctx->old_flag = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00002871 ctx->stack = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002872 done_command(ctx); /* creates the memory for working child */
2873}
2874
2875/* normal return is 0
2876 * if a reserved word is found, and processed, return 1
2877 * should handle if, then, elif, else, fi, for, while, until, do, done.
2878 * case, function, and select are obnoxious, save those for later.
2879 */
Denis Vlasenko06810332007-05-21 23:30:54 +00002880#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS
"Vladimir N. Oleynik"19c37012005-09-22 14:33:15 +00002881static int reserved_word(o_string *dest, struct p_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00002882{
2883 struct reserved_combo {
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002884 char literal[7];
2885 unsigned char code;
2886 int flag;
Eric Andersen25f27032001-04-26 23:22:31 +00002887 };
2888 /* Mostly a list of accepted follow-up reserved words.
2889 * FLAG_END means we are done with the sequence, and are ready
2890 * to turn the compound list into a command.
2891 * FLAG_START means the word must start a new compound list.
2892 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002893 static const struct reserved_combo reserved_list[] = {
Denis Vlasenko06810332007-05-21 23:30:54 +00002894#if ENABLE_HUSH_IF
Eric Andersen25f27032001-04-26 23:22:31 +00002895 { "if", RES_IF, FLAG_THEN | FLAG_START },
2896 { "then", RES_THEN, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2897 { "elif", RES_ELIF, FLAG_THEN },
2898 { "else", RES_ELSE, FLAG_FI },
2899 { "fi", RES_FI, FLAG_END },
Denis Vlasenko06810332007-05-21 23:30:54 +00002900#endif
2901#if ENABLE_HUSH_LOOPS
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002902 { "for", RES_FOR, FLAG_IN | FLAG_START },
Eric Andersen25f27032001-04-26 23:22:31 +00002903 { "while", RES_WHILE, FLAG_DO | FLAG_START },
2904 { "until", RES_UNTIL, FLAG_DO | FLAG_START },
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002905 { "in", RES_IN, FLAG_DO },
Eric Andersen25f27032001-04-26 23:22:31 +00002906 { "do", RES_DO, FLAG_DONE },
2907 { "done", RES_DONE, FLAG_END }
Denis Vlasenko06810332007-05-21 23:30:54 +00002908#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002909 };
Denis Vlasenko7d4c44e2007-04-16 22:34:39 +00002910 enum { NRES = sizeof(reserved_list)/sizeof(reserved_list[0]) };
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002911 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002912
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002913 for (r = reserved_list; r < reserved_list + NRES; r++) {
Denis Vlasenko1a735862007-05-23 00:32:25 +00002914 if (strcmp(dest->data, r->literal) != 0)
2915 continue;
2916 debug_printf("found reserved word %s, code %d\n", r->literal, r->code);
2917 if (r->flag & FLAG_START) {
2918 struct p_context *new;
2919 debug_printf("push stack\n");
Denis Vlasenko06810332007-05-21 23:30:54 +00002920#if ENABLE_HUSH_LOOPS
Denis Vlasenko1a735862007-05-23 00:32:25 +00002921 if (ctx->res_w == RES_IN || ctx->res_w == RES_FOR) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00002922 syntax("malformed for"); /* example: 'for if' */
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002923 ctx->res_w = RES_SNTX;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002924 b_reset(dest);
Eric Andersenaf44a0e2001-04-27 07:26:12 +00002925 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002926 }
Denis Vlasenko1a735862007-05-23 00:32:25 +00002927#endif
2928 new = xmalloc(sizeof(*new));
2929 *new = *ctx; /* physical copy */
2930 initialize_context(ctx);
2931 ctx->stack = new;
2932 } else if (ctx->res_w == RES_NONE || !(ctx->old_flag & (1 << r->code))) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00002933 syntax(NULL);
Denis Vlasenko1a735862007-05-23 00:32:25 +00002934 ctx->res_w = RES_SNTX;
Denis Vlasenkoff131b92007-04-10 15:42:06 +00002935 b_reset(dest);
Eric Andersen25f27032001-04-26 23:22:31 +00002936 return 1;
2937 }
Denis Vlasenko1a735862007-05-23 00:32:25 +00002938 ctx->res_w = r->code;
2939 ctx->old_flag = r->flag;
2940 if (ctx->old_flag & FLAG_END) {
2941 struct p_context *old;
2942 debug_printf("pop stack\n");
2943 done_pipe(ctx, PIPE_SEQ);
2944 old = ctx->stack;
2945 old->child->group = ctx->list_head;
2946 old->child->subshell = 0;
2947 *ctx = *old; /* physical copy */
2948 free(old);
2949 }
2950 b_reset(dest);
2951 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002952 }
2953 return 0;
2954}
Denis Vlasenko06810332007-05-21 23:30:54 +00002955#else
2956#define reserved_word(dest, ctx) ((int)0)
2957#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002958
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002959/* Normal return is 0.
Eric Andersen25f27032001-04-26 23:22:31 +00002960 * Syntax or xglob errors return 1. */
2961static int done_word(o_string *dest, struct p_context *ctx)
2962{
Denis Vlasenkobb81c582007-01-30 22:32:09 +00002963 struct child_prog *child = ctx->child;
Eric Andersen25f27032001-04-26 23:22:31 +00002964 glob_t *glob_target;
2965 int gr, flags = 0;
2966
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002967 debug_printf_parse("done_word entered: '%s' %p\n", dest->data, child);
Eric Andersen25f27032001-04-26 23:22:31 +00002968 if (dest->length == 0 && !dest->nonnull) {
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002969 debug_printf_parse("done_word return 0: true null, ignored\n");
Eric Andersen25f27032001-04-26 23:22:31 +00002970 return 0;
2971 }
2972 if (ctx->pending_redirect) {
2973 glob_target = &ctx->pending_redirect->word;
2974 } else {
2975 if (child->group) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00002976 syntax(NULL);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002977 debug_printf_parse("done_word return 1: syntax error, groups and arglists don't mix\n");
2978 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002979 }
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002980 if (!child->argv && (ctx->parse_type & PARSEFLAG_SEMICOLON)) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002981 debug_printf_parse(": checking '%s' for reserved-ness\n", dest->data);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002982 if (reserved_word(dest, ctx)) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002983 debug_printf_parse("done_word return %d\n", (ctx->res_w == RES_SNTX));
2984 return (ctx->res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002985 }
Eric Andersen25f27032001-04-26 23:22:31 +00002986 }
2987 glob_target = &child->glob_result;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002988 if (child->argv)
2989 flags |= GLOB_APPEND;
Eric Andersen25f27032001-04-26 23:22:31 +00002990 }
2991 gr = xglob(dest, flags, glob_target);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002992 if (gr != 0) {
2993 debug_printf_parse("done_word return 1: xglob returned %d\n", gr);
2994 return 1;
2995 }
Eric Andersen25f27032001-04-26 23:22:31 +00002996
2997 b_reset(dest);
2998 if (ctx->pending_redirect) {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00002999 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003000 if (glob_target->gl_pathc != 1) {
Manuel Novoa III cad53642003-03-19 09:13:01 +00003001 bb_error_msg("ambiguous redirect");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003002 debug_printf_parse("done_word return 1: ambiguous redirect\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003003 return 1;
3004 }
3005 } else {
3006 child->argv = glob_target->gl_pathv;
3007 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003008#if ENABLE_HUSH_LOOPS
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003009 if (ctx->res_w == RES_FOR) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003010 done_word(dest, ctx);
3011 done_pipe(ctx, PIPE_SEQ);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003012 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003013#endif
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003014 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003015 return 0;
3016}
3017
3018/* The only possible error here is out of memory, in which case
3019 * xmalloc exits. */
3020static int done_command(struct p_context *ctx)
3021{
3022 /* The child is really already in the pipe structure, so
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003023 * advance the pipe counter and make a new, null child. */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003024 struct pipe *pi = ctx->pipe;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003025 struct child_prog *child = ctx->child;
Eric Andersen25f27032001-04-26 23:22:31 +00003026
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003027 if (child) {
3028 if (child->group == NULL
3029 && child->argv == NULL
3030 && child->redirects == NULL
3031 ) {
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003032 debug_printf_parse("done_command: skipping null cmd, num_progs=%d\n", pi->num_progs);
3033 return pi->num_progs;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003034 }
Eric Andersen25f27032001-04-26 23:22:31 +00003035 pi->num_progs++;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003036 debug_printf_parse("done_command: ++num_progs=%d\n", pi->num_progs);
Eric Andersen25f27032001-04-26 23:22:31 +00003037 } else {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003038 debug_printf_parse("done_command: initializing, num_progs=%d\n", pi->num_progs);
Eric Andersen25f27032001-04-26 23:22:31 +00003039 }
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003040
3041 /* Only real trickiness here is that the uncommitted
3042 * child structure is not counted in pi->num_progs. */
Eric Andersen25f27032001-04-26 23:22:31 +00003043 pi->progs = xrealloc(pi->progs, sizeof(*pi->progs) * (pi->num_progs+1));
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003044 child = &pi->progs[pi->num_progs];
Eric Andersen25f27032001-04-26 23:22:31 +00003045
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003046 memset(child, 0, sizeof(*child));
3047 /*child->redirects = NULL;*/
3048 /*child->argv = NULL;*/
3049 /*child->is_stopped = 0;*/
3050 /*child->group = NULL;*/
3051 /*child->glob_result.gl_pathv = NULL;*/
3052 child->family = pi;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003053 //sp: /*child->sp = 0;*/
Denis Vlasenko262d7652007-05-20 21:52:49 +00003054 //pt: child->parse_type = ctx->parse_type;
Eric Andersen25f27032001-04-26 23:22:31 +00003055
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003056 ctx->child = child;
Eric Andersen25f27032001-04-26 23:22:31 +00003057 /* but ctx->pipe and ctx->list_head remain unchanged */
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003058
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003059 return pi->num_progs; /* used only for 0/nonzero check */
Eric Andersen25f27032001-04-26 23:22:31 +00003060}
3061
3062static int done_pipe(struct p_context *ctx, pipe_style type)
3063{
3064 struct pipe *new_p;
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003065 int not_null;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003066
3067 debug_printf_parse("done_pipe entered, followup %d\n", type);
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003068 not_null = done_command(ctx); /* implicit closure of previous command */
Eric Andersen25f27032001-04-26 23:22:31 +00003069 ctx->pipe->followup = type;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00003070 ctx->pipe->res_word = ctx->res_w;
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003071 /* Without this check, even just <enter> on command line generates
3072 * tree of three NOPs (!). Which is harmless but annoying.
3073 * IOW: it is safe to do it unconditionally. */
3074 if (not_null) {
3075 new_p = new_pipe();
3076 ctx->pipe->next = new_p;
3077 ctx->pipe = new_p;
3078 ctx->child = NULL;
3079 done_command(ctx); /* set up new pipe to accept commands */
3080 }
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003081 debug_printf_parse("done_pipe return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003082 return 0;
3083}
3084
3085/* peek ahead in the in_str to find out if we have a "&n" construct,
3086 * as in "2>&1", that represents duplicating a file descriptor.
3087 * returns either -2 (syntax error), -1 (no &), or the number found.
3088 */
3089static int redirect_dup_num(struct in_str *input)
3090{
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003091 int ch, d = 0, ok = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003092 ch = b_peek(input);
3093 if (ch != '&') return -1;
3094
3095 b_getch(input); /* get the & */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003096 ch = b_peek(input);
Eric Andersen83a2ae22001-05-07 17:59:25 +00003097 if (ch == '-') {
3098 b_getch(input);
3099 return -3; /* "-" represents "close me" */
3100 }
3101 while (isdigit(ch)) {
Denis Vlasenko7d4c44e2007-04-16 22:34:39 +00003102 d = d*10 + (ch-'0');
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003103 ok = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003104 b_getch(input);
Eric Andersen83a2ae22001-05-07 17:59:25 +00003105 ch = b_peek(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003106 }
3107 if (ok) return d;
3108
Manuel Novoa III cad53642003-03-19 09:13:01 +00003109 bb_error_msg("ambiguous redirect");
Eric Andersen25f27032001-04-26 23:22:31 +00003110 return -2;
3111}
3112
3113/* If a redirect is immediately preceded by a number, that number is
3114 * supposed to tell which file descriptor to redirect. This routine
3115 * looks for such preceding numbers. In an ideal world this routine
3116 * needs to handle all the following classes of redirects...
3117 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3118 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3119 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3120 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3121 * A -1 output from this program means no valid number was found, so the
3122 * caller should use the appropriate default for this redirection.
3123 */
3124static int redirect_opt_num(o_string *o)
3125{
3126 int num;
3127
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003128 if (o->length == 0)
3129 return -1;
3130 for (num = 0; num < o->length; num++) {
3131 if (!isdigit(*(o->data + num))) {
Eric Andersen25f27032001-04-26 23:22:31 +00003132 return -1;
3133 }
3134 }
3135 /* reuse num (and save an int) */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003136 num = atoi(o->data);
Eric Andersen25f27032001-04-26 23:22:31 +00003137 b_reset(o);
3138 return num;
3139}
3140
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003141#if ENABLE_HUSH_TICK
"Vladimir N. Oleynik"19c37012005-09-22 14:33:15 +00003142static FILE *generate_stream_from_list(struct pipe *head)
Eric Andersen25f27032001-04-26 23:22:31 +00003143{
3144 FILE *pf;
Eric Andersen25f27032001-04-26 23:22:31 +00003145 int pid, channel[2];
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003146 if (pipe(channel) < 0) bb_perror_msg_and_die("pipe");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003147#if BB_MMU
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003148 pid = fork();
Eric Andersen72f9a422001-10-28 05:12:20 +00003149#else
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003150 pid = vfork();
Eric Andersen72f9a422001-10-28 05:12:20 +00003151#endif
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003152 if (pid < 0) {
Manuel Novoa III cad53642003-03-19 09:13:01 +00003153 bb_perror_msg_and_die("fork");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003154 } else if (pid == 0) {
Eric Andersen25f27032001-04-26 23:22:31 +00003155 close(channel[0]);
3156 if (channel[1] != 1) {
Denis Vlasenko7d4c44e2007-04-16 22:34:39 +00003157 dup2(channel[1], 1);
Eric Andersen25f27032001-04-26 23:22:31 +00003158 close(channel[1]);
3159 }
Eric Andersen94ac2442001-05-22 19:05:18 +00003160 _exit(run_list_real(head)); /* leaks memory */
Eric Andersen25f27032001-04-26 23:22:31 +00003161 }
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003162 debug_printf("forked child %d\n", pid);
Eric Andersen25f27032001-04-26 23:22:31 +00003163 close(channel[1]);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003164 pf = fdopen(channel[0], "r");
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003165 debug_printf("pipe on FILE *%p\n", pf);
Eric Andersen25f27032001-04-26 23:22:31 +00003166 return pf;
3167}
3168
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003169/* Return code is exit status of the process that is run. */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003170static int process_command_subs(o_string *dest, struct p_context *ctx,
3171 struct in_str *input, const char *subst_end)
Eric Andersen25f27032001-04-26 23:22:31 +00003172{
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003173 int retcode, ch, eol_cnt;
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003174 o_string result = NULL_O_STRING;
Eric Andersen25f27032001-04-26 23:22:31 +00003175 struct p_context inner;
3176 FILE *p;
3177 struct in_str pipe_str;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003178
Eric Andersen25f27032001-04-26 23:22:31 +00003179 initialize_context(&inner);
3180
3181 /* recursion to generate command */
3182 retcode = parse_stream(&result, &inner, input, subst_end);
Denis Vlasenko1a735862007-05-23 00:32:25 +00003183 if (retcode != 0)
3184 return retcode; /* syntax error or EOF */
Eric Andersen25f27032001-04-26 23:22:31 +00003185 done_word(&result, &inner);
3186 done_pipe(&inner, PIPE_SEQ);
3187 b_free(&result);
3188
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003189 p = generate_stream_from_list(inner.list_head);
3190 if (p == NULL) return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003191 mark_open(fileno(p));
3192 setup_file_in_str(&pipe_str, p);
3193
3194 /* now send results of command back into original context */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003195 eol_cnt = 0;
3196 while ((ch = b_getch(&pipe_str)) != EOF) {
3197 if (ch == '\n') {
3198 eol_cnt++;
3199 continue;
3200 }
3201 while (eol_cnt) {
3202 b_addqchr(dest, '\n', dest->quote);
3203 eol_cnt--;
3204 }
3205 b_addqchr(dest, ch, dest->quote);
Eric Andersen25f27032001-04-26 23:22:31 +00003206 }
3207
3208 debug_printf("done reading from pipe, pclose()ing\n");
3209 /* This is the step that wait()s for the child. Should be pretty
3210 * safe, since we just read an EOF from its stdout. We could try
Denis Vlasenko262d7652007-05-20 21:52:49 +00003211 * to do better, by using wait(), and keeping track of background jobs
Eric Andersen25f27032001-04-26 23:22:31 +00003212 * at the same time. That would be a lot of work, and contrary
3213 * to the KISS philosophy of this program. */
3214 mark_closed(fileno(p));
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003215 retcode = pclose(p);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003216 free_pipe_list(inner.list_head, 0);
3217 debug_printf("pclosed, retcode=%d\n", retcode);
Eric Andersen25f27032001-04-26 23:22:31 +00003218 return retcode;
3219}
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003220#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003221
3222static int parse_group(o_string *dest, struct p_context *ctx,
3223 struct in_str *input, int ch)
3224{
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003225 int rcode;
3226 const char *endch = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003227 struct p_context sub;
3228 struct child_prog *child = ctx->child;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003229
3230 debug_printf_parse("parse_group entered\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003231 if (child->argv) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003232 syntax(NULL);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003233 debug_printf_parse("parse_group return 1: syntax error, groups and arglists don't mix\n");
3234 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003235 }
3236 initialize_context(&sub);
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003237 endch = "}";
3238 if (ch == '(') {
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003239 endch = ")";
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003240 child->subshell = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003241 }
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003242 rcode = parse_stream(dest, &sub, input, endch);
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00003243//vda: err chk?
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003244 done_word(dest, &sub); /* finish off the final word in the subcontext */
Eric Andersen25f27032001-04-26 23:22:31 +00003245 done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */
3246 child->group = sub.list_head;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003247
3248 debug_printf_parse("parse_group return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00003249 return rcode;
3250 /* child remains "open", available for possible redirects */
3251}
3252
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003253/* Basically useful version until someone wants to get fancier,
Eric Andersen25f27032001-04-26 23:22:31 +00003254 * see the bash man page under "Parameter Expansion" */
Denis Vlasenko15d78fb2007-01-30 22:28:21 +00003255static const char *lookup_param(const char *src)
Eric Andersen25f27032001-04-26 23:22:31 +00003256{
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003257 struct variable *var = get_local_var(src);
3258 if (var)
3259 return var->value;
3260 return NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003261}
3262
3263/* return code: 0 for OK, 1 for syntax error */
3264static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input)
3265{
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003266 int ch = b_peek(input); /* first character after the $ */
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003267 unsigned char quote_mask = dest->quote ? 0x80 : 0;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003268
3269 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003270 if (isalpha(ch)) {
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003271 b_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003272 //sp: ctx->child->sp++;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003273 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003274 debug_printf_parse(": '%c'\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003275 b_getch(input);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003276 b_addchr(dest, ch | quote_mask);
3277 quote_mask = 0;
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003278 ch = b_peek(input);
3279 if (!isalnum(ch) && ch != '_')
3280 break;
Eric Andersen25f27032001-04-26 23:22:31 +00003281 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003282 b_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003283 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003284 make_one_char_var:
3285 b_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003286 //sp: ctx->child->sp++;
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003287 debug_printf_parse(": '%c'\n", ch);
3288 b_getch(input);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003289 b_addchr(dest, ch | quote_mask);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003290 b_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003291 } else switch (ch) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003292 case '$': /* pid */
3293 case '!': /* last bg pid */
3294 case '?': /* last exit code */
3295 case '#': /* number of args */
3296 case '*': /* args */
3297 case '@': /* args */
3298 goto make_one_char_var;
Eric Andersen25f27032001-04-26 23:22:31 +00003299 case '{':
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003300 b_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003301 //sp: ctx->child->sp++;
Eric Andersen25f27032001-04-26 23:22:31 +00003302 b_getch(input);
3303 /* XXX maybe someone will try to escape the '}' */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003304 while (1) {
3305 ch = b_getch(input);
Denis Vlasenkob0550012007-05-24 12:18:16 +00003306 if (ch == '}')
3307 break;
3308 if (!isalnum(ch) && ch != '_') {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003309 syntax("unterminated ${name}");
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003310 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
3311 return 1;
3312 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003313 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003314 b_addchr(dest, ch | quote_mask);
3315 quote_mask = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003316 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003317 b_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003318 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003319#if ENABLE_HUSH_TICK
Eric Andersen25f27032001-04-26 23:22:31 +00003320 case '(':
Matt Kraai9f8caf12001-05-02 16:26:12 +00003321 b_getch(input);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003322 process_command_subs(dest, ctx, input, ")");
Eric Andersen25f27032001-04-26 23:22:31 +00003323 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003324#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003325 case '-':
3326 case '_':
3327 /* still unhandled, but should be eventually */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003328 bb_error_msg("unhandled syntax: $%c", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003329 return 1;
3330 break;
3331 default:
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003332 b_addqchr(dest, '$', dest->quote);
Eric Andersen25f27032001-04-26 23:22:31 +00003333 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003334 debug_printf_parse("handle_dollar return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003335 return 0;
3336}
3337
Eric Andersen25f27032001-04-26 23:22:31 +00003338/* return code is 0 for normal exit, 1 for syntax error */
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003339static int parse_stream(o_string *dest, struct p_context *ctx,
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003340 struct in_str *input, const char *end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00003341{
"Vladimir N. Oleynik"4ccd2b42006-01-31 09:27:48 +00003342 int ch, m;
Eric Andersen25f27032001-04-26 23:22:31 +00003343 int redir_fd;
3344 redir_type redir_style;
3345 int next;
3346
3347 /* Only double-quote state is handled in the state variable dest->quote.
3348 * A single-quote triggers a bypass of the main loop until its mate is
3349 * found. When recursing, quote state is passed in via dest->quote. */
3350
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003351 debug_printf_parse("parse_stream entered, end_trigger='%s'\n", end_trigger);
3352
Denis Vlasenko1a735862007-05-23 00:32:25 +00003353 while (1) {
Denis Vlasenko1a735862007-05-23 00:32:25 +00003354 m = CHAR_IFS;
3355 next = '\0';
Denis Vlasenko170435c2007-05-23 13:01:10 +00003356 ch = b_getch(input);
Denis Vlasenko1a735862007-05-23 00:32:25 +00003357 if (ch != EOF) {
3358 m = charmap[ch];
3359 if (ch != '\n')
3360 next = b_peek(input);
3361 }
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003362 debug_printf_parse(": ch=%c (%d) m=%d quote=%d\n",
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003363 ch, ch, m, dest->quote);
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003364 if (m == CHAR_ORDINARY
3365 || (m != CHAR_SPECIAL && dest->quote)
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003366 ) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00003367 if (ch == EOF) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003368 syntax("unterminated \"");
Denis Vlasenko170435c2007-05-23 13:01:10 +00003369 debug_printf_parse("parse_stream return 1: unterminated \"\n");
3370 return 1;
3371 }
Eric Andersen25f27032001-04-26 23:22:31 +00003372 b_addqchr(dest, ch, dest->quote);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003373 continue;
3374 }
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003375 if (m == CHAR_IFS) {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003376 if (done_word(dest, ctx)) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003377 debug_printf_parse("parse_stream return 1: done_word!=0\n");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003378 return 1;
Eric Andersenaac75e52001-04-30 18:18:45 +00003379 }
Denis Vlasenko1a735862007-05-23 00:32:25 +00003380 if (ch == EOF)
3381 break;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003382 /* If we aren't performing a substitution, treat
3383 * a newline as a command separator.
3384 * [why we don't handle it exactly like ';'? --vda] */
3385 if (end_trigger && ch == '\n') {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003386 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003387 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003388 }
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003389 if ((end_trigger && strchr(end_trigger, ch))
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003390 && !dest->quote && ctx->res_w == RES_NONE
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003391 ) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003392 debug_printf_parse("parse_stream return 0: end_trigger char found\n");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003393 return 0;
3394 }
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003395 if (m == CHAR_IFS)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003396 continue;
3397 switch (ch) {
Eric Andersen25f27032001-04-26 23:22:31 +00003398 case '#':
3399 if (dest->length == 0 && !dest->quote) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003400 while (1) {
3401 ch = b_peek(input);
3402 if (ch == EOF || ch == '\n')
3403 break;
3404 b_getch(input);
3405 }
Eric Andersen25f27032001-04-26 23:22:31 +00003406 } else {
3407 b_addqchr(dest, ch, dest->quote);
3408 }
3409 break;
3410 case '\\':
3411 if (next == EOF) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003412 syntax("\\<eof>");
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003413 debug_printf_parse("parse_stream return 1: \\<eof>\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003414 return 1;
3415 }
3416 b_addqchr(dest, '\\', dest->quote);
3417 b_addqchr(dest, b_getch(input), dest->quote);
3418 break;
3419 case '$':
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003420 if (handle_dollar(dest, ctx, input) != 0) {
3421 debug_printf_parse("parse_stream return 1: handle_dollar returned non-0\n");
3422 return 1;
3423 }
Eric Andersen25f27032001-04-26 23:22:31 +00003424 break;
3425 case '\'':
3426 dest->nonnull = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003427 while (1) {
3428 ch = b_getch(input);
3429 if (ch == EOF || ch == '\'')
3430 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003431 b_addchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003432 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003433 if (ch == EOF) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003434 syntax("unterminated '");
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003435 debug_printf_parse("parse_stream return 1: unterminated '\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003436 return 1;
3437 }
3438 break;
3439 case '"':
3440 dest->nonnull = 1;
3441 dest->quote = !dest->quote;
3442 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003443#if ENABLE_HUSH_TICK
Eric Andersen25f27032001-04-26 23:22:31 +00003444 case '`':
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003445 process_command_subs(dest, ctx, input, "`");
Eric Andersen25f27032001-04-26 23:22:31 +00003446 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003447#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003448 case '>':
3449 redir_fd = redirect_opt_num(dest);
3450 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003451 redir_style = REDIRECT_OVERWRITE;
Eric Andersen25f27032001-04-26 23:22:31 +00003452 if (next == '>') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003453 redir_style = REDIRECT_APPEND;
Eric Andersen25f27032001-04-26 23:22:31 +00003454 b_getch(input);
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003455 }
3456#if 0
3457 else if (next == '(') {
3458 syntax(">(process) not supported");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003459 debug_printf_parse("parse_stream return 1: >(process) not supported\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003460 return 1;
3461 }
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003462#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003463 setup_redirect(ctx, redir_fd, redir_style, input);
3464 break;
3465 case '<':
3466 redir_fd = redirect_opt_num(dest);
3467 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003468 redir_style = REDIRECT_INPUT;
Eric Andersen25f27032001-04-26 23:22:31 +00003469 if (next == '<') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003470 redir_style = REDIRECT_HEREIS;
Eric Andersen25f27032001-04-26 23:22:31 +00003471 b_getch(input);
3472 } else if (next == '>') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003473 redir_style = REDIRECT_IO;
Eric Andersen25f27032001-04-26 23:22:31 +00003474 b_getch(input);
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003475 }
3476#if 0
3477 else if (next == '(') {
3478 syntax("<(process) not supported");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003479 debug_printf_parse("parse_stream return 1: <(process) not supported\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003480 return 1;
3481 }
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003482#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003483 setup_redirect(ctx, redir_fd, redir_style, input);
3484 break;
3485 case ';':
3486 done_word(dest, ctx);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003487 done_pipe(ctx, PIPE_SEQ);
Eric Andersen25f27032001-04-26 23:22:31 +00003488 break;
3489 case '&':
3490 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003491 if (next == '&') {
Eric Andersen25f27032001-04-26 23:22:31 +00003492 b_getch(input);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003493 done_pipe(ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00003494 } else {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003495 done_pipe(ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00003496 }
3497 break;
3498 case '|':
3499 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003500 if (next == '|') {
Eric Andersen25f27032001-04-26 23:22:31 +00003501 b_getch(input);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003502 done_pipe(ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00003503 } else {
3504 /* we could pick up a file descriptor choice here
3505 * with redirect_opt_num(), but bash doesn't do it.
3506 * "echo foo 2| cat" yields "foo 2". */
3507 done_command(ctx);
3508 }
3509 break;
3510 case '(':
3511 case '{':
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003512 if (parse_group(dest, ctx, input, ch) != 0) {
3513 debug_printf_parse("parse_stream return 1: parse_group returned non-0\n");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003514 return 1;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003515 }
Eric Andersen25f27032001-04-26 23:22:31 +00003516 break;
3517 case ')':
3518 case '}':
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003519 syntax("unexpected }"); /* Proper use of this character is caught by end_trigger */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003520 debug_printf_parse("parse_stream return 1: unexpected '}'\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003521 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003522 default:
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003523 if (ENABLE_HUSH_DEBUG)
3524 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003525 }
3526 }
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003527 /* Complain if quote? No, maybe we just finished a command substitution
Eric Andersen25f27032001-04-26 23:22:31 +00003528 * that was quoted. Example:
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003529 * $ echo "`cat foo` plus more"
Eric Andersen25f27032001-04-26 23:22:31 +00003530 * and we just got the EOF generated by the subshell that ran "cat foo"
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003531 * The only real complaint is if we got an EOF when end_trigger != NULL,
Eric Andersen25f27032001-04-26 23:22:31 +00003532 * that is, we were really supposed to get end_trigger, and never got
3533 * one before the EOF. Can't use the standard "syntax error" return code,
3534 * so that parse_stream_outer can distinguish the EOF and exit smoothly. */
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003535 debug_printf_parse("parse_stream return %d\n", -(end_trigger != NULL));
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003536 if (end_trigger)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003537 return -1;
Eric Andersen25f27032001-04-26 23:22:31 +00003538 return 0;
3539}
3540
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003541static void set_in_charmap(const char *set, int code)
Eric Andersen25f27032001-04-26 23:22:31 +00003542{
Denis Vlasenkof5294e12007-04-14 10:09:57 +00003543 while (*set)
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003544 charmap[(unsigned char)*set++] = code;
Eric Andersen25f27032001-04-26 23:22:31 +00003545}
3546
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003547static void update_charmap(void)
Eric Andersen25f27032001-04-26 23:22:31 +00003548{
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003549 /* char *ifs and char charmap[256] are both globals. */
Eric Andersen25f27032001-04-26 23:22:31 +00003550 ifs = getenv("IFS");
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003551 if (ifs == NULL)
3552 ifs = " \t\n";
Eric Andersen25f27032001-04-26 23:22:31 +00003553 /* Precompute a list of 'flow through' behavior so it can be treated
3554 * quickly up front. Computation is necessary because of IFS.
3555 * Special case handling of IFS == " \t\n" is not implemented.
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003556 * The charmap[] array only really needs two bits each,
3557 * and on most machines that would be faster (reduced L1 cache use).
Eric Andersen25f27032001-04-26 23:22:31 +00003558 */
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003559 memset(charmap, CHAR_ORDINARY, sizeof(charmap));
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003560#if ENABLE_HUSH_TICK
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003561 set_in_charmap("\\$\"`", CHAR_SPECIAL);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003562#else
3563 set_in_charmap("\\$\"", CHAR_SPECIAL);
3564#endif
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003565 set_in_charmap("<>;&|(){}#'", CHAR_ORDINARY_IF_QUOTED);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003566 set_in_charmap(ifs, CHAR_IFS); /* are ordinary if quoted */
Eric Andersen25f27032001-04-26 23:22:31 +00003567}
3568
Eric Andersenaff114c2004-04-14 17:51:38 +00003569/* most recursion does not come through here, the exception is
Denis Vlasenko170435c2007-05-23 13:01:10 +00003570 * from builtin_source() and builtin_eval() */
3571static int parse_and_run_stream(struct in_str *inp, int parse_flag)
Eric Andersen25f27032001-04-26 23:22:31 +00003572{
Eric Andersen25f27032001-04-26 23:22:31 +00003573 struct p_context ctx;
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003574 o_string temp = NULL_O_STRING;
Eric Andersen25f27032001-04-26 23:22:31 +00003575 int rcode;
3576 do {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003577 ctx.parse_type = parse_flag;
Eric Andersen25f27032001-04-26 23:22:31 +00003578 initialize_context(&ctx);
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003579 update_charmap();
Denis Vlasenko219e88d2007-05-21 10:18:23 +00003580 if (!(parse_flag & PARSEFLAG_SEMICOLON) || (parse_flag & PARSEFLAG_REPARSING))
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003581 set_in_charmap(";$&|", CHAR_ORDINARY);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003582#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00003583 inp->promptmode = 0; /* PS1 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003584#endif
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003585 /* We will stop & execute after each ';' or '\n'.
3586 * Example: "sleep 9999; echo TEST" + ctrl-C:
3587 * TEST should be printed */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003588 rcode = parse_stream(&temp, &ctx, inp, ";\n");
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003589 if (rcode != 1 && ctx.old_flag != 0) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003590 syntax(NULL);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003591 }
3592 if (rcode != 1 && ctx.old_flag == 0) {
3593 done_word(&temp, &ctx);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003594 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003595 debug_print_tree(ctx.list_head, 0);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003596 debug_printf_exec("parse_stream_outer: run_list\n");
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003597 run_list(ctx.list_head);
3598 } else {
3599 if (ctx.old_flag != 0) {
3600 free(ctx.stack);
3601 b_reset(&temp);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003602 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003603 temp.nonnull = 0;
3604 temp.quote = 0;
3605 inp->p = NULL;
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00003606 free_pipe_list(ctx.list_head, 0);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003607 }
Eric Andersena813afc2001-05-24 16:19:36 +00003608 b_free(&temp);
Denis Vlasenko219e88d2007-05-21 10:18:23 +00003609 } while (rcode != -1 && !(parse_flag & PARSEFLAG_EXIT_FROM_LOOP)); /* loop on syntax errors, return on EOF */
Eric Andersen25f27032001-04-26 23:22:31 +00003610 return 0;
3611}
3612
Denis Vlasenko170435c2007-05-23 13:01:10 +00003613static int parse_and_run_string(const char *s, int parse_flag)
Eric Andersen25f27032001-04-26 23:22:31 +00003614{
3615 struct in_str input;
3616 setup_string_in_str(&input, s);
Denis Vlasenko170435c2007-05-23 13:01:10 +00003617 return parse_and_run_stream(&input, parse_flag);
Eric Andersen25f27032001-04-26 23:22:31 +00003618}
3619
Denis Vlasenko170435c2007-05-23 13:01:10 +00003620static int parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00003621{
3622 int rcode;
3623 struct in_str input;
3624 setup_file_in_str(&input, f);
Denis Vlasenko170435c2007-05-23 13:01:10 +00003625 rcode = parse_and_run_stream(&input, PARSEFLAG_SEMICOLON);
Eric Andersen25f27032001-04-26 23:22:31 +00003626 return rcode;
3627}
3628
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003629#if ENABLE_HUSH_JOB
Eric Andersen6c947d22001-06-25 22:24:38 +00003630/* Make sure we have a controlling tty. If we get started under a job
3631 * aware app (like bash for example), make sure we are now in charge so
3632 * we don't fight over who gets the foreground */
Eric Anderseneaecbf32001-10-31 10:41:31 +00003633static void setup_job_control(void)
Eric Andersen52a97ca2001-06-22 06:49:26 +00003634{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003635 pid_t shell_pgrp;
3636
Denis Vlasenkoa6a17852007-04-28 16:42:11 +00003637 saved_task_pgrp = shell_pgrp = getpgrp();
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003638 debug_printf_jobs("saved_task_pgrp=%d\n", saved_task_pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003639 fcntl(interactive_fd, F_SETFD, FD_CLOEXEC);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003640
Denis Vlasenkoa6a17852007-04-28 16:42:11 +00003641 /* If we were ran as 'hush &',
3642 * sleep until we are in the foreground. */
3643 while (tcgetpgrp(interactive_fd) != shell_pgrp) {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003644 /* Send TTIN to ourself (should stop us) */
Denis Vlasenkoff131b92007-04-10 15:42:06 +00003645 kill(- shell_pgrp, SIGTTIN);
Denis Vlasenkoa6a17852007-04-28 16:42:11 +00003646 shell_pgrp = getpgrp();
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003647 }
Eric Andersen52a97ca2001-06-22 06:49:26 +00003648
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003649 /* Ignore job-control and misc signals. */
3650 set_jobctrl_sighandler(SIG_IGN);
3651 set_misc_sighandler(SIG_IGN);
3652//huh? signal(SIGCHLD, SIG_IGN);
3653
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003654 /* We _must_ restore tty pgrp on fatal signals */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003655 set_fatal_sighandler(sigexit);
Eric Andersen6c947d22001-06-25 22:24:38 +00003656
3657 /* Put ourselves in our own process group. */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003658 setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
Eric Andersen6c947d22001-06-25 22:24:38 +00003659 /* Grab control of the terminal. */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003660 tcsetpgrp(interactive_fd, getpid());
Eric Andersen6c947d22001-06-25 22:24:38 +00003661}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003662#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00003663
Denis Vlasenko06af2162007-02-03 17:28:39 +00003664int hush_main(int argc, char **argv);
Matt Kraai2d91deb2001-08-01 17:21:35 +00003665int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00003666{
3667 int opt;
3668 FILE *input;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003669 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003670 struct variable *cur_var;
Eric Andersenbc604a22001-05-16 05:24:03 +00003671
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00003672 PTR_TO_GLOBALS = xzalloc(sizeof(G));
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003673
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00003674 shell_ver = const_shell_ver; /* copying struct here */
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003675 top_var = &shell_ver;
3676 /* initialize our shell local variables with the values
3677 * currently living in the environment */
3678 e = environ;
3679 cur_var = top_var;
3680 if (e) while (*e) {
3681 char *value = strchr(*e, '=');
3682 if (value) { /* paranoia */
3683 cur_var->next = xzalloc(sizeof(*cur_var));
3684 cur_var = cur_var->next;
3685 cur_var->name = *e;
3686 cur_var->value = value + 1;
3687 cur_var->max_len = strlen(*e);
3688 cur_var->flg_export = 1;
3689 }
3690 e++;
3691 }
3692 putenv(shell_ver.name);
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00003693
Denis Vlasenko38f63192007-01-22 09:03:07 +00003694#if ENABLE_FEATURE_EDITING
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00003695 line_input_state = new_line_input_t(FOR_SHELL);
3696#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003697 /* XXX what should these be while sourcing /etc/profile? */
3698 global_argc = argc;
3699 global_argv = argv;
Eric Andersen94ac2442001-05-22 19:05:18 +00003700 /* Initialize some more globals to non-zero values */
3701 set_cwd();
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003702#if ENABLE_HUSH_INTERACTIVE
3703#if ENABLE_FEATURE_EDITING
3704 cmdedit_set_initial_prompt();
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003705#endif
Eric Andersen94ac2442001-05-22 19:05:18 +00003706 PS2 = "> ";
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003707#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00003708
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003709 if (EXIT_SUCCESS) /* otherwise is already done */
3710 last_return_code = EXIT_SUCCESS;
Eric Andersen25f27032001-04-26 23:22:31 +00003711
3712 if (argv[0] && argv[0][0] == '-') {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003713 debug_printf("sourcing /etc/profile\n");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003714 input = fopen("/etc/profile", "r");
3715 if (input != NULL) {
Eric Andersena90f20b2001-06-26 23:00:21 +00003716 mark_open(fileno(input));
Denis Vlasenko170435c2007-05-23 13:01:10 +00003717 parse_and_run_file(input);
Eric Andersena90f20b2001-06-26 23:00:21 +00003718 mark_closed(fileno(input));
3719 fclose(input);
3720 }
Eric Andersen25f27032001-04-26 23:22:31 +00003721 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003722 input = stdin;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003723
Eric Andersen25f27032001-04-26 23:22:31 +00003724 while ((opt = getopt(argc, argv, "c:xif")) > 0) {
3725 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003726 case 'c':
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003727 global_argv = argv + optind;
3728 global_argc = argc - optind;
Denis Vlasenko170435c2007-05-23 13:01:10 +00003729 opt = parse_and_run_string(optarg, PARSEFLAG_SEMICOLON);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003730 goto final_return;
3731 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003732 /* Well, we cannot just declare interactiveness,
3733 * we have to have some stuff (ctty, etc) */
3734 /* interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003735 break;
3736 case 'f':
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00003737 fake_mode = 1;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003738 break;
3739 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00003740#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003741 fprintf(stderr, "Usage: sh [FILE]...\n"
3742 " or: sh -c command [args]...\n\n");
3743 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00003744#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003745 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00003746#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003747 }
3748 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003749#if ENABLE_HUSH_JOB
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003750 /* A shell is interactive if the '-i' flag was given, or if all of
Eric Andersen25f27032001-04-26 23:22:31 +00003751 * the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00003752 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00003753 * no arguments remaining or the -s flag given
3754 * standard input is a terminal
3755 * standard output is a terminal
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003756 * Refer to Posix.2, the description of the 'sh' utility. */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003757 if (argv[optind] == NULL && input == stdin
3758 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3759 ) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003760 saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
3761 debug_printf("saved_tty_pgrp=%d\n", saved_tty_pgrp);
3762 if (saved_tty_pgrp >= 0) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003763 /* try to dup to high fd#, >= 255 */
3764 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3765 if (interactive_fd < 0) {
3766 /* try to dup to any fd */
3767 interactive_fd = dup(STDIN_FILENO);
3768 if (interactive_fd < 0)
3769 /* give up */
3770 interactive_fd = 0;
3771 }
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00003772 // TODO: track & disallow any attempts of user
3773 // to (inadvertently) close/redirect it
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003774 }
Eric Andersen25f27032001-04-26 23:22:31 +00003775 }
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003776 debug_printf("interactive_fd=%d\n", interactive_fd);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003777 if (interactive_fd) {
Eric Andersen25f27032001-04-26 23:22:31 +00003778 /* Looks like they want an interactive shell */
Eric Andersen52a97ca2001-06-22 06:49:26 +00003779 setup_job_control();
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003780 /* Make xfuncs do cleanup on exit */
3781 die_sleep = -1; /* flag */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003782// FIXME: should we reset die_sleep = 0 whereever we fork?
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003783 if (setjmp(die_jmp)) {
3784 /* xfunc has failed! die die die */
3785 hush_exit(xfunc_error_retval);
3786 }
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00003787#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denis Vlasenkoef36ead2007-05-02 15:34:47 +00003788 printf("\n\n%s hush - the humble shell v"HUSH_VER_STR"\n", BB_BANNER);
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00003789 printf("Enter 'help' for a list of built-in commands.\n\n");
3790#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00003791 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003792#elif ENABLE_HUSH_INTERACTIVE
3793/* no job control compiled, only prompt/line editing */
3794 if (argv[optind] == NULL && input == stdin
3795 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3796 ) {
3797 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3798 if (interactive_fd < 0) {
3799 /* try to dup to any fd */
3800 interactive_fd = dup(STDIN_FILENO);
3801 if (interactive_fd < 0)
3802 /* give up */
3803 interactive_fd = 0;
3804 }
3805 }
3806
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003807#endif
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003808
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003809 if (argv[optind] == NULL) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00003810 opt = parse_and_run_file(stdin);
Eric Andersene67c3ce2001-05-02 02:09:36 +00003811 goto final_return;
Eric Andersen25f27032001-04-26 23:22:31 +00003812 }
Eric Andersen25f27032001-04-26 23:22:31 +00003813
3814 debug_printf("\nrunning script '%s'\n", argv[optind]);
Denis Vlasenko4c978632007-02-03 03:31:13 +00003815 global_argv = argv + optind;
3816 global_argc = argc - optind;
Rob Landleyd921b2e2006-08-03 15:41:12 +00003817 input = xfopen(argv[optind], "r");
Denis Vlasenko170435c2007-05-23 13:01:10 +00003818 opt = parse_and_run_file(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003819
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003820 final_return:
3821
Denis Vlasenko38f63192007-01-22 09:03:07 +00003822#if ENABLE_FEATURE_CLEAN_UP
Eric Andersenaeb44c42001-05-22 20:29:00 +00003823 fclose(input);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003824 if (cwd != bb_msg_unknown)
Eric Andersenaeb44c42001-05-22 20:29:00 +00003825 free((char*)cwd);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003826 cur_var = top_var->next;
3827 while (cur_var) {
3828 struct variable *tmp = cur_var;
3829 if (!cur_var->max_len)
3830 free(cur_var->name);
3831 cur_var = cur_var->next;
3832 free(tmp);
Eric Andersenaeb44c42001-05-22 20:29:00 +00003833 }
Eric Andersen25f27032001-04-26 23:22:31 +00003834#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003835 hush_exit(opt ? opt : last_return_code);
Eric Andersen25f27032001-04-26 23:22:31 +00003836}