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