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