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