xref: /freebsd/contrib/tcsh/sh.c (revision f18976136625a7d016e97bfd9eabddf640b3e06d)
1 /*
2  * sh.c: Main shell routines
3  */
4 /*-
5  * Copyright (c) 1980, 1991 The Regents of the University of California.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 #define EXTERN	/* Intern */
33 #include "sh.h"
34 
35 #ifndef lint
36 char    copyright[] =
37 "@(#) Copyright (c) 1991 The Regents of the University of California.\n\
38  All rights reserved.\n";
39 #endif /* not lint */
40 
41 #include "tc.h"
42 #include "ed.h"
43 #include "tw.h"
44 
45 extern int MapsAreInited;
46 extern int NLSMapsAreInited;
47 
48 /*
49  * C Shell
50  *
51  * Bill Joy, UC Berkeley, California, USA
52  * October 1978, May 1980
53  *
54  * Jim Kulp, IIASA, Laxenburg, Austria
55  * April 1980
56  *
57  * Filename recognition added:
58  * Ken Greer, Ind. Consultant, Palo Alto CA
59  * October 1983.
60  *
61  * Karl Kleinpaste, Computer Consoles, Inc.
62  * Added precmd, periodic/tperiod, prompt changes,
63  * directory stack hack, and login watch.
64  * Sometime March 1983 - Feb 1984.
65  *
66  * Added scheduled commands, including the "sched" command,
67  * plus the call to sched_run near the precmd et al
68  * routines.
69  * Upgraded scheduled events for running events while
70  * sitting idle at command input.
71  *
72  * Paul Placeway, Ohio State
73  * added stuff for running with twenex/inputl  9 Oct 1984.
74  *
75  * ported to Apple Unix (TM) (OREO)  26 -- 29 Jun 1987
76  */
77 
78 jmp_buf_t reslab IZERO_STRUCT;
79 struct wordent paraml IZERO_STRUCT;
80 
81 static const char tcshstr[] = "tcsh";
82 
83 struct sigaction parintr;	/* Parents interrupt catch */
84 struct sigaction parterm;	/* Parents terminate catch */
85 
86 #ifdef TESLA
87 int do_logout = 0;
88 #endif /* TESLA */
89 
90 
91 int    use_fork = 0;		/* use fork() instead of vfork()? */
92 
93 /*
94  * Magic pointer values. Used to specify other invalid conditions aside
95  * from null.
96  */
97 static Char	INVCHAR;
98 Char    *INVPTR = &INVCHAR;
99 Char    **INVPPTR = &INVPTR;
100 
101 static int    fast = 0;
102 static int    mflag = 0;
103 static int    prompt = 1;
104 int     enterhist = 0;
105 int    tellwhat = 0;
106 time_t  t_period;
107 Char  *ffile = NULL;
108 int	dolzero = 0;
109 int	insource = 0;
110 int	exitset = 0;
111 static time_t  chktim;		/* Time mail last checked */
112 char *progname;
113 int tcsh;
114 
115 /*
116  * This preserves the input state of the shell. It is used by
117  * st_save and st_restore to manupulate shell state.
118  */
119 struct saved_state {
120     int		  insource;
121     int		  OLDSTD;
122     int		  SHIN;
123     int		  SHOUT;
124     int		  SHDIAG;
125     int		  intty;
126     struct whyle *whyles;
127     Char 	 *gointr;
128     Char 	 *arginp;
129     Char	 *evalp;
130     Char	**evalvec;
131     Char	 *alvecp;
132     Char	**alvec;
133     int		  onelflg;
134     int	  enterhist;
135     Char	**argv;
136     Char	**av;
137     Char	  HIST;
138     int	  cantell;
139     struct Bin	  B;
140     int		  justpr;
141 };
142 
143 static	int		  srccat	(Char *, Char *);
144 #ifndef WINNT_NATIVE
145 static	int		  srcfile	(const char *, int, int, Char **);
146 #else
147 int		  srcfile	(const char *, int, int, Char **);
148 #endif /*WINNT_NATIVE*/
149 static	void		  srcunit	(int, int, int, Char **);
150 static	void		  mailchk	(void);
151 #ifndef _PATH_DEFPATH
152 static	Char	 	**defaultpath	(void);
153 #endif
154 static	void		  record	(void);
155 static	void		  st_save	(struct saved_state *, int, int,
156 					 Char **, Char **);
157 static	void		  st_restore	(void *);
158 
159 	int		  main		(int, char **);
160 
161 #ifndef LOCALEDIR
162 #define LOCALEDIR "/usr/share/locale"
163 #endif
164 
165 #ifdef NLS_CATALOGS
166 static void
167 add_localedir_to_nlspath(const char *path)
168 {
169     static const char msgs_LOC[] = "/%L/LC_MESSAGES/%N.cat";
170     static const char msgs_lang[] = "/%l/LC_MESSAGES/%N.cat";
171     char *old;
172     char *new, *new_p;
173     size_t len;
174     int add_LOC = 1;
175     int add_lang = 1;
176     char trypath[MAXPATHLEN];
177     struct stat st;
178 
179     if (path == NULL)
180         return;
181 
182     (void) xsnprintf(trypath, sizeof(trypath), "%s/en/LC_MESSAGES/tcsh.cat",
183 	path);
184     if (stat(trypath, &st) == -1)
185 	return;
186 
187     if ((old = getenv("NLSPATH")) != NULL)
188         len = strlen(old) + 1;	/* don't forget the colon. */
189     else
190 	len = 0;
191 
192     len += 2 * strlen(path) +
193 	   sizeof(msgs_LOC) + sizeof(msgs_lang); /* includes the extra colon */
194 
195     new = new_p = xcalloc(len, 1);
196 
197     if (old != NULL) {
198 	size_t pathlen = strlen(path);
199 	char *old_p;
200 
201 	(void) xsnprintf(new_p, len, "%s", old);
202 	new_p += strlen(new_p);
203 	len -= new_p - new;
204 
205 	/* Check if the paths we try to add are already present in NLSPATH.
206 	   If so, note it by setting the appropriate flag to 0. */
207 	for (old_p = old; old_p; old_p = strchr(old_p, ':'),
208 				 old_p = old_p ? old_p + 1 : NULL) {
209 	    if (strncmp(old_p, path, pathlen) != 0)
210 	    	continue;
211 	    if (strncmp(old_p + pathlen, msgs_LOC, sizeof(msgs_LOC) - 1) == 0)
212 		add_LOC = 0;
213 	    else if (strncmp(old_p + pathlen, msgs_lang,
214 			      sizeof(msgs_lang) - 1) == 0)
215 		add_lang = 0;
216 	}
217     }
218 
219     /* Add the message catalog paths not already present to NLSPATH. */
220     if (add_LOC || add_lang)
221 	(void) xsnprintf(new_p, len, "%s%s%s%s%s%s",
222 			 old ? ":" : "",
223 			 add_LOC ? path : "", add_LOC ? msgs_LOC : "",
224 			 add_LOC && add_lang ? ":" : "",
225 			 add_lang ? path : "", add_lang ? msgs_lang : "");
226 
227     tsetenv(STRNLSPATH, str2short(new));
228     free(new);
229 }
230 #endif
231 
232 int
233 main(int argc, char **argv)
234 {
235     int batch = 0;
236     volatile int nexececho = 0;
237     int nofile = 0;
238     volatile int nverbose = 0;
239     volatile int rdirs = 0;
240     int quitit = 0;
241     Char *cp;
242 #ifdef AUTOLOGOUT
243     Char *cp2;
244 #endif
245     char *tcp, *ttyn;
246     int f, reenter;
247     char **tempv;
248     static const char *targinp = NULL;
249     int osetintr;
250     struct sigaction oparintr;
251 
252 #ifdef WINNT_NATIVE
253     nt_init();
254 #endif /* WINNT_NATIVE */
255 
256     (void)memset(&reslab, 0, sizeof(reslab));
257 #if defined(NLS_CATALOGS) && defined(LC_MESSAGES)
258     (void) setlocale(LC_MESSAGES, "");
259 #endif /* NLS_CATALOGS && LC_MESSAGES */
260 
261 #ifdef NLS
262 # ifdef LC_CTYPE
263     (void) setlocale(LC_CTYPE, ""); /* for iscntrl */
264 # endif /* LC_CTYPE */
265 #endif /* NLS */
266 
267     STR_environ = blk2short(environ);
268     environ = short2blk(STR_environ);	/* So that we can free it */
269 
270 #ifdef NLS_CATALOGS
271     add_localedir_to_nlspath(LOCALEDIR);
272 #endif
273 
274     nlsinit();
275     initlex(&paraml);
276 
277 #ifdef MALLOC_TRACE
278     mal_setstatsfile(fdopen(dmove(xopen("/tmp/tcsh.trace",
279 	O_WRONLY|O_CREAT|O_LARGEFILE, 0666), 25), "w"));
280     mal_trace(1);
281 #endif /* MALLOC_TRACE */
282 
283 #if !(defined(BSDTIMES) || defined(_SEQUENT_)) && defined(POSIX)
284 # ifdef _SC_CLK_TCK
285     clk_tck = (clock_t) sysconf(_SC_CLK_TCK);
286 # else /* ! _SC_CLK_TCK */
287 #  ifdef CLK_TCK
288     clk_tck = CLK_TCK;
289 #  else /* !CLK_TCK */
290     clk_tck = HZ;
291 #  endif /* CLK_TCK */
292 # endif /* _SC_CLK_TCK */
293 #endif /* !BSDTIMES && POSIX */
294 
295     settimes();			/* Immed. estab. timing base */
296 #ifdef TESLA
297     do_logout = 0;
298 #endif /* TESLA */
299 
300     /*
301      * Make sure we have 0, 1, 2 open
302      * Otherwise `` jobs will not work... (From knaff@poly.polytechnique.fr)
303      */
304     {
305 	do
306 	    if ((f = xopen(_PATH_DEVNULL, O_RDONLY|O_LARGEFILE)) == -1 &&
307 		(f = xopen("/", O_RDONLY|O_LARGEFILE)) == -1)
308 		exit(1);
309 	while (f < 3);
310 	xclose(f);
311     }
312 
313     osinit();			/* Os dependent initialization */
314 
315 
316     {
317 	char *t;
318 
319 	t = strrchr(argv[0], '/');
320 #ifdef WINNT_NATIVE
321 	{
322 	    char *s = strrchr(argv[0], '\\');
323 	    if (s)
324 		t = s;
325 	}
326 #endif /* WINNT_NATIVE */
327 	t = t ? t + 1 : argv[0];
328 	if (*t == '-') t++;
329 	progname = strsave((t && *t) ? t : tcshstr);    /* never want a null */
330 	tcsh = strncmp(progname, tcshstr, sizeof(tcshstr) - 1) == 0;
331     }
332 
333     /*
334      * Initialize non constant strings
335      */
336 #ifdef _PATH_BSHELL
337     STR_BSHELL = SAVE(_PATH_BSHELL);
338 #endif
339 #ifdef _PATH_TCSHELL
340     STR_SHELLPATH = SAVE(_PATH_TCSHELL);
341 #else
342 # ifdef _PATH_CSHELL
343     STR_SHELLPATH = SAVE(_PATH_CSHELL);
344 # endif
345 #endif
346     STR_WORD_CHARS = SAVE(WORD_CHARS);
347     STR_WORD_CHARS_VI = SAVE(WORD_CHARS_VI);
348 
349     HIST = '!';
350     HISTSUB = '^';
351     PRCH = tcsh ? '>' : '%';	/* to replace %# in $prompt for normal users */
352     PRCHROOT = '#';		/* likewise for root */
353     word_chars = STR_WORD_CHARS;
354     bslash_quote = 0;		/* PWP: do tcsh-style backslash quoting? */
355     anyerror = 1;		/* for compatibility */
356     setcopy(STRanyerror, STRNULL, VAR_READWRITE);
357 
358     /* Default history size to 100 */
359     setcopy(STRhistory, str2short("100"), VAR_READWRITE);
360     sethistory(100);
361 
362     tempv = argv;
363     ffile = SAVE(tempv[0]);
364     dolzero = 0;
365     if (eq(ffile, STRaout))	/* A.out's are quittable */
366 	quitit = 1;
367     uid = getuid();
368     gid = getgid();
369     euid = geteuid();
370     egid = getegid();
371     /*
372      * We are a login shell if: 1. we were invoked as -<something> with
373      * optional arguments 2. or we were invoked only with the -l flag
374      */
375     loginsh = (**tempv == '-') || (argc == 2 &&
376 				   tempv[1][0] == '-' && tempv[1][1] == 'l' &&
377 						tempv[1][2] == '\0');
378 #ifdef _VMS_POSIX
379     /* No better way to find if we are a login shell */
380     if (!loginsh) {
381 	loginsh = (argc == 1 && getppid() == 1);
382 	**tempv = '-';	/* Avoid giving VMS an acidic stomach */
383     }
384 #endif /* _VMS_POSIX */
385 
386     if (loginsh && **tempv != '-') {
387 	char *argv0;
388 
389 	/*
390 	 * Mangle the argv space
391 	 */
392 	tempv[1][0] = '\0';
393 	tempv[1][1] = '\0';
394 	tempv[1] = NULL;
395 	argv0 = strspl("-", *tempv);
396 	*tempv = argv0;
397 	argc--;
398     }
399     if (loginsh) {
400 	(void) time(&chktim);
401 	setNS(STRloginsh);
402     }
403 
404     NoNLSRebind = getenv("NOREBIND") != NULL;
405 #ifdef NLS
406 # ifdef SETLOCALEBUG
407     dont_free = 1;
408 # endif /* SETLOCALEBUG */
409     (void) setlocale(LC_ALL, "");
410 # ifdef LC_COLLATE
411     (void) setlocale(LC_COLLATE, "");
412 # endif
413 # ifdef SETLOCALEBUG
414     dont_free = 0;
415 # endif /* SETLOCALEBUG */
416 # ifdef STRCOLLBUG
417     fix_strcoll_bug();
418 # endif /* STRCOLLBUG */
419 
420     /*
421      * On solaris ISO8859-1 contains no printable characters in the upper half
422      * so we need to test only for MB_CUR_MAX == 1, otherwise for multi-byte
423      * locales we are always AsciiOnly == 0.
424      */
425     if (MB_CUR_MAX == 1) {
426 	int     k;
427 
428 	for (k = 0200; k <= 0377 && !isprint(CTL_ESC(k)); k++)
429 	    continue;
430 	AsciiOnly = k > 0377;
431     } else
432 	AsciiOnly = 0;
433 #else
434     AsciiOnly = getenv("LANG") == NULL && getenv("LC_CTYPE") == NULL;
435 #endif				/* NLS */
436     if (MapsAreInited && !NLSMapsAreInited)
437 	ed_InitNLSMaps();
438     ResetArrowKeys();
439 
440     /*
441      * Initialize for periodic command intervals. Also, initialize the dummy
442      * tty list for login-watch.
443      */
444     (void) time(&t_period);
445 #ifndef HAVENOUTMP
446     initwatch();
447 #endif /* !HAVENOUTMP */
448 
449 #if defined(alliant)
450     /*
451      * From:  Jim Pace <jdp@research.att.com>
452      * tcsh does not work properly on the alliants through an rlogin session.
453      * The shell generally hangs.  Also, reference to the controlling terminal
454      * does not work ( ie: echo foo > /dev/tty ).
455      *
456      * A security feature was added to rlogind affecting FX/80's Concentrix
457      * from revision 5.5.xx upwards (through 5.7 where this fix was implemented)
458      * This security change also affects the FX/2800 series.
459      * The security change to rlogind requires the process group of an rlogin
460      * session become disassociated with the tty in rlogind.
461      *
462      * The changes needed are:
463      * 1. set the process group
464      * 2. reenable the control terminal
465      */
466      if (loginsh && isatty(SHIN)) {
467 	 ttyn = ttyname(SHIN);
468 	 xclose(SHIN);
469 	 SHIN = xopen(ttyn, O_RDWR|O_LARGEFILE);
470 	 shpgrp = getpid();
471 	 (void) ioctl (SHIN, TIOCSPGRP, (ioctl_t) &shpgrp);
472 	 (void) setpgid(0, shpgrp);
473      }
474 #endif /* alliant */
475 
476     /*
477      * Move the descriptors to safe places. The variable didfds is 0 while we
478      * have only FSH* to work with. When didfds is true, we have 0,1,2 and
479      * prefer to use these.
480      */
481     initdesc();
482 
483     cdtohome = 1;
484     setv(STRcdtohome, SAVE(""), VAR_READWRITE);
485 
486     /*
487      * Get and set the tty now
488      */
489     if ((ttyn = ttyname(SHIN)) != NULL) {
490 	/*
491 	 * Could use rindex to get rid of other possible path components, but
492 	 * hpux preserves the subdirectory /pty/ when storing the tty name in
493 	 * utmp, so we keep it too.
494 	 */
495 	if (strncmp(ttyn, "/dev/", 5) == 0)
496 	    setv(STRtty, cp = SAVE(ttyn + 5), VAR_READWRITE);
497 	else
498 	    setv(STRtty, cp = SAVE(ttyn), VAR_READWRITE);
499     }
500     else
501 	setv(STRtty, cp = SAVE(""), VAR_READWRITE);
502 
503     /*
504      * Initialize the shell variables. ARGV and PROMPT are initialized later.
505      * STATUS is also munged in several places. CHILD is munged when
506      * forking/waiting
507      */
508 
509     /*
510      * 7-10-87 Paul Placeway autologout should be set ONLY on login shells and
511      * on shells running as root.  Out of these, autologout should NOT be set
512      * for any psudo-terminals (this catches most window systems) and not for
513      * any terminal running X windows.
514      *
515      * At Ohio State, we have had problems with a user having his X session
516      * drop out from under him (on a Sun) because the shell in his master
517      * xterm timed out and exited.
518      *
519      * Really, this should be done with a program external to the shell, that
520      * watches for no activity (and NO running programs, such as dump) on a
521      * terminal for a long peroid of time, and then SIGHUPS the shell on that
522      * terminal.
523      *
524      * bugfix by Rich Salz <rsalz@PINEAPPLE.BBN.COM>: For root rsh things
525      * allways first check to see if loginsh or really root, then do things
526      * with ttyname()
527      *
528      * Also by Jean-Francois Lamy <lamy%ai.toronto.edu@RELAY.CS.NET>: check the
529      * value of cp before using it! ("root can rsh too")
530      *
531      * PWP: keep the nested ifs; the order of the tests matters and a good
532      * (smart) C compiler might re-arange things wrong.
533      */
534 #ifdef AUTOLOGOUT
535 # ifdef convex
536     if (uid == 0)
537 	/*  root always has a 15 minute autologout  */
538 	setcopy(STRautologout, STRrootdefautologout, VAR_READWRITE);
539     else
540 	if (loginsh)
541 	    /*  users get autologout set to 0  */
542 	    setcopy(STRautologout, STR0, VAR_READWRITE);
543 # else /* convex */
544     if (loginsh || (uid == 0)) {
545 	if (*cp) {
546 	    /* only for login shells or root and we must have a tty */
547 	    if (((cp2 = Strrchr(cp, (Char) '/')) != NULL) &&
548 		(Strncmp(cp, STRptssl, 3) != 0)) {
549 		cp2 = cp2 + 1;
550 	    }
551 	    else
552 		cp2 = cp;
553 	    if (!(((Strncmp(cp2, STRtty, 3) == 0) && Isalpha(cp2[3])) ||
554 	          Strstr(cp, STRptssl) != NULL)) {
555 		if (getenv("DISPLAY") == NULL) {
556 		    /* NOT on X window shells */
557 		    setcopy(STRautologout, STRdefautologout, VAR_READWRITE);
558 		}
559 	    }
560 	}
561     }
562 # endif /* convex */
563 #endif /* AUTOLOGOUT */
564 
565     sigset_interrupting(SIGALRM, queue_alrmcatch);
566 
567     setcopy(STRstatus, STR0, VAR_READWRITE);
568 
569     /*
570      * get and set machine specific environment variables
571      */
572     getmachine();
573 
574 
575     /*
576      * Publish the selected echo style
577      */
578 #if ECHO_STYLE != BSD_ECHO
579     if (tcsh) {
580 # if ECHO_STYLE == NONE_ECHO
581 	setcopy(STRecho_style, STRnone, VAR_READWRITE);
582 # endif /* ECHO_STYLE == NONE_ECHO */
583 # if ECHO_STYLE == SYSV_ECHO
584 	setcopy(STRecho_style, STRsysv, VAR_READWRITE);
585 # endif /* ECHO_STYLE == SYSV_ECHO */
586 # if ECHO_STYLE == BOTH_ECHO
587 	setcopy(STRecho_style, STRboth, VAR_READWRITE);
588 # endif /* ECHO_STYLE == BOTH_ECHO */
589     } else
590 #endif /* ECHO_STYLE != BSD_ECHO */
591 	setcopy(STRecho_style, STRbsd, VAR_READWRITE);
592 
593     /*
594      * increment the shell level.
595      */
596     shlvl(1);
597 
598 #ifdef __ANDROID__
599     /* On Android, $HOME either isn't set or set to /data, a R/O location.
600        Check for the environment variable EXTERNAL_STORAGE, which contains
601        the mount point of the external storage (SD card, mostly).  If
602        EXTERNAL_STORAGE isn't set fall back to "/sdcard".  Eventually
603        override $HOME so the environment is on the same page. */
604     if (((tcp = getenv("HOME")) != NULL && strcmp (tcp, "/data") != 0)
605 	|| (tcp = getenv("EXTERNAL_STORAGE")) != NULL) {
606 	cp = quote(SAVE(tcp));
607     } else
608 	cp = quote(SAVE("/sdcard"));
609     tsetenv(STRKHOME, cp);
610 #else
611     if ((tcp = getenv("HOME")) != NULL)
612 	cp = quote(SAVE(tcp));
613     else
614 	cp = NULL;
615 #endif
616 
617     if (cp == NULL)
618 	fast = 1;		/* No home -> can't read scripts */
619     else
620 	setv(STRhome, cp, VAR_READWRITE);
621 
622     dinit(cp);			/* dinit thinks that HOME == cwd in a login
623 				 * shell */
624     /*
625      * Grab other useful things from the environment. Should we grab
626      * everything??
627      */
628     {
629 	char *cln, *cus, *cgr;
630 	struct passwd *pw;
631 	struct group *gr;
632 
633 
634 #ifdef apollo
635 	int     oid = getoid();
636 
637 	setv(STRoid, Itoa(oid, 0, 0), VAR_READWRITE);
638 #endif /* apollo */
639 
640 	setv(STReuid, Itoa(euid, 0, 0), VAR_READWRITE);
641 	if ((pw = xgetpwuid(euid)) == NULL)
642 	    setcopy(STReuser, STRunknown, VAR_READWRITE);
643 	else
644 	    setcopy(STReuser, str2short(pw->pw_name), VAR_READWRITE);
645 
646 	setv(STRuid, Itoa(uid, 0, 0), VAR_READWRITE);
647 
648 	setv(STRgid, Itoa(gid, 0, 0), VAR_READWRITE);
649 
650 	cln = getenv("LOGNAME");
651 	cus = getenv("USER");
652 	if (cus != NULL)
653 	    setv(STRuser, quote(SAVE(cus)), VAR_READWRITE);
654 	else if (cln != NULL)
655 	    setv(STRuser, quote(SAVE(cln)), VAR_READWRITE);
656 	else if ((pw = xgetpwuid(uid)) == NULL)
657 	    setcopy(STRuser, STRunknown, VAR_READWRITE);
658 	else
659 	    setcopy(STRuser, str2short(pw->pw_name), VAR_READWRITE);
660 	if (cln == NULL)
661 	    tsetenv(STRLOGNAME, varval(STRuser));
662 	if (cus == NULL)
663 	    tsetenv(STRKUSER, varval(STRuser));
664 
665 	cgr = getenv("GROUP");
666 	if (cgr != NULL)
667 	    setv(STRgroup, quote(SAVE(cgr)), VAR_READWRITE);
668 	else if ((gr = xgetgrgid(gid)) == NULL)
669 	    setcopy(STRgroup, STRunknown, VAR_READWRITE);
670 	else
671 	    setcopy(STRgroup, str2short(gr->gr_name), VAR_READWRITE);
672 	if (cgr == NULL)
673 	    tsetenv(STRKGROUP, varval(STRgroup));
674     }
675 
676     /*
677      * HOST may be wrong, since rexd transports the entire environment on sun
678      * 3.x Just set it again
679      */
680     {
681 	char    cbuff[MAXHOSTNAMELEN];
682 
683 	if (gethostname(cbuff, sizeof(cbuff)) >= 0) {
684 	    cbuff[sizeof(cbuff) - 1] = '\0';	/* just in case */
685 	    tsetenv(STRHOST, str2short(cbuff));
686 	}
687 	else
688 	    tsetenv(STRHOST, STRunknown);
689     }
690 
691 
692 #ifdef REMOTEHOST
693     /*
694      * Try to determine the remote host we were logged in from.
695      */
696     remotehost();
697 #endif /* REMOTEHOST */
698 
699 #ifdef apollo
700     if ((tcp = getenv("SYSTYPE")) == NULL)
701 	tcp = "bsd4.3";
702     tsetenv(STRSYSTYPE, quote(str2short(tcp)));
703 #endif /* apollo */
704 
705     /*
706      * set editing on by default, unless running under Emacs as an inferior
707      * shell.
708      * We try to do this intelligently. If $TERM is available, then it
709      * should determine if we should edit or not. $TERM is preserved
710      * across rlogin sessions, so we will not get confused if we rlogin
711      * under an emacs shell. Another advantage is that if we run an
712      * xterm under an emacs shell, then the $TERM will be set to
713      * xterm, so we are going to want to edit. Unfortunately emacs
714      * does not restore all the tty modes, so xterm is not very well
715      * set up. But this is not the shell's fault.
716      * Also don't edit if $TERM == wm, for when we're running under an ATK app.
717      * Finally, emacs compiled under terminfo, sets the terminal to dumb,
718      * so disable editing for that too.
719      *
720      * Unfortunately, in some cases the initial $TERM setting is "unknown",
721      * "dumb", or "network" which is then changed in the user's startup files.
722      * We fix this by setting noediting here if $TERM is unknown/dumb and
723      * if noediting is set, we switch on editing if $TERM is changed.
724      */
725     if ((tcp = getenv("TERM")) != NULL) {
726 	setv(STRterm, quote(SAVE(tcp)), VAR_READWRITE);
727 	noediting = strcmp(tcp, "unknown") == 0 || strcmp(tcp, "dumb") == 0 ||
728 		    strcmp(tcp, "network") == 0;
729 	editing = strcmp(tcp, "emacs") != 0 && strcmp(tcp, "wm") != 0 &&
730 		  !noediting;
731     }
732     else {
733 	noediting = 0;
734 	editing = ((tcp = getenv("EMACS")) == NULL || strcmp(tcp, "t") != 0);
735     }
736 
737     /*
738      * The 'edit' variable is either set or unset.  It doesn't
739      * need a value.  Making it 'emacs' might be confusing.
740      */
741     if (editing)
742 	setNS(STRedit);
743 
744 
745     /*
746      * still more mutability: make the complete routine automatically add the
747      * suffix of file names...
748      */
749     setNS(STRaddsuffix);
750 
751     /*
752      * Compatibility with tcsh >= 6.12 by default
753      */
754     setNS(STRcsubstnonl);
755 
756     /*
757      * Random default kill ring size
758      */
759     setcopy(STRkillring, str2short("30"), VAR_READWRITE);
760 
761     /*
762      * Re-initialize path if set in environment
763      */
764     if ((tcp = getenv("PATH")) == NULL)
765 #ifdef _PATH_DEFPATH
766 	importpath(str2short(_PATH_DEFPATH));
767 #else /* !_PATH_DEFPATH */
768 	setq(STRpath, defaultpath(), &shvhed, VAR_READWRITE);
769 #endif /* _PATH_DEFPATH */
770     else
771 	/* Importpath() allocates memory for the path, and the
772 	 * returned pointer from SAVE() was discarded, so
773 	 * this was a memory leak.. (sg)
774 	 *
775 	 * importpath(SAVE(tcp));
776 	 */
777 	importpath(str2short(tcp));
778 
779 
780     {
781 	/* If the SHELL environment variable ends with "tcsh", set
782 	 * STRshell to the same path.  This is to facilitate using
783 	 * the executable in environments where the compiled-in
784 	 * default isn't appropriate (sg).
785 	 */
786 
787 	size_t sh_len = 0;
788 
789 	if ((tcp = getenv("SHELL")) != NULL) {
790 	    sh_len = strlen(tcp);
791 	    if ((sh_len >= 5 && strcmp(tcp + (sh_len - 5), "/tcsh") == 0) ||
792 	        (!tcsh && sh_len >= 4 && strcmp(tcp + (sh_len - 4), "/csh") == 0))
793 		setv(STRshell, quote(SAVE(tcp)), VAR_READWRITE);
794 	    else
795 		sh_len = 0;
796 	}
797 	if (sh_len == 0)
798 	    setcopy(STRshell, STR_SHELLPATH, VAR_READWRITE);
799     }
800 
801 #ifdef _OSD_POSIX  /* BS2000 needs this variable set to "SHELL" */
802     if ((tcp = getenv("PROGRAM_ENVIRONMENT")) == NULL)
803 	tcp = "SHELL";
804     tsetenv(STRPROGRAM_ENVIRONMENT, quote(str2short(tcp)));
805 #endif /* _OSD_POSIX */
806 
807 #ifdef COLOR_LS_F
808     if ((tcp = getenv("LS_COLORS")) != NULL)
809 	parseLS_COLORS(str2short(tcp));
810     if ((tcp = getenv("LSCOLORS")) != NULL)
811 	parseLSCOLORS(str2short(tcp));
812 #endif /* COLOR_LS_F */
813 
814     mainpid = getpid();
815     doldol = putn((tcsh_number_t)mainpid);	/* For $$ */
816 #ifdef WINNT_NATIVE
817     {
818 	char *tmp;
819 	Char *tmp2;
820 	if ((tmp = getenv("TMP")) != NULL) {
821 	    tmp = xasprintf("%s/%s", tmp, "sh");
822 	    tmp2 = SAVE(tmp);
823 	    xfree(tmp);
824 	}
825 	else {
826 	    tmp2 = SAVE("");
827 	}
828 	shtemp = Strspl(tmp2, doldol);	/* For << */
829 	xfree(tmp2);
830     }
831 #else /* !WINNT_NATIVE */
832 #ifdef HAVE_MKSTEMP
833     {
834 	const char *tmpdir = getenv ("TMPDIR");
835 	if (!tmpdir)
836 	    tmpdir = "/tmp";
837 	shtemp = Strspl(SAVE(tmpdir), SAVE("/sh" TMP_TEMPLATE)); /* For << */
838     }
839 #else /* !HAVE_MKSTEMP */
840     shtemp = Strspl(STRtmpsh, doldol);	/* For << */
841 #endif /* HAVE_MKSTEMP */
842 #endif /* WINNT_NATIVE */
843 
844     /*
845      * Record the interrupt states from the parent process. If the parent is
846      * non-interruptible our hand must be forced or we (and our children) won't
847      * be either. Our children inherit termination from our parent. We catch it
848      * only if we are the login shell.
849      */
850     sigaction(SIGINT, NULL, &parintr);
851     sigaction(SIGTERM, NULL, &parterm);
852 
853 
854 #ifdef TCF
855     /* Enable process migration on ourselves and our progeny */
856     (void) signal(SIGMIGRATE, SIG_DFL);
857 #endif /* TCF */
858 
859     /*
860      * dspkanji/dspmbyte autosetting
861      */
862     /* PATCH IDEA FROM Issei.Suzuki VERY THANKS */
863 #if defined(DSPMBYTE)
864 #if defined(NLS) && defined(LC_CTYPE)
865     if (((tcp = setlocale(LC_CTYPE, NULL)) != NULL || (tcp = getenv("LANG")) != NULL) && !adrof(CHECK_MBYTEVAR))
866 #else
867     if ((tcp = getenv("LANG")) != NULL && !adrof(CHECK_MBYTEVAR))
868 #endif
869     {
870 	autoset_dspmbyte(str2short(tcp));
871     }
872 #if defined(WINNT_NATIVE)
873     else if (!adrof(CHECK_MBYTEVAR))
874       nt_autoset_dspmbyte();
875 #endif /* WINNT_NATIVE */
876 #endif
877 #if defined(AUTOSET_KANJI)
878 # if defined(NLS) && defined(LC_CTYPE)
879     if (setlocale(LC_CTYPE, NULL) != NULL || getenv("LANG") != NULL)
880 # else
881     if (getenv("LANG") != NULL)
882 # endif
883 	autoset_kanji();
884 #endif /* AUTOSET_KANJI */
885     fix_version();		/* publish the shell version */
886 
887     if (argc > 1 && strcmp(argv[1], "--version") == 0) {
888 	xprintf("%S\n", varval(STRversion));
889 	xexit(0);
890     }
891     if (argc > 1 && strcmp(argv[1], "--help") == 0) {
892 	xprintf("%S\n\n", varval(STRversion));
893 	xprintf("%s", CGETS(11, 8, HELP_STRING));
894 	xexit(0);
895     }
896     /*
897      * Process the arguments.
898      *
899      * Note that processing of -v/-x is actually delayed till after script
900      * processing.
901      *
902      * We set the first character of our name to be '-' if we are a shell
903      * running interruptible commands.  Many programs which examine ps'es
904      * use this to filter such shells out.
905      */
906     argc--, tempv++;
907     while (argc > 0 && (tcp = tempv[0])[0] == '-' &&
908 	   *++tcp != '\0' && !batch) {
909 	do
910 	    switch (*tcp++) {
911 
912 	    case 0:		/* -	Interruptible, no prompt */
913 		prompt = 0;
914 		setintr = 1;
915 		nofile = 1;
916 		break;
917 
918 	    case 'b':		/* -b	Next arg is input file */
919 		batch = 1;
920 		break;
921 
922 	    case 'c':		/* -c	Command input from arg */
923 		if (argc == 1)
924 		    xexit(0);
925 		argc--, tempv++;
926 #ifdef M_XENIX
927 		/* Xenix Vi bug:
928 		   it relies on a 7 bit environment (/bin/sh), so it
929 		   pass ascii arguments with the 8th bit set */
930 		if (!strcmp(argv[0], "sh"))
931 		  {
932 		    char *p;
933 
934 		    for (p = tempv[0]; *p; ++p)
935 		      *p &= ASCII;
936 		  }
937 #endif
938 		targinp = tempv[0];
939 		prompt = 0;
940 		nofile = 1;
941 		break;
942 	    case 'd':		/* -d	Load directory stack from file */
943 		rdirs = 1;
944 		break;
945 
946 #ifdef apollo
947 	    case 'D':		/* -D	Define environment variable */
948 		{
949 		    Char *dp;
950 
951 		    cp = str2short(tcp);
952 		    if (dp = Strchr(cp, '=')) {
953 			*dp++ = '\0';
954 			tsetenv(cp, dp);
955 		    }
956 		    else
957 			tsetenv(cp, STRNULL);
958 		}
959 		*tcp = '\0'; 	/* done with this argument */
960 		break;
961 #endif /* apollo */
962 
963 	    case 'e':		/* -e	Exit on any error */
964 		exiterr = 1;
965 		break;
966 
967 	    case 'f':		/* -f	Fast start */
968 		fast = 1;
969 		break;
970 
971 	    case 'i':		/* -i	Interactive, even if !intty */
972 		intact = 1;
973 		nofile = 1;
974 		break;
975 
976 	    case 'm':		/* -m	read .cshrc (from su) */
977 		mflag = 1;
978 		break;
979 
980 	    case 'n':		/* -n	Don't execute */
981 		noexec = 1;
982 		break;
983 
984 	    case 'q':		/* -q	(Undoc'd) ... die on quit */
985 		quitit = 1;
986 		break;
987 
988 	    case 's':		/* -s	Read from std input */
989 		nofile = 1;
990 		break;
991 
992 	    case 't':		/* -t	Read one line from input */
993 		onelflg = 2;
994 		prompt = 0;
995 		nofile = 1;
996 		break;
997 
998 	    case 'v':		/* -v	Echo hist expanded input */
999 		nverbose = 1;	/* ... later */
1000 		break;
1001 
1002 	    case 'x':		/* -x	Echo just before execution */
1003 		nexececho = 1;	/* ... later */
1004 		break;
1005 
1006 	    case 'V':		/* -V	Echo hist expanded input */
1007 		setNS(STRverbose);	/* NOW! */
1008 		break;
1009 
1010 	    case 'X':		/* -X	Echo just before execution */
1011 		setNS(STRecho);	/* NOW! */
1012 		break;
1013 
1014 	    case 'F':
1015 		/*
1016 		 * This will cause children to be created using fork instead of
1017 		 * vfork.
1018 		 */
1019 		use_fork = 1;
1020 		break;
1021 
1022 	    case ' ':
1023 	    case '\t':
1024 	    case '\r':
1025 	    case '\n':
1026 		/*
1027 		 * for O/S's that don't do the argument parsing right in
1028 		 * "#!/foo -f " scripts
1029 		 */
1030 		break;
1031 
1032 	    default:		/* Unknown command option */
1033 		exiterr = 1;
1034 		stderror(ERR_TCSHUSAGE, tcp-1, progname);
1035 		break;
1036 
1037 	} while (*tcp);
1038 	tempv++, argc--;
1039     }
1040 
1041     if (quitit)			/* With all due haste, for debugging */
1042 	(void) signal(SIGQUIT, SIG_DFL);
1043 
1044     /*
1045      * Unless prevented by -, -c, -i, -s, or -t, if there are remaining
1046      * arguments the first of them is the name of a shell file from which to
1047      * read commands.
1048      */
1049     if (nofile == 0 && argc > 0) {
1050 	nofile = xopen(tempv[0], O_RDONLY|O_LARGEFILE);
1051 	if (nofile < 0) {
1052 	    child = 1;		/* So this ... */
1053 	    /* ... doesn't return */
1054 	    stderror(ERR_SYSTEM, tempv[0], strerror(errno));
1055 	}
1056 	xfree(ffile);
1057 	dolzero = 1;
1058 	ffile = SAVE(tempv[0]);
1059 	/*
1060 	 * Replace FSHIN. Handle /dev/std{in,out,err} specially
1061 	 * since once they are closed we cannot open them again.
1062 	 * In that case we use our own saved descriptors
1063 	 */
1064 	if ((SHIN = dmove(nofile, FSHIN)) < 0)
1065 	    switch(nofile) {
1066 	    case 0:
1067 		SHIN = FSHIN;
1068 		break;
1069 	    case 1:
1070 		SHIN = FSHOUT;
1071 		break;
1072 	    case 2:
1073 		SHIN = FSHDIAG;
1074 		break;
1075 	    default:
1076 		stderror(ERR_SYSTEM, tempv[0], strerror(errno));
1077 		break;
1078 	    }
1079 	(void) close_on_exec(SHIN, 1);
1080 	prompt = 0;
1081 	 /* argc not used any more */ tempv++;
1082     }
1083 
1084     /*
1085      * Call to closem() used to be part of initdesc(). Now called below where
1086      * the script name argument has become stdin. Kernel may have used a file
1087      * descriptor to hold the name of the script (setuid case) and this name
1088      * mustn't be lost by closing the fd too soon.
1089      */
1090     closem();
1091 
1092     /*
1093      * Consider input a tty if it really is or we are interactive. but not for
1094      * editing (christos)
1095      */
1096     if (!(intty = isatty(SHIN))) {
1097 	if (adrof(STRedit))
1098 	    unsetv(STRedit);
1099 	editing = 0;
1100     }
1101     intty |= intact;
1102 #ifndef convex
1103     if (intty || (intact && isatty(SHOUT))) {
1104 	if (!batch && (uid != euid || gid != egid)) {
1105 	    errno = EACCES;
1106 	    child = 1;		/* So this ... */
1107 	    /* ... doesn't return */
1108 	    stderror(ERR_SYSTEM, progname, strerror(errno));
1109 	}
1110     }
1111 #endif /* convex */
1112     isoutatty = isatty(SHOUT);
1113     isdiagatty = isatty(SHDIAG);
1114     /*
1115      * Decide whether we should play with signals or not. If we are explicitly
1116      * told (via -i, or -) or we are a login shell (arg0 starts with -) or the
1117      * input and output are both the ttys("csh", or "csh</dev/ttyx>/dev/ttyx")
1118      * Note that in only the login shell is it likely that parent may have set
1119      * signals to be ignored
1120      */
1121     if (loginsh || intact || (intty && isatty(SHOUT)))
1122 	setintr = 1;
1123     settell();
1124     /*
1125      * Save the remaining arguments in argv.
1126      */
1127     setq(STRargv, blk2short(tempv), &shvhed, VAR_READWRITE);
1128 
1129     /*
1130      * Set up the prompt.
1131      */
1132     if (prompt) {
1133 	setcopy(STRprompt, STRdefprompt, VAR_READWRITE);
1134 	/* that's a meta-questionmark */
1135 	setcopy(STRprompt2, STRmquestion, VAR_READWRITE);
1136 	setcopy(STRprompt3, STRKCORRECT, VAR_READWRITE);
1137     }
1138 
1139     /*
1140      * If we are an interactive shell, then start fiddling with the signals;
1141      * this is a tricky game.
1142      */
1143     shpgrp = mygetpgrp();
1144     opgrp = tpgrp = -1;
1145     if (setintr) {
1146 	struct sigaction osig;
1147 
1148 	**argv = '-';
1149 	if (!quitit)		/* Wary! */
1150 	    (void) signal(SIGQUIT, SIG_IGN);
1151 	pintr_disabled = 1;
1152 	sigset_interrupting(SIGINT, queue_pintr);
1153 	(void) signal(SIGTERM, SIG_IGN);
1154 
1155 	/*
1156 	 * No reason I can see not to save history on all these events..
1157 	 * Most usual occurrence is in a window system, where we're not a login
1158 	 * shell, but might as well be... (sg)
1159 	 * But there might be races when lots of shells exit together...
1160 	 * [this is also incompatible].
1161 	 * We have to be mre careful here. If the parent wants to
1162 	 * ignore the signals then we leave them untouched...
1163 	 * We also only setup the handlers for shells that are trully
1164 	 * interactive.
1165 	 */
1166 	sigaction(SIGHUP, NULL, &osig);
1167 	if (loginsh || osig.sa_handler != SIG_IGN)
1168 	    /* exit processing on HUP */
1169 	    sigset_interrupting(SIGHUP, queue_phup);
1170 #ifdef SIGXCPU
1171 	sigaction(SIGXCPU, NULL, &osig);
1172 	if (loginsh || osig.sa_handler != SIG_IGN)
1173 	    /* exit processing on XCPU */
1174 	    sigset_interrupting(SIGXCPU, queue_phup);
1175 #endif
1176 #ifdef SIGXFSZ
1177 	sigaction(SIGXFSZ, NULL, &osig);
1178 	if (loginsh || osig.sa_handler != SIG_IGN)
1179 	    /* exit processing on XFSZ */
1180 	    sigset_interrupting(SIGXFSZ, queue_phup);
1181 #endif
1182 
1183 	if (quitit == 0 && targinp == 0) {
1184 #ifdef SIGTSTP
1185 	    (void) signal(SIGTSTP, SIG_IGN);
1186 #endif
1187 #ifdef SIGTTIN
1188 	    (void) signal(SIGTTIN, SIG_IGN);
1189 #endif
1190 #ifdef SIGTTOU
1191 	    (void) signal(SIGTTOU, SIG_IGN);
1192 #endif
1193 	    /*
1194 	     * Wait till in foreground, in case someone stupidly runs csh &
1195 	     * dont want to try to grab away the tty.
1196 	     */
1197 	    if (isatty(FSHDIAG))
1198 		f = FSHDIAG;
1199 	    else if (isatty(FSHOUT))
1200 		f = FSHOUT;
1201 	    else if (isatty(OLDSTD))
1202 		f = OLDSTD;
1203 	    else
1204 		f = -1;
1205 
1206 #ifdef NeXT
1207 	    /* NeXT 2.0 /usr/etc/rlogind, does not set our process group! */
1208 	    if (f != -1 && shpgrp == 0) {
1209 	        shpgrp = getpid();
1210 		(void) setpgid(0, shpgrp);
1211 	        (void) tcsetpgrp(f, shpgrp);
1212 	    }
1213 #endif /* NeXT */
1214 #ifdef BSDJOBS			/* if we have tty job control */
1215 	    if (f != -1 && grabpgrp(f, shpgrp) != -1) {
1216 		/*
1217 		 * Thanks to Matt Day for the POSIX references, and to
1218 		 * Paul Close for the SGI clarification.
1219 		 */
1220 		if (setdisc(f) != -1) {
1221 		    opgrp = shpgrp;
1222 		    shpgrp = getpid();
1223 		    tpgrp = shpgrp;
1224 		    if (tcsetpgrp(f, shpgrp) == -1) {
1225 			/*
1226 			 * On hpux 7.03 this fails with EPERM. This happens on
1227 			 * the 800 when opgrp != shpgrp at this point. (we were
1228 			 * forked from a non job control shell)
1229 			 * POSIX 7.2.4, says we failed because the process
1230 			 * group specified did not belong to a process
1231 			 * in the same session with the tty. So we set our
1232 			 * process group and try again.
1233 			 */
1234 			if (setpgid(0, shpgrp) == -1) {
1235 			    xprintf("setpgid:");
1236 			    goto notty;
1237 			}
1238 			if (tcsetpgrp(f, shpgrp) == -1) {
1239 			    xprintf("tcsetpgrp:");
1240 			    goto notty;
1241 			}
1242 		    }
1243 		    /*
1244 		     * We check the process group now. If it is the same, then
1245 		     * we don't need to set it again. On hpux 7.0 on the 300's
1246 		     * if we set it again it fails with EPERM. This is the
1247 		     * correct behavior according to POSIX 4.3.3 if the process
1248 		     * was a session leader .
1249 		     */
1250 		    else if (shpgrp != mygetpgrp()) {
1251 			if(setpgid(0, shpgrp) == -1) {
1252 			    xprintf("setpgid:");
1253 			    goto notty;
1254 			}
1255 		    }
1256 #ifdef IRIS4D
1257 		    /*
1258 		     * But on irix 3.3 we need to set it again, even if it is
1259 		     * the same. We do that to tell the system that we
1260 		     * need BSD process group compatibility.
1261 		     */
1262 		    else
1263 			(void) setpgid(0, shpgrp);
1264 #endif
1265 		    (void) close_on_exec(dcopy(f, FSHTTY), 1);
1266 		}
1267 		else
1268 		    tpgrp = -1;
1269 	    }
1270 	    if (tpgrp == -1) {
1271 	notty:
1272 	        xprintf(CGETS(11, 1, "Warning: no access to tty (%s).\n"),
1273 		    strerror(errno));
1274 		xprintf("%s",
1275 		    CGETS(11, 2, "Thus no job control in this shell.\n"));
1276 		/*
1277 		 * Fix from:Sakari Jalovaara <sja@sirius.hut.fi> if we don't
1278 		 * have access to tty, disable editing too
1279 		 */
1280 		if (adrof(STRedit))
1281 		    unsetv(STRedit);
1282 		editing = 0;
1283 	    }
1284 #else	/* BSDJOBS */		/* don't have job control, so frotz it */
1285 	    tpgrp = -1;
1286 #endif				/* BSDJOBS */
1287 	}
1288     }
1289     if (setintr == 0 && parintr.sa_handler == SIG_DFL)
1290 	setintr = 1;
1291 
1292 /*
1293  * SVR4 doesn't send a SIGCHLD when a child is stopped or continued if the
1294  * handler is installed with signal(2) or sigset(2).  sigaction(2) must
1295  * be used instead.
1296  *
1297  * David Dawes (dawes@physics.su.oz.au) Sept 1991
1298  */
1299     sigset_interrupting(SIGCHLD, queue_pchild);
1300 
1301     if (intty && !targinp)
1302 	(void) ed_Setup(editing);/* Get the tty state, and set defaults */
1303 				 /* Only alter the tty state if editing */
1304 
1305     /*
1306      * Set an exit here in case of an interrupt or error reading the shell
1307      * start-up scripts.
1308      */
1309     osetintr = setintr;
1310     oparintr = parintr;
1311     (void)cleanup_push_mark(); /* There is no outer handler */
1312     if (setexit() != 0) /* PWP */
1313 	reenter = 1;
1314     else
1315 	reenter = 0;
1316     exitset++;
1317     haderr = 0;			/* In case second time through */
1318     if (!fast && reenter == 0) {
1319 	/* Will have varval(STRhome) here because set fast if don't */
1320 	{
1321 	    pintr_disabled++;
1322 	    cleanup_push(&pintr_disabled, disabled_cleanup);
1323 	    setintr = 0;/*FIXRESET:cleanup*/
1324 	    /* onintr in /etc/ files has no effect */
1325 	    parintr.sa_handler = SIG_IGN;/*FIXRESET: cleanup*/
1326 #ifdef LOGINFIRST
1327 #ifdef _PATH_DOTLOGIN
1328 	    if (loginsh)
1329 		(void) srcfile(_PATH_DOTLOGIN, 0, 0, NULL);
1330 #endif
1331 #endif
1332 
1333 #ifdef _PATH_DOTCSHRC
1334 	    (void) srcfile(_PATH_DOTCSHRC, 0, 0, NULL);
1335 #endif
1336 	    if (!targinp && !onelflg && !havhash)
1337 		dohash(NULL,NULL);
1338 #ifndef LOGINFIRST
1339 #ifdef _PATH_DOTLOGIN
1340 	    if (loginsh)
1341 		(void) srcfile(_PATH_DOTLOGIN, 0, 0, NULL);
1342 #endif
1343 #endif
1344 	    cleanup_until(&pintr_disabled);
1345 	    setintr = osetintr;
1346 	    parintr = oparintr;
1347 	}
1348 #ifdef LOGINFIRST
1349 	if (loginsh)
1350 	    (void) srccat(varval(STRhome), STRsldotlogin);
1351 #endif
1352 	/* upward compat. */
1353 	if (!srccat(varval(STRhome), STRsldottcshrc))
1354 	    (void) srccat(varval(STRhome), STRsldotcshrc);
1355 
1356 	if (!targinp && !onelflg && !havhash)
1357 	    dohash(NULL,NULL);
1358 
1359 	/*
1360 	 * Source history before .login so that it is available in .login
1361 	 */
1362 	loadhist(NULL, 0);
1363 #ifndef LOGINFIRST
1364 	if (loginsh)
1365 	    (void) srccat(varval(STRhome), STRsldotlogin);
1366 #endif
1367 	if (loginsh || rdirs)
1368 	    loaddirs(NULL);
1369     }
1370     /* Reset interrupt flag */
1371     setintr = osetintr;
1372     parintr = oparintr;
1373     exitset--;
1374 
1375     /* Initing AFTER .cshrc is the Right Way */
1376     if (intty && !targinp) {	/* PWP setup stuff */
1377 	ed_Init();		/* init the new line editor */
1378 #ifdef SIG_WINDOW
1379 	check_window_size(1);	/* mung environment */
1380 #endif				/* SIG_WINDOW */
1381     }
1382 
1383     /*
1384      * Now are ready for the -v and -x flags
1385      */
1386     if (nverbose)
1387 	setNS(STRverbose);
1388     if (nexececho)
1389 	setNS(STRecho);
1390 
1391 
1392     if (targinp) {
1393 	arginp = SAVE(targinp);
1394 	/*
1395 	 * we put the command into a variable
1396 	 */
1397 	if (arginp != NULL)
1398 	    setv(STRcommand, quote(Strsave(arginp)), VAR_READWRITE);
1399 
1400 	/*
1401 	 * * Give an error on -c arguments that end in * backslash to
1402 	 * ensure that you don't make * nonportable csh scripts.
1403 	 */
1404 	{
1405 	    int count;
1406 
1407 	    cp = Strend(arginp);
1408 	    count = 0;
1409 	    while (cp > arginp && *--cp == '\\')
1410 		++count;
1411 	    if ((count & 1) != 0) {
1412 		exiterr = 1;
1413 		stderror(ERR_ARGC);
1414 	    }
1415 	}
1416     }
1417     /*
1418      * All the rest of the world is inside this call. The argument to process
1419      * indicates whether it should catch "error unwinds".  Thus if we are a
1420      * interactive shell our call here will never return by being blown past on
1421      * an error.
1422      */
1423     process(setintr);
1424 
1425     /*
1426      * Mop-up.
1427      */
1428     /* Take care of these (especially HUP) here instead of inside flush. */
1429     handle_pending_signals();
1430     if (intty) {
1431 	if (loginsh) {
1432 	    xprintf("logout\n");
1433 	    xclose(SHIN);
1434 	    child = 1;
1435 #ifdef TESLA
1436 	    do_logout = 1;
1437 #endif				/* TESLA */
1438 	    goodbye(NULL, NULL);
1439 	}
1440 	else {
1441 	    xprintf("exit\n");
1442 	}
1443     }
1444     record();
1445     exitstat();
1446     return (0);
1447 }
1448 
1449 void
1450 untty(void)
1451 {
1452 #ifdef BSDJOBS
1453     if (tpgrp > 0 && opgrp != shpgrp) {
1454 	(void) setpgid(0, opgrp);
1455 	(void) tcsetpgrp(FSHTTY, opgrp);
1456 	(void) resetdisc(FSHTTY);
1457     }
1458 #endif /* BSDJOBS */
1459 }
1460 
1461 void
1462 importpath(Char *cp)
1463 {
1464     size_t i = 0;
1465     Char *dp;
1466     Char **pv;
1467     int     c;
1468 
1469     for (dp = cp; *dp; dp++)
1470 	if (*dp == PATHSEP)
1471 	    i++;
1472     /*
1473      * i+2 where i is the number of colons in the path. There are i+1
1474      * directories in the path plus we need room for a zero terminator.
1475      */
1476     pv = xcalloc(i + 2, sizeof(Char *));
1477     dp = cp;
1478     i = 0;
1479     if (*dp)
1480 	for (;;) {
1481 	    if ((c = *dp) == PATHSEP || c == 0) {
1482 		*dp = 0;
1483 		pv[i++] = Strsave(*cp ? cp : STRdot);
1484 		if (c) {
1485 		    cp = dp + 1;
1486 		    *dp = PATHSEP;
1487 		}
1488 		else
1489 		    break;
1490 	    }
1491 #ifdef WINNT_NATIVE
1492 	    else if (*dp == '\\')
1493 		*dp = '/';
1494 #endif /* WINNT_NATIVE */
1495 	    dp++;
1496 	}
1497     pv[i] = 0;
1498     cleanup_push(pv, blk_cleanup);
1499     setq(STRpath, pv, &shvhed, VAR_READWRITE);
1500     cleanup_ignore(pv);
1501     cleanup_until(pv);
1502 }
1503 
1504 /*
1505  * Source to the file which is the catenation of the argument names.
1506  */
1507 static int
1508 srccat(Char *cp, Char *dp)
1509 {
1510     if (cp[0] == '/' && cp[1] == '\0')
1511 	return srcfile(short2str(dp), (mflag ? 0 : 1), 0, NULL);
1512     else {
1513 	Char *ep;
1514 	char   *ptr;
1515 	int rv;
1516 
1517 #ifdef WINNT_NATIVE
1518 	ep = Strend(cp);
1519 	if (ep != cp && ep[-1] == '/' && dp[0] == '/') /* silly win95 */
1520 	    dp++;
1521 #endif /* WINNT_NATIVE */
1522 
1523 	ep = Strspl(cp, dp);
1524 	cleanup_push(ep, xfree);
1525 	ptr = short2str(ep);
1526 
1527 	rv = srcfile(ptr, (mflag ? 0 : 1), 0, NULL);
1528 	cleanup_until(ep);
1529 	return rv;
1530     }
1531 }
1532 
1533 /*
1534  * Source to a file putting the file descriptor in a safe place (> 2).
1535  */
1536 #ifndef WINNT_NATIVE
1537 static int
1538 #else
1539 int
1540 #endif /*WINNT_NATIVE*/
1541 srcfile(const char *f, int onlyown, int flag, Char **av)
1542 {
1543     int unit;
1544 
1545     if ((unit = xopen(f, O_RDONLY|O_LARGEFILE)) == -1)
1546 	return 0;
1547     cleanup_push(&unit, open_cleanup);
1548     unit = dmove(unit, -1);
1549     cleanup_ignore(&unit);
1550     cleanup_until(&unit);
1551 
1552     (void) close_on_exec(unit, 1);
1553     srcunit(unit, onlyown, flag, av);
1554     return 1;
1555 }
1556 
1557 
1558 /*
1559  * Save the shell state, and establish new argument vector, and new input
1560  * fd.
1561  */
1562 static void
1563 st_save(struct saved_state *st, int unit, int hflg, Char **al, Char **av)
1564 {
1565     st->insource	= insource;
1566     st->SHIN		= SHIN;
1567     /* Want to preserve the meaning of "source file >output".
1568      * Save old descriptors, move new 0,1,2 to safe places and assign
1569      * them to SH* and let process() redo 0,1,2 from them.
1570      *
1571      * The macro returns true if d1 and d2 are good and they point to
1572      * different things.  If you don't avoid saving duplicate
1573      * descriptors, you really limit the depth of "source" recursion
1574      * you can do because of all the open file descriptors.  -IAN!
1575      */
1576 #define NEED_SAVE_FD(d1,d2) \
1577     (fstat(d1, &s1) != -1 && fstat(d2, &s2) != -1 \
1578 	&& (s1.st_ino != s2.st_ino || s1.st_dev != s2.st_dev) )
1579 
1580     st->OLDSTD = st->SHOUT = st->SHDIAG = -1;/* test later to restore these */
1581     if (didfds) {
1582 	    struct stat s1, s2;
1583 	    if (NEED_SAVE_FD(0,OLDSTD)) {
1584 		    st->OLDSTD = OLDSTD;
1585 		    OLDSTD = dmove(0, -1);
1586 		    (void)close_on_exec(OLDSTD, 1);
1587 	    }
1588 	    if (NEED_SAVE_FD(1,SHOUT)) {
1589 		    st->SHOUT = SHOUT;
1590 		    SHOUT = dmove(1, -1);
1591 		    (void)close_on_exec(SHOUT, 1);
1592 	    }
1593 	    if (NEED_SAVE_FD(2,SHDIAG)) {
1594 		    st->SHDIAG = SHDIAG;
1595 		    SHDIAG = dmove(2, -1);
1596 		    (void)close_on_exec(SHDIAG, 1);
1597 	    }
1598 	    donefds();
1599     }
1600 
1601     st->intty		= intty;
1602     st->whyles		= whyles;
1603     st->gointr		= gointr;
1604     st->arginp		= arginp;
1605     st->evalp		= evalp;
1606     st->evalvec		= evalvec;
1607     st->alvecp		= alvecp;
1608     st->alvec		= alvec;
1609     st->onelflg		= onelflg;
1610     st->enterhist	= enterhist;
1611     st->justpr		= justpr;
1612     if (hflg)
1613 	st->HIST	= HIST;
1614     else
1615 	st->HIST	= '\0';
1616     st->cantell		= cantell;
1617     cpybin(st->B, B);
1618 
1619     /*
1620      * we can now pass arguments to source.
1621      * For compatibility we do that only if arguments were really
1622      * passed, otherwise we keep the old, global $argv like before.
1623      */
1624     if (av != NULL && *av != NULL) {
1625 	struct varent *vp;
1626 	if ((vp = adrof(STRargv)) != NULL && vp->vec != NULL)
1627 	    st->argv = saveblk(vp->vec);
1628 	else
1629 	    st->argv = NULL;
1630 	setq(STRargv, saveblk(av), &shvhed, VAR_READWRITE);
1631     }
1632     else
1633 	st->argv = NULL;
1634     st->av = av;
1635 
1636     SHIN	= unit;	/* Do this first */
1637 
1638     /* Establish new input arena */
1639     {
1640 	fbuf = NULL;
1641 	fseekp = feobp = fblocks = 0;
1642 	settell();
1643     }
1644 
1645     arginp	= 0;
1646     onelflg	= 0;
1647     intty	= isatty(SHIN);
1648     whyles	= 0;
1649     gointr	= 0;
1650     evalvec	= 0;
1651     evalp	= 0;
1652     alvec	= al;
1653     alvecp	= 0;
1654     enterhist	= hflg;
1655     if (enterhist)
1656 	HIST	= '\0';
1657     insource	= 1;
1658 }
1659 
1660 
1661 /*
1662  * Restore the shell to a saved state
1663  */
1664 static void
1665 st_restore(void *xst)
1666 {
1667     struct saved_state *st;
1668 
1669     st = xst;
1670     if (st->SHIN == -1)
1671 	return;
1672 
1673     /* Reset input arena */
1674     {
1675 	int i;
1676 	Char** nfbuf = fbuf;
1677 	int nfblocks = fblocks;
1678 
1679 	fblocks = 0;
1680 	fbuf = NULL;
1681 	for (i = 0; i < nfblocks; i++)
1682 	    xfree(nfbuf[i]);
1683 	xfree(nfbuf);
1684     }
1685     cpybin(B, st->B);
1686 
1687     xclose(SHIN);
1688 
1689     insource	= st->insource;
1690     SHIN	= st->SHIN;
1691     if (st->OLDSTD != -1)
1692 	xclose(OLDSTD), OLDSTD = st->OLDSTD;
1693     if (st->SHOUT != -1)
1694 	xclose(SHOUT),  SHOUT = st->SHOUT;
1695     if (st->SHDIAG != -1)
1696 	xclose(SHDIAG), SHDIAG = st->SHDIAG;
1697     arginp	= st->arginp;
1698     onelflg	= st->onelflg;
1699     evalp	= st->evalp;
1700     evalvec	= st->evalvec;
1701     alvecp	= st->alvecp;
1702     alvec	= st->alvec;
1703     intty	= st->intty;
1704     whyles	= st->whyles;
1705     gointr	= st->gointr;
1706     if (st->HIST != '\0')
1707 	HIST	= st->HIST;
1708     enterhist	= st->enterhist;
1709     cantell	= st->cantell;
1710     justpr	= st->justpr;
1711 
1712     if (st->argv != NULL)
1713 	setq(STRargv, st->argv, &shvhed, VAR_READWRITE);
1714     else if (st->av != NULL  && *st->av != NULL && adrof(STRargv) != NULL)
1715 	unsetv(STRargv);
1716 }
1717 
1718 /*
1719  * Source to a unit.  If onlyown it must be our file or our group or
1720  * we don't chance it.	This occurs on ".cshrc"s and the like.
1721  */
1722 static void
1723 srcunit(int unit, int onlyown, int hflg, Char **av)
1724 {
1725     struct saved_state st;
1726 
1727     st.SHIN = -1;	/* st_restore checks this */
1728 
1729     if (unit < 0)
1730 	return;
1731 
1732     if (onlyown) {
1733 	struct stat stb;
1734 
1735 	if (fstat(unit, &stb) < 0) {
1736 	    xclose(unit);
1737 	    return;
1738 	}
1739     }
1740 
1741     /* Does nothing before st_save() because st.SHIN == -1 */
1742     cleanup_push(&st, st_restore);
1743     if (setintr) {
1744 	pintr_disabled++;
1745 	cleanup_push(&pintr_disabled, disabled_cleanup);
1746     }
1747 
1748     /* Save the current state and move us to a new state */
1749     st_save(&st, unit, hflg, NULL, av);
1750 
1751     /*
1752      * Now if we are allowing commands to be interrupted, we let ourselves be
1753      * interrupted.
1754      */
1755     if (setintr) {
1756 	cleanup_until(&pintr_disabled);
1757 	pintr_disabled++;
1758 	cleanup_push(&pintr_disabled, disabled_cleanup);
1759     }
1760 
1761     process(0);		/* 0 -> blow away on errors */
1762 
1763     /* Restore the old state */
1764     cleanup_until(&st);
1765 }
1766 
1767 
1768 /*ARGSUSED*/
1769 void
1770 goodbye(Char **v, struct command *c)
1771 {
1772     USE(v);
1773     USE(c);
1774     record();
1775 
1776     if (loginsh) {
1777 	size_t omark;
1778 	sigset_t set;
1779 
1780 	sigemptyset(&set);
1781 	signal(SIGQUIT, SIG_IGN);
1782 	sigaddset(&set, SIGQUIT);
1783 	sigprocmask(SIG_UNBLOCK, &set, NULL);
1784 	signal(SIGINT, SIG_IGN);
1785 	sigaddset(&set, SIGINT);
1786 	signal(SIGTERM, SIG_IGN);
1787 	sigaddset(&set, SIGTERM);
1788 	signal(SIGHUP, SIG_IGN);
1789 	sigaddset(&set, SIGHUP);
1790 	sigprocmask(SIG_UNBLOCK, &set, NULL);
1791 	phup_disabled = 1;
1792 	setintr = 0;		/* No interrupts after "logout" */
1793 	/* Trap errors inside .logout */
1794 	omark = cleanup_push_mark();
1795 	if (setexit() == 0) {
1796 	    if (!(adrof(STRlogout)))
1797 		setcopy(STRlogout, STRnormal, VAR_READWRITE);
1798 #ifdef _PATH_DOTLOGOUT
1799 	    (void) srcfile(_PATH_DOTLOGOUT, 0, 0, NULL);
1800 #endif
1801 	    if (adrof(STRhome))
1802 		(void) srccat(varval(STRhome), STRsldtlogout);
1803 #ifdef TESLA
1804 	    do_logout = 1;
1805 #endif /* TESLA */
1806 	}
1807 	cleanup_pop_mark(omark);
1808     }
1809     exitstat();
1810 }
1811 
1812 void
1813 exitstat(void)
1814 {
1815 #ifdef PROF
1816     _mcleanup();
1817 #endif
1818     /*
1819      * Note that if STATUS is corrupted (i.e. getn bombs) then error will exit
1820      * directly because we poke child here. Otherwise we might continue
1821      * unwarrantedly (sic).
1822      */
1823     child = 1;
1824 
1825     xexit(getn(varval(STRstatus)));
1826 }
1827 
1828 /*
1829  * in the event of a HUP we want to save the history
1830  */
1831 void
1832 phup(void)
1833 {
1834     if (loginsh) {
1835 	setcopy(STRlogout, STRhangup, VAR_READWRITE);
1836 #ifdef _PATH_DOTLOGOUT
1837 	(void) srcfile(_PATH_DOTLOGOUT, 0, 0, NULL);
1838 #endif
1839 	if (adrof(STRhome))
1840 	    (void) srccat(varval(STRhome), STRsldtlogout);
1841     }
1842 
1843     record();
1844 
1845 #ifdef POSIXJOBS
1846     /*
1847      * We kill the last foreground process group. It then becomes
1848      * responsible to propagate the SIGHUP to its progeny.
1849      */
1850     {
1851 	struct process *pp, *np;
1852 
1853 	for (pp = proclist.p_next; pp; pp = pp->p_next) {
1854 	    np = pp;
1855 	    /*
1856 	     * Find if this job is in the foreground. It could be that
1857 	     * the process leader has exited and the foreground flag
1858 	     * is cleared for it.
1859 	     */
1860 	    do
1861 		/*
1862 		 * If a process is in the foreground we try to kill
1863 		 * it's process group. If we succeed, then the
1864 		 * whole job is gone. Otherwise we keep going...
1865 		 * But avoid sending HUP to the shell again.
1866 		 */
1867 		if (((np->p_flags & PFOREGND) != 0) && np->p_jobid != shpgrp) {
1868 		    np->p_flags &= ~PHUP;
1869 		    if (killpg(np->p_jobid, SIGHUP) != -1) {
1870 			/* In case the job was suspended... */
1871 #ifdef SIGCONT
1872 			(void) killpg(np->p_jobid, SIGCONT);
1873 #endif
1874 			break;
1875 		    }
1876 		}
1877 	    while ((np = np->p_friends) != pp);
1878 	}
1879     }
1880 #endif /* POSIXJOBS */
1881 
1882     xexit(SIGHUP);
1883 }
1884 
1885 static Char   *jobargv[2] = {STRjobs, 0};
1886 
1887 /*
1888  * Catch an interrupt, e.g. during lexical input.
1889  * If we are an interactive shell, we reset the interrupt catch
1890  * immediately.  In any case we drain the shell output,
1891  * and finally go through the normal error mechanism, which
1892  * gets a chance to make the shell go away.
1893  */
1894 int just_signaled;		/* bugfix by Michael Bloom (mg@ttidca.TTI.COM) */
1895 
1896 void
1897 pintr(void)
1898 {
1899     just_signaled = 1;
1900     pintr1(1);
1901 }
1902 
1903 void
1904 pintr1(int wantnl)
1905 {
1906     if (setintr) {
1907 	if (pjobs) {
1908 	    pjobs = 0;
1909 	    xputchar('\n');
1910 	    dojobs(jobargv, NULL);
1911 	    stderror(ERR_NAME | ERR_INTR);
1912 	}
1913     }
1914     /* MH - handle interrupted completions specially */
1915     {
1916 	if (InsideCompletion)
1917 	    stderror(ERR_SILENT);
1918     }
1919     /* JV - Make sure we shut off inputl */
1920     {
1921 	(void) Cookedmode();
1922 	GettingInput = 0;
1923 	if (evalvec)
1924 	    doneinp = 1;
1925     }
1926     drainoline();
1927 #ifdef HAVE_GETPWENT
1928     (void) endpwent();
1929 #endif
1930 
1931     /*
1932      * If we have an active "onintr" then we search for the label. Note that if
1933      * one does "onintr -" then we shan't be interruptible so we needn't worry
1934      * about that here.
1935      */
1936     if (gointr) {
1937 	gotolab(gointr);
1938 	reset();
1939     }
1940     else if (intty && wantnl) {
1941 	if (editing) {
1942 	    /*
1943 	     * If we are editing a multi-line input command, and move to
1944 	     * the beginning of the line, we don't want to trash it when
1945 	     * we hit ^C
1946 	     */
1947 	    PastBottom();
1948 	    ClearLines();
1949 	    ClearDisp();
1950 	}
1951 	else {
1952 	    /* xputchar('\n'); *//* Some like this, others don't */
1953 	    (void) putraw('\r');
1954 	    (void) putraw('\n');
1955 	}
1956     }
1957     stderror(ERR_SILENT);
1958 }
1959 
1960 /*
1961  * Process is the main driving routine for the shell.
1962  * It runs all command processing, except for those within { ... }
1963  * in expressions (which is run by a routine evalav in sh.exp.c which
1964  * is a stripped down process), and `...` evaluation which is run
1965  * also by a subset of this code in sh.glob.c in the routine backeval.
1966  *
1967  * The code here is a little strange because part of it is interruptible
1968  * and hence freeing of structures appears to occur when none is necessary
1969  * if this is ignored.
1970  *
1971  * Note that if catch is not set then we will unwind on any error.
1972  * If an end-of-file occurs, we return.
1973  */
1974 void
1975 process(int catch)
1976 {
1977     jmp_buf_t osetexit;
1978     /* PWP: This might get nuked by longjmp so don't make it a register var */
1979     size_t omark;
1980     volatile int didexitset = 0;
1981 
1982     getexit(osetexit);
1983     omark = cleanup_push_mark();
1984     for (;;) {
1985 	struct command *t;
1986 	int hadhist, old_pintr_disabled;
1987 
1988 	(void)setexit();
1989 	if (didexitset == 0) {
1990 	    exitset++;
1991 	    didexitset++;
1992 	}
1993 	pendjob();
1994 
1995 	justpr = enterhist;	/* execute if not entering history */
1996 
1997 	if (haderr) {
1998 	    if (!catch) {
1999 		/* unwind */
2000 		doneinp = 0;
2001 		cleanup_pop_mark(omark);
2002 		resexit(osetexit);
2003 		reset();
2004 	    }
2005 	    haderr = 0;
2006 	    /*
2007 	     * Every error is eventually caught here or the shell dies.  It is
2008 	     * at this point that we clean up any left-over open files, by
2009 	     * closing all but a fixed number of pre-defined files.  Thus
2010 	     * routines don't have to worry about leaving files open due to
2011 	     * deeper errors... they will get closed here.
2012 	     */
2013 	    closem();
2014 	    continue;
2015 	}
2016 	if (doneinp) {
2017 	    doneinp = 0;
2018 	    break;
2019 	}
2020 	if (chkstop)
2021 	    chkstop--;
2022 	if (neednote)
2023 	    pnote();
2024 	if (intty && prompt && evalvec == 0) {
2025 	    just_signaled = 0;
2026 	    mailchk();
2027 	    /*
2028 	     * Watch for logins/logouts. Next is scheduled commands stored
2029 	     * previously using "sched." Then execute periodic commands.
2030 	     * Following that, the prompt precmd is run.
2031 	     */
2032 #ifndef HAVENOUTMP
2033 	    watch_login(0);
2034 #endif /* !HAVENOUTMP */
2035 	    sched_run();
2036 	    period_cmd();
2037 	    precmd();
2038 	    /*
2039 	     * If we are at the end of the input buffer then we are going to
2040 	     * read fresh stuff. Otherwise, we are rereading input and don't
2041 	     * need or want to prompt.
2042 	     */
2043 	    if (fseekp == feobp && aret == TCSH_F_SEEK)
2044 		printprompt(0, NULL);
2045 	    flush();
2046 	    setalarm(1);
2047 	}
2048 	if (seterr) {
2049 	    xfree(seterr);
2050 	    seterr = NULL;
2051 	}
2052 
2053 	/*
2054 	 * Interruptible during interactive reads
2055 	 */
2056 	if (setintr)
2057 	    pintr_push_enable(&old_pintr_disabled);
2058 	freelex(&paraml);
2059 	hadhist = lex(&paraml);
2060 	if (setintr)
2061 	    cleanup_until(&old_pintr_disabled);
2062 	cleanup_push(&paraml, lex_cleanup);
2063 
2064 	/*
2065 	 * Echo not only on VERBOSE, but also with history expansion. If there
2066 	 * is a lexical error then we forego history echo.
2067 	 * Do not echo if we're only entering history (source -h).
2068 	 */
2069 	if ((hadhist && !seterr && intty && !tellwhat && !Expand && !whyles) ||
2070 	    (!enterhist && adrof(STRverbose)))
2071 	{
2072 	    int odidfds = didfds;
2073 	    haderr = 1;
2074 	    didfds = 0;
2075 	    prlex(&paraml);
2076 	    flush();
2077 	    haderr = 0;
2078 	    didfds = odidfds;
2079 	}
2080 	(void) alarm(0);	/* Autologout OFF */
2081 	alrmcatch_disabled = 1;
2082 
2083 	/*
2084 	 * Save input text on the history list if reading in old history, or it
2085 	 * is from the terminal at the top level and not in a loop.
2086 	 *
2087 	 * PWP: entry of items in the history list while in a while loop is done
2088 	 * elsewhere...
2089 	 */
2090 	if (enterhist || (catch && intty && !whyles && !tellwhat && !arun))
2091 	    savehist(&paraml, enterhist > 1);
2092 
2093 	if (Expand && seterr)
2094 	    Expand = 0;
2095 
2096 	/*
2097 	 * Print lexical error messages, except when sourcing history lists.
2098 	 */
2099 	if (!enterhist && seterr)
2100 	    stderror(ERR_OLD);
2101 
2102 	/*
2103 	 * If had a history command :p modifier then this is as far as we
2104 	 * should go
2105 	 */
2106 	if (justpr)
2107 	    goto cmd_done;
2108 
2109 	/*
2110 	 * If had a tellwhat from twenex() then do
2111 	 */
2112 	if (tellwhat) {
2113 	    (void) tellmewhat(&paraml, NULL);
2114 	    goto cmd_done;
2115 	}
2116 
2117 	alias(&paraml);
2118 
2119 #ifdef BSDJOBS
2120 	/*
2121 	 * If we are interactive, try to continue jobs that we have stopped
2122 	 */
2123 	if (prompt)
2124 	    continue_jobs(&paraml);
2125 #endif				/* BSDJOBS */
2126 
2127 	/*
2128 	 * Check to see if the user typed "rm * .o" or something
2129 	 */
2130 	if (prompt)
2131 	    rmstar(&paraml);
2132 	/*
2133 	 * Parse the words of the input into a parse tree.
2134 	 */
2135 	t = syntax(paraml.next, &paraml, 0);
2136 	/*
2137 	 * We cannot cleanup push here, because cd /blah; echo foo
2138 	 * would rewind t on the chdir error, and free the rest of the command
2139 	 */
2140 	if (seterr) {
2141 	    freesyn(t);
2142 	    stderror(ERR_OLD);
2143 	}
2144 
2145 	postcmd();
2146 	/*
2147 	 * Execute the parse tree From: Michael Schroeder
2148 	 * <mlschroe@immd4.informatik.uni-erlangen.de> was execute(t, tpgrp);
2149 	 */
2150 	execute(t, (tpgrp > 0 ? tpgrp : -1), NULL, NULL, TRUE);
2151 	freesyn(t);
2152 
2153 	/*
2154 	 * Made it!
2155 	 */
2156 #ifdef SIG_WINDOW
2157 	if (windowchg || (catch && intty && !whyles && !tellwhat)) {
2158 	    (void) check_window_size(0);	/* for window systems */
2159 	}
2160 #endif /* SIG_WINDOW */
2161 	setcopy(STR_, InputBuf, VAR_READWRITE | VAR_NOGLOB);
2162     cmd_done:
2163 	if (cleanup_reset())
2164 	    cleanup_until(&paraml);
2165 	else
2166 	    haderr = 1;
2167     }
2168     cleanup_pop_mark(omark);
2169     resexit(osetexit);
2170     exitset--;
2171     handle_pending_signals();
2172 }
2173 
2174 /*ARGSUSED*/
2175 void
2176 dosource(Char **t, struct command *c)
2177 {
2178     Char *f;
2179     int    hflg = 0;
2180     char *file;
2181 
2182     USE(c);
2183     t++;
2184     if (*t && eq(*t, STRmh)) {
2185 	if (*++t == NULL)
2186 	    stderror(ERR_NAME | ERR_HFLAG);
2187 	hflg++;
2188     }
2189     else if (*t && eq(*t, STRmm)) {
2190     	if (*++t == NULL)
2191 	    stderror(ERR_NAME | ERR_MFLAG);
2192 	hflg = 2;
2193     }
2194 
2195     f = globone(*t++, G_ERROR);
2196     file = strsave(short2str(f));
2197     cleanup_push(file, xfree);
2198     xfree(f);
2199     t = glob_all_or_error(t);
2200     cleanup_push(t, blk_cleanup);
2201     if ((!srcfile(file, 0, hflg, t)) && (!hflg) && (!bequiet))
2202 	stderror(ERR_SYSTEM, file, strerror(errno));
2203     cleanup_until(file);
2204 }
2205 
2206 /*
2207  * Check for mail.
2208  * If we are a login shell, then we don't want to tell
2209  * about any mail file unless its been modified
2210  * after the time we started.
2211  * This prevents us from telling the user things he already
2212  * knows, since the login program insists on saying
2213  * "You have mail."
2214  */
2215 
2216 /*
2217  * The AMS version.
2218  * This version checks if the file is a directory, and if so,
2219  * tells you the number of files in it, otherwise do the old thang.
2220  * The magic "+1" in the time calculation is to compensate for
2221  * an AFS bug where directory mtimes are set to 1 second in
2222  * the future.
2223  */
2224 
2225 static void
2226 mailchk(void)
2227 {
2228     struct varent *v;
2229     Char **vp;
2230     time_t  t;
2231     int     intvl, cnt;
2232     struct stat stb;
2233     int    new;
2234 
2235     v = adrof(STRmail);
2236     if (v == NULL || v->vec == NULL)
2237 	return;
2238     (void) time(&t);
2239     vp = v->vec;
2240     cnt = blklen(vp);
2241     intvl = (cnt && number(*vp)) ? (--cnt, getn(*vp++)) : MAILINTVL;
2242     if (intvl < 1)
2243 	intvl = 1;
2244     if (chktim + intvl > t)
2245 	return;
2246     for (; *vp; vp++) {
2247 	char *filename = short2str(*vp);
2248 	char *mboxdir = filename;
2249 
2250 	if (stat(filename, &stb) < 0)
2251 	    continue;
2252 #if defined(BSDTIMES) || defined(_SEQUENT_)
2253 	new = stb.st_mtime > time0.tv_sec;
2254 #else
2255 	new = stb.st_mtime > seconds0;
2256 #endif
2257 	if (S_ISDIR(stb.st_mode)) {
2258 	    DIR *mailbox;
2259 	    int mailcount = 0;
2260 	    char *tempfilename;
2261 	    struct stat stc;
2262 
2263 	    tempfilename = xasprintf("%s/new", filename);
2264 
2265 	    if (stat(tempfilename, &stc) != -1 && S_ISDIR(stc.st_mode)) {
2266 		/*
2267 		 * "filename/new" exists and is a directory; you are
2268 		 * using Qmail.
2269 		 */
2270 		stb = stc;
2271 #if defined(BSDTIMES) || defined(_SEQUENT_)
2272 		new = stb.st_mtime > time0.tv_sec;
2273 #else
2274 		new = stb.st_mtime > seconds0;
2275 #endif
2276 		mboxdir = tempfilename;
2277 	    }
2278 
2279 	    if (stb.st_mtime <= chktim + 1 || (loginsh && !new)) {
2280 		xfree(tempfilename);
2281 		continue;
2282 	    }
2283 
2284 	    mailbox = opendir(mboxdir);
2285 	    xfree(tempfilename);
2286 	    if (mailbox == NULL)
2287 		continue;
2288 
2289 	    /* skip . and .. */
2290 	    if (!readdir(mailbox) || !readdir(mailbox)) {
2291 		(void)closedir(mailbox);
2292 		continue;
2293 	    }
2294 
2295 	    while (readdir(mailbox))
2296 		mailcount++;
2297 
2298 	    (void)closedir(mailbox);
2299 	    if (mailcount == 0)
2300 		continue;
2301 
2302 	    if (cnt == 1)
2303 		xprintf(CGETS(11, 3, "You have %d mail messages.\n"),
2304 			mailcount);
2305 	    else
2306 		xprintf(CGETS(11, 4, "You have %d mail messages in %s.\n"),
2307 			mailcount, filename);
2308 	}
2309 	else {
2310 	    char *type;
2311 
2312 	    if (stb.st_size == 0 || stb.st_atime >= stb.st_mtime ||
2313 		(stb.st_atime <= chktim && stb.st_mtime <= chktim) ||
2314 		(loginsh && !new))
2315 		continue;
2316 	    type = strsave(new ? CGETS(11, 6, "new ") : "");
2317 	    cleanup_push(type, xfree);
2318 	    if (cnt == 1)
2319 		xprintf(CGETS(11, 5, "You have %smail.\n"), type);
2320 	    else
2321 	        xprintf(CGETS(11, 7, "You have %smail in %s.\n"), type, filename);
2322 	    cleanup_until(type);
2323 	}
2324     }
2325     chktim = t;
2326 }
2327 
2328 /*
2329  * Extract a home directory from the password file
2330  * The argument points to a buffer where the name of the
2331  * user whose home directory is sought is currently.
2332  * We return home directory of the user, or NULL.
2333  */
2334 Char *
2335 gethdir(const Char *home)
2336 {
2337     Char   *h;
2338 
2339     /*
2340      * Is it us?
2341      */
2342     if (*home == '\0') {
2343 	if ((h = varval(STRhome)) != STRNULL)
2344 	    return Strsave(h);
2345 	else
2346 	    return NULL;
2347     }
2348 
2349     /*
2350      * Look in the cache
2351      */
2352     if ((h = gettilde(home)) == NULL)
2353 	return NULL;
2354     else
2355 	return Strsave(h);
2356 }
2357 
2358 /*
2359  * Move the initial descriptors to their eventual
2360  * resting places, closing all other units.
2361  */
2362 void
2363 initdesc(void)
2364 {
2365 #ifdef NLS_BUGS
2366 #ifdef NLS_CATALOGS
2367     nlsclose();
2368 #endif /* NLS_CATALOGS */
2369 #endif /* NLS_BUGS */
2370 
2371 
2372     didfds = 0;			/* 0, 1, 2 aren't set up */
2373     (void) close_on_exec(SHIN = dcopy(0, FSHIN), 1);
2374     (void) close_on_exec(SHOUT = dcopy(1, FSHOUT), 1);
2375     (void) close_on_exec(SHDIAG = dcopy(2, FSHDIAG), 1);
2376     (void) close_on_exec(OLDSTD = dcopy(SHIN, FOLDSTD), 1);
2377 #ifndef CLOSE_ON_EXEC
2378     didcch = 0;			/* Havent closed for child */
2379 #endif /* CLOSE_ON_EXEC */
2380     if (SHDIAG >= 0)
2381 	isdiagatty = isatty(SHDIAG);
2382     else
2383     	isdiagatty = 0;
2384     if (SHDIAG >= 0)
2385 	isoutatty = isatty(SHOUT);
2386     else
2387     	isoutatty = 0;
2388 #ifdef NLS_BUGS
2389 #ifdef NLS_CATALOGS
2390     nlsinit();
2391 #endif /* NLS_CATALOGS */
2392 #endif /* NLS_BUGS */
2393 }
2394 
2395 
2396 void
2397 #ifdef PROF
2398 done(int i)
2399 #else
2400 xexit(int i)
2401 #endif
2402 {
2403 #ifdef TESLA
2404     if (loginsh && do_logout) {
2405 	/* this is to send hangup signal to the develcon */
2406 	/* we toggle DTR. clear dtr - sleep 1 - set dtr */
2407 	/* ioctl will return ENOTTY for pty's but we ignore it 	 */
2408 	/* exitstat will run after disconnect */
2409 	/* we sleep for 2 seconds to let things happen in */
2410 	/* .logout and rechist() */
2411 #ifdef TIOCCDTR
2412 	(void) sleep(2);
2413 	(void) ioctl(FSHTTY, TIOCCDTR, NULL);
2414 	(void) sleep(1);
2415 	(void) ioctl(FSHTTY, TIOCSDTR, NULL);
2416 #endif /* TIOCCDTR */
2417     }
2418 #endif /* TESLA */
2419 
2420     {
2421 	struct process *pp, *np;
2422 	pid_t mypid = getpid();
2423 	/* Kill all processes marked for hup'ing */
2424 	for (pp = proclist.p_next; pp; pp = pp->p_next) {
2425 	    np = pp;
2426 	    do
2427 		if ((np->p_flags & PHUP) && np->p_jobid != shpgrp &&
2428 		    np->p_parentid == mypid) {
2429 		    if (killpg(np->p_jobid, SIGHUP) != -1) {
2430 			/* In case the job was suspended... */
2431 #ifdef SIGCONT
2432 			(void) killpg(np->p_jobid, SIGCONT);
2433 #endif
2434 			break;
2435 		    }
2436 		}
2437 	    while ((np = np->p_friends) != pp);
2438 	}
2439     }
2440     untty();
2441 #ifdef NLS_CATALOGS
2442     /*
2443      * We need to call catclose, because SVR4 leaves symlinks behind otherwise
2444      * in the catalog directories. We cannot close on a vforked() child,
2445      * because messages will stop working on the parent too.
2446      */
2447     if (child == 0)
2448 	nlsclose();
2449 #endif /* NLS_CATALOGS */
2450 #ifdef WINNT_NATIVE
2451     nt_cleanup();
2452 #endif /* WINNT_NATIVE */
2453     _exit(i);
2454 }
2455 
2456 #ifndef _PATH_DEFPATH
2457 static Char **
2458 defaultpath(void)
2459 {
2460     char   *ptr;
2461     Char  **blk, **blkp;
2462     struct stat stb;
2463 
2464     blkp = blk = xmalloc(sizeof(Char *) * 10);
2465 
2466 #ifndef NODOT
2467 # ifndef DOTLAST
2468     *blkp++ = Strsave(STRdot);
2469 # endif
2470 #endif
2471 
2472 #define DIRAPPEND(a)  \
2473 	if (stat(ptr = a, &stb) == 0 && S_ISDIR(stb.st_mode)) \
2474 		*blkp++ = SAVE(ptr)
2475 
2476 #ifdef _PATH_LOCAL
2477     DIRAPPEND(_PATH_LOCAL);
2478 #endif
2479 
2480 #ifdef _PATH_USRUCB
2481     DIRAPPEND(_PATH_USRUCB);
2482 #endif
2483 
2484 #ifdef _PATH_USRBSD
2485     DIRAPPEND(_PATH_USRBSD);
2486 #endif
2487 
2488 #ifdef _PATH_BIN
2489     DIRAPPEND(_PATH_BIN);
2490 #endif
2491 
2492 #ifdef _PATH_USRBIN
2493     DIRAPPEND(_PATH_USRBIN);
2494 #endif
2495 
2496 #undef DIRAPPEND
2497 
2498 #ifndef NODOT
2499 # ifdef DOTLAST
2500     *blkp++ = Strsave(STRdot);
2501 # endif
2502 #endif
2503     *blkp = NULL;
2504     return (blk);
2505 }
2506 #endif
2507 
2508 static void
2509 record(void)
2510 {
2511     if (!fast) {
2512 	recdirs(NULL, adrof(STRsavedirs) != NULL);
2513 	rechist(NULL, adrof(STRsavehist) != NULL);
2514     }
2515     displayHistStats("Exiting");	/* no-op unless DEBUG_HIST */
2516 }
2517 
2518 /*
2519  * Grab the tty repeatedly, and give up if we are not in the correct
2520  * tty process group.
2521  */
2522 int
2523 grabpgrp(int fd, pid_t desired)
2524 {
2525     struct sigaction old;
2526     pid_t pgrp;
2527     size_t i;
2528 
2529     for (i = 0; i < 100; i++) {
2530 	if ((pgrp = tcgetpgrp(fd)) == -1)
2531 	    return -1;
2532 	if (pgrp == desired)
2533 	    return 0;
2534 	(void)sigaction(SIGTTIN, NULL, &old);
2535 	(void)signal(SIGTTIN, SIG_DFL);
2536 	(void)kill(0, SIGTTIN);
2537 	(void)sigaction(SIGTTIN, &old, NULL);
2538     }
2539     errno = EPERM;
2540     return -1;
2541 }
2542