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