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