1 /* $Header: /p/tcsh/cvsroot/tcsh/sh.c,v 3.185 2015/05/10 13:28:54 christos 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("$tcsh: sh.c,v 3.185 2015/05/10 13:28:54 christos 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 IZERO_STRUCT;
82 struct wordent paraml IZERO_STRUCT;
84 static const char tcshstr[] = "tcsh";
86 struct sigaction parintr; /* Parents interrupt catch */
87 struct sigaction parterm; /* Parents terminate catch */
94 int use_fork = 0; /* use fork() instead of vfork()? */
97 * Magic pointer values. Used to specify other invalid conditions aside
101 Char *INVPTR = &INVCHAR;
102 Char **INVPPTR = &INVPTR;
105 static int mflag = 0;
106 static int prompt = 1;
114 static time_t chktim; /* Time mail last checked */
119 * This preserves the input state of the shell. It is used by
120 * st_save and st_restore to manupulate shell state.
129 struct whyle *whyles;
146 static int srccat (Char *, Char *);
148 static int srcfile (const char *, int, int, Char **);
150 int srcfile (const char *, int, int, Char **);
151 #endif /*WINNT_NATIVE*/
152 static void srcunit (int, int, int, Char **);
153 static void mailchk (void);
154 #ifndef _PATH_DEFPATH
155 static Char **defaultpath (void);
157 static void record (void);
158 static void st_save (struct saved_state *, int, int,
160 static void st_restore (void *);
162 int main (int, char **);
165 #define LOCALEDIR "/usr/share/locale"
170 add_localedir_to_nlspath(const char *path)
172 static const char msgs_LOC[] = "/%L/LC_MESSAGES/%N.cat";
173 static const char msgs_lang[] = "/%l/LC_MESSAGES/%N.cat";
179 char trypath[MAXPATHLEN];
185 (void) xsnprintf(trypath, sizeof(trypath), "%s/en/LC_MESSAGES/tcsh.cat",
187 if (stat(trypath, &st) == -1)
190 if ((old = getenv("NLSPATH")) != NULL)
191 len = strlen(old) + 1; /* don't forget the colon. */
195 len += 2 * strlen(path) +
196 sizeof(msgs_LOC) + sizeof(msgs_lang); /* includes the extra colon */
198 new = new_p = xcalloc(len, 1);
201 size_t pathlen = strlen(path);
204 (void) xsnprintf(new_p, len, "%s", old);
205 new_p += strlen(new_p);
208 /* Check if the paths we try to add are already present in NLSPATH.
209 If so, note it by setting the appropriate flag to 0. */
210 for (old_p = old; old_p; old_p = strchr(old_p, ':'),
211 old_p = old_p ? old_p + 1 : NULL) {
212 if (strncmp(old_p, path, pathlen) != 0)
214 if (strncmp(old_p + pathlen, msgs_LOC, sizeof(msgs_LOC) - 1) == 0)
216 else if (strncmp(old_p + pathlen, msgs_lang,
217 sizeof(msgs_lang) - 1) == 0)
222 /* Add the message catalog paths not already present to NLSPATH. */
223 if (add_LOC || add_lang)
224 (void) xsnprintf(new_p, len, "%s%s%s%s%s%s",
226 add_LOC ? path : "", add_LOC ? msgs_LOC : "",
227 add_LOC && add_lang ? ":" : "",
228 add_lang ? path : "", add_lang ? msgs_lang : "");
230 tsetenv(STRNLSPATH, str2short(new));
236 main(int argc, char **argv)
239 volatile int nexececho = 0;
241 volatile int nverbose = 0;
242 volatile int rdirs = 0;
252 struct sigaction oparintr;
256 #endif /* WINNT_NATIVE */
258 (void)memset(&reslab, 0, sizeof(reslab));
259 #if defined(NLS_CATALOGS) && defined(LC_MESSAGES)
260 (void) setlocale(LC_MESSAGES, "");
261 #endif /* NLS_CATALOGS && LC_MESSAGES */
265 (void) setlocale(LC_CTYPE, ""); /* for iscntrl */
266 # endif /* LC_CTYPE */
269 STR_environ = blk2short(environ);
270 environ = short2blk(STR_environ); /* So that we can free it */
273 add_localedir_to_nlspath(LOCALEDIR);
279 mal_setstatsfile(fdopen(dmove(xopen("/tmp/tcsh.trace",
280 O_WRONLY|O_CREAT|O_LARGEFILE, 0666), 25), "w"));
282 #endif /* MALLOC_TRACE */
284 #if !(defined(BSDTIMES) || defined(_SEQUENT_)) && defined(POSIX)
286 clk_tck = (clock_t) sysconf(_SC_CLK_TCK);
287 # else /* ! _SC_CLK_TCK */
290 # else /* !CLK_TCK */
292 # endif /* CLK_TCK */
293 # endif /* _SC_CLK_TCK */
294 #endif /* !BSDTIMES && POSIX */
296 settimes(); /* Immed. estab. timing base */
302 * Make sure we have 0, 1, 2 open
303 * Otherwise `` jobs will not work... (From knaff@poly.polytechnique.fr)
307 if ((f = xopen(_PATH_DEVNULL, O_RDONLY|O_LARGEFILE)) == -1 &&
308 (f = xopen("/", O_RDONLY|O_LARGEFILE)) == -1)
314 osinit(); /* Os dependent initialization */
320 t = strrchr(argv[0], '/');
323 char *s = strrchr(argv[0], '\\');
327 #endif /* WINNT_NATIVE */
328 t = t ? t + 1 : argv[0];
330 progname = strsave((t && *t) ? t : tcshstr); /* never want a null */
331 tcsh = strncmp(progname, tcshstr, sizeof(tcshstr) - 1) == 0;
335 * Initialize non constant strings
338 STR_BSHELL = SAVE(_PATH_BSHELL);
341 STR_SHELLPATH = SAVE(_PATH_TCSHELL);
344 STR_SHELLPATH = SAVE(_PATH_CSHELL);
347 STR_WORD_CHARS = SAVE(WORD_CHARS);
351 PRCH = tcsh ? '>' : '%'; /* to replace %# in $prompt for normal users */
352 PRCHROOT = '#'; /* likewise for root */
353 word_chars = STR_WORD_CHARS;
354 bslash_quote = 0; /* PWP: do tcsh-style backslash quoting? */
355 anyerror = 1; /* for compatibility */
356 setcopy(STRanyerror, STRNULL, VAR_READWRITE);
358 /* Default history size to 100 */
359 setcopy(STRhistory, str2short("100"), VAR_READWRITE);
363 ffile = SAVE(tempv[0]);
365 if (eq(ffile, STRaout)) /* A.out's are quittable */
372 * We are a login shell if: 1. we were invoked as -<something> with
373 * optional arguments 2. or we were invoked only with the -l flag
375 loginsh = (**tempv == '-') || (argc == 2 &&
376 tempv[1][0] == '-' && tempv[1][1] == 'l' &&
377 tempv[1][2] == '\0');
379 /* No better way to find if we are a login shell */
381 loginsh = (argc == 1 && getppid() == 1);
382 **tempv = '-'; /* Avoid giving VMS an acidic stomach */
384 #endif /* _VMS_POSIX */
386 if (loginsh && **tempv != '-') {
390 * Mangle the argv space
395 argv0 = strspl("-", *tempv);
400 (void) time(&chktim);
404 NoNLSRebind = getenv("NOREBIND") != NULL;
408 # endif /* SETLOCALEBUG */
409 (void) setlocale(LC_ALL, "");
411 (void) setlocale(LC_COLLATE, "");
415 # endif /* SETLOCALEBUG */
418 # endif /* STRCOLLBUG */
421 * On solaris ISO8859-1 contains no printable characters in the upper half
422 * so we need to test only for MB_CUR_MAX == 1, otherwise for multi-byte
423 * locales we are always AsciiOnly == 0.
425 if (MB_CUR_MAX == 1) {
428 for (k = 0200; k <= 0377 && !isprint(CTL_ESC(k)); k++)
430 AsciiOnly = k > 0377;
434 AsciiOnly = getenv("LANG") == NULL && getenv("LC_CTYPE") == NULL;
436 if (MapsAreInited && !NLSMapsAreInited)
441 * Initialize for periodic command intervals. Also, initialize the dummy
442 * tty list for login-watch.
444 (void) time(&t_period);
447 #endif /* !HAVENOUTMP */
451 * From: Jim Pace <jdp@research.att.com>
452 * tcsh does not work properly on the alliants through an rlogin session.
453 * The shell generally hangs. Also, reference to the controlling terminal
454 * does not work ( ie: echo foo > /dev/tty ).
456 * A security feature was added to rlogind affecting FX/80's Concentrix
457 * from revision 5.5.xx upwards (through 5.7 where this fix was implemented)
458 * This security change also affects the FX/2800 series.
459 * The security change to rlogind requires the process group of an rlogin
460 * session become disassociated with the tty in rlogind.
462 * The changes needed are:
463 * 1. set the process group
464 * 2. reenable the control terminal
466 if (loginsh && isatty(SHIN)) {
467 ttyn = ttyname(SHIN);
469 SHIN = xopen(ttyn, O_RDWR|O_LARGEFILE);
471 (void) ioctl (SHIN, TIOCSPGRP, (ioctl_t) &shpgrp);
472 (void) setpgid(0, shpgrp);
477 * Move the descriptors to safe places. The variable didfds is 0 while we
478 * have only FSH* to work with. When didfds is true, we have 0,1,2 and
479 * prefer to use these.
484 setv(STRcdtohome, SAVE(""), VAR_READWRITE);
487 * Get and set the tty now
489 if ((ttyn = ttyname(SHIN)) != NULL) {
491 * Could use rindex to get rid of other possible path components, but
492 * hpux preserves the subdirectory /pty/ when storing the tty name in
493 * utmp, so we keep it too.
495 if (strncmp(ttyn, "/dev/", 5) == 0)
496 setv(STRtty, cp = SAVE(ttyn + 5), VAR_READWRITE);
498 setv(STRtty, cp = SAVE(ttyn), VAR_READWRITE);
501 setv(STRtty, cp = SAVE(""), VAR_READWRITE);
504 * Initialize the shell variables. ARGV and PROMPT are initialized later.
505 * STATUS is also munged in several places. CHILD is munged when
510 * 7-10-87 Paul Placeway autologout should be set ONLY on login shells and
511 * on shells running as root. Out of these, autologout should NOT be set
512 * for any psudo-terminals (this catches most window systems) and not for
513 * any terminal running X windows.
515 * At Ohio State, we have had problems with a user having his X session
516 * drop out from under him (on a Sun) because the shell in his master
517 * xterm timed out and exited.
519 * Really, this should be done with a program external to the shell, that
520 * watches for no activity (and NO running programs, such as dump) on a
521 * terminal for a long peroid of time, and then SIGHUPS the shell on that
524 * bugfix by Rich Salz <rsalz@PINEAPPLE.BBN.COM>: For root rsh things
525 * allways first check to see if loginsh or really root, then do things
528 * Also by Jean-Francois Lamy <lamy%ai.toronto.edu@RELAY.CS.NET>: check the
529 * value of cp before using it! ("root can rsh too")
531 * PWP: keep the nested ifs; the order of the tests matters and a good
532 * (smart) C compiler might re-arange things wrong.
537 /* root always has a 15 minute autologout */
538 setcopy(STRautologout, STRrootdefautologout, VAR_READWRITE);
541 /* users get autologout set to 0 */
542 setcopy(STRautologout, STR0, VAR_READWRITE);
544 if (loginsh || (uid == 0)) {
546 /* only for login shells or root and we must have a tty */
547 if (((cp2 = Strrchr(cp, (Char) '/')) != NULL) &&
548 (Strncmp(cp, STRptssl, 3) != 0)) {
553 if (!(((Strncmp(cp2, STRtty, 3) == 0) && Isalpha(cp2[3])) ||
554 Strstr(cp, STRptssl) != NULL)) {
555 if (getenv("DISPLAY") == NULL) {
556 /* NOT on X window shells */
557 setcopy(STRautologout, STRdefautologout, VAR_READWRITE);
563 #endif /* AUTOLOGOUT */
565 sigset_interrupting(SIGALRM, queue_alrmcatch);
567 setcopy(STRstatus, STR0, VAR_READWRITE);
570 * get and set machine specific environment variables
576 * Publish the selected echo style
578 #if ECHO_STYLE != BSD_ECHO
580 # if ECHO_STYLE == NONE_ECHO
581 setcopy(STRecho_style, STRnone, VAR_READWRITE);
582 # endif /* ECHO_STYLE == NONE_ECHO */
583 # if ECHO_STYLE == SYSV_ECHO
584 setcopy(STRecho_style, STRsysv, VAR_READWRITE);
585 # endif /* ECHO_STYLE == SYSV_ECHO */
586 # if ECHO_STYLE == BOTH_ECHO
587 setcopy(STRecho_style, STRboth, VAR_READWRITE);
588 # endif /* ECHO_STYLE == BOTH_ECHO */
590 #endif /* ECHO_STYLE != BSD_ECHO */
591 setcopy(STRecho_style, STRbsd, VAR_READWRITE);
594 * increment the shell level.
598 if ((tcp = getenv("HOME")) != NULL)
599 cp = quote(SAVE(tcp));
602 /* On Android, $HOME usually isn't set, so we can't load user RC files.
603 Check for the environment variable EXTERNAL_STORAGE, which contains
604 the mount point of the external storage (SD card, mostly). If
605 EXTERNAL_STORAGE isn't set fall back to "/sdcard". */
606 if ((tcp = getenv("EXTERNAL_STORAGE")) != NULL)
607 cp = quote(SAVE(tcp));
609 cp = quote(SAVE("/sdcard"));
615 fast = 1; /* No home -> can't read scripts */
617 setv(STRhome, cp, VAR_READWRITE);
619 dinit(cp); /* dinit thinks that HOME == cwd in a login
622 * Grab other useful things from the environment. Should we grab
626 char *cln, *cus, *cgr;
634 setv(STRoid, Itoa(oid, 0, 0), VAR_READWRITE);
637 setv(STReuid, Itoa(euid, 0, 0), VAR_READWRITE);
638 if ((pw = xgetpwuid(euid)) == NULL)
639 setcopy(STReuser, STRunknown, VAR_READWRITE);
641 setcopy(STReuser, str2short(pw->pw_name), VAR_READWRITE);
643 setv(STRuid, Itoa(uid, 0, 0), VAR_READWRITE);
645 setv(STRgid, Itoa(gid, 0, 0), VAR_READWRITE);
647 cln = getenv("LOGNAME");
648 cus = getenv("USER");
650 setv(STRuser, quote(SAVE(cus)), VAR_READWRITE);
651 else if (cln != NULL)
652 setv(STRuser, quote(SAVE(cln)), VAR_READWRITE);
653 else if ((pw = xgetpwuid(uid)) == NULL)
654 setcopy(STRuser, STRunknown, VAR_READWRITE);
656 setcopy(STRuser, str2short(pw->pw_name), VAR_READWRITE);
658 tsetenv(STRLOGNAME, varval(STRuser));
660 tsetenv(STRKUSER, varval(STRuser));
662 cgr = getenv("GROUP");
664 setv(STRgroup, quote(SAVE(cgr)), VAR_READWRITE);
665 else if ((gr = xgetgrgid(gid)) == NULL)
666 setcopy(STRgroup, STRunknown, VAR_READWRITE);
668 setcopy(STRgroup, str2short(gr->gr_name), VAR_READWRITE);
670 tsetenv(STRKGROUP, varval(STRgroup));
674 * HOST may be wrong, since rexd transports the entire environment on sun
675 * 3.x Just set it again
678 char cbuff[MAXHOSTNAMELEN];
680 if (gethostname(cbuff, sizeof(cbuff)) >= 0) {
681 cbuff[sizeof(cbuff) - 1] = '\0'; /* just in case */
682 tsetenv(STRHOST, str2short(cbuff));
685 tsetenv(STRHOST, STRunknown);
691 * Try to determine the remote host we were logged in from.
694 #endif /* REMOTEHOST */
697 if ((tcp = getenv("SYSTYPE")) == NULL)
699 tsetenv(STRSYSTYPE, quote(str2short(tcp)));
703 * set editing on by default, unless running under Emacs as an inferior
705 * We try to do this intelligently. If $TERM is available, then it
706 * should determine if we should edit or not. $TERM is preserved
707 * across rlogin sessions, so we will not get confused if we rlogin
708 * under an emacs shell. Another advantage is that if we run an
709 * xterm under an emacs shell, then the $TERM will be set to
710 * xterm, so we are going to want to edit. Unfortunately emacs
711 * does not restore all the tty modes, so xterm is not very well
712 * set up. But this is not the shell's fault.
713 * Also don't edit if $TERM == wm, for when we're running under an ATK app.
714 * Finally, emacs compiled under terminfo, sets the terminal to dumb,
715 * so disable editing for that too.
717 * Unfortunately, in some cases the initial $TERM setting is "unknown",
718 * "dumb", or "network" which is then changed in the user's startup files.
719 * We fix this by setting noediting here if $TERM is unknown/dumb and
720 * if noediting is set, we switch on editing if $TERM is changed.
722 if ((tcp = getenv("TERM")) != NULL) {
723 setv(STRterm, quote(SAVE(tcp)), VAR_READWRITE);
724 noediting = strcmp(tcp, "unknown") == 0 || strcmp(tcp, "dumb") == 0 ||
725 strcmp(tcp, "network") == 0;
726 editing = strcmp(tcp, "emacs") != 0 && strcmp(tcp, "wm") != 0 &&
731 editing = ((tcp = getenv("EMACS")) == NULL || strcmp(tcp, "t") != 0);
735 * The 'edit' variable is either set or unset. It doesn't
736 * need a value. Making it 'emacs' might be confusing.
743 * still more mutability: make the complete routine automatically add the
744 * suffix of file names...
749 * Compatibility with tcsh >= 6.12 by default
751 setNS(STRcsubstnonl);
754 * Random default kill ring size
756 setcopy(STRkillring, str2short("30"), VAR_READWRITE);
759 * Re-initialize path if set in environment
761 if ((tcp = getenv("PATH")) == NULL)
763 importpath(str2short(_PATH_DEFPATH));
764 #else /* !_PATH_DEFPATH */
765 setq(STRpath, defaultpath(), &shvhed, VAR_READWRITE);
766 #endif /* _PATH_DEFPATH */
768 /* Importpath() allocates memory for the path, and the
769 * returned pointer from SAVE() was discarded, so
770 * this was a memory leak.. (sg)
772 * importpath(SAVE(tcp));
774 importpath(str2short(tcp));
778 /* If the SHELL environment variable ends with "tcsh", set
779 * STRshell to the same path. This is to facilitate using
780 * the executable in environments where the compiled-in
781 * default isn't appropriate (sg).
786 if ((tcp = getenv("SHELL")) != NULL) {
787 sh_len = strlen(tcp);
788 if ((sh_len >= 5 && strcmp(tcp + (sh_len - 5), "/tcsh") == 0) ||
789 (!tcsh && sh_len >= 4 && strcmp(tcp + (sh_len - 4), "/csh") == 0))
790 setv(STRshell, quote(SAVE(tcp)), VAR_READWRITE);
795 setcopy(STRshell, STR_SHELLPATH, VAR_READWRITE);
798 #ifdef _OSD_POSIX /* BS2000 needs this variable set to "SHELL" */
799 if ((tcp = getenv("PROGRAM_ENVIRONMENT")) == NULL)
801 tsetenv(STRPROGRAM_ENVIRONMENT, quote(str2short(tcp)));
802 #endif /* _OSD_POSIX */
805 if ((tcp = getenv("LS_COLORS")) != NULL)
806 parseLS_COLORS(str2short(tcp));
807 if ((tcp = getenv("LSCOLORS")) != NULL)
808 parseLSCOLORS(str2short(tcp));
809 #endif /* COLOR_LS_F */
811 doldol = putn((tcsh_number_t)getpid()); /* For $$ */
816 if ((tmp = getenv("TMP")) != NULL) {
817 tmp = xasprintf("%s/%s", tmp, "sh");
824 shtemp = Strspl(tmp2, doldol); /* For << */
827 #else /* !WINNT_NATIVE */
830 const char *tmpdir = getenv ("TMPDIR");
833 shtemp = Strspl(SAVE(tmpdir), SAVE("/sh" TMP_TEMPLATE)); /* For << */
835 #else /* !HAVE_MKSTEMP */
836 shtemp = Strspl(STRtmpsh, doldol); /* For << */
837 #endif /* HAVE_MKSTEMP */
838 #endif /* WINNT_NATIVE */
841 * Record the interrupt states from the parent process. If the parent is
842 * non-interruptible our hand must be forced or we (and our children) won't
843 * be either. Our children inherit termination from our parent. We catch it
844 * only if we are the login shell.
846 sigaction(SIGINT, NULL, &parintr);
847 sigaction(SIGTERM, NULL, &parterm);
851 /* Enable process migration on ourselves and our progeny */
852 (void) signal(SIGMIGRATE, SIG_DFL);
856 * dspkanji/dspmbyte autosetting
858 /* PATCH IDEA FROM Issei.Suzuki VERY THANKS */
859 #if defined(DSPMBYTE)
860 #if defined(NLS) && defined(LC_CTYPE)
861 if (((tcp = setlocale(LC_CTYPE, NULL)) != NULL || (tcp = getenv("LANG")) != NULL) && !adrof(CHECK_MBYTEVAR))
863 if ((tcp = getenv("LANG")) != NULL && !adrof(CHECK_MBYTEVAR))
866 autoset_dspmbyte(str2short(tcp));
868 #if defined(WINNT_NATIVE)
869 else if (!adrof(CHECK_MBYTEVAR))
870 nt_autoset_dspmbyte();
871 #endif /* WINNT_NATIVE */
873 #if defined(AUTOSET_KANJI)
874 # if defined(NLS) && defined(LC_CTYPE)
875 if (setlocale(LC_CTYPE, NULL) != NULL || getenv("LANG") != NULL)
877 if (getenv("LANG") != NULL)
880 #endif /* AUTOSET_KANJI */
881 fix_version(); /* publish the shell version */
883 if (argc > 1 && strcmp(argv[1], "--version") == 0) {
884 xprintf("%S\n", varval(STRversion));
887 if (argc > 1 && strcmp(argv[1], "--help") == 0) {
888 xprintf("%S\n\n", varval(STRversion));
889 xprintf("%s", CGETS(11, 8, HELP_STRING));
893 * Process the arguments.
895 * Note that processing of -v/-x is actually delayed till after script
898 * We set the first character of our name to be '-' if we are a shell
899 * running interruptible commands. Many programs which examine ps'es
900 * use this to filter such shells out.
903 while (argc > 0 && (tcp = tempv[0])[0] == '-' &&
904 *++tcp != '\0' && !batch) {
908 case 0: /* - Interruptible, no prompt */
914 case 'b': /* -b Next arg is input file */
918 case 'c': /* -c Command input from arg */
924 it relies on a 7 bit environment (/bin/sh), so it
925 pass ascii arguments with the 8th bit set */
926 if (!strcmp(argv[0], "sh"))
930 for (p = tempv[0]; *p; ++p)
934 arginp = SAVE(tempv[0]);
937 * we put the command into a variable
940 setv(STRcommand, quote(Strsave(arginp)), VAR_READWRITE);
943 * * Give an error on -c arguments that end in * backslash to
944 * ensure that you don't make * nonportable csh scripts.
951 while (cp > arginp && *--cp == '\\')
953 if ((count & 1) != 0) {
961 case 'd': /* -d Load directory stack from file */
966 case 'D': /* -D Define environment variable */
971 if (dp = Strchr(cp, '=')) {
976 tsetenv(cp, STRNULL);
978 *tcp = '\0'; /* done with this argument */
982 case 'e': /* -e Exit on any error */
986 case 'f': /* -f Fast start */
990 case 'i': /* -i Interactive, even if !intty */
995 case 'm': /* -m read .cshrc (from su) */
999 case 'n': /* -n Don't execute */
1003 case 'q': /* -q (Undoc'd) ... die on quit */
1007 case 's': /* -s Read from std input */
1011 case 't': /* -t Read one line from input */
1017 case 'v': /* -v Echo hist expanded input */
1018 nverbose = 1; /* ... later */
1021 case 'x': /* -x Echo just before execution */
1022 nexececho = 1; /* ... later */
1025 case 'V': /* -V Echo hist expanded input */
1026 setNS(STRverbose); /* NOW! */
1029 case 'X': /* -X Echo just before execution */
1030 setNS(STRecho); /* NOW! */
1035 * This will cause children to be created using fork instead of
1046 * for O/S's that don't do the argument parsing right in
1047 * "#!/foo -f " scripts
1051 default: /* Unknown command option */
1053 stderror(ERR_TCSHUSAGE, tcp-1, progname);
1060 if (quitit) /* With all due haste, for debugging */
1061 (void) signal(SIGQUIT, SIG_DFL);
1064 * Unless prevented by -, -c, -i, -s, or -t, if there are remaining
1065 * arguments the first of them is the name of a shell file from which to
1068 if (nofile == 0 && argc > 0) {
1069 nofile = xopen(tempv[0], O_RDONLY|O_LARGEFILE);
1071 child = 1; /* So this ... */
1072 /* ... doesn't return */
1073 stderror(ERR_SYSTEM, tempv[0], strerror(errno));
1077 ffile = SAVE(tempv[0]);
1079 * Replace FSHIN. Handle /dev/std{in,out,err} specially
1080 * since once they are closed we cannot open them again.
1081 * In that case we use our own saved descriptors
1083 if ((SHIN = dmove(nofile, FSHIN)) < 0)
1095 stderror(ERR_SYSTEM, tempv[0], strerror(errno));
1098 (void) close_on_exec(SHIN, 1);
1100 /* argc not used any more */ tempv++;
1104 * Call to closem() used to be part of initdesc(). Now called below where
1105 * the script name argument has become stdin. Kernel may have used a file
1106 * descriptor to hold the name of the script (setuid case) and this name
1107 * mustn't be lost by closing the fd too soon.
1112 * Consider input a tty if it really is or we are interactive. but not for
1113 * editing (christos)
1115 if (!(intty = isatty(SHIN))) {
1122 if (intty || (intact && isatty(SHOUT))) {
1123 if (!batch && (uid != euid || gid != egid)) {
1125 child = 1; /* So this ... */
1126 /* ... doesn't return */
1127 stderror(ERR_SYSTEM, progname, strerror(errno));
1131 isoutatty = isatty(SHOUT);
1132 isdiagatty = isatty(SHDIAG);
1134 * Decide whether we should play with signals or not. If we are explicitly
1135 * told (via -i, or -) or we are a login shell (arg0 starts with -) or the
1136 * input and output are both the ttys("csh", or "csh</dev/ttyx>/dev/ttyx")
1137 * Note that in only the login shell is it likely that parent may have set
1138 * signals to be ignored
1140 if (loginsh || intact || (intty && isatty(SHOUT)))
1144 * Save the remaining arguments in argv.
1146 setq(STRargv, blk2short(tempv), &shvhed, VAR_READWRITE);
1149 * Set up the prompt.
1152 setcopy(STRprompt, STRdefprompt, VAR_READWRITE);
1153 /* that's a meta-questionmark */
1154 setcopy(STRprompt2, STRmquestion, VAR_READWRITE);
1155 setcopy(STRprompt3, STRKCORRECT, VAR_READWRITE);
1159 * If we are an interactive shell, then start fiddling with the signals;
1160 * this is a tricky game.
1162 shpgrp = mygetpgrp();
1165 struct sigaction osig;
1168 if (!quitit) /* Wary! */
1169 (void) signal(SIGQUIT, SIG_IGN);
1171 sigset_interrupting(SIGINT, queue_pintr);
1172 (void) signal(SIGTERM, SIG_IGN);
1175 * No reason I can see not to save history on all these events..
1176 * Most usual occurrence is in a window system, where we're not a login
1177 * shell, but might as well be... (sg)
1178 * But there might be races when lots of shells exit together...
1179 * [this is also incompatible].
1180 * We have to be mre careful here. If the parent wants to
1181 * ignore the signals then we leave them untouched...
1182 * We also only setup the handlers for shells that are trully
1185 sigaction(SIGHUP, NULL, &osig);
1186 if (loginsh || osig.sa_handler != SIG_IGN)
1187 /* exit processing on HUP */
1188 sigset_interrupting(SIGHUP, queue_phup);
1190 sigaction(SIGXCPU, NULL, &osig);
1191 if (loginsh || osig.sa_handler != SIG_IGN)
1192 /* exit processing on XCPU */
1193 sigset_interrupting(SIGXCPU, queue_phup);
1196 sigaction(SIGXFSZ, NULL, &osig);
1197 if (loginsh || osig.sa_handler != SIG_IGN)
1198 /* exit processing on XFSZ */
1199 sigset_interrupting(SIGXFSZ, queue_phup);
1202 if (quitit == 0 && arginp == 0) {
1204 (void) signal(SIGTSTP, SIG_IGN);
1207 (void) signal(SIGTTIN, SIG_IGN);
1210 (void) signal(SIGTTOU, SIG_IGN);
1213 * Wait till in foreground, in case someone stupidly runs csh &
1214 * dont want to try to grab away the tty.
1216 if (isatty(FSHDIAG))
1218 else if (isatty(FSHOUT))
1220 else if (isatty(OLDSTD))
1226 /* NeXT 2.0 /usr/etc/rlogind, does not set our process group! */
1227 if (f != -1 && shpgrp == 0) {
1229 (void) setpgid(0, shpgrp);
1230 (void) tcsetpgrp(f, shpgrp);
1233 #ifdef BSDJOBS /* if we have tty job control */
1234 if (f != -1 && grabpgrp(f, shpgrp) != -1) {
1236 * Thanks to Matt Day for the POSIX references, and to
1237 * Paul Close for the SGI clarification.
1239 if (setdisc(f) != -1) {
1243 if (tcsetpgrp(f, shpgrp) == -1) {
1245 * On hpux 7.03 this fails with EPERM. This happens on
1246 * the 800 when opgrp != shpgrp at this point. (we were
1247 * forked from a non job control shell)
1248 * POSIX 7.2.4, says we failed because the process
1249 * group specified did not belong to a process
1250 * in the same session with the tty. So we set our
1251 * process group and try again.
1253 if (setpgid(0, shpgrp) == -1) {
1254 xprintf("setpgid:");
1257 if (tcsetpgrp(f, shpgrp) == -1) {
1258 xprintf("tcsetpgrp:");
1263 * We check the process group now. If it is the same, then
1264 * we don't need to set it again. On hpux 7.0 on the 300's
1265 * if we set it again it fails with EPERM. This is the
1266 * correct behavior according to POSIX 4.3.3 if the process
1267 * was a session leader .
1269 else if (shpgrp != mygetpgrp()) {
1270 if(setpgid(0, shpgrp) == -1) {
1271 xprintf("setpgid:");
1277 * But on irix 3.3 we need to set it again, even if it is
1278 * the same. We do that to tell the system that we
1279 * need BSD process group compatibility.
1282 (void) setpgid(0, shpgrp);
1284 (void) close_on_exec(dcopy(f, FSHTTY), 1);
1291 xprintf(CGETS(11, 1, "Warning: no access to tty (%s).\n"),
1294 CGETS(11, 2, "Thus no job control in this shell.\n"));
1296 * Fix from:Sakari Jalovaara <sja@sirius.hut.fi> if we don't
1297 * have access to tty, disable editing too
1303 #else /* BSDJOBS */ /* don't have job control, so frotz it */
1305 #endif /* BSDJOBS */
1308 if (setintr == 0 && parintr.sa_handler == SIG_DFL)
1312 * SVR4 doesn't send a SIGCHLD when a child is stopped or continued if the
1313 * handler is installed with signal(2) or sigset(2). sigaction(2) must
1316 * David Dawes (dawes@physics.su.oz.au) Sept 1991
1318 sigset_interrupting(SIGCHLD, queue_pchild);
1320 if (intty && !arginp)
1321 (void) ed_Setup(editing);/* Get the tty state, and set defaults */
1322 /* Only alter the tty state if editing */
1325 * Set an exit here in case of an interrupt or error reading the shell
1330 (void)cleanup_push_mark(); /* There is no outer handler */
1331 if (setexit() != 0) /* PWP */
1336 haderr = 0; /* In case second time through */
1337 if (!fast && reenter == 0) {
1338 /* Will have varval(STRhome) here because set fast if don't */
1341 cleanup_push(&pintr_disabled, disabled_cleanup);
1342 setintr = 0;/*FIXRESET:cleanup*/
1343 /* onintr in /etc/ files has no effect */
1344 parintr.sa_handler = SIG_IGN;/*FIXRESET: cleanup*/
1346 #ifdef _PATH_DOTLOGIN
1348 (void) srcfile(_PATH_DOTLOGIN, 0, 0, NULL);
1352 #ifdef _PATH_DOTCSHRC
1353 (void) srcfile(_PATH_DOTCSHRC, 0, 0, NULL);
1355 if (!arginp && !onelflg && !havhash)
1358 #ifdef _PATH_DOTLOGIN
1360 (void) srcfile(_PATH_DOTLOGIN, 0, 0, NULL);
1363 cleanup_until(&pintr_disabled);
1369 (void) srccat(varval(STRhome), STRsldotlogin);
1371 /* upward compat. */
1372 if (!srccat(varval(STRhome), STRsldottcshrc))
1373 (void) srccat(varval(STRhome), STRsldotcshrc);
1375 if (!arginp && !onelflg && !havhash)
1379 * Source history before .login so that it is available in .login
1384 (void) srccat(varval(STRhome), STRsldotlogin);
1386 if (loginsh || rdirs)
1389 /* Reset interrupt flag */
1394 /* Initing AFTER .cshrc is the Right Way */
1395 if (intty && !arginp) { /* PWP setup stuff */
1396 ed_Init(); /* init the new line editor */
1398 check_window_size(1); /* mung environment */
1399 #endif /* SIG_WINDOW */
1403 * Now are ready for the -v and -x flags
1411 * All the rest of the world is inside this call. The argument to process
1412 * indicates whether it should catch "error unwinds". Thus if we are a
1413 * interactive shell our call here will never return by being blown past on
1421 /* Take care of these (especially HUP) here instead of inside flush. */
1422 handle_pending_signals();
1425 xprintf("logout\n");
1431 goodbye(NULL, NULL);
1446 if (tpgrp > 0 && opgrp != shpgrp) {
1447 (void) setpgid(0, opgrp);
1448 (void) tcsetpgrp(FSHTTY, opgrp);
1449 (void) resetdisc(FSHTTY);
1451 #endif /* BSDJOBS */
1455 importpath(Char *cp)
1462 for (dp = cp; *dp; dp++)
1466 * i+2 where i is the number of colons in the path. There are i+1
1467 * directories in the path plus we need room for a zero terminator.
1469 pv = xcalloc(i + 2, sizeof(Char *));
1474 if ((c = *dp) == PATHSEP || c == 0) {
1476 pv[i++] = Strsave(*cp ? cp : STRdot);
1485 else if (*dp == '\\')
1487 #endif /* WINNT_NATIVE */
1491 cleanup_push(pv, blk_cleanup);
1492 setq(STRpath, pv, &shvhed, VAR_READWRITE);
1498 * Source to the file which is the catenation of the argument names.
1501 srccat(Char *cp, Char *dp)
1503 if (cp[0] == '/' && cp[1] == '\0')
1504 return srcfile(short2str(dp), (mflag ? 0 : 1), 0, NULL);
1512 if (ep != cp && ep[-1] == '/' && dp[0] == '/') /* silly win95 */
1514 #endif /* WINNT_NATIVE */
1516 ep = Strspl(cp, dp);
1517 cleanup_push(ep, xfree);
1518 ptr = short2str(ep);
1520 rv = srcfile(ptr, (mflag ? 0 : 1), 0, NULL);
1527 * Source to a file putting the file descriptor in a safe place (> 2).
1529 #ifndef WINNT_NATIVE
1533 #endif /*WINNT_NATIVE*/
1534 srcfile(const char *f, int onlyown, int flag, Char **av)
1538 if ((unit = xopen(f, O_RDONLY|O_LARGEFILE)) == -1)
1540 cleanup_push(&unit, open_cleanup);
1541 unit = dmove(unit, -1);
1542 cleanup_ignore(&unit);
1543 cleanup_until(&unit);
1545 (void) close_on_exec(unit, 1);
1546 srcunit(unit, onlyown, flag, av);
1552 * Save the shell state, and establish new argument vector, and new input
1556 st_save(struct saved_state *st, int unit, int hflg, Char **al, Char **av)
1558 st->insource = insource;
1560 /* Want to preserve the meaning of "source file >output".
1561 * Save old descriptors, move new 0,1,2 to safe places and assign
1562 * them to SH* and let process() redo 0,1,2 from them.
1564 * The macro returns true if d1 and d2 are good and they point to
1565 * different things. If you don't avoid saving duplicate
1566 * descriptors, you really limit the depth of "source" recursion
1567 * you can do because of all the open file descriptors. -IAN!
1569 #define NEED_SAVE_FD(d1,d2) \
1570 (fstat(d1, &s1) != -1 && fstat(d2, &s2) != -1 \
1571 && (s1.st_ino != s2.st_ino || s1.st_dev != s2.st_dev) )
1573 st->OLDSTD = st->SHOUT = st->SHDIAG = -1;/* test later to restore these */
1576 if (NEED_SAVE_FD(0,OLDSTD)) {
1577 st->OLDSTD = OLDSTD;
1578 OLDSTD = dmove(0, -1);
1579 (void)close_on_exec(OLDSTD, 1);
1581 if (NEED_SAVE_FD(1,SHOUT)) {
1583 SHOUT = dmove(1, -1);
1584 (void)close_on_exec(SHOUT, 1);
1586 if (NEED_SAVE_FD(2,SHDIAG)) {
1587 st->SHDIAG = SHDIAG;
1588 SHDIAG = dmove(2, -1);
1589 (void)close_on_exec(SHDIAG, 1);
1595 st->whyles = whyles;
1596 st->gointr = gointr;
1597 st->arginp = arginp;
1599 st->evalvec = evalvec;
1600 st->alvecp = alvecp;
1602 st->onelflg = onelflg;
1603 st->enterhist = enterhist;
1604 st->justpr = justpr;
1609 st->cantell = cantell;
1613 * we can now pass arguments to source.
1614 * For compatibility we do that only if arguments were really
1615 * passed, otherwise we keep the old, global $argv like before.
1617 if (av != NULL && *av != NULL) {
1619 if ((vp = adrof(STRargv)) != NULL && vp->vec != NULL)
1620 st->argv = saveblk(vp->vec);
1623 setq(STRargv, saveblk(av), &shvhed, VAR_READWRITE);
1629 SHIN = unit; /* Do this first */
1631 /* Establish new input arena */
1634 fseekp = feobp = fblocks = 0;
1640 intty = isatty(SHIN);
1655 * Restore the shell to a saved state
1658 st_restore(void *xst)
1660 struct saved_state *st;
1666 /* Reset input arena */
1669 Char** nfbuf = fbuf;
1670 int nfblocks = fblocks;
1674 for (i = 0; i < nfblocks; i++)
1682 insource = st->insource;
1684 if (st->OLDSTD != -1)
1685 xclose(OLDSTD), OLDSTD = st->OLDSTD;
1686 if (st->SHOUT != -1)
1687 xclose(SHOUT), SHOUT = st->SHOUT;
1688 if (st->SHDIAG != -1)
1689 xclose(SHDIAG), SHDIAG = st->SHDIAG;
1690 arginp = st->arginp;
1691 onelflg = st->onelflg;
1693 evalvec = st->evalvec;
1694 alvecp = st->alvecp;
1697 whyles = st->whyles;
1698 gointr = st->gointr;
1699 if (st->HIST != '\0')
1701 enterhist = st->enterhist;
1702 cantell = st->cantell;
1703 justpr = st->justpr;
1705 if (st->argv != NULL)
1706 setq(STRargv, st->argv, &shvhed, VAR_READWRITE);
1707 else if (st->av != NULL && *st->av != NULL && adrof(STRargv) != NULL)
1712 * Source to a unit. If onlyown it must be our file or our group or
1713 * we don't chance it. This occurs on ".cshrc"s and the like.
1716 srcunit(int unit, int onlyown, int hflg, Char **av)
1718 struct saved_state st;
1720 st.SHIN = -1; /* st_restore checks this */
1728 if (fstat(unit, &stb) < 0) {
1734 /* Does nothing before st_save() because st.SHIN == -1 */
1735 cleanup_push(&st, st_restore);
1738 cleanup_push(&pintr_disabled, disabled_cleanup);
1741 /* Save the current state and move us to a new state */
1742 st_save(&st, unit, hflg, NULL, av);
1745 * Now if we are allowing commands to be interrupted, we let ourselves be
1749 cleanup_until(&pintr_disabled);
1751 cleanup_push(&pintr_disabled, disabled_cleanup);
1754 process(0); /* 0 -> blow away on errors */
1756 /* Restore the old state */
1763 goodbye(Char **v, struct command *c)
1774 signal(SIGQUIT, SIG_IGN);
1775 sigaddset(&set, SIGQUIT);
1776 sigprocmask(SIG_UNBLOCK, &set, NULL);
1777 signal(SIGINT, SIG_IGN);
1778 sigaddset(&set, SIGINT);
1779 signal(SIGTERM, SIG_IGN);
1780 sigaddset(&set, SIGTERM);
1781 signal(SIGHUP, SIG_IGN);
1782 sigaddset(&set, SIGHUP);
1783 sigprocmask(SIG_UNBLOCK, &set, NULL);
1785 setintr = 0; /* No interrupts after "logout" */
1786 /* Trap errors inside .logout */
1787 omark = cleanup_push_mark();
1788 if (setexit() == 0) {
1789 if (!(adrof(STRlogout)))
1790 setcopy(STRlogout, STRnormal, VAR_READWRITE);
1791 #ifdef _PATH_DOTLOGOUT
1792 (void) srcfile(_PATH_DOTLOGOUT, 0, 0, NULL);
1795 (void) srccat(varval(STRhome), STRsldtlogout);
1800 cleanup_pop_mark(omark);
1812 * Note that if STATUS is corrupted (i.e. getn bombs) then error will exit
1813 * directly because we poke child here. Otherwise we might continue
1814 * unwarrantedly (sic).
1818 xexit(getn(varval(STRstatus)));
1822 * in the event of a HUP we want to save the history
1828 setcopy(STRlogout, STRhangup, VAR_READWRITE);
1829 #ifdef _PATH_DOTLOGOUT
1830 (void) srcfile(_PATH_DOTLOGOUT, 0, 0, NULL);
1833 (void) srccat(varval(STRhome), STRsldtlogout);
1840 * We kill the last foreground process group. It then becomes
1841 * responsible to propagate the SIGHUP to its progeny.
1844 struct process *pp, *np;
1846 for (pp = proclist.p_next; pp; pp = pp->p_next) {
1849 * Find if this job is in the foreground. It could be that
1850 * the process leader has exited and the foreground flag
1851 * is cleared for it.
1855 * If a process is in the foreground we try to kill
1856 * it's process group. If we succeed, then the
1857 * whole job is gone. Otherwise we keep going...
1858 * But avoid sending HUP to the shell again.
1860 if (((np->p_flags & PFOREGND) != 0) && np->p_jobid != shpgrp) {
1861 np->p_flags &= ~PHUP;
1862 if (killpg(np->p_jobid, SIGHUP) != -1) {
1863 /* In case the job was suspended... */
1865 (void) killpg(np->p_jobid, SIGCONT);
1870 while ((np = np->p_friends) != pp);
1873 #endif /* POSIXJOBS */
1878 static Char *jobargv[2] = {STRjobs, 0};
1881 * Catch an interrupt, e.g. during lexical input.
1882 * If we are an interactive shell, we reset the interrupt catch
1883 * immediately. In any case we drain the shell output,
1884 * and finally go through the normal error mechanism, which
1885 * gets a chance to make the shell go away.
1887 int just_signaled; /* bugfix by Michael Bloom (mg@ttidca.TTI.COM) */
1903 dojobs(jobargv, NULL);
1904 stderror(ERR_NAME | ERR_INTR);
1907 /* MH - handle interrupted completions specially */
1909 if (InsideCompletion)
1910 stderror(ERR_SILENT);
1912 /* JV - Make sure we shut off inputl */
1914 (void) Cookedmode();
1920 #ifdef HAVE_GETPWENT
1925 * If we have an active "onintr" then we search for the label. Note that if
1926 * one does "onintr -" then we shan't be interruptible so we needn't worry
1933 else if (intty && wantnl) {
1936 * If we are editing a multi-line input command, and move to
1937 * the beginning of the line, we don't want to trash it when
1945 /* xputchar('\n'); *//* Some like this, others don't */
1946 (void) putraw('\r');
1947 (void) putraw('\n');
1950 stderror(ERR_SILENT);
1954 * Process is the main driving routine for the shell.
1955 * It runs all command processing, except for those within { ... }
1956 * in expressions (which is run by a routine evalav in sh.exp.c which
1957 * is a stripped down process), and `...` evaluation which is run
1958 * also by a subset of this code in sh.glob.c in the routine backeval.
1960 * The code here is a little strange because part of it is interruptible
1961 * and hence freeing of structures appears to occur when none is necessary
1962 * if this is ignored.
1964 * Note that if catch is not set then we will unwind on any error.
1965 * If an end-of-file occurs, we return.
1971 /* PWP: This might get nuked by longjmp so don't make it a register var */
1973 volatile int didexitset = 0;
1976 omark = cleanup_push_mark();
1979 int hadhist, old_pintr_disabled;
1982 if (didexitset == 0) {
1988 justpr = enterhist; /* execute if not entering history */
1994 cleanup_pop_mark(omark);
2000 * Every error is eventually caught here or the shell dies. It is
2001 * at this point that we clean up any left-over open files, by
2002 * closing all but a fixed number of pre-defined files. Thus
2003 * routines don't have to worry about leaving files open due to
2004 * deeper errors... they will get closed here.
2017 if (intty && prompt && evalvec == 0) {
2021 * Watch for logins/logouts. Next is scheduled commands stored
2022 * previously using "sched." Then execute periodic commands.
2023 * Following that, the prompt precmd is run.
2027 #endif /* !HAVENOUTMP */
2032 * If we are at the end of the input buffer then we are going to
2033 * read fresh stuff. Otherwise, we are rereading input and don't
2034 * need or want to prompt.
2036 if (fseekp == feobp && aret == TCSH_F_SEEK)
2037 printprompt(0, NULL);
2047 * Interruptible during interactive reads
2050 pintr_push_enable(&old_pintr_disabled);
2051 hadhist = lex(¶ml);
2053 cleanup_until(&old_pintr_disabled);
2054 cleanup_push(¶ml, lex_cleanup);
2057 * Echo not only on VERBOSE, but also with history expansion. If there
2058 * is a lexical error then we forego history echo.
2059 * Do not echo if we're only entering history (source -h).
2061 if ((hadhist && !seterr && intty && !tellwhat && !Expand && !whyles) ||
2062 (!enterhist && adrof(STRverbose)))
2064 int odidfds = didfds;
2072 (void) alarm(0); /* Autologout OFF */
2073 alrmcatch_disabled = 1;
2076 * Save input text on the history list if reading in old history, or it
2077 * is from the terminal at the top level and not in a loop.
2079 * PWP: entry of items in the history list while in a while loop is done
2082 if (enterhist || (catch && intty && !whyles && !tellwhat && !arun))
2083 savehist(¶ml, enterhist > 1);
2085 if (Expand && seterr)
2089 * Print lexical error messages, except when sourcing history lists.
2091 if (!enterhist && seterr)
2095 * If had a history command :p modifier then this is as far as we
2102 * If had a tellwhat from twenex() then do
2105 (void) tellmewhat(¶ml, NULL);
2113 * If we are interactive, try to continue jobs that we have stopped
2116 continue_jobs(¶ml);
2117 #endif /* BSDJOBS */
2120 * Check to see if the user typed "rm * .o" or something
2125 * Parse the words of the input into a parse tree.
2127 t = syntax(paraml.next, ¶ml, 0);
2129 * We cannot cleanup push here, because cd /blah; echo foo
2130 * would rewind t on the chdir error, and free the rest of the command
2139 * Execute the parse tree From: Michael Schroeder
2140 * <mlschroe@immd4.informatik.uni-erlangen.de> was execute(t, tpgrp);
2142 execute(t, (tpgrp > 0 ? tpgrp : -1), NULL, NULL, TRUE);
2149 if (windowchg || (catch && intty && !whyles && !tellwhat)) {
2150 (void) check_window_size(0); /* for window systems */
2152 #endif /* SIG_WINDOW */
2153 setcopy(STR_, InputBuf, VAR_READWRITE | VAR_NOGLOB);
2155 if (cleanup_reset())
2156 cleanup_until(¶ml);
2160 cleanup_pop_mark(omark);
2163 handle_pending_signals();
2168 dosource(Char **t, struct command *c)
2176 if (*t && eq(*t, STRmh)) {
2178 stderror(ERR_NAME | ERR_HFLAG);
2181 else if (*t && eq(*t, STRmm)) {
2183 stderror(ERR_NAME | ERR_MFLAG);
2187 f = globone(*t++, G_ERROR);
2188 file = strsave(short2str(f));
2189 cleanup_push(file, xfree);
2191 t = glob_all_or_error(t);
2192 cleanup_push(t, blk_cleanup);
2193 if ((!srcfile(file, 0, hflg, t)) && (!hflg) && (!bequiet))
2194 stderror(ERR_SYSTEM, file, strerror(errno));
2195 cleanup_until(file);
2200 * If we are a login shell, then we don't want to tell
2201 * about any mail file unless its been modified
2202 * after the time we started.
2203 * This prevents us from telling the user things he already
2204 * knows, since the login program insists on saying
2210 * This version checks if the file is a directory, and if so,
2211 * tells you the number of files in it, otherwise do the old thang.
2212 * The magic "+1" in the time calculation is to compensate for
2213 * an AFS bug where directory mtimes are set to 1 second in
2228 if (v == NULL || v->vec == NULL)
2233 intvl = (cnt && number(*vp)) ? (--cnt, getn(*vp++)) : MAILINTVL;
2236 if (chktim + intvl > t)
2239 char *filename = short2str(*vp);
2240 char *mboxdir = filename;
2242 if (stat(filename, &stb) < 0)
2244 #if defined(BSDTIMES) || defined(_SEQUENT_)
2245 new = stb.st_mtime > time0.tv_sec;
2247 new = stb.st_mtime > seconds0;
2249 if (S_ISDIR(stb.st_mode)) {
2255 tempfilename = xasprintf("%s/new", filename);
2257 if (stat(tempfilename, &stc) != -1 && S_ISDIR(stc.st_mode)) {
2259 * "filename/new" exists and is a directory; you are
2263 #if defined(BSDTIMES) || defined(_SEQUENT_)
2264 new = stb.st_mtime > time0.tv_sec;
2266 new = stb.st_mtime > seconds0;
2268 mboxdir = tempfilename;
2271 if (stb.st_mtime <= chktim + 1 || (loginsh && !new)) {
2272 xfree(tempfilename);
2276 mailbox = opendir(mboxdir);
2277 xfree(tempfilename);
2278 if (mailbox == NULL)
2282 if (!readdir(mailbox) || !readdir(mailbox)) {
2283 (void)closedir(mailbox);
2287 while (readdir(mailbox))
2290 (void)closedir(mailbox);
2295 xprintf(CGETS(11, 3, "You have %d mail messages.\n"),
2298 xprintf(CGETS(11, 4, "You have %d mail messages in %s.\n"),
2299 mailcount, filename);
2304 if (stb.st_size == 0 || stb.st_atime >= stb.st_mtime ||
2305 (stb.st_atime <= chktim && stb.st_mtime <= chktim) ||
2308 type = strsave(new ? CGETS(11, 6, "new ") : "");
2309 cleanup_push(type, xfree);
2311 xprintf(CGETS(11, 5, "You have %smail.\n"), type);
2313 xprintf(CGETS(11, 7, "You have %smail in %s.\n"), type, filename);
2314 cleanup_until(type);
2321 * Extract a home directory from the password file
2322 * The argument points to a buffer where the name of the
2323 * user whose home directory is sought is currently.
2324 * We return home directory of the user, or NULL.
2327 gethdir(const Char *home)
2334 if (*home == '\0') {
2335 if ((h = varval(STRhome)) != STRNULL)
2344 if ((h = gettilde(home)) == NULL)
2351 * Move the initial descriptors to their eventual
2352 * resting places, closing all other units.
2360 #endif /* NLS_CATALOGS */
2361 #endif /* NLS_BUGS */
2364 didfds = 0; /* 0, 1, 2 aren't set up */
2365 (void) close_on_exec(SHIN = dcopy(0, FSHIN), 1);
2366 (void) close_on_exec(SHOUT = dcopy(1, FSHOUT), 1);
2367 (void) close_on_exec(SHDIAG = dcopy(2, FSHDIAG), 1);
2368 (void) close_on_exec(OLDSTD = dcopy(SHIN, FOLDSTD), 1);
2369 #ifndef CLOSE_ON_EXEC
2370 didcch = 0; /* Havent closed for child */
2371 #endif /* CLOSE_ON_EXEC */
2373 isdiagatty = isatty(SHDIAG);
2377 isoutatty = isatty(SHOUT);
2383 #endif /* NLS_CATALOGS */
2384 #endif /* NLS_BUGS */
2396 if (loginsh && do_logout) {
2397 /* this is to send hangup signal to the develcon */
2398 /* we toggle DTR. clear dtr - sleep 1 - set dtr */
2399 /* ioctl will return ENOTTY for pty's but we ignore it */
2400 /* exitstat will run after disconnect */
2401 /* we sleep for 2 seconds to let things happen in */
2402 /* .logout and rechist() */
2405 (void) ioctl(FSHTTY, TIOCCDTR, NULL);
2407 (void) ioctl(FSHTTY, TIOCSDTR, NULL);
2408 #endif /* TIOCCDTR */
2413 struct process *pp, *np;
2414 pid_t mypid = getpid();
2415 /* Kill all processes marked for hup'ing */
2416 for (pp = proclist.p_next; pp; pp = pp->p_next) {
2419 if ((np->p_flags & PHUP) && np->p_jobid != shpgrp &&
2420 np->p_parentid == mypid) {
2421 if (killpg(np->p_jobid, SIGHUP) != -1) {
2422 /* In case the job was suspended... */
2424 (void) killpg(np->p_jobid, SIGCONT);
2429 while ((np = np->p_friends) != pp);
2435 * We need to call catclose, because SVR4 leaves symlinks behind otherwise
2436 * in the catalog directories. We cannot close on a vforked() child,
2437 * because messages will stop working on the parent too.
2441 #endif /* NLS_CATALOGS */
2444 #endif /* WINNT_NATIVE */
2448 #ifndef _PATH_DEFPATH
2456 blkp = blk = xmalloc(sizeof(Char *) * 10);
2460 *blkp++ = Strsave(STRdot);
2464 #define DIRAPPEND(a) \
2465 if (stat(ptr = a, &stb) == 0 && S_ISDIR(stb.st_mode)) \
2469 DIRAPPEND(_PATH_LOCAL);
2473 DIRAPPEND(_PATH_USRUCB);
2477 DIRAPPEND(_PATH_USRBSD);
2481 DIRAPPEND(_PATH_BIN);
2485 DIRAPPEND(_PATH_USRBIN);
2492 *blkp++ = Strsave(STRdot);
2504 recdirs(NULL, adrof(STRsavedirs) != NULL);
2505 rechist(NULL, adrof(STRsavehist) != NULL);
2507 displayHistStats("Exiting"); /* no-op unless DEBUG_HIST */
2511 * Grab the tty repeatedly, and give up if we are not in the correct
2512 * tty process group.
2515 grabpgrp(int fd, pid_t desired)
2517 struct sigaction old;
2521 for (i = 0; i < 100; i++) {
2522 if ((pgrp = tcgetpgrp(fd)) == -1)
2524 if (pgrp == desired)
2526 (void)sigaction(SIGTTIN, NULL, &old);
2527 (void)signal(SIGTTIN, SIG_DFL);
2528 (void)kill(0, SIGTTIN);
2529 (void)sigaction(SIGTTIN, &old, NULL);