1 /* $Header: /src/pub/tcsh/sh.c,v 3.123 2005/03/21 21:26:36 kim Exp $ */
3 * sh.c: Main shell routines
6 * Copyright (c) 1980, 1991 The Regents of the University of California.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 #define EXTERN /* Intern */
38 "@(#) Copyright (c) 1991 The Regents of the University of California.\n\
39 All rights reserved.\n";
42 RCSID("$Id: sh.c,v 3.123 2005/03/21 21:26:36 kim Exp $")
48 extern int MapsAreInited;
49 extern int NLSMapsAreInited;
54 * Bill Joy, UC Berkeley, California, USA
55 * October 1978, May 1980
57 * Jim Kulp, IIASA, Laxenburg, Austria
60 * Filename recognition added:
61 * Ken Greer, Ind. Consultant, Palo Alto CA
64 * Karl Kleinpaste, Computer Consoles, Inc.
65 * Added precmd, periodic/tperiod, prompt changes,
66 * directory stack hack, and login watch.
67 * Sometime March 1983 - Feb 1984.
69 * Added scheduled commands, including the "sched" command,
70 * plus the call to sched_run near the precmd et al
72 * Upgraded scheduled events for running events while
73 * sitting idle at command input.
75 * Paul Placeway, Ohio State
76 * added stuff for running with twenex/inputl 9 Oct 1984.
78 * ported to Apple Unix (TM) (OREO) 26 -- 29 Jun 1987
81 jmp_buf_t reslab INIT_ZERO_STRUCT;
83 static const char tcshstr[] = "tcsh";
85 static const char tcshstr_nt[] = "tcsh.exe";
86 #endif /* WINNT_NATIVE */
88 signalfun_t parintr = 0; /* Parents interrupt catch */
89 signalfun_t parterm = 0; /* Parents terminate catch */
96 int use_fork = 0; /* use fork() instead of vfork()? */
99 * Magic pointer values. Used to specify other invalid conditions aside
103 Char *INVPTR = &INVCHAR;
104 Char **INVPPTR = &INVPTR;
106 static int nofile = 0;
107 static int reenter = 0;
108 static int nverbose = 0;
109 static int nexececho = 0;
110 static int quitit = 0;
111 static int rdirs = 0;
113 static int batch = 0;
114 static int mflag = 0;
115 static int prompt = 1;
123 static time_t chktim; /* Time mail last checked */
126 extern char **environ;
129 * This preserves the input state of the shell. It is used by
130 * st_save and st_restore to manupulate shell state.
139 struct whyle *whyles;
152 /* These keep signal state and setjump state */
160 static int srccat __P((Char *, Char *));
162 static int srcfile __P((const char *, int, int, Char **));
164 int srcfile __P((const char *, int, int, Char **));
165 #endif /*WINNT_NATIVE*/
166 static RETSIGTYPE phup __P((int));
167 static void srcunit __P((int, int, int, Char **));
168 static void mailchk __P((void));
169 #ifndef _PATH_DEFPATH
170 static Char **defaultpath __P((void));
172 static void record __P((void));
173 static void st_save __P((struct saved_state *, int, int,
175 static void st_restore __P((struct saved_state *, Char **));
177 int main __P((int, char **));
192 signalfun_t oparintr;
200 #endif /* WINNT_NATIVE */
201 #if defined(NLS_CATALOGS) && defined(LC_MESSAGES)
202 (void) setlocale(LC_MESSAGES, "");
203 #endif /* NLS_CATALOGS && LC_MESSAGES */
207 (void) setlocale(LC_CTYPE, ""); /* for iscntrl */
208 # endif /* LC_CTYPE */
214 mal_setstatsfile(fdopen(dmove(open("/tmp/tcsh.trace",
215 O_WRONLY|O_CREAT|O_LARGEFILE, 0666), 25), "w"));
217 #endif /* MALLOC_TRACE */
219 #if !(defined(BSDTIMES) || defined(_SEQUENT_)) && defined(POSIX)
221 clk_tck = (clock_t) sysconf(_SC_CLK_TCK);
222 # else /* ! _SC_CLK_TCK */
225 # else /* !CLK_TCK */
227 # endif /* CLK_TCK */
228 # endif /* _SC_CLK_TCK */
229 #endif /* !BSDTIMES && POSIX */
231 settimes(); /* Immed. estab. timing base */
237 * Make sure we have 0, 1, 2 open
238 * Otherwise `` jobs will not work... (From knaff@poly.polytechnique.fr)
242 if ((f = open(_PATH_DEVNULL, O_RDONLY|O_LARGEFILE)) == -1 &&
243 (f = open("/", O_RDONLY|O_LARGEFILE)) == -1)
253 osinit(); /* Os dependent initialization */
259 t = strrchr(argv[0], '/');
262 char *s = strrchr(argv[0], '\\');
266 #endif /* WINNT_NATIVE */
267 t = t ? t + 1 : argv[0];
269 progname = strsave((t && *t) ? t : tcshstr); /* never want a null */
270 tcsh = strcmp(progname, tcshstr) == 0;
274 * Initialize non constant strings
277 STR_BSHELL = SAVE(_PATH_BSHELL);
280 STR_SHELLPATH = SAVE(_PATH_TCSHELL);
283 STR_SHELLPATH = SAVE(_PATH_CSHELL);
286 STR_environ = blk2short(environ);
287 environ = short2blk(STR_environ); /* So that we can free it */
288 STR_WORD_CHARS = SAVE(WORD_CHARS);
294 word_chars = STR_WORD_CHARS;
295 bslash_quote = 0; /* PWP: do tcsh-style backslash quoting? */
297 /* Default history size to 100 */
298 set(STRhistory, SAVE("100"), VAR_READWRITE);
301 ffile = SAVE(tempv[0]);
303 if (eq(ffile, STRaout)) /* A.out's are quittable */
310 * We are a login shell if: 1. we were invoked as -<something> with
311 * optional arguments 2. or we were invoked only with the -l flag
313 loginsh = (**tempv == '-') || (argc == 2 &&
314 tempv[1][0] == '-' && tempv[1][1] == 'l' &&
315 tempv[1][2] == '\0');
317 /* No better way to find if we are a login shell */
319 loginsh = (argc == 1 && getppid() == 1);
320 **tempv = '-'; /* Avoid giving VMS an acidic stomach */
322 #endif /* _VMS_POSIX */
324 if (loginsh && **tempv != '-') {
326 * Mangle the argv space
331 for (tcp = *tempv; *tcp++;)
333 for (tcp--; tcp >= *tempv; tcp--)
339 (void) time(&chktim);
340 set(STRloginsh, Strsave(STRNULL), VAR_READWRITE);
344 NoNLSRebind = getenv("NOREBIND") != NULL;
348 # endif /* SETLOCALEBUG */
349 (void) setlocale(LC_ALL, "");
351 (void) setlocale(LC_COLLATE, "");
355 # endif /* SETLOCALEBUG */
358 # endif /* STRCOLLBUG */
363 for (k = 0200; k <= 0377 && !Isprint(k); k++)
365 AsciiOnly = MB_CUR_MAX == 1 && k > 0377;
368 AsciiOnly = getenv("LANG") == NULL && getenv("LC_CTYPE") == NULL;
370 if (MapsAreInited && !NLSMapsAreInited)
375 * Initialize for periodic command intervals. Also, initialize the dummy
376 * tty list for login-watch.
378 (void) time(&t_period);
381 #endif /* !HAVENOUTMP */
385 * From: Jim Pace <jdp@research.att.com>
386 * tcsh does not work properly on the alliants through an rlogin session.
387 * The shell generally hangs. Also, reference to the controlling terminal
388 * does not work ( ie: echo foo > /dev/tty ).
390 * A security feature was added to rlogind affecting FX/80's Concentrix
391 * from revision 5.5.xx upwards (through 5.7 where this fix was implemented)
392 * This security change also affects the FX/2800 series.
393 * The security change to rlogind requires the process group of an rlogin
394 * session become disassociated with the tty in rlogind.
396 * The changes needed are:
397 * 1. set the process group
398 * 2. reenable the control terminal
400 if (loginsh && isatty(SHIN)) {
401 ttyn = (char *) ttyname(SHIN);
403 SHIN = open(ttyn, O_RDWR|O_LARGEFILE);
405 (void) ioctl (SHIN, TIOCSPGRP, (ioctl_t) &shpgrp);
406 (void) setpgid(0, shpgrp);
411 * Move the descriptors to safe places. The variable didfds is 0 while we
412 * have only FSH* to work with. When didfds is true, we have 0,1,2 and
413 * prefer to use these.
418 * Get and set the tty now
420 if ((ttyn = ttyname(SHIN)) != NULL) {
422 * Could use rindex to get rid of other possible path components, but
423 * hpux preserves the subdirectory /pty/ when storing the tty name in
424 * utmp, so we keep it too.
426 if (strncmp(ttyn, "/dev/", 5) == 0)
427 set(STRtty, cp = SAVE(ttyn + 5), VAR_READWRITE);
429 set(STRtty, cp = SAVE(ttyn), VAR_READWRITE);
432 set(STRtty, cp = SAVE(""), VAR_READWRITE);
434 * Initialize the shell variables. ARGV and PROMPT are initialized later.
435 * STATUS is also munged in several places. CHILD is munged when
440 * 7-10-87 Paul Placeway autologout should be set ONLY on login shells and
441 * on shells running as root. Out of these, autologout should NOT be set
442 * for any psudo-terminals (this catches most window systems) and not for
443 * any terminal running X windows.
445 * At Ohio State, we have had problems with a user having his X session
446 * drop out from under him (on a Sun) because the shell in his master
447 * xterm timed out and exited.
449 * Really, this should be done with a program external to the shell, that
450 * watches for no activity (and NO running programs, such as dump) on a
451 * terminal for a long peroid of time, and then SIGHUPS the shell on that
454 * bugfix by Rich Salz <rsalz@PINEAPPLE.BBN.COM>: For root rsh things
455 * allways first check to see if loginsh or really root, then do things
458 * Also by Jean-Francois Lamy <lamy%ai.toronto.edu@RELAY.CS.NET>: check the
459 * value of cp before using it! ("root can rsh too")
461 * PWP: keep the nested ifs; the order of the tests matters and a good
462 * (smart) C compiler might re-arange things wrong.
467 /* root always has a 15 minute autologout */
468 set(STRautologout, Strsave(STRrootdefautologout), VAR_READWRITE);
472 /* users get autologout set to 0 */
473 set(STRautologout, Strsave(STR0), VAR_READWRITE);
475 if (loginsh || (uid == 0)) {
477 /* only for login shells or root and we must have a tty */
478 if ((cp2 = Strrchr(cp, (Char) '/')) != NULL) {
483 if (!(((Strncmp(cp2, STRtty, 3) == 0) && Isalpha(cp2[3])) ||
484 ((Strncmp(cp, STRpts, 3) == 0) && cp[3] == '/'))) {
485 if (getenv("DISPLAY") == NULL) {
486 /* NOT on X window shells */
487 set(STRautologout, Strsave(STRdefautologout),
494 #endif /* AUTOLOGOUT */
496 (void) sigset(SIGALRM, alrmcatch);
498 set(STRstatus, Strsave(STR0), VAR_READWRITE);
501 * get and set machine specific environment variables
507 * Publish the selected echo style
509 #if ECHO_STYLE != BSD_ECHO
511 # if ECHO_STYLE == NONE_ECHO
512 set(STRecho_style, Strsave(STRnone), VAR_READWRITE);
513 # endif /* ECHO_STYLE == NONE_ECHO */
514 # if ECHO_STYLE == SYSV_ECHO
515 set(STRecho_style, Strsave(STRsysv), VAR_READWRITE);
516 # endif /* ECHO_STYLE == SYSV_ECHO */
517 # if ECHO_STYLE == BOTH_ECHO
518 set(STRecho_style, Strsave(STRboth), VAR_READWRITE);
519 # endif /* ECHO_STYLE == BOTH_ECHO */
521 #endif /* ECHO_STYLE != BSD_ECHO */
522 set(STRecho_style, Strsave(STRbsd), VAR_READWRITE);
525 * increment the shell level.
529 if ((tcp = getenv("HOME")) != NULL) {
530 if (strlen(tcp) >= MAXPATHLEN) {
532 if ((pw = getpwuid(getuid())) != NULL)
533 cp = quote(SAVE(pw->pw_dir));
535 tcp[MAXPATHLEN-1] = '\0';
536 cp = quote(SAVE(tcp));
539 cp = quote(SAVE(tcp));
545 fast = 1; /* No home -> can't read scripts */
547 set(STRhome, cp, VAR_READWRITE);
549 dinit(cp); /* dinit thinks that HOME == cwd in a login
552 * Grab other useful things from the environment. Should we grab
556 char *cln, *cus, *cgr;
565 (void) Itoa(oid, buff, 0, 0);
566 set(STRoid, Strsave(buff), VAR_READWRITE);
569 (void) Itoa(uid, buff, 0, 0);
570 set(STRuid, Strsave(buff), VAR_READWRITE);
572 (void) Itoa(gid, buff, 0, 0);
573 set(STRgid, Strsave(buff), VAR_READWRITE);
575 cln = getenv("LOGNAME");
576 cus = getenv("USER");
578 set(STRuser, quote(SAVE(cus)), VAR_READWRITE);
579 else if (cln != NULL)
580 set(STRuser, quote(SAVE(cln)), VAR_READWRITE);
581 else if ((pw = getpwuid(uid)) == NULL)
582 set(STRuser, SAVE("unknown"), VAR_READWRITE);
584 set(STRuser, SAVE(pw->pw_name), VAR_READWRITE);
586 tsetenv(STRLOGNAME, varval(STRuser));
588 tsetenv(STRKUSER, varval(STRuser));
590 cgr = getenv("GROUP");
592 set(STRgroup, quote(SAVE(cgr)), VAR_READWRITE);
593 else if ((gr = getgrgid(gid)) == NULL)
594 set(STRgroup, SAVE("unknown"), VAR_READWRITE);
596 set(STRgroup, SAVE(gr->gr_name), VAR_READWRITE);
598 tsetenv(STRKGROUP, varval(STRgroup));
602 * HOST may be wrong, since rexd transports the entire environment on sun
603 * 3.x Just set it again
606 char cbuff[MAXHOSTNAMELEN];
608 if (gethostname(cbuff, sizeof(cbuff)) >= 0) {
609 cbuff[sizeof(cbuff) - 1] = '\0'; /* just in case */
610 tsetenv(STRHOST, str2short(cbuff));
613 tsetenv(STRHOST, str2short("unknown"));
619 * Try to determine the remote host we were logged in from.
622 #endif /* REMOTEHOST */
625 if ((tcp = getenv("SYSTYPE")) == NULL)
627 tsetenv(STRSYSTYPE, quote(str2short(tcp)));
631 * set editing on by default, unless running under Emacs as an inferior
633 * We try to do this intelligently. If $TERM is available, then it
634 * should determine if we should edit or not. $TERM is preserved
635 * across rlogin sessions, so we will not get confused if we rlogin
636 * under an emacs shell. Another advantage is that if we run an
637 * xterm under an emacs shell, then the $TERM will be set to
638 * xterm, so we are going to want to edit. Unfortunately emacs
639 * does not restore all the tty modes, so xterm is not very well
640 * set up. But this is not the shell's fault.
641 * Also don't edit if $TERM == wm, for when we're running under an ATK app.
642 * Finally, emacs compiled under terminfo, sets the terminal to dumb,
643 * so disable editing for that too.
645 * Unfortunately, in some cases the initial $TERM setting is "unknown",
646 * "dumb", or "network" which is then changed in the user's startup files.
647 * We fix this by setting noediting here if $TERM is unknown/dumb and
648 * if noediting is set, we switch on editing if $TERM is changed.
650 if ((tcp = getenv("TERM")) != NULL) {
651 set(STRterm, quote(SAVE(tcp)), VAR_READWRITE);
652 noediting = strcmp(tcp, "unknown") == 0 || strcmp(tcp, "dumb") == 0 ||
653 strcmp(tcp, "network") == 0;
654 editing = strcmp(tcp, "emacs") != 0 && strcmp(tcp, "wm") != 0 &&
659 editing = ((tcp = getenv("EMACS")) == NULL || strcmp(tcp, "t") != 0);
663 * The 'edit' variable is either set or unset. It doesn't
664 * need a value. Making it 'emacs' might be confusing.
667 set(STRedit, Strsave(STRNULL), VAR_READWRITE);
671 * still more mutability: make the complete routine automatically add the
672 * suffix of file names...
674 set(STRaddsuffix, Strsave(STRNULL), VAR_READWRITE);
677 * Compatibility with tcsh >= 6.12 by default
679 set(STRcsubstnonl, Strsave(STRNULL), VAR_READWRITE);
682 * Random default kill ring size
684 set(STRkillring, SAVE("30"), VAR_READWRITE);
687 * Re-initialize path if set in environment
689 if ((tcp = getenv("PATH")) == NULL)
691 importpath(str2short(_PATH_DEFPATH));
692 #else /* !_PATH_DEFPATH */
693 setq(STRpath, defaultpath(), &shvhed, VAR_READWRITE);
694 #endif /* _PATH_DEFPATH */
696 /* Importpath() allocates memory for the path, and the
697 * returned pointer from SAVE() was discarded, so
698 * this was a memory leak.. (sg)
700 * importpath(SAVE(tcp));
702 importpath(str2short(tcp));
706 /* If the SHELL environment variable ends with "tcsh", set
707 * STRshell to the same path. This is to facilitate using
708 * the executable in environments where the compiled-in
709 * default isn't appropriate (sg).
714 if ((tcp = getenv("SHELL")) != NULL) {
715 sh_len = strlen(tcp);
716 if ((sh_len >= 5 && strcmp(tcp + (sh_len - 5), "/tcsh") == 0) ||
717 (!tcsh && sh_len >= 4 && strcmp(tcp + (sh_len - 4), "/csh") == 0))
718 set(STRshell, quote(SAVE(tcp)), VAR_READWRITE);
723 set(STRshell, Strsave(STR_SHELLPATH), VAR_READWRITE);
727 if ((tcp = getenv("LS_COLORS")) != NULL)
728 parseLS_COLORS(str2short(tcp));
729 #endif /* COLOR_LS_F */
731 doldol = putn((int) getpid()); /* For $$ */
734 char *strtmp1, strtmp2[MAXPATHLEN];
735 if ((strtmp1 = getenv("TMP")) != NULL)
736 wsprintf(strtmp2, "%s/%s", strtmp1, "sh");
737 shtemp = Strspl(SAVE(strtmp2), doldol); /* For << */
739 #else /* !WINNT_NATIVE */
740 shtemp = Strspl(STRtmpsh, doldol); /* For << */
741 #endif /* WINNT_NATIVE */
744 * Record the interrupt states from the parent process. If the parent is
745 * non-interruptible our hand must be forced or we (and our children) won't
746 * be either. Our children inherit termination from our parent. We catch it
747 * only if we are the login shell.
751 * PURIFY-2 claims that osv does not get
752 * initialized after the sigvec call
754 setzero((char*) &osv, sizeof(osv));
755 /* parents interruptibility */
756 (void) mysigvec(SIGINT, NULL, &osv);
757 parintr = (signalfun_t) osv.sv_handler;
758 (void) mysigvec(SIGTERM, NULL, &osv);
759 parterm = (signalfun_t) osv.sv_handler;
761 parintr = signal(SIGINT, SIG_IGN); /* parents interruptibility */
762 (void) sigset(SIGINT, parintr); /* ... restore */
765 if (loginsh) /* it seems that SIGTERM is always set to SIG_IGN by */
766 /* init/getty so it should be set to SIG_DFL - there may be */
767 /* a better fix for this. */
770 # else /* !COHERENT */
771 parterm = signal(SIGTERM, SIG_IGN); /* parents terminability */
772 # endif /* COHERENT */
773 (void) sigset(SIGTERM, parterm); /* ... restore */
779 /* Enable process migration on ourselves and our progeny */
780 (void) signal(SIGMIGRATE, SIG_DFL);
784 * dspkanji/dspmbyte autosetting
786 /* PATCH IDEA FROM Issei.Suzuki VERY THANKS */
787 #if defined(DSPMBYTE)
788 #if defined(NLS) && defined(LC_CTYPE)
789 if (((tcp = setlocale(LC_CTYPE, NULL)) != NULL || (tcp = getenv("LANG")) != NULL) && !adrof(CHECK_MBYTEVAR)) {
791 if ((tcp = getenv("LANG")) != NULL && !adrof(CHECK_MBYTEVAR)) {
793 autoset_dspmbyte(str2short(tcp));
795 #if defined(WINNT_NATIVE)
796 else if (!adrof(CHECK_MBYTEVAR))
797 nt_autoset_dspmbyte();
798 #endif /* WINNT_NATIVE */
801 fix_version(); /* publish the shell version */
803 if (argc > 1 && strcmp(argv[1], "--version") == 0) {
804 xprintf("%S\n", varval(STRversion));
807 if (argc > 1 && strcmp(argv[1], "--help") == 0) {
808 xprintf("%S\n\n", varval(STRversion));
809 xprintf(CGETS(11, 8, HELP_STRING));
813 * Process the arguments.
815 * Note that processing of -v/-x is actually delayed till after script
818 * We set the first character of our name to be '-' if we are a shell
819 * running interruptible commands. Many programs which examine ps'es
820 * use this to filter such shells out.
823 while (argc > 0 && (tcp = tempv[0])[0] == '-' &&
824 *++tcp != '\0' && !batch) {
828 case 0: /* - Interruptible, no prompt */
834 case 'b': /* -b Next arg is input file */
838 case 'c': /* -c Command input from arg */
844 it relies on a 7 bit environment (/bin/sh), so it
845 pass ascii arguments with the 8th bit set */
846 if (!strcmp(argv[0], "sh"))
850 for (p = tempv[0]; *p; ++p)
854 arginp = SAVE(tempv[0]);
857 * we put the command into a variable
860 set(STRcommand, quote(Strsave(arginp)), VAR_READWRITE);
863 * * Give an error on -c arguments that end in * backslash to
864 * ensure that you don't make * nonportable csh scripts.
869 cp = arginp + Strlen(arginp);
871 while (cp > arginp && *--cp == '\\')
873 if ((count & 1) != 0) {
881 case 'd': /* -d Load directory stack from file */
886 case 'D': /* -D Define environment variable */
891 if (dp = Strchr(cp, '=')) {
896 tsetenv(cp, STRNULL);
898 *tcp = '\0'; /* done with this argument */
902 case 'e': /* -e Exit on any error */
906 case 'f': /* -f Fast start */
910 case 'i': /* -i Interactive, even if !intty */
915 case 'm': /* -m read .cshrc (from su) */
919 case 'n': /* -n Don't execute */
923 case 'q': /* -q (Undoc'd) ... die on quit */
927 case 's': /* -s Read from std input */
931 case 't': /* -t Read one line from input */
937 case 'v': /* -v Echo hist expanded input */
938 nverbose = 1; /* ... later */
941 case 'x': /* -x Echo just before execution */
942 nexececho = 1; /* ... later */
945 case 'V': /* -V Echo hist expanded input */
946 setNS(STRverbose); /* NOW! */
949 case 'X': /* -X Echo just before execution */
950 setNS(STRecho); /* NOW! */
953 case 'F': /* Undocumented flag */
955 * This will cause children to be created using fork instead of
964 * for O/S's that don't do the argument parsing right in
965 * "#!/foo -f " scripts
969 default: /* Unknown command option */
971 stderror(ERR_TCSHUSAGE, tcp-1, progname);
978 if (quitit) /* With all due haste, for debugging */
979 (void) signal(SIGQUIT, SIG_DFL);
982 * Unless prevented by -, -c, -i, -s, or -t, if there are remaining
983 * arguments the first of them is the name of a shell file from which to
986 if (nofile == 0 && argc > 0) {
987 nofile = open(tempv[0], O_RDONLY|O_LARGEFILE);
989 child = 1; /* So this ... */
990 /* ... doesn't return */
991 stderror(ERR_SYSTEM, tempv[0], strerror(errno));
994 setmode(nofile, O_TEXT);
997 xfree((ptr_t) ffile);
999 ffile = SAVE(tempv[0]);
1001 * Replace FSHIN. Handle /dev/std{in,out,err} specially
1002 * since once they are closed we cannot open them again.
1003 * In that case we use our own saved descriptors
1005 if ((SHIN = dmove(nofile, FSHIN)) < 0)
1017 stderror(ERR_SYSTEM, tempv[0], strerror(errno));
1020 (void) close_on_exec(SHIN, 1);
1022 /* argc not used any more */ tempv++;
1026 * Call to closem() used to be part of initdesc(). Now called below where
1027 * the script name argument has become stdin. Kernel may have used a file
1028 * descriptor to hold the name of the script (setuid case) and this name
1029 * mustn't be lost by closing the fd too soon.
1034 * Consider input a tty if it really is or we are interactive. but not for
1035 * editing (christos)
1037 if (!(intty = isatty(SHIN))) {
1044 if (intty || (intact && isatty(SHOUT))) {
1045 if (!batch && (uid != euid || gid != egid)) {
1047 child = 1; /* So this ... */
1048 /* ... doesn't return */
1049 stderror(ERR_SYSTEM, progname, strerror(errno));
1053 isoutatty = isatty(SHOUT);
1054 isdiagatty = isatty(SHDIAG);
1056 * Decide whether we should play with signals or not. If we are explicitly
1057 * told (via -i, or -) or we are a login shell (arg0 starts with -) or the
1058 * input and output are both the ttys("csh", or "csh</dev/ttyx>/dev/ttyx")
1059 * Note that in only the login shell is it likely that parent may have set
1060 * signals to be ignored
1062 if (loginsh || intact || (intty && isatty(SHOUT)))
1066 * Save the remaining arguments in argv.
1068 setq(STRargv, blk2short(tempv), &shvhed, VAR_READWRITE);
1071 * Set up the prompt.
1075 set(STRprompt, Strsave(STRdeftcshprompt), VAR_READWRITE);
1077 set(STRprompt, Strsave(STRdefcshprompt), VAR_READWRITE);
1078 /* that's a meta-questionmark */
1079 set(STRprompt2, Strsave(STRmquestion), VAR_READWRITE);
1080 set(STRprompt3, Strsave(STRKCORRECT), VAR_READWRITE);
1084 * If we are an interactive shell, then start fiddling with the signals;
1085 * this is a tricky game.
1087 shpgrp = mygetpgrp();
1092 if (!quitit) /* Wary! */
1093 (void) signal(SIGQUIT, SIG_IGN);
1094 (void) sigset(SIGINT, pintr);
1095 (void) sighold(SIGINT);
1096 (void) signal(SIGTERM, SIG_IGN);
1099 * No reason I can see not to save history on all these events..
1100 * Most usual occurrence is in a window system, where we're not a login
1101 * shell, but might as well be... (sg)
1102 * But there might be races when lots of shells exit together...
1103 * [this is also incompatible].
1104 * We have to be mre careful here. If the parent wants to
1105 * ignore the signals then we leave them untouched...
1106 * We also only setup the handlers for shells that are trully
1109 osig = signal(SIGHUP, phup); /* exit processing on HUP */
1110 if (!loginsh && osig == SIG_IGN)
1111 (void) signal(SIGHUP, osig);
1113 osig = signal(SIGXCPU, phup); /* exit processing on XCPU */
1114 if (!loginsh && osig == SIG_IGN)
1115 (void) signal(SIGXCPU, osig);
1118 osig = signal(SIGXFSZ, phup); /* exit processing on XFSZ */
1119 if (!loginsh && osig == SIG_IGN)
1120 (void) signal(SIGXFSZ, osig);
1123 if (quitit == 0 && arginp == 0) {
1125 (void) signal(SIGTSTP, SIG_IGN);
1128 (void) signal(SIGTTIN, SIG_IGN);
1131 (void) signal(SIGTTOU, SIG_IGN);
1134 * Wait till in foreground, in case someone stupidly runs csh &
1135 * dont want to try to grab away the tty.
1137 if (isatty(FSHDIAG))
1139 else if (isatty(FSHOUT))
1141 else if (isatty(OLDSTD))
1147 /* NeXT 2.0 /usr/etc/rlogind, does not set our process group! */
1150 (void) setpgid(0, shpgrp);
1151 (void) tcsetpgrp(f, shpgrp);
1154 #ifdef BSDJOBS /* if we have tty job control */
1156 if ((tpgrp = tcgetpgrp(f)) != -1) {
1157 if (tpgrp != shpgrp) {
1158 signalfun_t old = signal(SIGTTIN, SIG_DFL);
1159 (void) kill(0, SIGTTIN);
1160 (void) signal(SIGTTIN, old);
1164 * Thanks to Matt Day for the POSIX references, and to
1165 * Paul Close for the SGI clarification.
1167 if (setdisc(f) != -1) {
1171 if (tcsetpgrp(f, shpgrp) == -1) {
1173 * On hpux 7.03 this fails with EPERM. This happens on
1174 * the 800 when opgrp != shpgrp at this point. (we were
1175 * forked from a non job control shell)
1176 * POSIX 7.2.4, says we failed because the process
1177 * group specified did not belong to a process
1178 * in the same session with the tty. So we set our
1179 * process group and try again.
1181 if (setpgid(0, shpgrp) == -1) {
1182 xprintf("setpgid:");
1185 if (tcsetpgrp(f, shpgrp) == -1) {
1186 xprintf("tcsetpgrp:");
1191 * We check the process group now. If it is the same, then
1192 * we don't need to set it again. On hpux 7.0 on the 300's
1193 * if we set it again it fails with EPERM. This is the
1194 * correct behavior according to POSIX 4.3.3 if the process
1195 * was a session leader .
1197 else if (shpgrp != mygetpgrp()) {
1198 if(setpgid(0, shpgrp) == -1) {
1199 xprintf("setpgid:");
1205 * But on irix 3.3 we need to set it again, even if it is
1206 * the same. We do that to tell the system that we
1207 * need BSD process group compatibility.
1210 (void) setpgid(0, shpgrp);
1212 (void) close_on_exec(dcopy(f, FSHTTY), 1);
1219 xprintf(CGETS(11, 1, "Warning: no access to tty (%s).\n"),
1221 xprintf(CGETS(11, 2, "Thus no job control in this shell.\n"));
1223 * Fix from:Sakari Jalovaara <sja@sirius.hut.fi> if we don't
1224 * have access to tty, disable editing too
1230 #else /* BSDJOBS */ /* don't have job control, so frotz it */
1232 #endif /* BSDJOBS */
1235 if ((setintr == 0) && (parintr == SIG_DFL))
1239 * SVR4 doesn't send a SIGCHLD when a child is stopped or continued if the
1240 * handler is installed with signal(2) or sigset(2). sigaction(2) must
1243 * David Dawes (dawes@physics.su.oz.au) Sept 1991
1248 struct sigaction act;
1249 act.sa_handler=pchild;
1250 (void) sigemptyset(&(act.sa_mask)); /* Don't block any extra sigs
1251 * when the handler is called
1253 act.sa_flags=0; /* want behaviour of sigset() without
1257 if ((sigaction(SIGCHLD,&act,(struct sigaction *)NULL)) == -1)
1258 stderror(ERR_SYSTEM, "sigaction", strerror(errno));
1260 #else /* SYSVREL <= 3 */
1261 (void) sigset(SIGCHLD, pchild); /* while signals not ready */
1262 #endif /* SYSVREL <= 3 */
1265 if (intty && !arginp)
1266 (void) ed_Setup(editing);/* Get the tty state, and set defaults */
1267 /* Only alter the tty state if editing */
1270 * Set an exit here in case of an interrupt or error reading the shell
1275 reenter = setexit(); /* PWP */
1277 haderr = 0; /* In case second time through */
1278 if (!fast && reenter == 0) {
1279 /* Will have varval(STRhome) here because set fast if don't */
1282 sigmask_t omask = sigblock(sigmask(SIGINT));
1284 (void) sighold(SIGINT);
1287 parintr = SIG_IGN; /* onintr in /etc/ files has no effect */
1289 #ifdef _PATH_DOTLOGIN
1291 (void) srcfile(_PATH_DOTLOGIN, 0, 0, NULL);
1295 #ifdef _PATH_DOTCSHRC
1296 (void) srcfile(_PATH_DOTCSHRC, 0, 0, NULL);
1298 if (!arginp && !onelflg && !havhash)
1301 #ifdef _PATH_DOTLOGIN
1303 (void) srcfile(_PATH_DOTLOGIN, 0, 0, NULL);
1307 (void) sigsetmask(omask);
1309 (void) sigrelse(SIGINT);
1316 (void) srccat(varval(STRhome), STRsldotlogin);
1318 /* upward compat. */
1319 if (!srccat(varval(STRhome), STRsldottcshrc))
1320 (void) srccat(varval(STRhome), STRsldotcshrc);
1322 if (!fast && !arginp && !onelflg && !havhash)
1326 * Source history before .login so that it is available in .login
1331 (void) srccat(varval(STRhome), STRsldotlogin);
1333 if (!fast && (loginsh || rdirs))
1336 /* Reset interrupt flag */
1340 /* Initing AFTER .cshrc is the Right Way */
1341 if (intty && !arginp) { /* PWP setup stuff */
1342 ed_Init(); /* init the new line editor */
1344 check_window_size(1); /* mung environment */
1345 #endif /* SIG_WINDOW */
1349 * Now are ready for the -v and -x flags
1357 * All the rest of the world is inside this call. The argument to process
1358 * indicates whether it should catch "error unwinds". Thus if we are a
1359 * interactive shell our call here will never return by being blown past on
1369 xprintf("logout\n");
1375 goodbye(NULL, NULL);
1390 if (tpgrp > 0 && opgrp != shpgrp) {
1391 (void) setpgid(0, opgrp);
1392 (void) tcsetpgrp(FSHTTY, opgrp);
1393 (void) resetdisc(FSHTTY);
1395 #endif /* BSDJOBS */
1407 for (dp = cp; *dp; dp++)
1411 * i+2 where i is the number of colons in the path. There are i+1
1412 * directories in the path plus we need room for a zero terminator.
1414 pv = (Char **) xcalloc((size_t) (i + 2), sizeof(Char *));
1419 if ((c = *dp) == PATHSEP || c == 0) {
1421 pv[i++] = Strsave(*cp ? cp : STRdot);
1430 else if (*dp == '\\')
1432 #endif /* WINNT_NATIVE */
1436 setq(STRpath, pv, &shvhed, VAR_READWRITE);
1440 * Source to the file which is the catenation of the argument names.
1446 if (cp[0] == '/' && cp[1] == '\0')
1447 return srcfile(short2str(dp), (mflag ? 0 : 1), 0, NULL);
1457 if (ep[-1] == '/' && dp[0] == '/') /* silly win95 */
1459 #endif /* WINNT_NATIVE */
1461 ep = Strspl(cp, dp);
1462 ptr = short2str(ep);
1464 rv = srcfile(ptr, (mflag ? 0 : 1), 0, NULL);
1471 * Source to a file putting the file descriptor in a safe place (> 2).
1473 #ifndef WINNT_NATIVE
1477 #endif /*WINNT_NATIVE*/
1478 srcfile(f, onlyown, flag, av)
1486 if ((unit = open(f, O_RDONLY|O_LARGEFILE)) == -1)
1489 setmode(unit, O_TEXT);
1491 unit = dmove(unit, -1);
1493 (void) close_on_exec(unit, 1);
1494 srcunit(unit, onlyown, flag, av);
1500 * Save the shell state, and establish new argument vector, and new input
1504 st_save(st, unit, hflg, al, av)
1505 struct saved_state *st;
1509 st->insource = insource;
1511 /* Want to preserve the meaning of "source file >output".
1512 * Save old descriptors, move new 0,1,2 to safe places and assign
1513 * them to SH* and let process() redo 0,1,2 from them.
1515 * The macro returns true if d1 and d2 are good and they point to
1516 * different things. If you don't avoid saving duplicate
1517 * descriptors, you really limit the depth of "source" recursion
1518 * you can do because of all the open file descriptors. -IAN!
1520 #define NEED_SAVE_FD(d1,d2) \
1521 (fstat(d1, &s1) != -1 && fstat(d2, &s2) != -1 \
1522 && (s1.st_ino != s2.st_ino || s1.st_dev != s2.st_dev) )
1524 st->OLDSTD = st->SHOUT = st->SHDIAG = -1;/* test later to restore these */
1527 if (NEED_SAVE_FD(0,OLDSTD)) {
1528 st->OLDSTD = OLDSTD;
1529 OLDSTD = dmove(0, -1);
1530 (void)close_on_exec(OLDSTD, 1);
1532 if (NEED_SAVE_FD(1,SHOUT)) {
1534 SHOUT = dmove(1, -1);
1535 (void)close_on_exec(SHOUT, 1);
1537 if (NEED_SAVE_FD(2,SHDIAG)) {
1538 st->SHDIAG = SHDIAG;
1539 SHDIAG = dmove(2, -1);
1540 (void)close_on_exec(SHDIAG, 1);
1546 st->whyles = whyles;
1547 st->gointr = gointr;
1548 st->arginp = arginp;
1550 st->evalvec = evalvec;
1551 st->alvecp = alvecp;
1553 st->onelflg = onelflg;
1554 st->enterhist = enterhist;
1559 st->cantell = cantell;
1563 * we can now pass arguments to source.
1564 * For compatibility we do that only if arguments were really
1565 * passed, otherwise we keep the old, global $argv like before.
1567 if (av != NULL && *av != NULL) {
1569 if ((vp = adrof(STRargv)) != NULL && vp->vec != NULL)
1570 st->argv = saveblk(vp->vec);
1573 setq(STRargv, saveblk(av), &shvhed, VAR_READWRITE);
1578 SHIN = unit; /* Do this first */
1580 /* Establish new input arena */
1583 fseekp = feobp = fblocks = 0;
1589 intty = isatty(SHIN);
1604 * Restore the shell to a saved state
1608 struct saved_state *st;
1614 /* Reset input arena */
1617 Char** nfbuf = fbuf;
1618 int nfblocks = fblocks;
1622 for (i = 0; i < nfblocks; i++)
1623 xfree((ptr_t) nfbuf[i]);
1624 xfree((ptr_t) nfbuf);
1630 insource = st->insource;
1632 if (st->OLDSTD != -1)
1633 (void)close(OLDSTD), OLDSTD = st->OLDSTD;
1634 if (st->SHOUT != -1)
1635 (void)close(SHOUT), SHOUT = st->SHOUT;
1636 if (st->SHDIAG != -1)
1637 (void)close(SHDIAG), SHDIAG = st->SHDIAG;
1638 arginp = st->arginp;
1639 onelflg = st->onelflg;
1641 evalvec = st->evalvec;
1642 alvecp = st->alvecp;
1645 whyles = st->whyles;
1646 gointr = st->gointr;
1647 if (st->HIST != '\0')
1649 enterhist = st->enterhist;
1650 cantell = st->cantell;
1652 if (st->argv != NULL)
1653 setq(STRargv, st->argv, &shvhed, VAR_READWRITE);
1654 else if (av != NULL && *av != NULL && adrof(STRargv) != NULL)
1659 * Source to a unit. If onlyown it must be our file or our group or
1660 * we don't chance it. This occurs on ".cshrc"s and the like.
1663 srcunit(unit, onlyown, hflg, av)
1669 struct saved_state st;
1670 st.SHIN = -1; /* st_restore checks this */
1678 if (fstat(unit, &stb) < 0) {
1684 getexit(st.oldexit);
1688 st.mask = sigblock(sigmask(SIGINT));
1690 (void) sighold(SIGINT);
1693 /* Save the current state and move us to a new state */
1694 st_save(&st, unit, hflg, NULL, av);
1697 * Now if we are allowing commands to be interrupted, we let ourselves be
1702 (void) sigsetmask(st.mask);
1704 (void) sigrelse(SIGINT);
1708 * Bugfix for running out of memory by: Jak Kirman
1709 * <jak%cs.brown.edu@RELAY.CS.NET>. Solution: pay attention to what
1710 * setexit() is returning because reenter _may_ be in a register, and
1711 * thus restored to 0 on a longjump(). (PWP: insert flames about
1712 * compiler-dependant code here) PWP: THANKS LOTS !!!
1714 * PWP: think of this as like a LISP (unwind-protect ...)
1715 * thanks to Diana Smetters for pointing out how this _should_ be written
1718 st.reenter = 1; /* assume non-zero return val */
1719 if (setexit() == 0) {
1720 st.reenter = 0; /* Oh well, we were wrong */
1722 if ((st.reenter = setexit()) == 0) {
1724 process(0); /* 0 -> blow away on errors */
1729 (void) sigsetmask(st.mask);
1731 (void) sigrelse(SIGINT);
1734 /* Restore the old state */
1735 st_restore(&st, av);
1736 resexit(st.oldexit);
1738 * If process reset() (effectively an unwind) then we must also unwind.
1741 stderror(ERR_SILENT);
1756 (void) sigset(SIGQUIT, SIG_IGN);
1757 (void) sigset(SIGINT, SIG_IGN);
1758 (void) sigset(SIGTERM, SIG_IGN);
1759 (void) sigset(SIGHUP, SIG_IGN);
1760 setintr = 0; /* No interrupts after "logout" */
1761 /* Trap errors inside .logout */
1762 reenter = setexit();
1765 if (!(adrof(STRlogout)))
1766 set(STRlogout, Strsave(STRnormal), VAR_READWRITE);
1767 #ifdef _PATH_DOTLOGOUT
1768 (void) srcfile(_PATH_DOTLOGOUT, 0, 0, NULL);
1771 (void) srccat(varval(STRhome), STRsldtlogout);
1786 * Note that if STATUS is corrupted (i.e. getn bombs) then error will exit
1787 * directly because we poke child here. Otherwise we might continue
1788 * unwarrantedly (sic).
1792 xexit(getn(varval(STRstatus)));
1796 * in the event of a HUP we want to save the history
1803 * There is no return from here,
1804 * so we are not going to release SIGHUP
1809 (void) sigset(snum, SIG_IGN);
1812 (void) sigblock(sigmask(SIGHUP));
1814 (void) sighold(SIGHUP);
1815 # endif /* BSDSIGS */
1816 #endif /* UNRELSIGS */
1819 set(STRlogout, Strsave(STRhangup), VAR_READWRITE);
1820 #ifdef _PATH_DOTLOGOUT
1821 (void) srcfile(_PATH_DOTLOGOUT, 0, 0, NULL);
1824 (void) srccat(varval(STRhome), STRsldtlogout);
1831 * We kill the last foreground process group. It then becomes
1832 * responsible to propagate the SIGHUP to its progeny.
1835 struct process *pp, *np;
1837 for (pp = proclist.p_next; pp; pp = pp->p_next) {
1840 * Find if this job is in the foreground. It could be that
1841 * the process leader has exited and the foreground flag
1842 * is cleared for it.
1846 * If a process is in the foreground we try to kill
1847 * it's process group. If we succeed, then the
1848 * whole job is gone. Otherwise we keep going...
1849 * But avoid sending HUP to the shell again.
1851 if (((np->p_flags & PFOREGND) != 0) && np->p_jobid != shpgrp) {
1852 np->p_flags &= ~PHUP;
1853 if (killpg(np->p_jobid, SIGHUP) != -1) {
1854 /* In case the job was suspended... */
1856 (void) killpg(np->p_jobid, SIGCONT);
1861 while ((np = np->p_friends) != pp);
1864 #endif /* POSIXJOBS */
1869 static Char *jobargv[2] = {STRjobs, 0};
1872 * Catch an interrupt, e.g. during lexical input.
1873 * If we are an interactive shell, we reset the interrupt catch
1874 * immediately. In any case we drain the shell output,
1875 * and finally go through the normal error mechanism, which
1876 * gets a chance to make the shell go away.
1878 int just_signaled; /* bugfix by Michael Bloom (mg@ttidca.TTI.COM) */
1887 (void) sigset(snum, pintr);
1888 #endif /* UNRELSIGS */
1903 omask = sigblock((sigmask_t) 0);
1907 (void) sigsetmask(omask & ~sigmask(SIGINT));
1909 (void) sigrelse(SIGINT);
1914 dojobs(jobargv, NULL);
1915 stderror(ERR_NAME | ERR_INTR);
1918 /* MH - handle interrupted completions specially */
1920 if (InsideCompletion)
1921 stderror(ERR_SILENT);
1923 /* JV - Make sure we shut off inputl */
1925 (void) Cookedmode();
1929 (void) sigsetmask(omask & ~sigmask(SIGCHLD));
1932 (void) sighold(SIGINT);
1933 (void) sigrelse(SIGCHLD);
1936 #ifdef HAVE_GETPWENT
1941 * If we have an active "onintr" then we search for the label. Note that if
1942 * one does "onintr -" then we shan't be interruptible so we needn't worry
1948 if ((v = pargv) != 0)
1949 pargv = 0, blkfree(v);
1950 if ((v = gargv) != 0)
1951 gargv = 0, blkfree(v);
1954 else if (intty && wantnl) {
1957 * If we are editing a multi-line input command, and move to
1958 * the beginning of the line, we don't want to trash it when
1966 /* xputchar('\n'); *//* Some like this, others don't */
1967 (void) putraw('\r');
1968 (void) putraw('\n');
1971 stderror(ERR_SILENT);
1975 * Process is the main driving routine for the shell.
1976 * It runs all command processing, except for those within { ... }
1977 * in expressions (which is run by a routine evalav in sh.exp.c which
1978 * is a stripped down process), and `...` evaluation which is run
1979 * also by a subset of this code in sh.glob.c in the routine backeval.
1981 * The code here is a little strange because part of it is interruptible
1982 * and hence freeing of structures appears to occur when none is necessary
1983 * if this is ignored.
1985 * Note that if catch is not set then we will unwind on any error.
1986 * If an end-of-file occurs, we return.
1988 static struct command *savet = NULL;
1994 /* PWP: This might get nuked my longjmp so don't make it a register var */
1995 struct command *t = savet;
2003 /* This was leaking memory badly, particularly when sourcing
2004 * files, etc.. For whatever reason we were arriving here with
2005 * allocated pointers still active, and the code was simply
2006 * overwriting them. I can't say I fully understand the
2007 * control flow here, but according to Purify this particular
2008 * leak has been plugged, and I haven't noticed any ill
2011 if (paraml.next && paraml.next != ¶ml)
2014 paraml.next = paraml.prev = ¶ml;
2015 paraml.word = STRNULL;
2017 justpr = enterhist; /* execute if not entering history */
2020 * Interruptible during interactive reads
2024 (void) sigsetmask(sigblock((sigmask_t) 0) & ~sigmask(SIGINT));
2026 (void) sigrelse(SIGINT);
2031 * For the sake of reset()
2035 freesyn(savet), savet = NULL;
2047 * Every error is eventually caught here or the shell dies. It is
2048 * at this point that we clean up any left-over open files, by
2049 * closing all but a fixed number of pre-defined files. Thus
2050 * routines don't have to worry about leaving files open due to
2051 * deeper errors... they will get closed here.
2064 if (intty && prompt && evalvec == 0) {
2068 * Watch for logins/logouts. Next is scheduled commands stored
2069 * previously using "sched." Then execute periodic commands.
2070 * Following that, the prompt precmd is run.
2074 #endif /* !HAVENOUTMP */
2079 * If we are at the end of the input buffer then we are going to
2080 * read fresh stuff. Otherwise, we are rereading input and don't
2081 * need or want to prompt.
2083 if (fseekp == feobp && aret == TCSH_F_SEEK)
2084 printprompt(0, NULL);
2089 xfree((ptr_t) seterr);
2094 * Echo not only on VERBOSE, but also with history expansion. If there
2095 * is a lexical error then we forego history echo.
2097 if ((lex(¶ml) && !seterr && intty && !tellwhat && !Expand &&
2098 !whyles) || adrof(STRverbose)) {
2099 int odidfds = didfds;
2107 (void) alarm(0); /* Autologout OFF */
2110 * The parser may lose space if interrupted.
2114 (void) sigblock(sigmask(SIGINT));
2116 (void) sighold(SIGINT);
2120 * Save input text on the history list if reading in old history, or it
2121 * is from the terminal at the top level and not in a loop.
2123 * PWP: entry of items in the history list while in a while loop is done
2126 if (enterhist || (catch && intty && !whyles && !tellwhat && !arun))
2127 savehist(¶ml, enterhist > 1);
2129 if (Expand && seterr)
2133 * Print lexical error messages, except when sourcing history lists.
2135 if (!enterhist && seterr)
2139 * If had a history command :p modifier then this is as far as we
2146 * If had a tellwhat from twenex() then do
2149 (void) tellmewhat(¶ml, NULL);
2157 * If we are interactive, try to continue jobs that we have stopped
2160 continue_jobs(¶ml);
2161 #endif /* BSDJOBS */
2164 * Check to see if the user typed "rm * .o" or something
2169 * Parse the words of the input into a parse tree.
2171 savet = syntax(paraml.next, ¶ml, 0);
2177 * Execute the parse tree From: Michael Schroeder
2178 * <mlschroe@immd4.informatik.uni-erlangen.de> was execute(t, tpgrp);
2180 execute(savet, (tpgrp > 0 ? tpgrp : -1), NULL, NULL, TRUE);
2186 freesyn(savet), savet = NULL;
2188 if (windowchg || (catch && intty && !whyles && !tellwhat)) {
2189 (void) check_window_size(0); /* for window systems */
2191 #endif /* SIG_WINDOW */
2192 set(STR_, Strsave(InputBuf), VAR_READWRITE | VAR_NOGLOB);
2210 if (*t && eq(*t, STRmh)) {
2212 stderror(ERR_NAME | ERR_HFLAG);
2215 else if (*t && eq(*t, STRmm)) {
2217 stderror(ERR_NAME | ERR_MFLAG);
2221 f = globone(*t++, G_ERROR);
2222 (void) strcpy(buf, short2str(f));
2224 gflag = 0, tglob(t);
2228 stderror(ERR_NAME | ERR_NOMATCH);
2233 if ((!srcfile(buf, 0, hflg, t)) && (!hflg) && (!bequiet))
2234 stderror(ERR_SYSTEM, buf, strerror(errno));
2239 * If we are a login shell, then we don't want to tell
2240 * about any mail file unless its been modified
2241 * after the time we started.
2242 * This prevents us from telling the user things he already
2243 * knows, since the login program insists on saying
2249 * This version checks if the file is a directory, and if so,
2250 * tells you the number of files in it, otherwise do the old thang.
2251 * The magic "+1" in the time calculation is to compensate for
2252 * an AFS bug where directory mtimes are set to 1 second in
2267 if (v == NULL || v->vec == NULL)
2272 intvl = (cnt && number(*vp)) ? (--cnt, getn(*vp++)) : MAILINTVL;
2275 if (chktim + intvl > t)
2278 char *filename = short2str(*vp);
2279 char *mboxdir = filename;
2281 if (stat(filename, &stb) < 0)
2283 #if defined(BSDTIMES) || defined(_SEQUENT_)
2284 new = stb.st_mtime > time0.tv_sec;
2286 new = stb.st_mtime > seconds0;
2288 if (S_ISDIR(stb.st_mode)) {
2291 char tempfilename[MAXPATHLEN];
2294 xsnprintf(tempfilename, MAXPATHLEN, "%s/new", filename);
2296 if (stat(tempfilename, &stc) != -1 && S_ISDIR(stc.st_mode)) {
2298 * "filename/new" exists and is a directory; you are
2302 #if defined(BSDTIMES) || defined(_SEQUENT_)
2303 new = stb.st_mtime > time0.tv_sec;
2305 new = stb.st_mtime > seconds0;
2307 mboxdir = tempfilename;
2310 if (stb.st_mtime <= chktim + 1 || (loginsh && !new))
2313 if ((mailbox = opendir(mboxdir)) == NULL)
2317 if (!readdir(mailbox) || !readdir(mailbox))
2320 while (readdir(mailbox))
2327 xprintf(CGETS(11, 3, "You have %d mail messages.\n"),
2330 xprintf(CGETS(11, 4, "You have %d mail messages in %s.\n"),
2331 mailcount, filename);
2336 if (stb.st_size == 0 || stb.st_atime > stb.st_mtime ||
2337 (stb.st_atime <= chktim && stb.st_mtime <= chktim) ||
2340 type = strsave(new ? CGETS(11, 6, "new ") : "");
2342 xprintf(CGETS(11, 5, "You have %smail.\n"), type);
2344 xprintf(CGETS(11, 7, "You have %smail in %s.\n"), type, filename);
2352 * Extract a home directory from the password file
2353 * The argument points to a buffer where the name of the
2354 * user whose home directory is sought is currently.
2355 * We write the home directory of the user back there.
2366 if (*home == '\0') {
2367 if ((h = varval(STRhome)) != STRNULL) {
2368 (void) Strcpy(home, h);
2378 if ((h = gettilde(home)) == NULL)
2381 (void) Strcpy(home, h);
2387 * Move the initial descriptors to their eventual
2388 * resting places, closing all other units.
2396 #endif /* NLS_CATALOGS */
2397 #endif /* NLS_BUGS */
2400 didfds = 0; /* 0, 1, 2 aren't set up */
2401 (void) close_on_exec(SHIN = dcopy(0, FSHIN), 1);
2402 (void) close_on_exec(SHOUT = dcopy(1, FSHOUT), 1);
2403 (void) close_on_exec(SHDIAG = dcopy(2, FSHDIAG), 1);
2404 (void) close_on_exec(OLDSTD = dcopy(SHIN, FOLDSTD), 1);
2405 #ifndef CLOSE_ON_EXEC
2406 didcch = 0; /* Havent closed for child */
2407 #endif /* CLOSE_ON_EXEC */
2408 isdiagatty = isatty(SHDIAG);
2409 isoutatty = isatty(SHOUT);
2413 #endif /* NLS_CATALOGS */
2414 #endif /* NLS_BUGS */
2427 if (loginsh && do_logout) {
2428 /* this is to send hangup signal to the develcon */
2429 /* we toggle DTR. clear dtr - sleep 1 - set dtr */
2430 /* ioctl will return ENOTTY for pty's but we ignore it */
2431 /* exitstat will run after disconnect */
2432 /* we sleep for 2 seconds to let things happen in */
2433 /* .logout and rechist() */
2436 (void) ioctl(FSHTTY, TIOCCDTR, NULL);
2438 (void) ioctl(FSHTTY, TIOCSDTR, NULL);
2439 #endif /* TIOCCDTR */
2444 struct process *pp, *np;
2446 /* Kill all processes marked for hup'ing */
2447 for (pp = proclist.p_next; pp; pp = pp->p_next) {
2450 if ((np->p_flags & PHUP) && np->p_jobid != shpgrp) {
2451 if (killpg(np->p_jobid, SIGHUP) != -1) {
2452 /* In case the job was suspended... */
2454 (void) killpg(np->p_jobid, SIGCONT);
2459 while ((np = np->p_friends) != pp);
2465 * We need to call catclose, because SVR4 leaves symlinks behind otherwise
2466 * in the catalog directories. We cannot close on a vforked() child,
2467 * because messages will stop working on the parent too.
2471 #endif /* NLS_CATALOGS */
2474 #endif /* WINNT_NATIVE */
2478 #ifndef _PATH_DEFPATH
2486 blkp = blk = (Char **) xmalloc((size_t) sizeof(Char *) * 10);
2490 *blkp++ = Strsave(STRdot);
2494 #define DIRAPPEND(a) \
2495 if (stat(ptr = a, &stb) == 0 && S_ISDIR(stb.st_mode)) \
2499 DIRAPPEND(_PATH_LOCAL);
2503 DIRAPPEND(_PATH_USRUCB);
2507 DIRAPPEND(_PATH_USRBSD);
2511 DIRAPPEND(_PATH_BIN);
2515 DIRAPPEND(_PATH_USRBIN);
2522 *blkp++ = Strsave(STRdot);
2534 recdirs(NULL, adrof(STRsavedirs) != NULL);
2535 rechist(NULL, adrof(STRsavehist) != NULL);