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