]> git.ipfire.org Git - thirdparty/bash.git/blob - shell.c
commit bash-20120406 snapshot
[thirdparty/bash.git] / shell.c
1 /* shell.c -- GNU's idea of the POSIX shell specification. */
2
3 /* Copyright (C) 1987-2010 Free Software Foundation, Inc.
4
5 This file is part of GNU Bash, the Bourne Again SHell.
6
7 Bash is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
11
12 Bash is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with Bash. If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 /*
22 Birthdate:
23 Sunday, January 10th, 1988.
24 Initial author: Brian Fox
25 */
26 #define INSTALL_DEBUG_MODE
27
28 #include "config.h"
29
30 #include "bashtypes.h"
31 #if !defined (_MINIX) && defined (HAVE_SYS_FILE_H)
32 # include <sys/file.h>
33 #endif
34 #include "posixstat.h"
35 #include "posixtime.h"
36 #include "bashansi.h"
37 #include <stdio.h>
38 #include <signal.h>
39 #include <errno.h>
40 #include "filecntl.h"
41 #include <pwd.h>
42
43 #if defined (HAVE_UNISTD_H)
44 # include <unistd.h>
45 #endif
46
47 #include "bashintl.h"
48
49 #define NEED_SH_SETLINEBUF_DECL /* used in externs.h */
50
51 #include "shell.h"
52 #include "flags.h"
53 #include "trap.h"
54 #include "mailcheck.h"
55 #include "builtins.h"
56 #include "builtins/common.h"
57
58 #if defined (JOB_CONTROL)
59 #include "jobs.h"
60 #endif /* JOB_CONTROL */
61
62 #include "input.h"
63 #include "execute_cmd.h"
64 #include "findcmd.h"
65
66 #if defined (USING_BASH_MALLOC) && defined (DEBUG) && !defined (DISABLE_MALLOC_WRAPPERS)
67 # include <malloc/shmalloc.h>
68 #endif
69
70 #if defined (HISTORY)
71 # include "bashhist.h"
72 # include <readline/history.h>
73 #endif
74
75 #if defined (READLINE)
76 # include "bashline.h"
77 #endif
78
79 #include <tilde/tilde.h>
80 #include <glob/strmatch.h>
81
82 #if defined (__OPENNT)
83 # include <opennt/opennt.h>
84 #endif
85
86 #if !defined (HAVE_GETPW_DECLS)
87 extern struct passwd *getpwuid ();
88 #endif /* !HAVE_GETPW_DECLS */
89
90 #if !defined (errno)
91 extern int errno;
92 #endif
93
94 #if defined (NO_MAIN_ENV_ARG)
95 extern char **environ; /* used if no third argument to main() */
96 #endif
97
98 extern char *dist_version, *release_status;
99 extern int patch_level, build_version;
100 extern int shell_level;
101 extern int subshell_environment;
102 extern int last_command_exit_value;
103 extern int line_number;
104 extern int expand_aliases;
105 extern int array_needs_making;
106 extern int gnu_error_format;
107 extern char *primary_prompt, *secondary_prompt;
108 extern char *this_command_name;
109
110 /* Non-zero means that this shell has already been run; i.e. you should
111 call shell_reinitialize () if you need to start afresh. */
112 int shell_initialized = 0;
113
114 COMMAND *global_command = (COMMAND *)NULL;
115
116 /* Information about the current user. */
117 struct user_info current_user =
118 {
119 (uid_t)-1, (uid_t)-1, (gid_t)-1, (gid_t)-1,
120 (char *)NULL, (char *)NULL, (char *)NULL
121 };
122
123 /* The current host's name. */
124 char *current_host_name = (char *)NULL;
125
126 /* Non-zero means that this shell is a login shell.
127 Specifically:
128 0 = not login shell.
129 1 = login shell from getty (or equivalent fake out)
130 -1 = login shell from "--login" (or -l) flag.
131 -2 = both from getty, and from flag.
132 */
133 int login_shell = 0;
134
135 /* Non-zero means that at this moment, the shell is interactive. In
136 general, this means that the shell is at this moment reading input
137 from the keyboard. */
138 int interactive = 0;
139
140 /* Non-zero means that the shell was started as an interactive shell. */
141 int interactive_shell = 0;
142
143 /* Non-zero means to send a SIGHUP to all jobs when an interactive login
144 shell exits. */
145 int hup_on_exit = 0;
146
147 /* Non-zero means to list status of running and stopped jobs at shell exit */
148 int check_jobs_at_exit = 0;
149
150 /* Non-zero means to change to a directory name supplied as a command name */
151 int autocd = 0;
152
153 /* Tells what state the shell was in when it started:
154 0 = non-interactive shell script
155 1 = interactive
156 2 = -c command
157 3 = wordexp evaluation
158 This is a superset of the information provided by interactive_shell.
159 */
160 int startup_state = 0;
161
162 /* Special debugging helper. */
163 int debugging_login_shell = 0;
164
165 /* The environment that the shell passes to other commands. */
166 char **shell_environment;
167
168 /* Non-zero when we are executing a top-level command. */
169 int executing = 0;
170
171 /* The number of commands executed so far. */
172 int current_command_number = 1;
173
174 /* Non-zero is the recursion depth for commands. */
175 int indirection_level = 0;
176
177 /* The name of this shell, as taken from argv[0]. */
178 char *shell_name = (char *)NULL;
179
180 /* time in seconds when the shell was started */
181 time_t shell_start_time;
182
183 /* Are we running in an emacs shell window? */
184 int running_under_emacs;
185
186 /* Do we have /dev/fd? */
187 #ifdef HAVE_DEV_FD
188 int have_devfd = HAVE_DEV_FD;
189 #else
190 int have_devfd = 0;
191 #endif
192
193 /* The name of the .(shell)rc file. */
194 static char *bashrc_file = "~/.bashrc";
195
196 /* Non-zero means to act more like the Bourne shell on startup. */
197 static int act_like_sh;
198
199 /* Non-zero if this shell is being run by `su'. */
200 static int su_shell;
201
202 /* Non-zero if we have already expanded and sourced $ENV. */
203 static int sourced_env;
204
205 /* Is this shell running setuid? */
206 static int running_setuid;
207
208 /* Values for the long-winded argument names. */
209 static int debugging; /* Do debugging things. */
210 static int no_rc; /* Don't execute ~/.bashrc */
211 static int no_profile; /* Don't execute .profile */
212 static int do_version; /* Display interesting version info. */
213 static int make_login_shell; /* Make this shell be a `-bash' shell. */
214 static int want_initial_help; /* --help option */
215
216 int debugging_mode = 0; /* In debugging mode with --debugger */
217 #if defined (READLINE)
218 int no_line_editing = 0; /* non-zero -> don't do fancy line editing. */
219 #else
220 int no_line_editing = 1; /* can't have line editing without readline */
221 #endif
222 int dump_translatable_strings; /* Dump strings in $"...", don't execute. */
223 int dump_po_strings; /* Dump strings in $"..." in po format */
224 int wordexp_only = 0; /* Do word expansion only */
225 int protected_mode = 0; /* No command substitution with --wordexp */
226
227 #if defined (STRICT_POSIX)
228 int posixly_correct = 1; /* Non-zero means posix.2 superset. */
229 #else
230 int posixly_correct = 0; /* Non-zero means posix.2 superset. */
231 #endif
232
233 /* Some long-winded argument names. These are obviously new. */
234 #define Int 1
235 #define Charp 2
236 static const struct {
237 const char *name;
238 int type;
239 int *int_value;
240 char **char_value;
241 } long_args[] = {
242 { "debug", Int, &debugging, (char **)0x0 },
243 #if defined (DEBUGGER)
244 { "debugger", Int, &debugging_mode, (char **)0x0 },
245 #endif
246 { "dump-po-strings", Int, &dump_po_strings, (char **)0x0 },
247 { "dump-strings", Int, &dump_translatable_strings, (char **)0x0 },
248 { "help", Int, &want_initial_help, (char **)0x0 },
249 { "init-file", Charp, (int *)0x0, &bashrc_file },
250 { "login", Int, &make_login_shell, (char **)0x0 },
251 { "noediting", Int, &no_line_editing, (char **)0x0 },
252 { "noprofile", Int, &no_profile, (char **)0x0 },
253 { "norc", Int, &no_rc, (char **)0x0 },
254 { "posix", Int, &posixly_correct, (char **)0x0 },
255 { "protected", Int, &protected_mode, (char **)0x0 },
256 { "rcfile", Charp, (int *)0x0, &bashrc_file },
257 #if defined (RESTRICTED_SHELL)
258 { "restricted", Int, &restricted, (char **)0x0 },
259 #endif
260 { "verbose", Int, &echo_input_at_read, (char **)0x0 },
261 { "version", Int, &do_version, (char **)0x0 },
262 #if defined (WORDEXP_OPTION)
263 { "wordexp", Int, &wordexp_only, (char **)0x0 },
264 #endif
265 { (char *)0x0, Int, (int *)0x0, (char **)0x0 }
266 };
267
268 /* These are extern so execute_simple_command can set them, and then
269 longjmp back to main to execute a shell script, instead of calling
270 main () again and resulting in indefinite, possibly fatal, stack
271 growth. */
272 procenv_t subshell_top_level;
273 int subshell_argc;
274 char **subshell_argv;
275 char **subshell_envp;
276
277 char *exec_argv0;
278
279 #if defined (BUFFERED_INPUT)
280 /* The file descriptor from which the shell is reading input. */
281 int default_buffered_input = -1;
282 #endif
283
284 /* The following two variables are not static so they can show up in $-. */
285 int read_from_stdin; /* -s flag supplied */
286 int want_pending_command; /* -c flag supplied */
287
288 /* This variable is not static so it can be bound to $BASH_EXECUTION_STRING */
289 char *command_execution_string; /* argument to -c option */
290
291 int malloc_trace_at_exit = 0;
292
293 static int shell_reinitialized = 0;
294
295 static FILE *default_input;
296
297 static STRING_INT_ALIST *shopt_alist;
298 static int shopt_ind = 0, shopt_len = 0;
299
300 static int parse_long_options __P((char **, int, int));
301 static int parse_shell_options __P((char **, int, int));
302 static int bind_args __P((char **, int, int, int));
303
304 static void start_debugger __P((void));
305
306 static void add_shopt_to_alist __P((char *, int));
307 static void run_shopt_alist __P((void));
308
309 static void execute_env_file __P((char *));
310 static void run_startup_files __P((void));
311 static int open_shell_script __P((char *));
312 static void set_bash_input __P((void));
313 static int run_one_command __P((char *));
314 #if defined (WORDEXP_OPTION)
315 static int run_wordexp __P((char *));
316 #endif
317
318 static int uidget __P((void));
319
320 static void init_interactive __P((void));
321 static void init_noninteractive __P((void));
322 static void init_interactive_script __P((void));
323
324 static void set_shell_name __P((char *));
325 static void shell_initialize __P((void));
326 static void shell_reinitialize __P((void));
327
328 static void show_shell_usage __P((FILE *, int));
329
330 #ifdef __CYGWIN__
331 static void
332 _cygwin32_check_tmp ()
333 {
334 struct stat sb;
335
336 if (stat ("/tmp", &sb) < 0)
337 internal_warning (_("could not find /tmp, please create!"));
338 else
339 {
340 if (S_ISDIR (sb.st_mode) == 0)
341 internal_warning (_("/tmp must be a valid directory name"));
342 }
343 }
344 #endif /* __CYGWIN__ */
345
346 #if defined (NO_MAIN_ENV_ARG)
347 /* systems without third argument to main() */
348 int
349 main (argc, argv)
350 int argc;
351 char **argv;
352 #else /* !NO_MAIN_ENV_ARG */
353 int
354 main (argc, argv, env)
355 int argc;
356 char **argv, **env;
357 #endif /* !NO_MAIN_ENV_ARG */
358 {
359 register int i;
360 int code, old_errexit_flag;
361 #if defined (RESTRICTED_SHELL)
362 int saverst;
363 #endif
364 volatile int locally_skip_execution;
365 volatile int arg_index, top_level_arg_index;
366 #ifdef __OPENNT
367 char **env;
368
369 env = environ;
370 #endif /* __OPENNT */
371
372 USE_VAR(argc);
373 USE_VAR(argv);
374 USE_VAR(env);
375 USE_VAR(code);
376 USE_VAR(old_errexit_flag);
377 #if defined (RESTRICTED_SHELL)
378 USE_VAR(saverst);
379 #endif
380
381 /* Catch early SIGINTs. */
382 code = setjmp (top_level);
383 if (code)
384 exit (2);
385
386 xtrace_init ();
387
388 #if defined (USING_BASH_MALLOC) && defined (DEBUG) && !defined (DISABLE_MALLOC_WRAPPERS)
389 # if 1
390 malloc_set_register (1);
391 # endif
392 #endif
393
394 check_dev_tty ();
395
396 #ifdef __CYGWIN__
397 _cygwin32_check_tmp ();
398 #endif /* __CYGWIN__ */
399
400 /* Wait forever if we are debugging a login shell. */
401 while (debugging_login_shell) sleep (3);
402
403 set_default_locale ();
404
405 running_setuid = uidget ();
406
407 if (getenv ("POSIXLY_CORRECT") || getenv ("POSIX_PEDANTIC"))
408 posixly_correct = 1;
409
410 #if defined (USE_GNU_MALLOC_LIBRARY)
411 mcheck (programming_error, (void (*) ())0);
412 #endif /* USE_GNU_MALLOC_LIBRARY */
413
414 if (setjmp (subshell_top_level))
415 {
416 argc = subshell_argc;
417 argv = subshell_argv;
418 env = subshell_envp;
419 sourced_env = 0;
420 }
421
422 shell_reinitialized = 0;
423
424 /* Initialize `local' variables for all `invocations' of main (). */
425 arg_index = 1;
426 if (arg_index > argc)
427 arg_index = argc;
428 command_execution_string = (char *)NULL;
429 want_pending_command = locally_skip_execution = read_from_stdin = 0;
430 default_input = stdin;
431 #if defined (BUFFERED_INPUT)
432 default_buffered_input = -1;
433 #endif
434
435 /* Fix for the `infinite process creation' bug when running shell scripts
436 from startup files on System V. */
437 login_shell = make_login_shell = 0;
438
439 /* If this shell has already been run, then reinitialize it to a
440 vanilla state. */
441 if (shell_initialized || shell_name)
442 {
443 /* Make sure that we do not infinitely recurse as a login shell. */
444 if (*shell_name == '-')
445 shell_name++;
446
447 shell_reinitialize ();
448 if (setjmp (top_level))
449 exit (2);
450 }
451
452 shell_environment = env;
453 set_shell_name (argv[0]);
454 shell_start_time = NOW; /* NOW now defined in general.h */
455
456 /* Parse argument flags from the input line. */
457
458 /* Find full word arguments first. */
459 arg_index = parse_long_options (argv, arg_index, argc);
460
461 if (want_initial_help)
462 {
463 show_shell_usage (stdout, 1);
464 exit (EXECUTION_SUCCESS);
465 }
466
467 if (do_version)
468 {
469 show_shell_version (1);
470 exit (EXECUTION_SUCCESS);
471 }
472
473 /* All done with full word options; do standard shell option parsing.*/
474 this_command_name = shell_name; /* for error reporting */
475 arg_index = parse_shell_options (argv, arg_index, argc);
476
477 /* If user supplied the "--login" (or -l) flag, then set and invert
478 LOGIN_SHELL. */
479 if (make_login_shell)
480 {
481 login_shell++;
482 login_shell = -login_shell;
483 }
484
485 set_login_shell ("login_shell", login_shell != 0);
486
487 if (dump_po_strings)
488 dump_translatable_strings = 1;
489
490 if (dump_translatable_strings)
491 read_but_dont_execute = 1;
492
493 if (running_setuid && privileged_mode == 0)
494 disable_priv_mode ();
495
496 /* Need to get the argument to a -c option processed in the
497 above loop. The next arg is a command to execute, and the
498 following args are $0...$n respectively. */
499 if (want_pending_command)
500 {
501 command_execution_string = argv[arg_index];
502 if (command_execution_string == 0)
503 {
504 report_error (_("%s: option requires an argument"), "-c");
505 exit (EX_BADUSAGE);
506 }
507 arg_index++;
508 }
509 this_command_name = (char *)NULL;
510
511 cmd_init(); /* initialize the command object caches */
512
513 /* First, let the outside world know about our interactive status.
514 A shell is interactive if the `-i' flag was given, or if all of
515 the following conditions are met:
516 no -c command
517 no arguments remaining or the -s flag given
518 standard input is a terminal
519 standard error is a terminal
520 Refer to Posix.2, the description of the `sh' utility. */
521
522 if (forced_interactive || /* -i flag */
523 (!command_execution_string && /* No -c command and ... */
524 wordexp_only == 0 && /* No --wordexp and ... */
525 ((arg_index == argc) || /* no remaining args or... */
526 read_from_stdin) && /* -s flag with args, and */
527 isatty (fileno (stdin)) && /* Input is a terminal and */
528 isatty (fileno (stderr)))) /* error output is a terminal. */
529 init_interactive ();
530 else
531 init_noninteractive ();
532
533 /*
534 * Some systems have the bad habit of starting login shells with lots of open
535 * file descriptors. For instance, most systems that have picked up the
536 * pre-4.0 Sun YP code leave a file descriptor open each time you call one
537 * of the getpw* functions, and it's set to be open across execs. That
538 * means one for login, one for xterm, one for shelltool, etc. There are
539 * also systems that open persistent FDs to other agents or files as part
540 * of process startup; these need to be set to be close-on-exec.
541 */
542 if (login_shell && interactive_shell)
543 {
544 for (i = 3; i < 20; i++)
545 SET_CLOSE_ON_EXEC (i);
546 }
547
548 /* If we're in a strict Posix.2 mode, turn on interactive comments,
549 alias expansion in non-interactive shells, and other Posix.2 things. */
550 if (posixly_correct)
551 {
552 bind_variable ("POSIXLY_CORRECT", "y", 0);
553 sv_strict_posix ("POSIXLY_CORRECT");
554 }
555
556 /* Now we run the shopt_alist and process the options. */
557 if (shopt_alist)
558 run_shopt_alist ();
559
560 /* From here on in, the shell must be a normal functioning shell.
561 Variables from the environment are expected to be set, etc. */
562 shell_initialize ();
563
564 set_default_lang ();
565 set_default_locale_vars ();
566
567 /*
568 * M-x term -> TERM=eterm EMACS=22.1 (term:0.96) (eterm)
569 * M-x shell -> TERM=dumb EMACS=t (no line editing)
570 * M-x terminal -> TERM=emacs-em7955 EMACS= (line editing)
571 */
572 if (interactive_shell)
573 {
574 char *term, *emacs;
575
576 term = get_string_value ("TERM");
577 emacs = get_string_value ("EMACS");
578
579 /* Not sure any emacs terminal emulator sets TERM=emacs any more */
580 no_line_editing |= term && (STREQ (term, "emacs"));
581 no_line_editing |= emacs && emacs[0] == 't' && emacs[1] == '\0' && STREQ (term, "dumb");
582
583 /* running_under_emacs == 2 for `eterm' */
584 running_under_emacs = (emacs != 0) || (term && STREQN (term, "emacs", 5));
585 running_under_emacs += term && STREQN (term, "eterm", 5) && emacs && strstr (emacs, "term");
586
587 if (running_under_emacs)
588 gnu_error_format = 1;
589 }
590
591 top_level_arg_index = arg_index;
592 old_errexit_flag = exit_immediately_on_error;
593
594 /* Give this shell a place to longjmp to before executing the
595 startup files. This allows users to press C-c to abort the
596 lengthy startup. */
597 code = setjmp (top_level);
598 if (code)
599 {
600 if (code == EXITPROG || code == ERREXIT)
601 exit_shell (last_command_exit_value);
602 else
603 {
604 #if defined (JOB_CONTROL)
605 /* Reset job control, since run_startup_files turned it off. */
606 set_job_control (interactive_shell);
607 #endif
608 /* Reset value of `set -e', since it's turned off before running
609 the startup files. */
610 exit_immediately_on_error += old_errexit_flag;
611 locally_skip_execution++;
612 }
613 }
614
615 arg_index = top_level_arg_index;
616
617 /* Execute the start-up scripts. */
618
619 if (interactive_shell == 0)
620 {
621 unbind_variable ("PS1");
622 unbind_variable ("PS2");
623 interactive = 0;
624 #if 0
625 /* This has already been done by init_noninteractive */
626 expand_aliases = posixly_correct;
627 #endif
628 }
629 else
630 {
631 change_flag ('i', FLAG_ON);
632 interactive = 1;
633 }
634
635 #if defined (RESTRICTED_SHELL)
636 /* Set restricted_shell based on whether the basename of $0 indicates that
637 the shell should be restricted or if the `-r' option was supplied at
638 startup. */
639 restricted_shell = shell_is_restricted (shell_name);
640
641 /* If the `-r' option is supplied at invocation, make sure that the shell
642 is not in restricted mode when running the startup files. */
643 saverst = restricted;
644 restricted = 0;
645 #endif
646
647 /* The startup files are run with `set -e' temporarily disabled. */
648 if (locally_skip_execution == 0 && running_setuid == 0)
649 {
650 old_errexit_flag = exit_immediately_on_error;
651 exit_immediately_on_error = 0;
652
653 run_startup_files ();
654 exit_immediately_on_error += old_errexit_flag;
655 }
656
657 /* If we are invoked as `sh', turn on Posix mode. */
658 if (act_like_sh)
659 {
660 bind_variable ("POSIXLY_CORRECT", "y", 0);
661 sv_strict_posix ("POSIXLY_CORRECT");
662 }
663
664 #if defined (RESTRICTED_SHELL)
665 /* Turn on the restrictions after executing the startup files. This
666 means that `bash -r' or `set -r' invoked from a startup file will
667 turn on the restrictions after the startup files are executed. */
668 restricted = saverst || restricted;
669 if (shell_reinitialized == 0)
670 maybe_make_restricted (shell_name);
671 #endif /* RESTRICTED_SHELL */
672
673 #if defined (WORDEXP_OPTION)
674 if (wordexp_only)
675 {
676 startup_state = 3;
677 last_command_exit_value = run_wordexp (argv[arg_index]);
678 exit_shell (last_command_exit_value);
679 }
680 #endif
681
682 if (command_execution_string)
683 {
684 arg_index = bind_args (argv, arg_index, argc, 0);
685 startup_state = 2;
686
687 if (debugging_mode)
688 start_debugger ();
689
690 #if defined (ONESHOT)
691 executing = 1;
692 run_one_command (command_execution_string);
693 exit_shell (last_command_exit_value);
694 #else /* ONESHOT */
695 with_input_from_string (command_execution_string, "-c");
696 goto read_and_execute;
697 #endif /* !ONESHOT */
698 }
699
700 /* Get possible input filename and set up default_buffered_input or
701 default_input as appropriate. */
702 if (arg_index != argc && read_from_stdin == 0)
703 {
704 open_shell_script (argv[arg_index]);
705 arg_index++;
706 }
707 else if (interactive == 0)
708 /* In this mode, bash is reading a script from stdin, which is a
709 pipe or redirected file. */
710 #if defined (BUFFERED_INPUT)
711 default_buffered_input = fileno (stdin); /* == 0 */
712 #else
713 setbuf (default_input, (char *)NULL);
714 #endif /* !BUFFERED_INPUT */
715
716 set_bash_input ();
717
718 /* Bind remaining args to $1 ... $n */
719 arg_index = bind_args (argv, arg_index, argc, 1);
720
721 if (debugging_mode && locally_skip_execution == 0 && running_setuid == 0)
722 start_debugger ();
723
724 /* Do the things that should be done only for interactive shells. */
725 if (interactive_shell)
726 {
727 /* Set up for checking for presence of mail. */
728 reset_mail_timer ();
729 init_mail_dates ();
730
731 #if defined (HISTORY)
732 /* Initialize the interactive history stuff. */
733 bash_initialize_history ();
734 /* Don't load the history from the history file if we've already
735 saved some lines in this session (e.g., by putting `history -s xx'
736 into one of the startup files). */
737 if (shell_initialized == 0 && history_lines_this_session == 0)
738 load_history ();
739 #endif /* HISTORY */
740
741 /* Initialize terminal state for interactive shells after the
742 .bash_profile and .bashrc are interpreted. */
743 get_tty_state ();
744 }
745
746 #if !defined (ONESHOT)
747 read_and_execute:
748 #endif /* !ONESHOT */
749
750 shell_initialized = 1;
751
752 /* Read commands until exit condition. */
753 reader_loop ();
754 exit_shell (last_command_exit_value);
755 }
756
757 static int
758 parse_long_options (argv, arg_start, arg_end)
759 char **argv;
760 int arg_start, arg_end;
761 {
762 int arg_index, longarg, i;
763 char *arg_string;
764
765 arg_index = arg_start;
766 while ((arg_index != arg_end) && (arg_string = argv[arg_index]) &&
767 (*arg_string == '-'))
768 {
769 longarg = 0;
770
771 /* Make --login equivalent to -login. */
772 if (arg_string[1] == '-' && arg_string[2])
773 {
774 longarg = 1;
775 arg_string++;
776 }
777
778 for (i = 0; long_args[i].name; i++)
779 {
780 if (STREQ (arg_string + 1, long_args[i].name))
781 {
782 if (long_args[i].type == Int)
783 *long_args[i].int_value = 1;
784 else if (argv[++arg_index] == 0)
785 {
786 report_error (_("%s: option requires an argument"), long_args[i].name);
787 exit (EX_BADUSAGE);
788 }
789 else
790 *long_args[i].char_value = argv[arg_index];
791
792 break;
793 }
794 }
795 if (long_args[i].name == 0)
796 {
797 if (longarg)
798 {
799 report_error (_("%s: invalid option"), argv[arg_index]);
800 show_shell_usage (stderr, 0);
801 exit (EX_BADUSAGE);
802 }
803 break; /* No such argument. Maybe flag arg. */
804 }
805
806 arg_index++;
807 }
808
809 return (arg_index);
810 }
811
812 static int
813 parse_shell_options (argv, arg_start, arg_end)
814 char **argv;
815 int arg_start, arg_end;
816 {
817 int arg_index;
818 int arg_character, on_or_off, next_arg, i;
819 char *o_option, *arg_string;
820
821 arg_index = arg_start;
822 while (arg_index != arg_end && (arg_string = argv[arg_index]) &&
823 (*arg_string == '-' || *arg_string == '+'))
824 {
825 /* There are flag arguments, so parse them. */
826 next_arg = arg_index + 1;
827
828 /* A single `-' signals the end of options. From the 4.3 BSD sh.
829 An option `--' means the same thing; this is the standard
830 getopt(3) meaning. */
831 if (arg_string[0] == '-' &&
832 (arg_string[1] == '\0' ||
833 (arg_string[1] == '-' && arg_string[2] == '\0')))
834 return (next_arg);
835
836 i = 1;
837 on_or_off = arg_string[0];
838 while (arg_character = arg_string[i++])
839 {
840 switch (arg_character)
841 {
842 case 'c':
843 want_pending_command = 1;
844 break;
845
846 case 'l':
847 make_login_shell = 1;
848 break;
849
850 case 's':
851 read_from_stdin = 1;
852 break;
853
854 case 'o':
855 o_option = argv[next_arg];
856 if (o_option == 0)
857 {
858 list_minus_o_opts (-1, (on_or_off == '-') ? 0 : 1);
859 break;
860 }
861 if (set_minus_o_option (on_or_off, o_option) != EXECUTION_SUCCESS)
862 exit (EX_BADUSAGE);
863 next_arg++;
864 break;
865
866 case 'O':
867 /* Since some of these can be overridden by the normal
868 interactive/non-interactive shell initialization or
869 initializing posix mode, we save the options and process
870 them after initialization. */
871 o_option = argv[next_arg];
872 if (o_option == 0)
873 {
874 shopt_listopt (o_option, (on_or_off == '-') ? 0 : 1);
875 break;
876 }
877 add_shopt_to_alist (o_option, on_or_off);
878 next_arg++;
879 break;
880
881 case 'D':
882 dump_translatable_strings = 1;
883 break;
884
885 default:
886 if (change_flag (arg_character, on_or_off) == FLAG_ERROR)
887 {
888 report_error (_("%c%c: invalid option"), on_or_off, arg_character);
889 show_shell_usage (stderr, 0);
890 exit (EX_BADUSAGE);
891 }
892 }
893 }
894 /* Can't do just a simple increment anymore -- what about
895 "bash -abouo emacs ignoreeof -hP"? */
896 arg_index = next_arg;
897 }
898
899 return (arg_index);
900 }
901
902 /* Exit the shell with status S. */
903 void
904 exit_shell (s)
905 int s;
906 {
907 fflush (stdout); /* XXX */
908 fflush (stderr);
909
910 /* Do trap[0] if defined. Allow it to override the exit status
911 passed to us. */
912 if (signal_is_trapped (0))
913 s = run_exit_trap ();
914
915 #if defined (PROCESS_SUBSTITUTION)
916 unlink_fifo_list ();
917 #endif /* PROCESS_SUBSTITUTION */
918
919 #if defined (HISTORY)
920 if (remember_on_history)
921 maybe_save_shell_history ();
922 #endif /* HISTORY */
923
924 #if defined (COPROCESS_SUPPORT)
925 coproc_flush ();
926 #endif
927
928 #if defined (JOB_CONTROL)
929 /* If the user has run `shopt -s huponexit', hangup all jobs when we exit
930 an interactive login shell. ksh does this unconditionally. */
931 if (interactive_shell && login_shell && hup_on_exit)
932 hangup_all_jobs ();
933
934 /* If this shell is interactive, terminate all stopped jobs and
935 restore the original terminal process group. Don't do this if we're
936 in a subshell and calling exit_shell after, for example, a failed
937 word expansion. */
938 if (subshell_environment == 0)
939 end_job_control ();
940 #endif /* JOB_CONTROL */
941
942 /* Always return the exit status of the last command to our parent. */
943 sh_exit (s);
944 }
945
946 /* A wrapper for exit that (optionally) can do other things, like malloc
947 statistics tracing. */
948 void
949 sh_exit (s)
950 int s;
951 {
952 #if defined (MALLOC_DEBUG) && defined (USING_BASH_MALLOC)
953 if (malloc_trace_at_exit)
954 trace_malloc_stats (get_name_for_error (), (char *)NULL);
955 #endif
956
957 exit (s);
958 }
959
960 /* Source the bash startup files. If POSIXLY_CORRECT is non-zero, we obey
961 the Posix.2 startup file rules: $ENV is expanded, and if the file it
962 names exists, that file is sourced. The Posix.2 rules are in effect
963 for interactive shells only. (section 4.56.5.3) */
964
965 /* Execute ~/.bashrc for most shells. Never execute it if
966 ACT_LIKE_SH is set, or if NO_RC is set.
967
968 If the executable file "/usr/gnu/src/bash/foo" contains:
969
970 #!/usr/gnu/bin/bash
971 echo hello
972
973 then:
974
975 COMMAND EXECUTE BASHRC
976 --------------------------------
977 bash -c foo NO
978 bash foo NO
979 foo NO
980 rsh machine ls YES (for rsh, which calls `bash -c')
981 rsh machine foo YES (for shell started by rsh) NO (for foo!)
982 echo ls | bash NO
983 login NO
984 bash YES
985 */
986
987 static void
988 execute_env_file (env_file)
989 char *env_file;
990 {
991 char *fn;
992
993 if (env_file && *env_file)
994 {
995 fn = expand_string_unsplit_to_string (env_file, Q_DOUBLE_QUOTES);
996 if (fn && *fn)
997 maybe_execute_file (fn, 1);
998 FREE (fn);
999 }
1000 }
1001
1002 static void
1003 run_startup_files ()
1004 {
1005 #if defined (JOB_CONTROL)
1006 int old_job_control;
1007 #endif
1008 int sourced_login, run_by_ssh;
1009
1010 /* get the rshd/sshd case out of the way first. */
1011 if (interactive_shell == 0 && no_rc == 0 && login_shell == 0 &&
1012 act_like_sh == 0 && command_execution_string)
1013 {
1014 #ifdef SSH_SOURCE_BASHRC
1015 run_by_ssh = (find_variable ("SSH_CLIENT") != (SHELL_VAR *)0) ||
1016 (find_variable ("SSH2_CLIENT") != (SHELL_VAR *)0);
1017 #else
1018 run_by_ssh = 0;
1019 #endif
1020
1021 /* If we were run by sshd or we think we were run by rshd, execute
1022 ~/.bashrc if we are a top-level shell. */
1023 if ((run_by_ssh || isnetconn (fileno (stdin))) && shell_level < 2)
1024 {
1025 #ifdef SYS_BASHRC
1026 # if defined (__OPENNT)
1027 maybe_execute_file (_prefixInstallPath(SYS_BASHRC, NULL, 0), 1);
1028 # else
1029 maybe_execute_file (SYS_BASHRC, 1);
1030 # endif
1031 #endif
1032 maybe_execute_file (bashrc_file, 1);
1033 return;
1034 }
1035 }
1036
1037 #if defined (JOB_CONTROL)
1038 /* Startup files should be run without job control enabled. */
1039 old_job_control = interactive_shell ? set_job_control (0) : 0;
1040 #endif
1041
1042 sourced_login = 0;
1043
1044 /* A shell begun with the --login (or -l) flag that is not in posix mode
1045 runs the login shell startup files, no matter whether or not it is
1046 interactive. If NON_INTERACTIVE_LOGIN_SHELLS is defined, run the
1047 startup files if argv[0][0] == '-' as well. */
1048 #if defined (NON_INTERACTIVE_LOGIN_SHELLS)
1049 if (login_shell && posixly_correct == 0)
1050 #else
1051 if (login_shell < 0 && posixly_correct == 0)
1052 #endif
1053 {
1054 /* We don't execute .bashrc for login shells. */
1055 no_rc++;
1056
1057 /* Execute /etc/profile and one of the personal login shell
1058 initialization files. */
1059 if (no_profile == 0)
1060 {
1061 maybe_execute_file (SYS_PROFILE, 1);
1062
1063 if (act_like_sh) /* sh */
1064 maybe_execute_file ("~/.profile", 1);
1065 else if ((maybe_execute_file ("~/.bash_profile", 1) == 0) &&
1066 (maybe_execute_file ("~/.bash_login", 1) == 0)) /* bash */
1067 maybe_execute_file ("~/.profile", 1);
1068 }
1069
1070 sourced_login = 1;
1071 }
1072
1073 /* A non-interactive shell not named `sh' and not in posix mode reads and
1074 executes commands from $BASH_ENV. If `su' starts a shell with `-c cmd'
1075 and `-su' as the name of the shell, we want to read the startup files.
1076 No other non-interactive shells read any startup files. */
1077 if (interactive_shell == 0 && !(su_shell && login_shell))
1078 {
1079 if (posixly_correct == 0 && act_like_sh == 0 && privileged_mode == 0 &&
1080 sourced_env++ == 0)
1081 execute_env_file (get_string_value ("BASH_ENV"));
1082 return;
1083 }
1084
1085 /* Interactive shell or `-su' shell. */
1086 if (posixly_correct == 0) /* bash, sh */
1087 {
1088 if (login_shell && sourced_login++ == 0)
1089 {
1090 /* We don't execute .bashrc for login shells. */
1091 no_rc++;
1092
1093 /* Execute /etc/profile and one of the personal login shell
1094 initialization files. */
1095 if (no_profile == 0)
1096 {
1097 maybe_execute_file (SYS_PROFILE, 1);
1098
1099 if (act_like_sh) /* sh */
1100 maybe_execute_file ("~/.profile", 1);
1101 else if ((maybe_execute_file ("~/.bash_profile", 1) == 0) &&
1102 (maybe_execute_file ("~/.bash_login", 1) == 0)) /* bash */
1103 maybe_execute_file ("~/.profile", 1);
1104 }
1105 }
1106
1107 /* bash */
1108 if (act_like_sh == 0 && no_rc == 0)
1109 {
1110 #ifdef SYS_BASHRC
1111 # if defined (__OPENNT)
1112 maybe_execute_file (_prefixInstallPath(SYS_BASHRC, NULL, 0), 1);
1113 # else
1114 maybe_execute_file (SYS_BASHRC, 1);
1115 # endif
1116 #endif
1117 maybe_execute_file (bashrc_file, 1);
1118 }
1119 /* sh */
1120 else if (act_like_sh && privileged_mode == 0 && sourced_env++ == 0)
1121 execute_env_file (get_string_value ("ENV"));
1122 }
1123 else /* bash --posix, sh --posix */
1124 {
1125 /* bash and sh */
1126 if (interactive_shell && privileged_mode == 0 && sourced_env++ == 0)
1127 execute_env_file (get_string_value ("ENV"));
1128 }
1129
1130 #if defined (JOB_CONTROL)
1131 set_job_control (old_job_control);
1132 #endif
1133 }
1134
1135 #if defined (RESTRICTED_SHELL)
1136 /* Return 1 if the shell should be a restricted one based on NAME or the
1137 value of `restricted'. Don't actually do anything, just return a
1138 boolean value. */
1139 int
1140 shell_is_restricted (name)
1141 char *name;
1142 {
1143 char *temp;
1144
1145 if (restricted)
1146 return 1;
1147 temp = base_pathname (name);
1148 if (*temp == '-')
1149 temp++;
1150 return (STREQ (temp, RESTRICTED_SHELL_NAME));
1151 }
1152
1153 /* Perhaps make this shell a `restricted' one, based on NAME. If the
1154 basename of NAME is "rbash", then this shell is restricted. The
1155 name of the restricted shell is a configurable option, see config.h.
1156 In a restricted shell, PATH, SHELL, ENV, and BASH_ENV are read-only
1157 and non-unsettable.
1158 Do this also if `restricted' is already set to 1; maybe the shell was
1159 started with -r. */
1160 int
1161 maybe_make_restricted (name)
1162 char *name;
1163 {
1164 char *temp;
1165
1166 temp = base_pathname (name);
1167 if (*temp == '-')
1168 temp++;
1169 if (restricted || (STREQ (temp, RESTRICTED_SHELL_NAME)))
1170 {
1171 set_var_read_only ("PATH");
1172 set_var_read_only ("SHELL");
1173 set_var_read_only ("ENV");
1174 set_var_read_only ("BASH_ENV");
1175 restricted = 1;
1176 }
1177 return (restricted);
1178 }
1179 #endif /* RESTRICTED_SHELL */
1180
1181 /* Fetch the current set of uids and gids and return 1 if we're running
1182 setuid or setgid. */
1183 static int
1184 uidget ()
1185 {
1186 uid_t u;
1187
1188 u = getuid ();
1189 if (current_user.uid != u)
1190 {
1191 FREE (current_user.user_name);
1192 FREE (current_user.shell);
1193 FREE (current_user.home_dir);
1194 current_user.user_name = current_user.shell = current_user.home_dir = (char *)NULL;
1195 }
1196 current_user.uid = u;
1197 current_user.gid = getgid ();
1198 current_user.euid = geteuid ();
1199 current_user.egid = getegid ();
1200
1201 /* See whether or not we are running setuid or setgid. */
1202 return (current_user.uid != current_user.euid) ||
1203 (current_user.gid != current_user.egid);
1204 }
1205
1206 void
1207 disable_priv_mode ()
1208 {
1209 setuid (current_user.uid);
1210 setgid (current_user.gid);
1211 current_user.euid = current_user.uid;
1212 current_user.egid = current_user.gid;
1213 }
1214
1215 #if defined (WORDEXP_OPTION)
1216 static int
1217 run_wordexp (words)
1218 char *words;
1219 {
1220 int code, nw, nb;
1221 WORD_LIST *wl, *tl, *result;
1222
1223 code = setjmp (top_level);
1224
1225 if (code != NOT_JUMPED)
1226 {
1227 switch (code)
1228 {
1229 /* Some kind of throw to top_level has occured. */
1230 case FORCE_EOF:
1231 return last_command_exit_value = 127;
1232 case ERREXIT:
1233 case EXITPROG:
1234 return last_command_exit_value;
1235 case DISCARD:
1236 return last_command_exit_value = 1;
1237 default:
1238 command_error ("run_wordexp", CMDERR_BADJUMP, code, 0);
1239 }
1240 }
1241
1242 /* Run it through the parser to get a list of words and expand them */
1243 if (words && *words)
1244 {
1245 with_input_from_string (words, "--wordexp");
1246 if (parse_command () != 0)
1247 return (126);
1248 if (global_command == 0)
1249 {
1250 printf ("0\n0\n");
1251 return (0);
1252 }
1253 if (global_command->type != cm_simple)
1254 return (126);
1255 wl = global_command->value.Simple->words;
1256 if (protected_mode)
1257 for (tl = wl; tl; tl = tl->next)
1258 tl->word->flags |= W_NOCOMSUB|W_NOPROCSUB;
1259 result = wl ? expand_words_no_vars (wl) : (WORD_LIST *)0;
1260 }
1261 else
1262 result = (WORD_LIST *)0;
1263
1264 last_command_exit_value = 0;
1265
1266 if (result == 0)
1267 {
1268 printf ("0\n0\n");
1269 return (0);
1270 }
1271
1272 /* Count up the number of words and bytes, and print them. Don't count
1273 the trailing NUL byte. */
1274 for (nw = nb = 0, wl = result; wl; wl = wl->next)
1275 {
1276 nw++;
1277 nb += strlen (wl->word->word);
1278 }
1279 printf ("%u\n%u\n", nw, nb);
1280 /* Print each word on a separate line. This will have to be changed when
1281 the interface to glibc is completed. */
1282 for (wl = result; wl; wl = wl->next)
1283 printf ("%s\n", wl->word->word);
1284
1285 return (0);
1286 }
1287 #endif
1288
1289 #if defined (ONESHOT)
1290 /* Run one command, given as the argument to the -c option. Tell
1291 parse_and_execute not to fork for a simple command. */
1292 static int
1293 run_one_command (command)
1294 char *command;
1295 {
1296 int code;
1297
1298 code = setjmp (top_level);
1299
1300 if (code != NOT_JUMPED)
1301 {
1302 #if defined (PROCESS_SUBSTITUTION)
1303 unlink_fifo_list ();
1304 #endif /* PROCESS_SUBSTITUTION */
1305 switch (code)
1306 {
1307 /* Some kind of throw to top_level has occured. */
1308 case FORCE_EOF:
1309 return last_command_exit_value = 127;
1310 case ERREXIT:
1311 case EXITPROG:
1312 return last_command_exit_value;
1313 case DISCARD:
1314 return last_command_exit_value = 1;
1315 default:
1316 command_error ("run_one_command", CMDERR_BADJUMP, code, 0);
1317 }
1318 }
1319 return (parse_and_execute (savestring (command), "-c", SEVAL_NOHIST));
1320 }
1321 #endif /* ONESHOT */
1322
1323 static int
1324 bind_args (argv, arg_start, arg_end, start_index)
1325 char **argv;
1326 int arg_start, arg_end, start_index;
1327 {
1328 register int i;
1329 WORD_LIST *args;
1330
1331 for (i = arg_start, args = (WORD_LIST *)NULL; i < arg_end; i++)
1332 args = make_word_list (make_word (argv[i]), args);
1333 if (args)
1334 {
1335 args = REVERSE_LIST (args, WORD_LIST *);
1336 if (start_index == 0) /* bind to $0...$n for sh -c command */
1337 {
1338 /* Posix.2 4.56.3 says that the first argument after sh -c command
1339 becomes $0, and the rest of the arguments become $1...$n */
1340 shell_name = savestring (args->word->word);
1341 FREE (dollar_vars[0]);
1342 dollar_vars[0] = savestring (args->word->word);
1343 remember_args (args->next, 1);
1344 push_args (args->next); /* BASH_ARGV and BASH_ARGC */
1345 }
1346 else /* bind to $1...$n for shell script */
1347 {
1348 remember_args (args, 1);
1349 push_args (args); /* BASH_ARGV and BASH_ARGC */
1350 }
1351
1352 dispose_words (args);
1353 }
1354
1355 return (i);
1356 }
1357
1358 void
1359 unbind_args ()
1360 {
1361 remember_args ((WORD_LIST *)NULL, 1);
1362 pop_args (); /* Reset BASH_ARGV and BASH_ARGC */
1363 }
1364
1365 static void
1366 start_debugger ()
1367 {
1368 #if defined (DEBUGGER) && defined (DEBUGGER_START_FILE)
1369 int old_errexit;
1370
1371 old_errexit = exit_immediately_on_error;
1372 exit_immediately_on_error = 0;
1373
1374 maybe_execute_file (DEBUGGER_START_FILE, 1);
1375 function_trace_mode = 1;
1376
1377 exit_immediately_on_error += old_errexit;
1378 #endif
1379 }
1380
1381 static int
1382 open_shell_script (script_name)
1383 char *script_name;
1384 {
1385 int fd, e, fd_is_tty;
1386 char *filename, *path_filename, *t;
1387 char sample[80];
1388 int sample_len;
1389 struct stat sb;
1390 #if defined (ARRAY_VARS)
1391 SHELL_VAR *funcname_v, *bash_source_v, *bash_lineno_v;
1392 ARRAY *funcname_a, *bash_source_a, *bash_lineno_a;
1393 #endif
1394
1395 filename = savestring (script_name);
1396
1397 fd = open (filename, O_RDONLY);
1398 if ((fd < 0) && (errno == ENOENT) && (absolute_program (filename) == 0))
1399 {
1400 e = errno;
1401 /* If it's not in the current directory, try looking through PATH
1402 for it. */
1403 path_filename = find_path_file (script_name);
1404 if (path_filename)
1405 {
1406 free (filename);
1407 filename = path_filename;
1408 fd = open (filename, O_RDONLY);
1409 }
1410 else
1411 errno = e;
1412 }
1413
1414 if (fd < 0)
1415 {
1416 e = errno;
1417 file_error (filename);
1418 exit ((e == ENOENT) ? EX_NOTFOUND : EX_NOINPUT);
1419 }
1420
1421 free (dollar_vars[0]);
1422 dollar_vars[0] = exec_argv0 ? savestring (exec_argv0) : savestring (script_name);
1423 if (exec_argv0)
1424 {
1425 free (exec_argv0);
1426 exec_argv0 = (char *)NULL;
1427 }
1428
1429 #if defined (ARRAY_VARS)
1430 GET_ARRAY_FROM_VAR ("FUNCNAME", funcname_v, funcname_a);
1431 GET_ARRAY_FROM_VAR ("BASH_SOURCE", bash_source_v, bash_source_a);
1432 GET_ARRAY_FROM_VAR ("BASH_LINENO", bash_lineno_v, bash_lineno_a);
1433
1434 array_push (bash_source_a, filename);
1435 if (bash_lineno_a)
1436 {
1437 t = itos (executing_line_number ());
1438 array_push (bash_lineno_a, t);
1439 free (t);
1440 }
1441 array_push (funcname_a, "main");
1442 #endif
1443
1444 #ifdef HAVE_DEV_FD
1445 fd_is_tty = isatty (fd);
1446 #else
1447 fd_is_tty = 0;
1448 #endif
1449
1450 /* Only do this with non-tty file descriptors we can seek on. */
1451 if (fd_is_tty == 0 && (lseek (fd, 0L, 1) != -1))
1452 {
1453 /* Check to see if the `file' in `bash file' is a binary file
1454 according to the same tests done by execute_simple_command (),
1455 and report an error and exit if it is. */
1456 sample_len = read (fd, sample, sizeof (sample));
1457 if (sample_len < 0)
1458 {
1459 e = errno;
1460 if ((fstat (fd, &sb) == 0) && S_ISDIR (sb.st_mode))
1461 internal_error (_("%s: is a directory"), filename);
1462 else
1463 {
1464 errno = e;
1465 file_error (filename);
1466 }
1467 exit (EX_NOEXEC);
1468 }
1469 else if (sample_len > 0 && (check_binary_file (sample, sample_len)))
1470 {
1471 internal_error (_("%s: cannot execute binary file"), filename);
1472 exit (EX_BINARY_FILE);
1473 }
1474 /* Now rewind the file back to the beginning. */
1475 lseek (fd, 0L, 0);
1476 }
1477
1478 /* Open the script. But try to move the file descriptor to a randomly
1479 large one, in the hopes that any descriptors used by the script will
1480 not match with ours. */
1481 fd = move_to_high_fd (fd, 1, -1);
1482
1483 #if defined (BUFFERED_INPUT)
1484 default_buffered_input = fd;
1485 SET_CLOSE_ON_EXEC (default_buffered_input);
1486 #else /* !BUFFERED_INPUT */
1487 default_input = fdopen (fd, "r");
1488
1489 if (default_input == 0)
1490 {
1491 file_error (filename);
1492 exit (EX_NOTFOUND);
1493 }
1494
1495 SET_CLOSE_ON_EXEC (fd);
1496 if (fileno (default_input) != fd)
1497 SET_CLOSE_ON_EXEC (fileno (default_input));
1498 #endif /* !BUFFERED_INPUT */
1499
1500 /* Just about the only way for this code to be executed is if something
1501 like `bash -i /dev/stdin' is executed. */
1502 if (interactive_shell && fd_is_tty)
1503 {
1504 dup2 (fd, 0);
1505 close (fd);
1506 fd = 0;
1507 #if defined (BUFFERED_INPUT)
1508 default_buffered_input = 0;
1509 #else
1510 fclose (default_input);
1511 default_input = stdin;
1512 #endif
1513 }
1514 else if (forced_interactive && fd_is_tty == 0)
1515 /* But if a script is called with something like `bash -i scriptname',
1516 we need to do a non-interactive setup here, since we didn't do it
1517 before. */
1518 init_interactive_script ();
1519
1520 free (filename);
1521 return (fd);
1522 }
1523
1524 /* Initialize the input routines for the parser. */
1525 static void
1526 set_bash_input ()
1527 {
1528 /* Make sure the fd from which we are reading input is not in
1529 no-delay mode. */
1530 #if defined (BUFFERED_INPUT)
1531 if (interactive == 0)
1532 sh_unset_nodelay_mode (default_buffered_input);
1533 else
1534 #endif /* !BUFFERED_INPUT */
1535 sh_unset_nodelay_mode (fileno (stdin));
1536
1537 /* with_input_from_stdin really means `with_input_from_readline' */
1538 if (interactive && no_line_editing == 0)
1539 with_input_from_stdin ();
1540 #if defined (BUFFERED_INPUT)
1541 else if (interactive == 0)
1542 with_input_from_buffered_stream (default_buffered_input, dollar_vars[0]);
1543 #endif /* BUFFERED_INPUT */
1544 else
1545 with_input_from_stream (default_input, dollar_vars[0]);
1546 }
1547
1548 /* Close the current shell script input source and forget about it. This is
1549 extern so execute_cmd.c:initialize_subshell() can call it. If CHECK_ZERO
1550 is non-zero, we close default_buffered_input even if it's the standard
1551 input (fd 0). */
1552 void
1553 unset_bash_input (check_zero)
1554 int check_zero;
1555 {
1556 #if defined (BUFFERED_INPUT)
1557 if ((check_zero && default_buffered_input >= 0) ||
1558 (check_zero == 0 && default_buffered_input > 0))
1559 {
1560 close_buffered_fd (default_buffered_input);
1561 default_buffered_input = bash_input.location.buffered_fd = -1;
1562 bash_input.type = st_none; /* XXX */
1563 }
1564 #else /* !BUFFERED_INPUT */
1565 if (default_input)
1566 {
1567 fclose (default_input);
1568 default_input = (FILE *)NULL;
1569 }
1570 #endif /* !BUFFERED_INPUT */
1571 }
1572
1573
1574 #if !defined (PROGRAM)
1575 # define PROGRAM "bash"
1576 #endif
1577
1578 static void
1579 set_shell_name (argv0)
1580 char *argv0;
1581 {
1582 /* Here's a hack. If the name of this shell is "sh", then don't do
1583 any startup files; just try to be more like /bin/sh. */
1584 shell_name = argv0 ? base_pathname (argv0) : PROGRAM;
1585
1586 if (argv0 && *argv0 == '-')
1587 {
1588 if (*shell_name == '-')
1589 shell_name++;
1590 login_shell++;
1591 }
1592
1593 if (shell_name[0] == 's' && shell_name[1] == 'h' && shell_name[2] == '\0')
1594 act_like_sh++;
1595 if (shell_name[0] == 's' && shell_name[1] == 'u' && shell_name[2] == '\0')
1596 su_shell++;
1597
1598 shell_name = argv0 ? argv0 : PROGRAM;
1599 FREE (dollar_vars[0]);
1600 dollar_vars[0] = savestring (shell_name);
1601
1602 /* A program may start an interactive shell with
1603 "execl ("/bin/bash", "-", NULL)".
1604 If so, default the name of this shell to our name. */
1605 if (!shell_name || !*shell_name || (shell_name[0] == '-' && !shell_name[1]))
1606 shell_name = PROGRAM;
1607 }
1608
1609 static void
1610 init_interactive ()
1611 {
1612 expand_aliases = interactive_shell = startup_state = 1;
1613 interactive = 1;
1614 }
1615
1616 static void
1617 init_noninteractive ()
1618 {
1619 #if defined (HISTORY)
1620 bash_history_reinit (0);
1621 #endif /* HISTORY */
1622 interactive_shell = startup_state = interactive = 0;
1623 expand_aliases = posixly_correct; /* XXX - was 0 not posixly_correct */
1624 no_line_editing = 1;
1625 #if defined (JOB_CONTROL)
1626 /* Even if the shell is not interactive, enable job control if the -i or
1627 -m option is supplied at startup. */
1628 set_job_control (forced_interactive||jobs_m_flag);
1629 #endif /* JOB_CONTROL */
1630 }
1631
1632 static void
1633 init_interactive_script ()
1634 {
1635 init_noninteractive ();
1636 expand_aliases = interactive_shell = startup_state = 1;
1637 }
1638
1639 void
1640 get_current_user_info ()
1641 {
1642 struct passwd *entry;
1643
1644 /* Don't fetch this more than once. */
1645 if (current_user.user_name == 0)
1646 {
1647 #if defined (__TANDEM)
1648 entry = getpwnam (getlogin ());
1649 #else
1650 entry = getpwuid (current_user.uid);
1651 #endif
1652 if (entry)
1653 {
1654 current_user.user_name = savestring (entry->pw_name);
1655 current_user.shell = (entry->pw_shell && entry->pw_shell[0])
1656 ? savestring (entry->pw_shell)
1657 : savestring ("/bin/sh");
1658 current_user.home_dir = savestring (entry->pw_dir);
1659 }
1660 else
1661 {
1662 current_user.user_name = _("I have no name!");
1663 current_user.user_name = savestring (current_user.user_name);
1664 current_user.shell = savestring ("/bin/sh");
1665 current_user.home_dir = savestring ("/");
1666 }
1667 endpwent ();
1668 }
1669 }
1670
1671 /* Do whatever is necessary to initialize the shell.
1672 Put new initializations in here. */
1673 static void
1674 shell_initialize ()
1675 {
1676 char hostname[256];
1677
1678 /* Line buffer output for stderr and stdout. */
1679 if (shell_initialized == 0)
1680 {
1681 sh_setlinebuf (stderr);
1682 sh_setlinebuf (stdout);
1683 }
1684
1685 /* Sort the array of shell builtins so that the binary search in
1686 find_shell_builtin () works correctly. */
1687 initialize_shell_builtins ();
1688
1689 /* Initialize the trap signal handlers before installing our own
1690 signal handlers. traps.c:restore_original_signals () is responsible
1691 for restoring the original default signal handlers. That function
1692 is called when we make a new child. */
1693 initialize_traps ();
1694 initialize_signals (0);
1695
1696 /* It's highly unlikely that this will change. */
1697 if (current_host_name == 0)
1698 {
1699 /* Initialize current_host_name. */
1700 if (gethostname (hostname, 255) < 0)
1701 current_host_name = "??host??";
1702 else
1703 current_host_name = savestring (hostname);
1704 }
1705
1706 /* Initialize the stuff in current_user that comes from the password
1707 file. We don't need to do this right away if the shell is not
1708 interactive. */
1709 if (interactive_shell)
1710 get_current_user_info ();
1711
1712 /* Initialize our interface to the tilde expander. */
1713 tilde_initialize ();
1714
1715 /* Initialize internal and environment variables. Don't import shell
1716 functions from the environment if we are running in privileged or
1717 restricted mode or if the shell is running setuid. */
1718 #if defined (RESTRICTED_SHELL)
1719 initialize_shell_variables (shell_environment, privileged_mode||restricted||running_setuid);
1720 #else
1721 initialize_shell_variables (shell_environment, privileged_mode||running_setuid);
1722 #endif
1723
1724 /* Initialize the data structures for storing and running jobs. */
1725 initialize_job_control (jobs_m_flag);
1726
1727 /* Initialize input streams to null. */
1728 initialize_bash_input ();
1729
1730 initialize_flags ();
1731
1732 /* Initialize the shell options. Don't import the shell options
1733 from the environment variables $SHELLOPTS or $BASHOPTS if we are
1734 running in privileged or restricted mode or if the shell is running
1735 setuid. */
1736 #if defined (RESTRICTED_SHELL)
1737 initialize_shell_options (privileged_mode||restricted||running_setuid);
1738 initialize_bashopts (privileged_mode||restricted||running_setuid);
1739 #else
1740 initialize_shell_options (privileged_mode||running_setuid);
1741 initialize_bashopts (privileged_mode||running_setuid);
1742 #endif
1743 }
1744
1745 /* Function called by main () when it appears that the shell has already
1746 had some initialization performed. This is supposed to reset the world
1747 back to a pristine state, as if we had been exec'ed. */
1748 static void
1749 shell_reinitialize ()
1750 {
1751 /* The default shell prompts. */
1752 primary_prompt = PPROMPT;
1753 secondary_prompt = SPROMPT;
1754
1755 /* Things that get 1. */
1756 current_command_number = 1;
1757
1758 /* We have decided that the ~/.bashrc file should not be executed
1759 for the invocation of each shell script. If the variable $ENV
1760 (or $BASH_ENV) is set, its value is used as the name of a file
1761 to source. */
1762 no_rc = no_profile = 1;
1763
1764 /* Things that get 0. */
1765 login_shell = make_login_shell = interactive = executing = 0;
1766 debugging = do_version = line_number = last_command_exit_value = 0;
1767 forced_interactive = interactive_shell = subshell_environment = 0;
1768 expand_aliases = 0;
1769
1770 /* XXX - should we set jobs_m_flag to 0 here? */
1771
1772 #if defined (HISTORY)
1773 bash_history_reinit (0);
1774 #endif /* HISTORY */
1775
1776 #if defined (RESTRICTED_SHELL)
1777 restricted = 0;
1778 #endif /* RESTRICTED_SHELL */
1779
1780 /* Ensure that the default startup file is used. (Except that we don't
1781 execute this file for reinitialized shells). */
1782 bashrc_file = "~/.bashrc";
1783
1784 /* Delete all variables and functions. They will be reinitialized when
1785 the environment is parsed. */
1786 delete_all_contexts (shell_variables);
1787 delete_all_variables (shell_functions);
1788
1789 reinit_special_variables ();
1790
1791 #if defined (READLINE)
1792 bashline_reinitialize ();
1793 #endif
1794
1795 shell_reinitialized = 1;
1796 }
1797
1798 static void
1799 show_shell_usage (fp, extra)
1800 FILE *fp;
1801 int extra;
1802 {
1803 int i;
1804 char *set_opts, *s, *t;
1805
1806 if (extra)
1807 fprintf (fp, _("GNU bash, version %s-(%s)\n"), shell_version_string (), MACHTYPE);
1808 fprintf (fp, _("Usage:\t%s [GNU long option] [option] ...\n\t%s [GNU long option] [option] script-file ...\n"),
1809 shell_name, shell_name);
1810 fputs (_("GNU long options:\n"), fp);
1811 for (i = 0; long_args[i].name; i++)
1812 fprintf (fp, "\t--%s\n", long_args[i].name);
1813
1814 fputs (_("Shell options:\n"), fp);
1815 fputs (_("\t-irsD or -c command or -O shopt_option\t\t(invocation only)\n"), fp);
1816
1817 for (i = 0, set_opts = 0; shell_builtins[i].name; i++)
1818 if (STREQ (shell_builtins[i].name, "set"))
1819 set_opts = savestring (shell_builtins[i].short_doc);
1820 if (set_opts)
1821 {
1822 s = strchr (set_opts, '[');
1823 if (s == 0)
1824 s = set_opts;
1825 while (*++s == '-')
1826 ;
1827 t = strchr (s, ']');
1828 if (t)
1829 *t = '\0';
1830 fprintf (fp, _("\t-%s or -o option\n"), s);
1831 free (set_opts);
1832 }
1833
1834 if (extra)
1835 {
1836 fprintf (fp, _("Type `%s -c \"help set\"' for more information about shell options.\n"), shell_name);
1837 fprintf (fp, _("Type `%s -c help' for more information about shell builtin commands.\n"), shell_name);
1838 fprintf (fp, _("Use the `bashbug' command to report bugs.\n"));
1839 }
1840 }
1841
1842 static void
1843 add_shopt_to_alist (opt, on_or_off)
1844 char *opt;
1845 int on_or_off;
1846 {
1847 if (shopt_ind >= shopt_len)
1848 {
1849 shopt_len += 8;
1850 shopt_alist = (STRING_INT_ALIST *)xrealloc (shopt_alist, shopt_len * sizeof (shopt_alist[0]));
1851 }
1852 shopt_alist[shopt_ind].word = opt;
1853 shopt_alist[shopt_ind].token = on_or_off;
1854 shopt_ind++;
1855 }
1856
1857 static void
1858 run_shopt_alist ()
1859 {
1860 register int i;
1861
1862 for (i = 0; i < shopt_ind; i++)
1863 if (shopt_setopt (shopt_alist[i].word, (shopt_alist[i].token == '-')) != EXECUTION_SUCCESS)
1864 exit (EX_BADUSAGE);
1865 free (shopt_alist);
1866 shopt_alist = 0;
1867 shopt_ind = shopt_len = 0;
1868 }