Home | History | Annotate | Line # | Download | only in csh
csh.c revision 1.5
      1 /*-
      2  * Copyright (c) 1980, 1991 The Regents of the University of California.
      3  * All rights reserved.
      4  *
      5  * Redistribution and use in source and binary forms, with or without
      6  * modification, are permitted provided that the following conditions
      7  * are met:
      8  * 1. Redistributions of source code must retain the above copyright
      9  *    notice, this list of conditions and the following disclaimer.
     10  * 2. Redistributions in binary form must reproduce the above copyright
     11  *    notice, this list of conditions and the following disclaimer in the
     12  *    documentation and/or other materials provided with the distribution.
     13  * 3. All advertising materials mentioning features or use of this software
     14  *    must display the following acknowledgement:
     15  *	This product includes software developed by the University of
     16  *	California, Berkeley and its contributors.
     17  * 4. 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.
     20  *
     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
     31  * SUCH DAMAGE.
     32  */
     33 
     34 #ifndef lint
     35 char copyright[] =
     36 "@(#) Copyright (c) 1991 The Regents of the University of California.\n\
     37  All rights reserved.\n";
     38 #endif /* not lint */
     39 
     40 #ifndef lint
     41 /*static char sccsid[] = "from: @(#)csh.c	5.26 (Berkeley) 6/8/91";*/
     42 static char rcsid[] = "$Id: csh.c,v 1.5 1993/11/12 15:58:14 cgd Exp $";
     43 #endif /* not lint */
     44 
     45 #include <sys/types.h>
     46 #include <sys/ioctl.h>
     47 #include <sys/stat.h>
     48 #include <fcntl.h>
     49 #include <errno.h>
     50 #include <pwd.h>
     51 #include <stdlib.h>
     52 #include <string.h>
     53 #include <locale.h>
     54 #include <unistd.h>
     55 #if __STDC__
     56 # include <stdarg.h>
     57 #else
     58 # include <varargs.h>
     59 #endif
     60 
     61 #include "csh.h"
     62 #include "extern.h"
     63 #include "pathnames.h"
     64 #include "proc.h"
     65 
     66 extern bool MapsAreInited;
     67 extern bool NLSMapsAreInited;
     68 
     69 /*
     70  * C Shell
     71  *
     72  * Bill Joy, UC Berkeley, California, USA
     73  * October 1978, May 1980
     74  *
     75  * Jim Kulp, IIASA, Laxenburg, Austria
     76  * April 1980
     77  *
     78  * Christos Zoulas, Cornell University
     79  * June, 1991
     80  */
     81 
     82 Char   *dumphist[] = {STRhistory, STRmh, 0, 0};
     83 Char   *loadhist[] = {STRsource, STRmh, STRhistfile, 0};
     84 
     85 int     nofile = 0;
     86 bool    reenter = 0;
     87 bool    nverbose = 0;
     88 bool    nexececho = 0;
     89 bool    quitit = 0;
     90 bool    fast = 0;
     91 bool    batch = 0;
     92 bool    mflag = 0;
     93 bool    prompt = 1;
     94 bool    enterhist = 0;
     95 bool    tellwhat = 0;
     96 
     97 extern char **environ;
     98 
     99 static int	srccat __P((Char *, Char *));
    100 static int	srcfile __P((char *, bool, bool));
    101 static void	phup __P((int));
    102 static void	srcunit __P((int, bool, bool));
    103 static void	mailchk __P((void));
    104 static Char   **defaultpath __P((void));
    105 
    106 int
    107 main(argc, argv)
    108     int     argc;
    109     char  **argv;
    110 {
    111     register Char *cp;
    112     register char *tcp;
    113     register int f;
    114     register char **tempv;
    115     struct sigvec osv;
    116 
    117 
    118     settimes();			/* Immed. estab. timing base */
    119 
    120     /*
    121      * Initialize non constant strings
    122      */
    123 #ifdef _PATH_BSHELL
    124     STR_BSHELL = SAVE(_PATH_BSHELL);
    125 #endif
    126 #ifdef _PATH_CSHELL
    127     STR_SHELLPATH = SAVE(_PATH_CSHELL);
    128 #endif
    129     STR_environ = blk2short(environ);
    130     environ = short2blk(STR_environ);	/* So that we can free it */
    131     STR_WORD_CHARS = SAVE(WORD_CHARS);
    132 
    133     HIST = '!';
    134     HISTSUB = '^';
    135     word_chars = STR_WORD_CHARS;
    136 
    137     tempv = argv;
    138     if (eq(str2short(tempv[0]), STRaout))	/* A.out's are quittable */
    139 	quitit = 1;
    140     uid = getuid();
    141     gid = getgid();
    142     /*
    143      * We are a login shell if: 1. we were invoked as -<something> and we had
    144      * no arguments 2. or we were invoked only with the -l flag
    145      */
    146     loginsh = (**tempv == '-' && argc == 1) ||
    147 	(argc == 2 && tempv[1][0] == '-' && tempv[1][1] == 'l' &&
    148 	 tempv[1][2] == '\0');
    149 
    150     if (loginsh && **tempv != '-') {
    151 	/*
    152 	 * Mangle the argv space
    153 	 */
    154 	tempv[1][0] = '\0';
    155 	tempv[1][1] = '\0';
    156 	tempv[1] = NULL;
    157 	for (tcp = *tempv; *tcp++;);
    158 	for (tcp--; tcp >= *tempv; tcp--)
    159 	    tcp[1] = tcp[0];
    160 	*++tcp = '-';
    161 	argc--;
    162     }
    163     if (loginsh)
    164 	(void) time(&chktim);
    165 
    166     AsciiOnly = 1;
    167 #ifdef NLS
    168     (void) setlocale(LC_ALL, "");
    169     {
    170 	int     k;
    171 
    172 	for (k = 0200; k <= 0377 && !Isprint(k); k++);
    173 	AsciiOnly = k > 0377;
    174     }
    175 #else
    176     AsciiOnly = getenv("LANG") == NULL && getenv("LC_CTYPE") == NULL;
    177 #endif				/* NLS */
    178 
    179     /*
    180      * Move the descriptors to safe places. The variable didfds is 0 while we
    181      * have only FSH* to work with. When didfds is true, we have 0,1,2 and
    182      * prefer to use these.
    183      */
    184     initdesc();
    185 
    186     /*
    187      * Initialize the shell variables. ARGV and PROMPT are initialized later.
    188      * STATUS is also munged in several places. CHILD is munged when
    189      * forking/waiting
    190      */
    191     set(STRstatus, Strsave(STR0));
    192 
    193     if ((tcp = getenv("HOME")) != NULL)
    194 	cp = SAVE(tcp);
    195     else
    196 	cp = NULL;
    197 
    198     if (cp == NULL)
    199 	fast = 1;		/* No home -> can't read scripts */
    200     else
    201 	set(STRhome, cp);
    202     dinit(cp);			/* dinit thinks that HOME == cwd in a login
    203 				 * shell */
    204     /*
    205      * Grab other useful things from the environment. Should we grab
    206      * everything??
    207      */
    208     if ((tcp = getenv("LOGNAME")) != NULL ||
    209 	(tcp = getenv("USER")) != NULL)
    210 	set(STRuser, SAVE(tcp));
    211     if ((tcp = getenv("TERM")) != NULL)
    212 	set(STRterm, SAVE(tcp));
    213 
    214     /*
    215      * Re-initialize path if set in environment
    216      */
    217     if ((tcp = getenv("PATH")) == NULL)
    218 	set1(STRpath, defaultpath(), &shvhed);
    219     else
    220 	importpath(SAVE(tcp));
    221 
    222     set(STRshell, Strsave(STR_SHELLPATH));
    223 
    224     doldol = putn((int) getpid());	/* For $$ */
    225     shtemp = Strspl(STRtmpsh, doldol);	/* For << */
    226 
    227     /*
    228      * Record the interrupt states from the parent process. If the parent is
    229      * non-interruptible our hand must be forced or we (and our children) won't
    230      * be either. Our children inherit termination from our parent. We catch it
    231      * only if we are the login shell.
    232      */
    233     /* parents interruptibility */
    234     (void) sigvec(SIGINT, NULL, &osv);
    235     parintr = (void (*) ()) osv.sv_handler;
    236     (void) sigvec(SIGTERM, NULL, &osv);
    237     parterm = (void (*) ()) osv.sv_handler;
    238 
    239     /* catch these all, login shell or not */
    240     (void) signal(SIGHUP, phup);	/* exit processing on HUP */
    241     (void) signal(SIGXCPU, phup);	/* ...and on XCPU */
    242     (void) signal(SIGXFSZ, phup);	/* ...and on XFSZ */
    243 
    244     /*
    245      * Process the arguments.
    246      *
    247      * Note that processing of -v/-x is actually delayed till after script
    248      * processing.
    249      *
    250      * We set the first character of our name to be '-' if we are a shell running
    251      * interruptible commands.  Many programs which examine ps'es use this to
    252      * filter such shells out.
    253      */
    254     argc--, tempv++;
    255     while (argc > 0 && (tcp = tempv[0])[0] == '-' && *++tcp != '\0' && !batch) {
    256 	do
    257 	    switch (*tcp++) {
    258 
    259 	    case 0:		/* -	Interruptible, no prompt */
    260 		prompt = 0;
    261 		setintr = 1;
    262 		nofile = 1;
    263 		break;
    264 
    265 	    case 'b':		/* -b	Next arg is input file */
    266 		batch = 1;
    267 		break;
    268 
    269 	    case 'c':		/* -c	Command input from arg */
    270 		if (argc == 1)
    271 		    xexit(0);
    272 		argc--, tempv++;
    273 		arginp = SAVE(tempv[0]);
    274 		prompt = 0;
    275 		nofile = 1;
    276 		break;
    277 
    278 	    case 'e':		/* -e	Exit on any error */
    279 		exiterr = 1;
    280 		break;
    281 
    282 	    case 'f':		/* -f	Fast start */
    283 		fast = 1;
    284 		break;
    285 
    286 	    case 'i':		/* -i	Interactive, even if !intty */
    287 		intact = 1;
    288 		nofile = 1;
    289 		break;
    290 
    291 	    case 'm':		/* -m	read .cshrc (from su) */
    292 		mflag = 1;
    293 		break;
    294 
    295 	    case 'n':		/* -n	Don't execute */
    296 		noexec = 1;
    297 		break;
    298 
    299 	    case 'q':		/* -q	(Undoc'd) ... die on quit */
    300 		quitit = 1;
    301 		break;
    302 
    303 	    case 's':		/* -s	Read from std input */
    304 		nofile = 1;
    305 		break;
    306 
    307 	    case 't':		/* -t	Read one line from input */
    308 		onelflg = 2;
    309 		prompt = 0;
    310 		nofile = 1;
    311 		break;
    312 
    313 	    case 'v':		/* -v	Echo hist expanded input */
    314 		nverbose = 1;	/* ... later */
    315 		break;
    316 
    317 	    case 'x':		/* -x	Echo just before execution */
    318 		nexececho = 1;	/* ... later */
    319 		break;
    320 
    321 	    case 'V':		/* -V	Echo hist expanded input */
    322 		setNS(STRverbose);	/* NOW! */
    323 		break;
    324 
    325 	    case 'X':		/* -X	Echo just before execution */
    326 		setNS(STRecho);	/* NOW! */
    327 		break;
    328 
    329 	} while (*tcp);
    330 	tempv++, argc--;
    331     }
    332 
    333     if (quitit)			/* With all due haste, for debugging */
    334 	(void) signal(SIGQUIT, SIG_DFL);
    335 
    336     /*
    337      * Unless prevented by -, -c, -i, -s, or -t, if there are remaining
    338      * arguments the first of them is the name of a shell file from which to
    339      * read commands.
    340      */
    341     if (nofile == 0 && argc > 0) {
    342 	nofile = open(tempv[0], O_RDONLY);
    343 	if (nofile < 0) {
    344 	    child = 1;		/* So this doesn't return */
    345 	    stderror(ERR_SYSTEM, tempv[0], strerror(errno));
    346 	}
    347 	ffile = SAVE(tempv[0]);
    348 	/*
    349 	 * Replace FSHIN. Handle /dev/std{in,out,err} specially
    350 	 * since once they are closed we cannot open them again.
    351 	 * In that case we use our own saved descriptors
    352 	 */
    353 	if ((SHIN = dmove(nofile, FSHIN)) < 0)
    354 	    switch(nofile) {
    355 	    case 0:
    356 		SHIN = FSHIN;
    357 		break;
    358 	    case 1:
    359 		SHIN = FSHOUT;
    360 		break;
    361 	    case 2:
    362 		SHIN = FSHDIAG;
    363 		break;
    364 	    default:
    365 		stderror(ERR_SYSTEM, tempv[0], strerror(errno));
    366 		break;
    367 	    }
    368 	(void) ioctl(SHIN, FIOCLEX, NULL);
    369 	prompt = 0;
    370 	 /* argc not used any more */ tempv++;
    371     }
    372     intty = isatty(SHIN);
    373     intty |= intact;
    374     if (intty || (intact && isatty(SHOUT))) {
    375 	if (!batch && (uid != geteuid() || gid != getegid())) {
    376 	    errno = EACCES;
    377 	    child = 1;		/* So this doesn't return */
    378 	    stderror(ERR_SYSTEM, "csh", strerror(errno));
    379 	}
    380     }
    381     /*
    382      * Decide whether we should play with signals or not. If we are explicitly
    383      * told (via -i, or -) or we are a login shell (arg0 starts with -) or the
    384      * input and output are both the ttys("csh", or "csh</dev/ttyx>/dev/ttyx")
    385      * Note that in only the login shell is it likely that parent may have set
    386      * signals to be ignored
    387      */
    388     if (loginsh || intact || intty && isatty(SHOUT))
    389 	setintr = 1;
    390     settell();
    391     /*
    392      * Save the remaining arguments in argv.
    393      */
    394     setq(STRargv, blk2short(tempv), &shvhed);
    395 
    396     /*
    397      * Set up the prompt.
    398      */
    399     if (prompt) {
    400 	set(STRprompt, Strsave(uid == 0 ? STRsymhash : STRsymcent));
    401 	/* that's a meta-questionmark */
    402 	set(STRprompt2, Strsave(STRmquestion));
    403     }
    404 
    405     /*
    406      * If we are an interactive shell, then start fiddling with the signals;
    407      * this is a tricky game.
    408      */
    409     shpgrp = getpgrp();
    410     opgrp = tpgrp = -1;
    411     if (setintr) {
    412 	**argv = '-';
    413 	if (!quitit)		/* Wary! */
    414 	    (void) signal(SIGQUIT, SIG_IGN);
    415 	(void) signal(SIGINT, pintr);
    416 	(void) sigblock(sigmask(SIGINT));
    417 	(void) signal(SIGTERM, SIG_IGN);
    418 	if (quitit == 0 && arginp == 0) {
    419 	    (void) signal(SIGTSTP, SIG_IGN);
    420 	    (void) signal(SIGTTIN, SIG_IGN);
    421 	    (void) signal(SIGTTOU, SIG_IGN);
    422 	    /*
    423 	     * Wait till in foreground, in case someone stupidly runs csh &
    424 	     * dont want to try to grab away the tty.
    425 	     */
    426 	    if (isatty(FSHDIAG))
    427 		f = FSHDIAG;
    428 	    else if (isatty(FSHOUT))
    429 		f = FSHOUT;
    430 	    else if (isatty(OLDSTD))
    431 		f = OLDSTD;
    432 	    else
    433 		f = -1;
    434     retry:
    435 	    if ((tpgrp = tcgetpgrp(f)) != -1) {
    436 		if (tpgrp != shpgrp) {
    437 		    sig_t old = signal(SIGTTIN, SIG_DFL);
    438 		    (void) kill(0, SIGTTIN);
    439 		    (void) signal(SIGTTIN, old);
    440 		    goto retry;
    441 		}
    442 		opgrp = shpgrp;
    443 		shpgrp = getpid();
    444 		tpgrp = shpgrp;
    445 		/*
    446 		 * Setpgid will fail if we are a session leader and
    447 		 * mypid == mypgrp (POSIX 4.3.3)
    448 		 */
    449 		if (opgrp != shpgrp)
    450 		    if (setpgid(0, shpgrp) == -1)
    451 			goto notty;
    452 		/*
    453 		 * We do that after we set our process group, to make sure
    454 		 * that the process group belongs to a process in the same
    455 		 * session as the tty (our process and our group) (POSIX 7.2.4)
    456 		 */
    457 		if (tcsetpgrp(f, shpgrp) == -1)
    458 		    goto notty;
    459 		(void) ioctl(dcopy(f, FSHTTY), FIOCLEX, NULL);
    460 	    }
    461 	    if (tpgrp == -1) {
    462 notty:
    463 		xprintf("Warning: no access to tty (%s).\n", strerror(errno));
    464 		xprintf("Thus no job control in this shell.\n");
    465 	    }
    466 	}
    467     }
    468     if ((setintr == 0) && (parintr == SIG_DFL))
    469 	setintr = 1;
    470     (void) signal(SIGCHLD, pchild);	/* while signals not ready */
    471 
    472     /*
    473      * Set an exit here in case of an interrupt or error reading the shell
    474      * start-up scripts.
    475      */
    476     reenter = setexit();	/* PWP */
    477     haderr = 0;			/* In case second time through */
    478     if (!fast && reenter == 0) {
    479 	/* Will have value(STRhome) here because set fast if don't */
    480 	{
    481 	    int     osetintr = setintr;
    482 	    sigset_t omask = sigblock(sigmask(SIGINT));
    483 
    484 	    setintr = 0;
    485 #ifdef _PATH_DOTCSHRC
    486 	    (void) srcfile(_PATH_DOTCSHRC, 0, 0);
    487 #endif
    488 	    if (!fast && !arginp && !onelflg)
    489 		dohash();
    490 #ifdef _PATH_DOTLOGIN
    491 	    if (loginsh)
    492 		(void) srcfile(_PATH_DOTLOGIN, 0, 0);
    493 #endif
    494 	    (void) sigsetmask(omask);
    495 	    setintr = osetintr;
    496 	}
    497 	(void) srccat(value(STRhome), STRsldotcshrc);
    498 
    499 	if (!fast && !arginp && !onelflg && !havhash)
    500 	    dohash();
    501         if (loginsh)
    502 	      (void) srccat(value(STRhome), STRsldotlogin);
    503 	dosource(loadhist);
    504     }
    505 
    506     /*
    507      * Now are ready for the -v and -x flags
    508      */
    509     if (nverbose)
    510 	setNS(STRverbose);
    511     if (nexececho)
    512 	setNS(STRecho);
    513 
    514     /*
    515      * All the rest of the world is inside this call. The argument to process
    516      * indicates whether it should catch "error unwinds".  Thus if we are a
    517      * interactive shell our call here will never return by being blown past on
    518      * an error.
    519      */
    520     process(setintr);
    521 
    522     /*
    523      * Mop-up.
    524      */
    525     if (intty) {
    526 	if (loginsh) {
    527 	    xprintf("logout\n");
    528 	    (void) close(SHIN);
    529 	    child = 1;
    530 	    goodbye();
    531 	}
    532 	else {
    533 	    xprintf("exit\n");
    534 	}
    535     }
    536     rechist();
    537     exitstat();
    538     return (0);
    539 }
    540 
    541 void
    542 untty()
    543 {
    544     if (tpgrp > 0) {
    545 	(void) setpgid(0, opgrp);
    546 	(void) tcsetpgrp(FSHTTY, opgrp);
    547     }
    548 }
    549 
    550 void
    551 importpath(cp)
    552     Char   *cp;
    553 {
    554     register int i = 0;
    555     register Char *dp;
    556     register Char **pv;
    557     int     c;
    558 
    559     for (dp = cp; *dp; dp++)
    560 	if (*dp == ':')
    561 	    i++;
    562     /*
    563      * i+2 where i is the number of colons in the path. There are i+1
    564      * directories in the path plus we need room for a zero terminator.
    565      */
    566     pv = (Char **) xcalloc((size_t) (i + 2), sizeof(Char **));
    567     dp = cp;
    568     i = 0;
    569     if (*dp)
    570 	for (;;) {
    571 	    if ((c = *dp) == ':' || c == 0) {
    572 		*dp = 0;
    573 		pv[i++] = Strsave(*cp ? cp : STRdot);
    574 		if (c) {
    575 		    cp = dp + 1;
    576 		    *dp = ':';
    577 		}
    578 		else
    579 		    break;
    580 	    }
    581 	    dp++;
    582 	}
    583     pv[i] = 0;
    584     set1(STRpath, pv, &shvhed);
    585 }
    586 
    587 /*
    588  * Source to the file which is the catenation of the argument names.
    589  */
    590 static int
    591 srccat(cp, dp)
    592     Char   *cp, *dp;
    593 {
    594     register Char *ep = Strspl(cp, dp);
    595     char   *ptr = short2str(ep);
    596 
    597     xfree((ptr_t) ep);
    598     return srcfile(ptr, mflag ? 0 : 1, 0);
    599 }
    600 
    601 /*
    602  * Source to a file putting the file descriptor in a safe place (> 2).
    603  */
    604 static int
    605 srcfile(f, onlyown, flag)
    606     char   *f;
    607     bool    onlyown, flag;
    608 {
    609     register int unit;
    610 
    611     if ((unit = open(f, O_RDONLY)) == -1)
    612 	return 0;
    613     unit = dmove(unit, -1);
    614 
    615     (void) ioctl(unit, FIOCLEX, NULL);
    616     srcunit(unit, onlyown, flag);
    617     return 1;
    618 }
    619 
    620 /*
    621  * Source to a unit.  If onlyown it must be our file or our group or
    622  * we don't chance it.	This occurs on ".cshrc"s and the like.
    623  */
    624 int     insource;
    625 static void
    626 srcunit(unit, onlyown, hflg)
    627     register int unit;
    628     bool    onlyown, hflg;
    629 {
    630     /* We have to push down a lot of state here */
    631     /* All this could go into a structure */
    632     int     oSHIN = -1, oldintty = intty, oinsource = insource;
    633     struct whyle *oldwhyl = whyles;
    634     Char   *ogointr = gointr, *oarginp = arginp;
    635     Char   *oevalp = evalp, **oevalvec = evalvec;
    636     int     oonelflg = onelflg;
    637     bool    oenterhist = enterhist;
    638     char    OHIST = HIST;
    639     bool    otell = cantell;
    640 
    641     struct Bin saveB;
    642     sigset_t omask;
    643     jmp_buf oldexit;
    644 
    645     /* The (few) real local variables */
    646     int     my_reenter;
    647 
    648     if (unit < 0)
    649 	return;
    650     if (didfds)
    651 	donefds();
    652     if (onlyown) {
    653 	struct stat stb;
    654 
    655 	if (fstat(unit, &stb) < 0) {
    656 	    (void) close(unit);
    657 	    return;
    658 	}
    659     }
    660 
    661     /*
    662      * There is a critical section here while we are pushing down the input
    663      * stream since we have stuff in different structures. If we weren't
    664      * careful an interrupt could corrupt SHIN's Bin structure and kill the
    665      * shell.
    666      *
    667      * We could avoid the critical region by grouping all the stuff in a single
    668      * structure and pointing at it to move it all at once.  This is less
    669      * efficient globally on many variable references however.
    670      */
    671     insource = 1;
    672     getexit(oldexit);
    673     omask = 0;
    674 
    675     if (setintr)
    676 	omask = sigblock(sigmask(SIGINT));
    677     /* Setup the new values of the state stuff saved above */
    678     bcopy((char *) &B, (char *) &(saveB), sizeof(B));
    679     fbuf = NULL;
    680     fseekp = feobp = fblocks = 0;
    681     oSHIN = SHIN, SHIN = unit, arginp = 0, onelflg = 0;
    682     intty = isatty(SHIN), whyles = 0, gointr = 0;
    683     evalvec = 0;
    684     evalp = 0;
    685     enterhist = hflg;
    686     if (enterhist)
    687 	HIST = '\0';
    688 
    689     /*
    690      * Now if we are allowing commands to be interrupted, we let ourselves be
    691      * interrupted.
    692      */
    693     if (setintr)
    694 	(void) sigsetmask(omask);
    695     settell();
    696 
    697     if ((my_reenter = setexit()) == 0)
    698 	process(0);		/* 0 -> blow away on errors */
    699 
    700     if (setintr)
    701 	(void) sigsetmask(omask);
    702     if (oSHIN >= 0) {
    703 	register int i;
    704 
    705 	/* We made it to the new state... free up its storage */
    706 	/* This code could get run twice but xfree doesn't care */
    707 	for (i = 0; i < fblocks; i++)
    708 	    xfree((ptr_t) fbuf[i]);
    709 	xfree((ptr_t) fbuf);
    710 
    711 	/* Reset input arena */
    712 	bcopy((char *) &(saveB), (char *) &B, sizeof(B));
    713 
    714 	(void) close(SHIN), SHIN = oSHIN;
    715 	arginp = oarginp, onelflg = oonelflg;
    716 	evalp = oevalp, evalvec = oevalvec;
    717 	intty = oldintty, whyles = oldwhyl, gointr = ogointr;
    718 	if (enterhist)
    719 	    HIST = OHIST;
    720 	enterhist = oenterhist;
    721 	cantell = otell;
    722     }
    723 
    724     resexit(oldexit);
    725     /*
    726      * If process reset() (effectively an unwind) then we must also unwind.
    727      */
    728     if (my_reenter)
    729 	stderror(ERR_SILENT);
    730     insource = oinsource;
    731 }
    732 
    733 void
    734 rechist()
    735 {
    736     Char    buf[BUFSIZ];
    737     int     fp, ftmp, oldidfds;
    738 
    739     if (!fast) {
    740 	if (value(STRsavehist)[0] == '\0')
    741 	    return;
    742 	(void) Strcpy(buf, value(STRhome));
    743 	(void) Strcat(buf, STRsldthist);
    744 	fp = creat(short2str(buf), 0600);
    745 	if (fp == -1)
    746 	    return;
    747 	oldidfds = didfds;
    748 	didfds = 0;
    749 	ftmp = SHOUT;
    750 	SHOUT = fp;
    751 	(void) Strcpy(buf, value(STRsavehist));
    752 	dumphist[2] = buf;
    753 	dohist(dumphist);
    754 	(void) close(fp);
    755 	SHOUT = ftmp;
    756 	didfds = oldidfds;
    757     }
    758 }
    759 
    760 void
    761 goodbye()
    762 {
    763     rechist();
    764 
    765     if (loginsh) {
    766 	(void) signal(SIGQUIT, SIG_IGN);
    767 	(void) signal(SIGINT, SIG_IGN);
    768 	(void) signal(SIGTERM, SIG_IGN);
    769 	setintr = 0;		/* No interrupts after "logout" */
    770 	if (!(adrof(STRlogout)))
    771 	    set(STRlogout, STRnormal);
    772 #ifdef _PATH_DOTLOGOUT
    773 	(void) srcfile(_PATH_DOTLOGOUT, 0, 0);
    774 #endif
    775 	if (adrof(STRhome))
    776 	    (void) srccat(value(STRhome), STRsldtlogout);
    777     }
    778     exitstat();
    779 }
    780 
    781 void
    782 exitstat()
    783 {
    784 
    785 #ifdef PROF
    786     monitor(0);
    787 #endif
    788     /*
    789      * Note that if STATUS is corrupted (i.e. getn bombs) then error will exit
    790      * directly because we poke child here. Otherwise we might continue
    791      * unwarrantedly (sic).
    792      */
    793     child = 1;
    794     xexit(getn(value(STRstatus)));
    795 }
    796 
    797 /*
    798  * in the event of a HUP we want to save the history
    799  */
    800 static void
    801 phup(sig)
    802 int sig;
    803 {
    804 	struct process *pp, *np;
    805 	int foregnd;
    806 
    807 	rechist();
    808 
    809 	/*
    810 	 * the following adopted from tcsh with light mods
    811 	 *
    812 	 * We kill the last foreground process group. It then becomes
    813 	 * responsible to propagate the SIGHUP to its progeny.
    814 	 */
    815 	for (pp = proclist.p_next; pp; pp = pp->p_next) {
    816 		np = pp;
    817 		foregnd = 0;
    818 
    819 		/*
    820 		 * Find if this job is in the foreground. It could be that
    821 		 * the process leader has exited and the foreground flag
    822 		 * is cleared for it.
    823 		 */
    824 		do {
    825 			/*
    826 			 * If a process is in the foreground; we try to kill
    827 			 * it's process group. If we succeed, then the
    828 			 * whole job is gone. Otherwise we keep going...
    829 			 * But avoid sending HUP to the shell again.
    830 			 */
    831 			if ((np->p_flags & PFOREGND) != 0 &&
    832 			    np->p_jobid != shpgrp &&
    833 			    killpg(np->p_jobid, SIGHUP) != -1) {
    834 				/* In case the job was suspended... */
    835 				(void) killpg(np->p_jobid, SIGCONT);
    836 				break;
    837 			}
    838 		} while ((np = np->p_friends) != pp);
    839         }
    840 
    841 	xexit(sig);
    842 }
    843 
    844 Char   *jobargv[2] = {STRjobs, 0};
    845 
    846 /*
    847  * Catch an interrupt, e.g. during lexical input.
    848  * If we are an interactive shell, we reset the interrupt catch
    849  * immediately.  In any case we drain the shell output,
    850  * and finally go through the normal error mechanism, which
    851  * gets a chance to make the shell go away.
    852  */
    853 /* ARGSUSED */
    854 void
    855 pintr(notused)
    856 	int notused;
    857 {
    858     pintr1(1);
    859 }
    860 
    861 void
    862 pintr1(wantnl)
    863     bool    wantnl;
    864 {
    865     register Char **v;
    866     sigset_t omask;
    867 
    868     omask = sigblock((sigset_t) 0);
    869     if (setintr) {
    870 	(void) sigsetmask(omask & ~sigmask(SIGINT));
    871 	if (pjobs) {
    872 	    pjobs = 0;
    873 	    xprintf("\n");
    874 	    dojobs(jobargv);
    875 	    stderror(ERR_NAME | ERR_INTR);
    876 	}
    877     }
    878     (void) sigsetmask(omask & ~sigmask(SIGCHLD));
    879     draino();
    880     (void) endpwent();
    881 
    882     /*
    883      * If we have an active "onintr" then we search for the label. Note that if
    884      * one does "onintr -" then we shan't be interruptible so we needn't worry
    885      * about that here.
    886      */
    887     if (gointr) {
    888 	search(T_GOTO, 0, gointr);
    889 	timflg = 0;
    890 	if (v = pargv)
    891 	    pargv = 0, blkfree(v);
    892 	if (v = gargv)
    893 	    gargv = 0, blkfree(v);
    894 	reset();
    895     }
    896     else if (intty && wantnl) {
    897 	(void) putraw('\r');
    898 	(void) putraw('\n');
    899     }
    900     stderror(ERR_SILENT);
    901 }
    902 
    903 /*
    904  * Process is the main driving routine for the shell.
    905  * It runs all command processing, except for those within { ... }
    906  * in expressions (which is run by a routine evalav in sh.exp.c which
    907  * is a stripped down process), and `...` evaluation which is run
    908  * also by a subset of this code in sh.glob.c in the routine backeval.
    909  *
    910  * The code here is a little strange because part of it is interruptible
    911  * and hence freeing of structures appears to occur when none is necessary
    912  * if this is ignored.
    913  *
    914  * Note that if catch is not set then we will unwind on any error.
    915  * If an end-of-file occurs, we return.
    916  */
    917 void
    918 process(catch)
    919     bool    catch;
    920 {
    921     jmp_buf osetexit;
    922     struct command *t;
    923 
    924     getexit(osetexit);
    925     for (;;) {
    926 	pendjob();
    927 	paraml.next = paraml.prev = &paraml;
    928 	paraml.word = STRNULL;
    929 	t = 0;
    930 	(void) setexit();
    931 	justpr = enterhist;	/* execute if not entering history */
    932 
    933 	/*
    934 	 * Interruptible during interactive reads
    935 	 */
    936 	if (setintr)
    937 	    (void) sigsetmask(sigblock((sigset_t) 0) & ~sigmask(SIGINT));
    938 
    939 	/*
    940 	 * For the sake of reset()
    941 	 */
    942 	freelex(&paraml);
    943 	freesyn(t);
    944 	t = 0;
    945 
    946 	if (haderr) {
    947 	    if (!catch) {
    948 		/* unwind */
    949 		doneinp = 0;
    950 		resexit(osetexit);
    951 		reset();
    952 	    }
    953 	    haderr = 0;
    954 	    /*
    955 	     * Every error is eventually caught here or the shell dies.  It is
    956 	     * at this point that we clean up any left-over open files, by
    957 	     * closing all but a fixed number of pre-defined files.  Thus
    958 	     * routines don't have to worry about leaving files open due to
    959 	     * deeper errors... they will get closed here.
    960 	     */
    961 	    closem();
    962 	    continue;
    963 	}
    964 	if (doneinp) {
    965 	    doneinp = 0;
    966 	    break;
    967 	}
    968 	if (chkstop)
    969 	    chkstop--;
    970 	if (neednote)
    971 	    pnote();
    972 	if (intty && prompt && evalvec == 0) {
    973 	    mailchk();
    974 	    /*
    975 	     * If we are at the end of the input buffer then we are going to
    976 	     * read fresh stuff. Otherwise, we are rereading input and don't
    977 	     * need or want to prompt.
    978 	     */
    979 	    if (fseekp == feobp)
    980 		printprompt();
    981 	    flush();
    982 	}
    983 	if (seterr) {
    984 	    xfree((ptr_t) seterr);
    985 	    seterr = NULL;
    986 	}
    987 
    988 	/*
    989 	 * Echo not only on VERBOSE, but also with history expansion. If there
    990 	 * is a lexical error then we forego history echo.
    991 	 */
    992 	if (lex(&paraml) && !seterr && intty || adrof(STRverbose)) {
    993 	    haderr = 1;
    994 	    prlex(&paraml);
    995 	    haderr = 0;
    996 	}
    997 
    998 	/*
    999 	 * The parser may lose space if interrupted.
   1000 	 */
   1001 	if (setintr)
   1002 	    (void) sigblock(sigmask(SIGINT));
   1003 
   1004 	/*
   1005 	 * Save input text on the history list if reading in old history, or it
   1006 	 * is from the terminal at the top level and not in a loop.
   1007 	 *
   1008 	 * PWP: entry of items in the history list while in a while loop is done
   1009 	 * elsewhere...
   1010 	 */
   1011 	if (enterhist || catch && intty && !whyles)
   1012 	    savehist(&paraml);
   1013 
   1014 	/*
   1015 	 * Print lexical error messages, except when sourcing history lists.
   1016 	 */
   1017 	if (!enterhist && seterr)
   1018 	    stderror(ERR_OLD);
   1019 
   1020 	/*
   1021 	 * If had a history command :p modifier then this is as far as we
   1022 	 * should go
   1023 	 */
   1024 	if (justpr)
   1025 	    reset();
   1026 
   1027 	alias(&paraml);
   1028 
   1029 	/*
   1030 	 * Parse the words of the input into a parse tree.
   1031 	 */
   1032 	t = syntax(paraml.next, &paraml, 0);
   1033 	if (seterr)
   1034 	    stderror(ERR_OLD);
   1035 
   1036 	execute(t, (tpgrp > 0 ? tpgrp : -1), NULL, NULL);
   1037 
   1038 	/*
   1039 	 * Made it!
   1040 	 */
   1041 	freelex(&paraml);
   1042 	freesyn(t);
   1043     }
   1044     resexit(osetexit);
   1045 }
   1046 
   1047 void
   1048 dosource(t)
   1049     register Char **t;
   1050 {
   1051     register Char *f;
   1052     bool    hflg = 0;
   1053     Char    buf[BUFSIZ];
   1054 
   1055     t++;
   1056     if (*t && eq(*t, STRmh)) {
   1057 	if (*++t == NULL)
   1058 	    stderror(ERR_NAME | ERR_HFLAG);
   1059 	hflg++;
   1060     }
   1061     (void) Strcpy(buf, *t);
   1062     f = globone(buf, G_ERROR);
   1063     (void) strcpy((char *) buf, short2str(f));
   1064     xfree((ptr_t) f);
   1065     if (!srcfile((char *) buf, 0, hflg) && !hflg)
   1066 	stderror(ERR_SYSTEM, (char *) buf, strerror(errno));
   1067 }
   1068 
   1069 /*
   1070  * Check for mail.
   1071  * If we are a login shell, then we don't want to tell
   1072  * about any mail file unless its been modified
   1073  * after the time we started.
   1074  * This prevents us from telling the user things he already
   1075  * knows, since the login program insists on saying
   1076  * "You have mail."
   1077  */
   1078 static void
   1079 mailchk()
   1080 {
   1081     register struct varent *v;
   1082     register Char **vp;
   1083     time_t  t;
   1084     int     intvl, cnt;
   1085     struct stat stb;
   1086     bool    new;
   1087 
   1088     v = adrof(STRmail);
   1089     if (v == 0)
   1090 	return;
   1091     (void) time(&t);
   1092     vp = v->vec;
   1093     cnt = blklen(vp);
   1094     intvl = (cnt && number(*vp)) ? (--cnt, getn(*vp++)) : MAILINTVL;
   1095     if (intvl < 1)
   1096 	intvl = 1;
   1097     if (chktim + intvl > t)
   1098 	return;
   1099     for (; *vp; vp++) {
   1100 	if (stat(short2str(*vp), &stb) < 0)
   1101 	    continue;
   1102 	new = stb.st_mtime > time0.tv_sec;
   1103 	if (stb.st_size == 0 || stb.st_atime > stb.st_mtime ||
   1104 	    (stb.st_atime < chktim && stb.st_mtime < chktim) ||
   1105 	    loginsh && !new)
   1106 	    continue;
   1107 	if (cnt == 1)
   1108 	    xprintf("You have %smail.\n", new ? "new " : "");
   1109 	else
   1110 	    xprintf("%s in %s.\n", new ? "New mail" : "Mail", short2str(*vp));
   1111     }
   1112     chktim = t;
   1113 }
   1114 
   1115 /*
   1116  * Extract a home directory from the password file
   1117  * The argument points to a buffer where the name of the
   1118  * user whose home directory is sought is currently.
   1119  * We write the home directory of the user back there.
   1120  */
   1121 int
   1122 gethdir(home)
   1123     Char   *home;
   1124 {
   1125     Char   *h;
   1126     struct passwd *pw;
   1127 
   1128     /*
   1129      * Is it us?
   1130      */
   1131     if (*home == '\0') {
   1132 	if (h = value(STRhome)) {
   1133 	    (void) Strcpy(home, h);
   1134 	    return 0;
   1135 	}
   1136 	else
   1137 	    return 1;
   1138     }
   1139 
   1140     if (pw = getpwnam(short2str(home))) {
   1141 	(void) Strcpy(home, str2short(pw->pw_dir));
   1142 	return 0;
   1143     }
   1144     else
   1145 	return 1;
   1146 }
   1147 
   1148 /*
   1149  * Move the initial descriptors to their eventual
   1150  * resting places, closin all other units.
   1151  */
   1152 void
   1153 initdesc()
   1154 {
   1155 
   1156     didfds = 0;			/* 0, 1, 2 aren't set up */
   1157     (void) ioctl(SHIN = dcopy(0, FSHIN), FIOCLEX, NULL);
   1158     (void) ioctl(SHOUT = dcopy(1, FSHOUT), FIOCLEX, NULL);
   1159     (void) ioctl(SHDIAG = dcopy(2, FSHDIAG), FIOCLEX, NULL);
   1160     (void) ioctl(OLDSTD = dcopy(SHIN, FOLDSTD), FIOCLEX, NULL);
   1161     closem();
   1162 }
   1163 
   1164 
   1165 void
   1166 #ifdef PROF
   1167 done(i)
   1168 #else
   1169 xexit(i)
   1170 #endif
   1171     int     i;
   1172 {
   1173     untty();
   1174     _exit(i);
   1175 }
   1176 
   1177 static Char **
   1178 defaultpath()
   1179 {
   1180     char   *ptr;
   1181     Char  **blk, **blkp;
   1182     struct stat stb;
   1183 
   1184     blkp = blk = (Char **) xmalloc((size_t) sizeof(Char *) * 10);
   1185 
   1186 #define DIRAPPEND(a)  \
   1187 	if (stat(ptr = a, &stb) == 0 && (stb.st_mode & S_IFMT) == S_IFDIR) \
   1188 		*blkp++ = SAVE(ptr)
   1189 
   1190     DIRAPPEND(_PATH_BIN);
   1191     DIRAPPEND(_PATH_USRBIN);
   1192 
   1193 #undef DIRAPPEND
   1194 
   1195     *blkp++ = Strsave(STRdot);
   1196     *blkp = NULL;
   1197     return (blk);
   1198 }
   1199 
   1200 void
   1201 printprompt()
   1202 {
   1203     register Char *cp;
   1204 
   1205     if (!whyles) {
   1206 	for (cp = value(STRprompt); *cp; cp++)
   1207 	    if (*cp == HIST)
   1208 		xprintf("%d", eventno + 1);
   1209 	    else {
   1210 		if (*cp == '\\' && cp[1] == HIST)
   1211 		    cp++;
   1212 		xputchar(*cp | QUOTE);
   1213 	    }
   1214     }
   1215     else
   1216 	/*
   1217 	 * Prompt for forward reading loop body content.
   1218 	 */
   1219 	xprintf("? ");
   1220     flush();
   1221 }
   1222