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