xref: /original-bsd/bin/csh/csh.c (revision ed5ac44c)
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.34 (Berkeley) 02/05/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, STRhistfile, 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         if (loginsh)
503 	      (void) srccat(value(STRhome), STRsldotlogin);
504 	dosource(loadhist, NULL);
505     }
506 
507     /*
508      * Now are ready for the -v and -x flags
509      */
510     if (nverbose)
511 	setNS(STRverbose);
512     if (nexececho)
513 	setNS(STRecho);
514 
515     /*
516      * All the rest of the world is inside this call. The argument to process
517      * indicates whether it should catch "error unwinds".  Thus if we are a
518      * interactive shell our call here will never return by being blown past on
519      * an error.
520      */
521     process(setintr);
522 
523     /*
524      * Mop-up.
525      */
526     if (intty) {
527 	if (loginsh) {
528 	    (void) fprintf(cshout, "logout\n");
529 	    (void) close(SHIN);
530 	    child = 1;
531 	    goodbye();
532 	}
533 	else {
534 	    (void) fprintf(cshout, "exit\n");
535 	}
536     }
537     rechist();
538     exitstat();
539     return (0);
540 }
541 
542 void
543 untty()
544 {
545     if (tpgrp > 0) {
546 	(void) setpgid(0, opgrp);
547 	(void) tcsetpgrp(FSHTTY, opgrp);
548     }
549 }
550 
551 void
552 importpath(cp)
553     Char   *cp;
554 {
555     register int i = 0;
556     register Char *dp;
557     register Char **pv;
558     int     c;
559 
560     for (dp = cp; *dp; dp++)
561 	if (*dp == ':')
562 	    i++;
563     /*
564      * i+2 where i is the number of colons in the path. There are i+1
565      * directories in the path plus we need room for a zero terminator.
566      */
567     pv = (Char **) xcalloc((size_t) (i + 2), sizeof(Char **));
568     dp = cp;
569     i = 0;
570     if (*dp)
571 	for (;;) {
572 	    if ((c = *dp) == ':' || c == 0) {
573 		*dp = 0;
574 		pv[i++] = Strsave(*cp ? cp : STRdot);
575 		if (c) {
576 		    cp = dp + 1;
577 		    *dp = ':';
578 		}
579 		else
580 		    break;
581 	    }
582 	    dp++;
583 	}
584     pv[i] = 0;
585     set1(STRpath, pv, &shvhed);
586 }
587 
588 /*
589  * Source to the file which is the catenation of the argument names.
590  */
591 static int
592 srccat(cp, dp)
593     Char   *cp, *dp;
594 {
595     register Char *ep = Strspl(cp, dp);
596     char   *ptr = short2str(ep);
597 
598     xfree((ptr_t) ep);
599     return srcfile(ptr, mflag ? 0 : 1, 0);
600 }
601 
602 /*
603  * Source to a file putting the file descriptor in a safe place (> 2).
604  */
605 static int
606 srcfile(f, onlyown, flag)
607     char   *f;
608     bool    onlyown, flag;
609 {
610     register int unit;
611 
612     if ((unit = open(f, O_RDONLY)) == -1)
613 	return 0;
614     unit = dmove(unit, -1);
615 
616     (void) ioctl(unit, FIOCLEX, NULL);
617     srcunit(unit, onlyown, flag);
618     return 1;
619 }
620 
621 /*
622  * Source to a unit.  If onlyown it must be our file or our group or
623  * we don't chance it.	This occurs on ".cshrc"s and the like.
624  */
625 int     insource;
626 static void
627 srcunit(unit, onlyown, hflg)
628     register int unit;
629     bool    onlyown, hflg;
630 {
631     /* We have to push down a lot of state here */
632     /* All this could go into a structure */
633     int     oSHIN = -1, oldintty = intty, oinsource = insource;
634     struct whyle *oldwhyl = whyles;
635     Char   *ogointr = gointr, *oarginp = arginp;
636     Char   *oevalp = evalp, **oevalvec = evalvec;
637     int     oonelflg = onelflg;
638     bool    oenterhist = enterhist;
639     char    OHIST = HIST;
640     bool    otell = cantell;
641 
642     struct Bin saveB;
643     volatile sigset_t omask;
644     jmp_buf oldexit;
645 
646     /* The (few) real local variables */
647     int     my_reenter;
648 
649     if (unit < 0)
650 	return;
651     if (didfds)
652 	donefds();
653     if (onlyown) {
654 	struct stat stb;
655 
656 	if (fstat(unit, &stb) < 0) {
657 	    (void) close(unit);
658 	    return;
659 	}
660     }
661 
662     /*
663      * There is a critical section here while we are pushing down the input
664      * stream since we have stuff in different structures. If we weren't
665      * careful an interrupt could corrupt SHIN's Bin structure and kill the
666      * shell.
667      *
668      * We could avoid the critical region by grouping all the stuff in a single
669      * structure and pointing at it to move it all at once.  This is less
670      * efficient globally on many variable references however.
671      */
672     insource = 1;
673     getexit(oldexit);
674     omask = 0;
675 
676     if (setintr)
677 	omask = sigblock(sigmask(SIGINT));
678     /* Setup the new values of the state stuff saved above */
679     bcopy((char *) &B, (char *) &(saveB), sizeof(B));
680     fbuf = NULL;
681     fseekp = feobp = fblocks = 0;
682     oSHIN = SHIN, SHIN = unit, arginp = 0, onelflg = 0;
683     intty = isatty(SHIN), whyles = 0, gointr = 0;
684     evalvec = 0;
685     evalp = 0;
686     enterhist = hflg;
687     if (enterhist)
688 	HIST = '\0';
689 
690     /*
691      * Now if we are allowing commands to be interrupted, we let ourselves be
692      * interrupted.
693      */
694     if (setintr)
695 	(void) sigsetmask(omask);
696     settell();
697 
698     if ((my_reenter = setexit()) == 0)
699 	process(0);		/* 0 -> blow away on errors */
700 
701     if (setintr)
702 	(void) sigsetmask(omask);
703     if (oSHIN >= 0) {
704 	register int i;
705 
706 	/* We made it to the new state... free up its storage */
707 	/* This code could get run twice but xfree doesn't care */
708 	for (i = 0; i < fblocks; i++)
709 	    xfree((ptr_t) fbuf[i]);
710 	xfree((ptr_t) fbuf);
711 
712 	/* Reset input arena */
713 	bcopy((char *) &(saveB), (char *) &B, sizeof(B));
714 
715 	(void) close(SHIN), SHIN = oSHIN;
716 	arginp = oarginp, onelflg = oonelflg;
717 	evalp = oevalp, evalvec = oevalvec;
718 	intty = oldintty, whyles = oldwhyl, gointr = ogointr;
719 	if (enterhist)
720 	    HIST = OHIST;
721 	enterhist = oenterhist;
722 	cantell = otell;
723     }
724 
725     resexit(oldexit);
726     /*
727      * If process reset() (effectively an unwind) then we must also unwind.
728      */
729     if (my_reenter)
730 	stderror(ERR_SILENT);
731     insource = oinsource;
732 }
733 
734 void
735 rechist()
736 {
737     Char    buf[BUFSIZ], hbuf[BUFSIZ], *hfile;
738     int     fp, ftmp, oldidfds;
739     struct  varent *shist;
740 
741     if (!fast) {
742 	/*
743 	 * If $savehist is just set, we use the value of $history
744 	 * else we use the value in $savehist
745 	 */
746 	if (shist = adrof(STRsavehist)) {
747 	    if (shist->vec[0][0] != '\0')
748 		(void) Strcpy(hbuf, shist->vec[0]);
749 	    else if ((shist = adrof(STRhistory)) && shist->vec[0][0] != '\0')
750 		(void) Strcpy(hbuf, shist->vec[0]);
751 	    else
752 		return;
753 	}
754 	else
755   	    return;
756 
757   	if ((hfile = value(STRhistfile)) == STRNULL) {
758   	    hfile = Strcpy(buf, value(STRhome));
759   	    (void) Strcat(buf, STRsldthist);
760   	}
761 
762   	if ((fp = creat(short2str(hfile), 0600)) == -1)
763   	    return;
764 
765 	oldidfds = didfds;
766 	didfds = 0;
767 	ftmp = SHOUT;
768 	SHOUT = fp;
769 	dumphist[2] = hbuf;
770 	dohist(dumphist, NULL);
771 	SHOUT = ftmp;
772 	(void) close(fp);
773 	didfds = oldidfds;
774     }
775 }
776 
777 void
778 goodbye()
779 {
780     rechist();
781 
782     if (loginsh) {
783 	(void) signal(SIGQUIT, SIG_IGN);
784 	(void) signal(SIGINT, SIG_IGN);
785 	(void) signal(SIGTERM, SIG_IGN);
786 	setintr = 0;		/* No interrupts after "logout" */
787 	if (!(adrof(STRlogout)))
788 	    set(STRlogout, STRnormal);
789 #ifdef _PATH_DOTLOGOUT
790 	(void) srcfile(_PATH_DOTLOGOUT, 0, 0);
791 #endif
792 	if (adrof(STRhome))
793 	    (void) srccat(value(STRhome), STRsldtlogout);
794     }
795     exitstat();
796 }
797 
798 void
799 exitstat()
800 {
801     Char *s;
802 #ifdef PROF
803     monitor(0);
804 #endif
805     /*
806      * Note that if STATUS is corrupted (i.e. getn bombs) then error will exit
807      * directly because we poke child here. Otherwise we might continue
808      * unwarrantedly (sic).
809      */
810     child = 1;
811     s = value(STRstatus);
812     xexit(s ? getn(s) : 0);
813 }
814 
815 /*
816  * in the event of a HUP we want to save the history
817  */
818 static void
819 phup(sig)
820 int sig;
821 {
822     rechist();
823     xexit(sig);
824 }
825 
826 Char   *jobargv[2] = {STRjobs, 0};
827 
828 /*
829  * Catch an interrupt, e.g. during lexical input.
830  * If we are an interactive shell, we reset the interrupt catch
831  * immediately.  In any case we drain the shell output,
832  * and finally go through the normal error mechanism, which
833  * gets a chance to make the shell go away.
834  */
835 /* ARGSUSED */
836 void
837 pintr(notused)
838 	int notused;
839 {
840     pintr1(1);
841 }
842 
843 void
844 pintr1(wantnl)
845     bool    wantnl;
846 {
847     Char **v;
848     sigset_t omask;
849 
850     omask = sigblock((sigset_t) 0);
851     if (setintr) {
852 	(void) sigsetmask(omask & ~sigmask(SIGINT));
853 	if (pjobs) {
854 	    pjobs = 0;
855 	    (void) fprintf(cshout, "\n");
856 	    dojobs(jobargv, NULL);
857 	    stderror(ERR_NAME | ERR_INTR);
858 	}
859     }
860     (void) sigsetmask(omask & ~sigmask(SIGCHLD));
861     (void) fpurge(cshout);
862     (void) endpwent();
863 
864     /*
865      * If we have an active "onintr" then we search for the label. Note that if
866      * one does "onintr -" then we shan't be interruptible so we needn't worry
867      * about that here.
868      */
869     if (gointr) {
870 	gotolab(gointr);
871 	timflg = 0;
872 	if (v = pargv)
873 	    pargv = 0, blkfree(v);
874 	if (v = gargv)
875 	    gargv = 0, blkfree(v);
876 	reset();
877     }
878     else if (intty && wantnl) {
879 	(void) fputc('\r', cshout);
880 	(void) fputc('\n', cshout);
881     }
882     stderror(ERR_SILENT);
883 }
884 
885 /*
886  * Process is the main driving routine for the shell.
887  * It runs all command processing, except for those within { ... }
888  * in expressions (which is run by a routine evalav in sh.exp.c which
889  * is a stripped down process), and `...` evaluation which is run
890  * also by a subset of this code in sh.glob.c in the routine backeval.
891  *
892  * The code here is a little strange because part of it is interruptible
893  * and hence freeing of structures appears to occur when none is necessary
894  * if this is ignored.
895  *
896  * Note that if catch is not set then we will unwind on any error.
897  * If an end-of-file occurs, we return.
898  */
899 static struct command *savet = NULL;
900 void
901 process(catch)
902     bool    catch;
903 {
904     jmp_buf osetexit;
905     struct command *t = savet;
906 
907     savet = NULL;
908     getexit(osetexit);
909     for (;;) {
910 	pendjob();
911 	paraml.next = paraml.prev = &paraml;
912 	paraml.word = STRNULL;
913 	(void) setexit();
914 	justpr = enterhist;	/* execute if not entering history */
915 
916 	/*
917 	 * Interruptible during interactive reads
918 	 */
919 	if (setintr)
920 	    (void) sigsetmask(sigblock((sigset_t) 0) & ~sigmask(SIGINT));
921 
922 	/*
923 	 * For the sake of reset()
924 	 */
925 	freelex(&paraml);
926 	if (savet)
927 	    freesyn(savet), savet = NULL;
928 
929 	if (haderr) {
930 	    if (!catch) {
931 		/* unwind */
932 		doneinp = 0;
933 		resexit(osetexit);
934 		savet = t;
935 		reset();
936 	    }
937 	    haderr = 0;
938 	    /*
939 	     * Every error is eventually caught here or the shell dies.  It is
940 	     * at this point that we clean up any left-over open files, by
941 	     * closing all but a fixed number of pre-defined files.  Thus
942 	     * routines don't have to worry about leaving files open due to
943 	     * deeper errors... they will get closed here.
944 	     */
945 	    closem();
946 	    continue;
947 	}
948 	if (doneinp) {
949 	    doneinp = 0;
950 	    break;
951 	}
952 	if (chkstop)
953 	    chkstop--;
954 	if (neednote)
955 	    pnote();
956 	if (intty && prompt && evalvec == 0) {
957 	    mailchk();
958 	    /*
959 	     * If we are at the end of the input buffer then we are going to
960 	     * read fresh stuff. Otherwise, we are rereading input and don't
961 	     * need or want to prompt.
962 	     */
963 	    if (aret == F_SEEK && fseekp == feobp)
964 		printprompt();
965 	    (void) fflush(cshout);
966 	}
967 	if (seterr) {
968 	    xfree((ptr_t) seterr);
969 	    seterr = NULL;
970 	}
971 
972 	/*
973 	 * Echo not only on VERBOSE, but also with history expansion. If there
974 	 * is a lexical error then we forego history echo.
975 	 */
976 	if (lex(&paraml) && !seterr && intty || adrof(STRverbose)) {
977 	    prlex(csherr, &paraml);
978 	}
979 
980 	/*
981 	 * The parser may lose space if interrupted.
982 	 */
983 	if (setintr)
984 	    (void) sigblock(sigmask(SIGINT));
985 
986 	/*
987 	 * Save input text on the history list if reading in old history, or it
988 	 * is from the terminal at the top level and not in a loop.
989 	 *
990 	 * PWP: entry of items in the history list while in a while loop is done
991 	 * elsewhere...
992 	 */
993 	if (enterhist || catch && intty && !whyles)
994 	    savehist(&paraml);
995 
996 	/*
997 	 * Print lexical error messages, except when sourcing history lists.
998 	 */
999 	if (!enterhist && seterr)
1000 	    stderror(ERR_OLD);
1001 
1002 	/*
1003 	 * If had a history command :p modifier then this is as far as we
1004 	 * should go
1005 	 */
1006 	if (justpr)
1007 	    reset();
1008 
1009 	alias(&paraml);
1010 
1011 	/*
1012 	 * Parse the words of the input into a parse tree.
1013 	 */
1014 	savet = syntax(paraml.next, &paraml, 0);
1015 	if (seterr)
1016 	    stderror(ERR_OLD);
1017 
1018 	execute(savet, (tpgrp > 0 ? tpgrp : -1), NULL, NULL);
1019 
1020 	/*
1021 	 * Made it!
1022 	 */
1023 	freelex(&paraml);
1024 	freesyn((struct command *) savet), savet = NULL;
1025     }
1026     resexit(osetexit);
1027     savet = t;
1028 }
1029 
1030 void
1031 /*ARGSUSED*/
1032 dosource(v, t)
1033     Char **v;
1034     struct command *t;
1035 
1036 {
1037     register Char *f;
1038     bool    hflg = 0;
1039     Char    buf[BUFSIZ];
1040 
1041     v++;
1042     if (*v && eq(*v, STRmh)) {
1043 	if (*++v == NULL)
1044 	    stderror(ERR_NAME | ERR_HFLAG);
1045 	hflg++;
1046     }
1047     (void) Strcpy(buf, *v);
1048     f = globone(buf, G_ERROR);
1049     (void) strcpy((char *) buf, short2str(f));
1050     xfree((ptr_t) f);
1051     if (!srcfile((char *) buf, 0, hflg) && !hflg)
1052 	stderror(ERR_SYSTEM, (char *) buf, strerror(errno));
1053 }
1054 
1055 /*
1056  * Check for mail.
1057  * If we are a login shell, then we don't want to tell
1058  * about any mail file unless its been modified
1059  * after the time we started.
1060  * This prevents us from telling the user things he already
1061  * knows, since the login program insists on saying
1062  * "You have mail."
1063  */
1064 static void
1065 mailchk()
1066 {
1067     register struct varent *v;
1068     register Char **vp;
1069     time_t  t;
1070     int     intvl, cnt;
1071     struct stat stb;
1072     bool    new;
1073 
1074     v = adrof(STRmail);
1075     if (v == 0)
1076 	return;
1077     (void) time(&t);
1078     vp = v->vec;
1079     cnt = blklen(vp);
1080     intvl = (cnt && number(*vp)) ? (--cnt, getn(*vp++)) : MAILINTVL;
1081     if (intvl < 1)
1082 	intvl = 1;
1083     if (chktim + intvl > t)
1084 	return;
1085     for (; *vp; vp++) {
1086 	if (stat(short2str(*vp), &stb) < 0)
1087 	    continue;
1088 	new = stb.st_mtime > time0.tv_sec;
1089 	if (stb.st_size == 0 || stb.st_atime > stb.st_mtime ||
1090 	    (stb.st_atime < chktim && stb.st_mtime < chktim) ||
1091 	    loginsh && !new)
1092 	    continue;
1093 	if (cnt == 1)
1094 	    (void) fprintf(cshout, "You have %smail.\n", new ? "new " : "");
1095 	else
1096 	    (void) fprintf(cshout, "%s in %s.\n", new ? "New mail" : "Mail",
1097 			   vis_str(*vp));
1098     }
1099     chktim = t;
1100 }
1101 
1102 /*
1103  * Extract a home directory from the password file
1104  * The argument points to a buffer where the name of the
1105  * user whose home directory is sought is currently.
1106  * We write the home directory of the user back there.
1107  */
1108 int
1109 gethdir(home)
1110     Char   *home;
1111 {
1112     Char   *h;
1113     struct passwd *pw;
1114 
1115     /*
1116      * Is it us?
1117      */
1118     if (*home == '\0') {
1119 	if (h = value(STRhome)) {
1120 	    (void) Strcpy(home, h);
1121 	    return 0;
1122 	}
1123 	else
1124 	    return 1;
1125     }
1126 
1127     if (pw = getpwnam(short2str(home))) {
1128 	(void) Strcpy(home, str2short(pw->pw_dir));
1129 	return 0;
1130     }
1131     else
1132 	return 1;
1133 }
1134 
1135 /*
1136  * When didfds is set, we do I/O from 0, 1, 2 otherwise from 15, 16, 17
1137  * We also check if the shell has already changed the decriptor to point to
1138  * 0, 1, 2 when didfds is set.
1139  */
1140 #define DESC(a) (*((int *) (a)) - (didfds && *((int *) a) >= FSHIN ? FSHIN : 0))
1141 
1142 static int
1143 readf(oreo, buf, siz)
1144     void *oreo;
1145     char *buf;
1146     int siz;
1147 {
1148     return read(DESC(oreo), buf, siz);
1149 }
1150 
1151 
1152 static int
1153 writef(oreo, buf, siz)
1154     void *oreo;
1155     const char *buf;
1156     int siz;
1157 {
1158     return write(DESC(oreo), buf, siz);
1159 }
1160 
1161 static fpos_t
1162 seekf(oreo, off, whence)
1163     void *oreo;
1164     fpos_t off;
1165     int whence;
1166 {
1167     return lseek(DESC(oreo), off, whence);
1168 }
1169 
1170 
1171 static int
1172 closef(oreo)
1173     void *oreo;
1174 {
1175     return close(DESC(oreo));
1176 }
1177 
1178 
1179 /*
1180  * Print the visible version of a string.
1181  */
1182 int
1183 vis_fputc(ch, fp)
1184     int ch;
1185     FILE *fp;
1186 {
1187     char uenc[5];	/* 4 + NULL */
1188 
1189     if (ch & QUOTE)
1190 	return fputc(ch & TRIM, fp);
1191     /*
1192      * XXX: When we are in AsciiOnly we want all characters >= 0200 to
1193      * be encoded, but currently there is no way in vis to do that.
1194      */
1195     (void) vis(uenc, ch & TRIM, VIS_NOSLASH, 0);
1196     return fputs(uenc, fp);
1197 }
1198 
1199 /*
1200  * Move the initial descriptors to their eventual
1201  * resting places, closin all other units.
1202  */
1203 void
1204 initdesc()
1205 {
1206 
1207     didfds = 0;			/* 0, 1, 2 aren't set up */
1208     (void) ioctl(SHIN = dcopy(0, FSHIN), FIOCLEX, NULL);
1209     (void) ioctl(SHOUT = dcopy(1, FSHOUT), FIOCLEX, NULL);
1210     (void) ioctl(SHERR = dcopy(2, FSHERR), FIOCLEX, NULL);
1211     (void) ioctl(OLDSTD = dcopy(SHIN, FOLDSTD), FIOCLEX, NULL);
1212     closem();
1213 }
1214 
1215 
1216 void
1217 #ifdef PROF
1218 done(i)
1219 #else
1220 xexit(i)
1221 #endif
1222     int     i;
1223 {
1224     untty();
1225     _exit(i);
1226 }
1227 
1228 static Char **
1229 defaultpath()
1230 {
1231     char   *ptr;
1232     Char  **blk, **blkp;
1233     struct stat stb;
1234 
1235     blkp = blk = (Char **) xmalloc((size_t) sizeof(Char *) * 10);
1236 
1237 #define DIRAPPEND(a)  \
1238 	if (stat(ptr = a, &stb) == 0 && (stb.st_mode & S_IFMT) == S_IFDIR) \
1239 		*blkp++ = SAVE(ptr)
1240 
1241     DIRAPPEND(_PATH_BIN);
1242     DIRAPPEND(_PATH_USRBIN);
1243 
1244 #undef DIRAPPEND
1245 
1246     *blkp++ = Strsave(STRdot);
1247     *blkp = NULL;
1248     return (blk);
1249 }
1250 
1251 void
1252 printprompt()
1253 {
1254     register Char *cp;
1255 
1256     if (!whyles) {
1257 	for (cp = value(STRprompt); *cp; cp++)
1258 	    if (*cp == HIST)
1259 		(void) fprintf(cshout, "%d", eventno + 1);
1260 	    else {
1261 		if (*cp == '\\' && cp[1] == HIST)
1262 		    cp++;
1263 		(void) vis_fputc(*cp | QUOTE, cshout);
1264 	    }
1265     }
1266     else
1267 	/*
1268 	 * Prompt for forward reading loop body content.
1269 	 */
1270 	(void) fprintf(cshout, "? ");
1271     (void) fflush(cshout);
1272 }
1273