Home | History | Annotate | Line # | Download | only in csh
csh.c revision 1.4
      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.4 1993/08/01 19:00:50 mycroft 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 
     65 extern bool MapsAreInited;
     66 extern bool NLSMapsAreInited;
     67 
     68 /*
     69  * C Shell
     70  *
     71  * Bill Joy, UC Berkeley, California, USA
     72  * October 1978, May 1980
     73  *
     74  * Jim Kulp, IIASA, Laxenburg, Austria
     75  * April 1980
     76  *
     77  * Christos Zoulas, Cornell University
     78  * June, 1991
     79  */
     80 
     81 Char   *dumphist[] = {STRhistory, STRmh, 0, 0};
     82 Char   *loadhist[] = {STRsource, STRmh, STRhistfile, 0};
     83 
     84 int     nofile = 0;
     85 bool    reenter = 0;
     86 bool    nverbose = 0;
     87 bool    nexececho = 0;
     88 bool    quitit = 0;
     89 bool    fast = 0;
     90 bool    batch = 0;
     91 bool    mflag = 0;
     92 bool    prompt = 1;
     93 bool    enterhist = 0;
     94 bool    tellwhat = 0;
     95 
     96 extern char **environ;
     97 
     98 static int	srccat __P((Char *, Char *));
     99 static int	srcfile __P((char *, bool, bool));
    100 static void	phup __P((int));
    101 static void	srcunit __P((int, bool, bool));
    102 static void	mailchk __P((void));
    103 static Char   **defaultpath __P((void));
    104 
    105 int
    106 main(argc, argv)
    107     int     argc;
    108     char  **argv;
    109 {
    110     register Char *cp;
    111     register char *tcp;
    112     register int f;
    113     register char **tempv;
    114     struct sigvec osv;
    115 
    116 
    117     settimes();			/* Immed. estab. timing base */
    118 
    119     /*
    120      * Initialize non constant strings
    121      */
    122 #ifdef _PATH_BSHELL
    123     STR_BSHELL = SAVE(_PATH_BSHELL);
    124 #endif
    125 #ifdef _PATH_CSHELL
    126     STR_SHELLPATH = SAVE(_PATH_CSHELL);
    127 #endif
    128     STR_environ = blk2short(environ);
    129     environ = short2blk(STR_environ);	/* So that we can free it */
    130     STR_WORD_CHARS = SAVE(WORD_CHARS);
    131 
    132     HIST = '!';
    133     HISTSUB = '^';
    134     word_chars = STR_WORD_CHARS;
    135 
    136     tempv = argv;
    137     if (eq(str2short(tempv[0]), STRaout))	/* A.out's are quittable */
    138 	quitit = 1;
    139     uid = getuid();
    140     gid = getgid();
    141     /*
    142      * We are a login shell if: 1. we were invoked as -<something> and we had
    143      * no arguments 2. or we were invoked only with the -l flag
    144      */
    145     loginsh = (**tempv == '-' && argc == 1) ||
    146 	(argc == 2 && tempv[1][0] == '-' && tempv[1][1] == 'l' &&
    147 	 tempv[1][2] == '\0');
    148 
    149     if (loginsh && **tempv != '-') {
    150 	/*
    151 	 * Mangle the argv space
    152 	 */
    153 	tempv[1][0] = '\0';
    154 	tempv[1][1] = '\0';
    155 	tempv[1] = NULL;
    156 	for (tcp = *tempv; *tcp++;);
    157 	for (tcp--; tcp >= *tempv; tcp--)
    158 	    tcp[1] = tcp[0];
    159 	*++tcp = '-';
    160 	argc--;
    161     }
    162     if (loginsh)
    163 	(void) time(&chktim);
    164 
    165     AsciiOnly = 1;
    166 #ifdef NLS
    167     (void) setlocale(LC_ALL, "");
    168     {
    169 	int     k;
    170 
    171 	for (k = 0200; k <= 0377 && !Isprint(k); k++);
    172 	AsciiOnly = k > 0377;
    173     }
    174 #else
    175     AsciiOnly = getenv("LANG") == NULL && getenv("LC_CTYPE") == NULL;
    176 #endif				/* NLS */
    177 
    178     /*
    179      * Move the descriptors to safe places. The variable didfds is 0 while we
    180      * have only FSH* to work with. When didfds is true, we have 0,1,2 and
    181      * prefer to use these.
    182      */
    183     initdesc();
    184 
    185     /*
    186      * Initialize the shell variables. ARGV and PROMPT are initialized later.
    187      * STATUS is also munged in several places. CHILD is munged when
    188      * forking/waiting
    189      */
    190     set(STRstatus, Strsave(STR0));
    191 
    192     if ((tcp = getenv("HOME")) != NULL)
    193 	cp = SAVE(tcp);
    194     else
    195 	cp = NULL;
    196 
    197     if (cp == NULL)
    198 	fast = 1;		/* No home -> can't read scripts */
    199     else
    200 	set(STRhome, cp);
    201     dinit(cp);			/* dinit thinks that HOME == cwd in a login
    202 				 * shell */
    203     /*
    204      * Grab other useful things from the environment. Should we grab
    205      * everything??
    206      */
    207     if ((tcp = getenv("LOGNAME")) != NULL ||
    208 	(tcp = getenv("USER")) != NULL)
    209 	set(STRuser, SAVE(tcp));
    210     if ((tcp = getenv("TERM")) != NULL)
    211 	set(STRterm, SAVE(tcp));
    212 
    213     /*
    214      * Re-initialize path if set in environment
    215      */
    216     if ((tcp = getenv("PATH")) == NULL)
    217 	set1(STRpath, defaultpath(), &shvhed);
    218     else
    219 	importpath(SAVE(tcp));
    220 
    221     set(STRshell, Strsave(STR_SHELLPATH));
    222 
    223     doldol = putn((int) getpid());	/* For $$ */
    224     shtemp = Strspl(STRtmpsh, doldol);	/* For << */
    225 
    226     /*
    227      * Record the interrupt states from the parent process. If the parent is
    228      * non-interruptible our hand must be forced or we (and our children) won't
    229      * be either. Our children inherit termination from our parent. We catch it
    230      * only if we are the login shell.
    231      */
    232     /* parents interruptibility */
    233     (void) sigvec(SIGINT, NULL, &osv);
    234     parintr = (void (*) ()) osv.sv_handler;
    235     (void) sigvec(SIGTERM, NULL, &osv);
    236     parterm = (void (*) ()) osv.sv_handler;
    237 
    238     if (loginsh) {
    239 	(void) signal(SIGHUP, phup);	/* exit processing on HUP */
    240 	(void) signal(SIGXCPU, phup);	/* ...and on XCPU */
    241 	(void) signal(SIGXFSZ, phup);	/* ...and on XFSZ */
    242     }
    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     rechist();
    805     xexit(sig);
    806 }
    807 
    808 Char   *jobargv[2] = {STRjobs, 0};
    809 
    810 /*
    811  * Catch an interrupt, e.g. during lexical input.
    812  * If we are an interactive shell, we reset the interrupt catch
    813  * immediately.  In any case we drain the shell output,
    814  * and finally go through the normal error mechanism, which
    815  * gets a chance to make the shell go away.
    816  */
    817 /* ARGSUSED */
    818 void
    819 pintr(notused)
    820 	int notused;
    821 {
    822     pintr1(1);
    823 }
    824 
    825 void
    826 pintr1(wantnl)
    827     bool    wantnl;
    828 {
    829     register Char **v;
    830     sigset_t omask;
    831 
    832     omask = sigblock((sigset_t) 0);
    833     if (setintr) {
    834 	(void) sigsetmask(omask & ~sigmask(SIGINT));
    835 	if (pjobs) {
    836 	    pjobs = 0;
    837 	    xprintf("\n");
    838 	    dojobs(jobargv);
    839 	    stderror(ERR_NAME | ERR_INTR);
    840 	}
    841     }
    842     (void) sigsetmask(omask & ~sigmask(SIGCHLD));
    843     draino();
    844     (void) endpwent();
    845 
    846     /*
    847      * If we have an active "onintr" then we search for the label. Note that if
    848      * one does "onintr -" then we shan't be interruptible so we needn't worry
    849      * about that here.
    850      */
    851     if (gointr) {
    852 	search(T_GOTO, 0, gointr);
    853 	timflg = 0;
    854 	if (v = pargv)
    855 	    pargv = 0, blkfree(v);
    856 	if (v = gargv)
    857 	    gargv = 0, blkfree(v);
    858 	reset();
    859     }
    860     else if (intty && wantnl) {
    861 	(void) putraw('\r');
    862 	(void) putraw('\n');
    863     }
    864     stderror(ERR_SILENT);
    865 }
    866 
    867 /*
    868  * Process is the main driving routine for the shell.
    869  * It runs all command processing, except for those within { ... }
    870  * in expressions (which is run by a routine evalav in sh.exp.c which
    871  * is a stripped down process), and `...` evaluation which is run
    872  * also by a subset of this code in sh.glob.c in the routine backeval.
    873  *
    874  * The code here is a little strange because part of it is interruptible
    875  * and hence freeing of structures appears to occur when none is necessary
    876  * if this is ignored.
    877  *
    878  * Note that if catch is not set then we will unwind on any error.
    879  * If an end-of-file occurs, we return.
    880  */
    881 void
    882 process(catch)
    883     bool    catch;
    884 {
    885     jmp_buf osetexit;
    886     struct command *t;
    887 
    888     getexit(osetexit);
    889     for (;;) {
    890 	pendjob();
    891 	paraml.next = paraml.prev = &paraml;
    892 	paraml.word = STRNULL;
    893 	t = 0;
    894 	(void) setexit();
    895 	justpr = enterhist;	/* execute if not entering history */
    896 
    897 	/*
    898 	 * Interruptible during interactive reads
    899 	 */
    900 	if (setintr)
    901 	    (void) sigsetmask(sigblock((sigset_t) 0) & ~sigmask(SIGINT));
    902 
    903 	/*
    904 	 * For the sake of reset()
    905 	 */
    906 	freelex(&paraml);
    907 	freesyn(t);
    908 	t = 0;
    909 
    910 	if (haderr) {
    911 	    if (!catch) {
    912 		/* unwind */
    913 		doneinp = 0;
    914 		resexit(osetexit);
    915 		reset();
    916 	    }
    917 	    haderr = 0;
    918 	    /*
    919 	     * Every error is eventually caught here or the shell dies.  It is
    920 	     * at this point that we clean up any left-over open files, by
    921 	     * closing all but a fixed number of pre-defined files.  Thus
    922 	     * routines don't have to worry about leaving files open due to
    923 	     * deeper errors... they will get closed here.
    924 	     */
    925 	    closem();
    926 	    continue;
    927 	}
    928 	if (doneinp) {
    929 	    doneinp = 0;
    930 	    break;
    931 	}
    932 	if (chkstop)
    933 	    chkstop--;
    934 	if (neednote)
    935 	    pnote();
    936 	if (intty && prompt && evalvec == 0) {
    937 	    mailchk();
    938 	    /*
    939 	     * If we are at the end of the input buffer then we are going to
    940 	     * read fresh stuff. Otherwise, we are rereading input and don't
    941 	     * need or want to prompt.
    942 	     */
    943 	    if (fseekp == feobp)
    944 		printprompt();
    945 	    flush();
    946 	}
    947 	if (seterr) {
    948 	    xfree((ptr_t) seterr);
    949 	    seterr = NULL;
    950 	}
    951 
    952 	/*
    953 	 * Echo not only on VERBOSE, but also with history expansion. If there
    954 	 * is a lexical error then we forego history echo.
    955 	 */
    956 	if (lex(&paraml) && !seterr && intty || adrof(STRverbose)) {
    957 	    haderr = 1;
    958 	    prlex(&paraml);
    959 	    haderr = 0;
    960 	}
    961 
    962 	/*
    963 	 * The parser may lose space if interrupted.
    964 	 */
    965 	if (setintr)
    966 	    (void) sigblock(sigmask(SIGINT));
    967 
    968 	/*
    969 	 * Save input text on the history list if reading in old history, or it
    970 	 * is from the terminal at the top level and not in a loop.
    971 	 *
    972 	 * PWP: entry of items in the history list while in a while loop is done
    973 	 * elsewhere...
    974 	 */
    975 	if (enterhist || catch && intty && !whyles)
    976 	    savehist(&paraml);
    977 
    978 	/*
    979 	 * Print lexical error messages, except when sourcing history lists.
    980 	 */
    981 	if (!enterhist && seterr)
    982 	    stderror(ERR_OLD);
    983 
    984 	/*
    985 	 * If had a history command :p modifier then this is as far as we
    986 	 * should go
    987 	 */
    988 	if (justpr)
    989 	    reset();
    990 
    991 	alias(&paraml);
    992 
    993 	/*
    994 	 * Parse the words of the input into a parse tree.
    995 	 */
    996 	t = syntax(paraml.next, &paraml, 0);
    997 	if (seterr)
    998 	    stderror(ERR_OLD);
    999 
   1000 	execute(t, (tpgrp > 0 ? tpgrp : -1), NULL, NULL);
   1001 
   1002 	/*
   1003 	 * Made it!
   1004 	 */
   1005 	freelex(&paraml);
   1006 	freesyn(t);
   1007     }
   1008     resexit(osetexit);
   1009 }
   1010 
   1011 void
   1012 dosource(t)
   1013     register Char **t;
   1014 {
   1015     register Char *f;
   1016     bool    hflg = 0;
   1017     Char    buf[BUFSIZ];
   1018 
   1019     t++;
   1020     if (*t && eq(*t, STRmh)) {
   1021 	if (*++t == NULL)
   1022 	    stderror(ERR_NAME | ERR_HFLAG);
   1023 	hflg++;
   1024     }
   1025     (void) Strcpy(buf, *t);
   1026     f = globone(buf, G_ERROR);
   1027     (void) strcpy((char *) buf, short2str(f));
   1028     xfree((ptr_t) f);
   1029     if (!srcfile((char *) buf, 0, hflg) && !hflg)
   1030 	stderror(ERR_SYSTEM, (char *) buf, strerror(errno));
   1031 }
   1032 
   1033 /*
   1034  * Check for mail.
   1035  * If we are a login shell, then we don't want to tell
   1036  * about any mail file unless its been modified
   1037  * after the time we started.
   1038  * This prevents us from telling the user things he already
   1039  * knows, since the login program insists on saying
   1040  * "You have mail."
   1041  */
   1042 static void
   1043 mailchk()
   1044 {
   1045     register struct varent *v;
   1046     register Char **vp;
   1047     time_t  t;
   1048     int     intvl, cnt;
   1049     struct stat stb;
   1050     bool    new;
   1051 
   1052     v = adrof(STRmail);
   1053     if (v == 0)
   1054 	return;
   1055     (void) time(&t);
   1056     vp = v->vec;
   1057     cnt = blklen(vp);
   1058     intvl = (cnt && number(*vp)) ? (--cnt, getn(*vp++)) : MAILINTVL;
   1059     if (intvl < 1)
   1060 	intvl = 1;
   1061     if (chktim + intvl > t)
   1062 	return;
   1063     for (; *vp; vp++) {
   1064 	if (stat(short2str(*vp), &stb) < 0)
   1065 	    continue;
   1066 	new = stb.st_mtime > time0.tv_sec;
   1067 	if (stb.st_size == 0 || stb.st_atime > stb.st_mtime ||
   1068 	    (stb.st_atime < chktim && stb.st_mtime < chktim) ||
   1069 	    loginsh && !new)
   1070 	    continue;
   1071 	if (cnt == 1)
   1072 	    xprintf("You have %smail.\n", new ? "new " : "");
   1073 	else
   1074 	    xprintf("%s in %s.\n", new ? "New mail" : "Mail", short2str(*vp));
   1075     }
   1076     chktim = t;
   1077 }
   1078 
   1079 /*
   1080  * Extract a home directory from the password file
   1081  * The argument points to a buffer where the name of the
   1082  * user whose home directory is sought is currently.
   1083  * We write the home directory of the user back there.
   1084  */
   1085 int
   1086 gethdir(home)
   1087     Char   *home;
   1088 {
   1089     Char   *h;
   1090     struct passwd *pw;
   1091 
   1092     /*
   1093      * Is it us?
   1094      */
   1095     if (*home == '\0') {
   1096 	if (h = value(STRhome)) {
   1097 	    (void) Strcpy(home, h);
   1098 	    return 0;
   1099 	}
   1100 	else
   1101 	    return 1;
   1102     }
   1103 
   1104     if (pw = getpwnam(short2str(home))) {
   1105 	(void) Strcpy(home, str2short(pw->pw_dir));
   1106 	return 0;
   1107     }
   1108     else
   1109 	return 1;
   1110 }
   1111 
   1112 /*
   1113  * Move the initial descriptors to their eventual
   1114  * resting places, closin all other units.
   1115  */
   1116 void
   1117 initdesc()
   1118 {
   1119 
   1120     didfds = 0;			/* 0, 1, 2 aren't set up */
   1121     (void) ioctl(SHIN = dcopy(0, FSHIN), FIOCLEX, NULL);
   1122     (void) ioctl(SHOUT = dcopy(1, FSHOUT), FIOCLEX, NULL);
   1123     (void) ioctl(SHDIAG = dcopy(2, FSHDIAG), FIOCLEX, NULL);
   1124     (void) ioctl(OLDSTD = dcopy(SHIN, FOLDSTD), FIOCLEX, NULL);
   1125     closem();
   1126 }
   1127 
   1128 
   1129 void
   1130 #ifdef PROF
   1131 done(i)
   1132 #else
   1133 xexit(i)
   1134 #endif
   1135     int     i;
   1136 {
   1137     untty();
   1138     _exit(i);
   1139 }
   1140 
   1141 static Char **
   1142 defaultpath()
   1143 {
   1144     char   *ptr;
   1145     Char  **blk, **blkp;
   1146     struct stat stb;
   1147 
   1148     blkp = blk = (Char **) xmalloc((size_t) sizeof(Char *) * 10);
   1149 
   1150 #define DIRAPPEND(a)  \
   1151 	if (stat(ptr = a, &stb) == 0 && (stb.st_mode & S_IFMT) == S_IFDIR) \
   1152 		*blkp++ = SAVE(ptr)
   1153 
   1154     DIRAPPEND(_PATH_BIN);
   1155     DIRAPPEND(_PATH_USRBIN);
   1156 
   1157 #undef DIRAPPEND
   1158 
   1159     *blkp++ = Strsave(STRdot);
   1160     *blkp = NULL;
   1161     return (blk);
   1162 }
   1163 
   1164 void
   1165 printprompt()
   1166 {
   1167     register Char *cp;
   1168 
   1169     if (!whyles) {
   1170 	for (cp = value(STRprompt); *cp; cp++)
   1171 	    if (*cp == HIST)
   1172 		xprintf("%d", eventno + 1);
   1173 	    else {
   1174 		if (*cp == '\\' && cp[1] == HIST)
   1175 		    cp++;
   1176 		xputchar(*cp | QUOTE);
   1177 	    }
   1178     }
   1179     else
   1180 	/*
   1181 	 * Prompt for forward reading loop body content.
   1182 	 */
   1183 	xprintf("? ");
   1184     flush();
   1185 }
   1186