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