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